diff --git a/.gitattributes b/.gitattributes index 74984602606fa17ed6785725a597675865c44e45..1f0bc8082ac28f893aecc764d3fecee79765f559 100644 --- a/.gitattributes +++ b/.gitattributes @@ -817,3 +817,5 @@ videochat2/lib/python3.10/site-packages/tensorflow/python/_pywrap_mlir.so filter videochat2/lib/python3.10/site-packages/tensorflow/python/_pywrap_parallel_device.so filter=lfs diff=lfs merge=lfs -text pllava/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_adv.so.9 filter=lfs diff=lfs merge=lfs -text videochat2/lib/python3.10/site-packages/tensorflow/lite/python/interpreter_wrapper/_pywrap_tensorflow_interpreter_wrapper.so filter=lfs diff=lfs merge=lfs -text +videochat2/lib/python3.10/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so filter=lfs diff=lfs merge=lfs -text +videochat2/lib/python3.10/site-packages/tensorflow/python/profiler/internal/_pywrap_traceme.so filter=lfs diff=lfs merge=lfs -text diff --git a/llava_next/share/terminfo/l/la120 b/llava_next/share/terminfo/l/la120 new file mode 100644 index 0000000000000000000000000000000000000000..834885b620c486d556b19625a38b9d31dc8ccb46 Binary files /dev/null and b/llava_next/share/terminfo/l/la120 differ diff --git a/llava_next/share/terminfo/l/lft b/llava_next/share/terminfo/l/lft new file mode 100644 index 0000000000000000000000000000000000000000..20c5b42c213f1e8bcf90dd645d60f68d292a7db6 Binary files /dev/null and b/llava_next/share/terminfo/l/lft differ diff --git a/llava_next/share/terminfo/l/linux b/llava_next/share/terminfo/l/linux new file mode 100644 index 0000000000000000000000000000000000000000..4ee980c810381db9f367393236bf2e6819d8f7ad Binary files /dev/null and b/llava_next/share/terminfo/l/linux differ diff --git a/llava_next/share/terminfo/l/linux-basic b/llava_next/share/terminfo/l/linux-basic new file mode 100644 index 0000000000000000000000000000000000000000..d388537c9244ac51baf220f19f3283442e20972e Binary files /dev/null and b/llava_next/share/terminfo/l/linux-basic differ diff --git a/llava_next/share/terminfo/l/linux-c b/llava_next/share/terminfo/l/linux-c new file mode 100644 index 0000000000000000000000000000000000000000..d25a9b181553d417e295fffc777ad1283f20c685 Binary files /dev/null and b/llava_next/share/terminfo/l/linux-c differ diff --git a/llava_next/share/terminfo/l/linux-vt b/llava_next/share/terminfo/l/linux-vt new file mode 100644 index 0000000000000000000000000000000000000000..1acf6d651d7578beaa7ee0d37bf650f8da2ab265 Binary files /dev/null and b/llava_next/share/terminfo/l/linux-vt differ diff --git a/llava_next/share/terminfo/l/linux2.2 b/llava_next/share/terminfo/l/linux2.2 new file mode 100644 index 0000000000000000000000000000000000000000..4b7d785aba7db1fb6ac7f2e8d1a723d0130b6fcb Binary files /dev/null and b/llava_next/share/terminfo/l/linux2.2 differ diff --git a/llava_next/share/terminfo/l/linux3.0 b/llava_next/share/terminfo/l/linux3.0 new file mode 100644 index 0000000000000000000000000000000000000000..8d329d1514c22caed206f0b4f084e35f4a6beb10 Binary files /dev/null and b/llava_next/share/terminfo/l/linux3.0 differ diff --git a/llava_next/share/terminfo/l/lisaterm b/llava_next/share/terminfo/l/lisaterm new file mode 100644 index 0000000000000000000000000000000000000000..34a362e10c6d997d3123dadd7fba8261f9c0ca4e Binary files /dev/null and b/llava_next/share/terminfo/l/lisaterm differ diff --git a/llava_next/share/terminfo/l/liswb b/llava_next/share/terminfo/l/liswb new file mode 100644 index 0000000000000000000000000000000000000000..058fb064fb577e5fe4c3b3840787bf500afb444e Binary files /dev/null and b/llava_next/share/terminfo/l/liswb differ diff --git a/llava_next/share/terminfo/l/ln03 b/llava_next/share/terminfo/l/ln03 new file mode 100644 index 0000000000000000000000000000000000000000..72fadfc5c29f5221852cdd200438723ff8520c38 Binary files /dev/null and b/llava_next/share/terminfo/l/ln03 differ diff --git a/llava_next/share/terminfo/l/ln03-w b/llava_next/share/terminfo/l/ln03-w new file mode 100644 index 0000000000000000000000000000000000000000..dd4877c9102fd748d6604822e373bac02462e00e Binary files /dev/null and b/llava_next/share/terminfo/l/ln03-w differ diff --git a/llava_next/share/terminfo/l/luna b/llava_next/share/terminfo/l/luna new file mode 100644 index 0000000000000000000000000000000000000000..c9a18a80e5849ac23dbbc22df44f922bb30835bc Binary files /dev/null and b/llava_next/share/terminfo/l/luna differ diff --git a/llava_next/share/terminfo/p/pc3r-m b/llava_next/share/terminfo/p/pc3r-m new file mode 100644 index 0000000000000000000000000000000000000000..e5cab4c9851f3866c647d13c1f8af5c88260bfff Binary files /dev/null and b/llava_next/share/terminfo/p/pc3r-m differ diff --git a/llava_next/share/terminfo/p/pccon+keys b/llava_next/share/terminfo/p/pccon+keys new file mode 100644 index 0000000000000000000000000000000000000000..75b7a4e80d5264e565cd919eee5eee93cd49d692 Binary files /dev/null and b/llava_next/share/terminfo/p/pccon+keys differ diff --git a/llava_next/share/terminfo/p/pccons b/llava_next/share/terminfo/p/pccons new file mode 100644 index 0000000000000000000000000000000000000000..5d7c9457abb34e75d0d0c1f5d58b68eefa697978 Binary files /dev/null and b/llava_next/share/terminfo/p/pccons differ diff --git a/llava_next/share/terminfo/p/putty-vt100 b/llava_next/share/terminfo/p/putty-vt100 new file mode 100644 index 0000000000000000000000000000000000000000..c0e68034c30804edfe107039f1d009fe7d305bd5 Binary files /dev/null and b/llava_next/share/terminfo/p/putty-vt100 differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so b/videochat2/lib/python3.10/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so new file mode 100644 index 0000000000000000000000000000000000000000..42670deb8bb6db5ab554b89514329816266293cb --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f70335777d9d8013cae9b48cd9ea2dec79cf4c18049bc41116c4fedcd5d47904 +size 2149625 diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/debug/__init__.py b/videochat2/lib/python3.10/site-packages/tensorflow/python/debug/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2ceb2d1bce0604e3f5897d2c95b07195572fbaed --- /dev/null +++ b/videochat2/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/videochat2/lib/python3.10/site-packages/tensorflow/python/debug/lib/debug_events_monitors.py b/videochat2/lib/python3.10/site-packages/tensorflow/python/debug/lib/debug_events_monitors.py new file mode 100644 index 0000000000000000000000000000000000000000..53ba03cddc7232d9548b876dae237c6b59d66fdc --- /dev/null +++ b/videochat2/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/videochat2/lib/python3.10/site-packages/tensorflow/python/debug/lib/grpc_debug_server.py b/videochat2/lib/python3.10/site-packages/tensorflow/python/debug/lib/grpc_debug_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d5ea1660e42a736f0e1bc33685ee61018ca504cf --- /dev/null +++ b/videochat2/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/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/__init__.py b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/__pycache__/__init__.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdf4881fb09c8be71869c60165c340648e2f307d Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/__init__.py b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/__pycache__/__init__.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1333b946a9885ae0ae416cc1b150ba717f68bdd Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/__pycache__/__init__.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/__pycache__/bias_op_base.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/__pycache__/bias_op_base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72557ec12f1dee3214b132bbecf276b8689f33fe Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/__pycache__/bias_op_base.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/__pycache__/cudnn_deterministic_base.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/__pycache__/cudnn_deterministic_base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ac15650c8628052133ba91446f7be8811a12486 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/__pycache__/cudnn_deterministic_base.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/__pycache__/depthwise_conv_op_base.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/__pycache__/depthwise_conv_op_base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89c226ab0f084c8827c0c8a7d8c63e5f789bd2d3 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/__pycache__/depthwise_conv_op_base.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/__pycache__/xent_op_test_base.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/__pycache__/xent_op_test_base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d67aabb5a4f37270704483b089fb7d5cff502633 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/__pycache__/xent_op_test_base.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/bias_op_base.py b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/bias_op_base.py new file mode 100644 index 0000000000000000000000000000000000000000..b70cc349140f45cf28d0c7f7c07763be39e26097 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/bias_op_base.py @@ -0,0 +1,322 @@ +# 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. +# ============================================================================== +"""Functional tests for BiasAdd.""" + +import numpy as np + +from tensorflow.python.eager import backprop +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_impl +from tensorflow.python.framework import test_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gradient_checker +from tensorflow.python.ops import gradient_checker_v2 +from tensorflow.python.ops import gradients_impl +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn_ops +import tensorflow.python.ops.nn_grad # pylint: disable=unused-import +from tensorflow.python.platform import test + + +@test_util.run_all_in_graph_and_eager_modes +class BiasAddTestBase(test.TestCase): + + def _npBias(self, inputs, bias): + assert len(bias.shape) == 1 + assert inputs.shape[-1] == bias.shape[0] + return inputs + bias.reshape(([1] * + (len(inputs.shape) - 1)) + [bias.shape[0]]) + + def testNpBias(self): + self.assertAllClose( + np.array([[11, 22, 33], [41, 52, 63]]), + self._npBias( + np.array([[10, 20, 30], [40, 50, 60]]), np.array([1, 2, 3]))) + + def _testBias(self, np_inputs, np_bias, use_gpu=False): + np_val = self._npBias(np_inputs, np_bias) + with self.cached_session(use_gpu=use_gpu): + tf_val = self.evaluate(nn_ops.bias_add(np_inputs, np_bias)) + self.assertAllCloseAccordingToType(np_val, tf_val) + + def _AtLeast3d(self, np_value): + # fill the input value to at least 3-dimension + if np_value.ndim < 3: + return np.reshape(np_value, (1,) * (3 - np_value.ndim) + np_value.shape) + return np_value + + def _NHWCToNCHW(self, np_value): + # fill the input value to at least 3-dimension + np_value = self._AtLeast3d(np_value) + # move the last dimension to second + np_dim = list(range(np_value.ndim)) + np_dim_new = list(np_dim[0:1]) + list(np_dim[-1:]) + list(np_dim[1:-1]) + return np.transpose(np_value, np_dim_new) + + def _NCHWToNHWC(self, np_value): + assert len(np_value.shape) >= 3 + np_dim = list(range(np_value.ndim)) + # move the second dimension to the last + np_dim_new = list(np_dim[0:1]) + list(np_dim[2:]) + list(np_dim[1:2]) + return np.transpose(np_value, np_dim_new) + + def _testBiasNCHW(self, np_inputs, np_bias, use_gpu): + np_val = self._npBias(np_inputs, np_bias) + np_inputs = self._NHWCToNCHW(np_inputs) + with self.cached_session(use_gpu=use_gpu): + tf_val = self.evaluate( + nn_ops.bias_add(np_inputs, np_bias, data_format="NCHW")) + tf_val = self._NCHWToNHWC(tf_val) + self.assertAllCloseAccordingToType(self._AtLeast3d(np_val), tf_val) + + def _testAll(self, np_inputs, np_bias): + self._testBias(np_inputs, np_bias, use_gpu=False) + self._testBiasNCHW(np_inputs, np_bias, use_gpu=False) + if np_inputs.dtype in [np.float16, np.float32, np.float64, np.int32]: + self._testBias(np_inputs, np_bias, use_gpu=True) + self._testBiasNCHW(np_inputs, np_bias, use_gpu=True) + + def _expectedException(self): + if context.executing_eagerly(): + return errors_impl.InvalidArgumentError + else: + return ValueError + + def testInputDims(self): + with self.assertRaises(self._expectedException()): + nn_ops.bias_add([1, 2], [1]) + + def testBiasVec(self): + with self.assertRaises(self._expectedException()): + nn_ops.bias_add( + array_ops.reshape([1, 2], shape=[1, 2]), + array_ops.reshape([1, 2], shape=[1, 2])) + + def testBiasInputsMatch(self): + with self.assertRaises(self._expectedException()): + nn_ops.bias_add( + array_ops.reshape([1, 2], shape=[1, 2]), + array_ops.reshape([1], shape=[1])) + + def testIntTypes(self): + for t in [np.int8, np.int16, np.int32, np.int64]: + self._testAll( + np.array([[10, 20, 30], [40, 50, 60]]).astype(t), + np.array([1, 2, 3]).astype(t)) + + def testFloatTypes(self): + for t in [ + np.float16, np.float32, np.float64, dtypes.bfloat16.as_numpy_dtype + ]: + self._testAll( + np.random.rand(4, 3, 3).astype(t), + np.random.rand(3).astype(t)) + + def test4DFloatTypes(self): + for t in [ + np.float16, np.float32, np.float64, dtypes.bfloat16.as_numpy_dtype + ]: + self._testAll( + np.random.rand(4, 3, 2, 3).astype(t), + np.random.rand(3).astype(t)) + self._testAll( + np.random.rand(2048, 4, 4, 4).astype(t), + np.random.rand(4).astype(t)) + self._testAll( + np.random.rand(4, 4, 4, 2048).astype(t), + np.random.rand(2048).astype(t)) + + def test5DFloatTypes(self): + for t in [ + np.float16, np.float32, np.float64, dtypes.bfloat16.as_numpy_dtype + ]: + self._testAll( + np.random.rand(4, 3, 2, 3, 4).astype(t), + np.random.rand(4).astype(t)) + + def _random_tensor(self, shape, dtype): + return constant_op.constant(2 * np.random.rand(*shape) - 1, dtype=dtype) + + def _computeGradient(self, np_input, bias, dtype, data_format): + input_shape = output_shape = np_input.shape + bias_shape = bias.shape + input_tensor = constant_op.constant( + np_input, shape=input_shape, dtype=dtype) + bias_tensor = constant_op.constant(bias, shape=bias_shape, dtype=dtype) + + if context.executing_eagerly(): + + def bias_add(input_tensor, bias_tensor): + return nn_ops.bias_add( + input_tensor, bias_tensor, data_format=data_format) + + # The following is a work-around for TF issue 33660. Instead of + # calculating the analytical and numerical gradients for both + # inputs in a single call to compute_gradient, compute_gradient + # is called for each input separately. + def bias_add_1(input_tensor): + return bias_add(input_tensor, bias_tensor) + + def bias_add_2(bias_tensor): + return bias_add(input_tensor, bias_tensor) + + input_jacob_a, input_jacob_n = gradient_checker_v2.compute_gradient( + bias_add_1, [input_tensor]) + bias_jacob_a, bias_jacob_n = gradient_checker_v2.compute_gradient( + bias_add_2, [bias_tensor]) + + # Test gradient of BiasAddGrad + def bias_add_grad_function(upstream_gradients): + with backprop.GradientTape() as tape: + tape.watch(bias_tensor) + bias_add_output = bias_add(input_tensor, bias_tensor) + gradient_injector_output = bias_add_output * upstream_gradients + return tape.gradient(gradient_injector_output, bias_tensor) + + upstream_tensor = self._random_tensor(output_shape, dtype) + grad_jacob_a, grad_jacob_n = gradient_checker_v2.compute_gradient( + bias_add_grad_function, [upstream_tensor]) + else: + output_tensor = nn_ops.bias_add( + input_tensor, bias_tensor, data_format=data_format) + jacobians = gradient_checker.compute_gradient([input_tensor, bias_tensor], + [input_shape, bias_shape], + output_tensor, output_shape) + (input_jacob_a, input_jacob_n), (bias_jacob_a, bias_jacob_n) = jacobians + # Test gradient of BiasAddGrad + if dtype == dtypes.bfloat16: + # L2Loss is not supported for bfloat16 on CPU. + output_tensor = math_ops.cast(output_tensor, dtype=dtypes.float32) + bias_add_grad = gradients_impl.gradients( + nn_ops.l2_loss(output_tensor), bias_tensor)[0] + grad_jacob_a, grad_jacob_n = gradient_checker.compute_gradient( + output_tensor, output_shape, bias_add_grad, bias_shape) + + return ((input_jacob_a, bias_jacob_a, grad_jacob_a), + (input_jacob_n, bias_jacob_n, grad_jacob_n)) + + def _testGradient(self, np_input, bias, dtype, data_format, use_gpu): + with self.cached_session(use_gpu=use_gpu): + if data_format == "NCHW": + np_input = self._NHWCToNCHW(np_input) + jacob_a, jacob_n = self._computeGradient(np_input, bias, dtype, + data_format) + input_jacob_a, bias_jacob_a, grad_jacob_a = jacob_a + input_jacob_n, bias_jacob_n, grad_jacob_n = jacob_n + + if dtype in [np.float16, dtypes.bfloat16.as_numpy_dtype]: + # Compare fp16/bf16 analytical gradients to fp32 numerical gradients, + # since fp16/bf16 numerical gradients are too imprecise unless great + # care is taken with choosing the inputs and the delta. This is + # a weaker, but pragmatic, check (in particular, it does not test + # the op itself, only its gradient). + _, jacob_n = self._computeGradient(np_input, bias, np.float32, + data_format) + input_jacob_n, bias_jacob_n, grad_jacob_n = jacob_n + + if dtype == dtypes.float64: + threshold = 1e-10 + elif np_input.size >= 512: + # The 5e-3 threshold seems to have been marginal in these cases, and + # small changes in the test were pushing it over the limit. + threshold = 5e-2 + else: + threshold = 5e-3 + self.assertAllClose(input_jacob_a, input_jacob_n, threshold, threshold) + self.assertAllClose(bias_jacob_a, bias_jacob_n, threshold, threshold) + self.assertAllClose(grad_jacob_a, grad_jacob_n, threshold, threshold) + + def testGradientTensor2D(self): + for (data_format, use_gpu) in ("NHWC", False), ("NHWC", True): + for dtype in (dtypes.float16, dtypes.float32, dtypes.float64, + dtypes.bfloat16): + np_input = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], + dtype=dtype.as_numpy_dtype).reshape(3, 2) + bias = np.array([1.3, 2.4], dtype=dtype.as_numpy_dtype) + self._testGradient(np_input, bias, dtype, data_format, use_gpu) + + def testGradientTensor3D(self): + for (data_format, use_gpu) in [("NHWC", False), ("NHWC", True), + ("NCHW", False), ("NCHW", True)]: + for dtype in (dtypes.float16, dtypes.float32, dtypes.float64, + dtypes.bfloat16): + # pylint: disable=too-many-function-args + np_input = np.array( + [1.0, 2.0, 3.0, 4.0, 5.0, 6.0], + dtype=dtype.as_numpy_dtype).reshape(1, 3, 2) + bias = np.array([1.3, 2.4], dtype=dtype.as_numpy_dtype) + self._testGradient(np_input, bias, dtype, data_format, use_gpu) + + def testGradientTensor4D(self): + for (data_format, use_gpu) in [("NHWC", False)]: + for dtype in (dtypes.float16, dtypes.float32, dtypes.float64, + dtypes.bfloat16): + np_input = np.arange( + 1.0, 49.0, + dtype=dtype.as_numpy_dtype).reshape([2, 3, 4, 2]).astype(np.float32) + bias = np.array([1.3, 2.4], dtype=dtype.as_numpy_dtype) + self._testGradient(np_input, bias, dtype, data_format, use_gpu) + np_input = np.arange( + 1.0, 513.0, + dtype=dtype.as_numpy_dtype).reshape([64, 2, 2, + 2]).astype(np.float32) + self._testGradient(np_input, bias, dtype, data_format, use_gpu) + np_input = np.arange( + 1.0, 513.0, + dtype=dtype.as_numpy_dtype).reshape([2, 2, 2, + 64]).astype(np.float32) + self._testGradient(np_input, + np.random.rand(64).astype(dtype.as_numpy_dtype), + dtype, data_format, use_gpu) + + def testGradientTensor5D(self): + for (data_format, use_gpu) in [("NHWC", False), ("NHWC", True), + ("NCHW", False), ("NCHW", True)]: + for dtype in (dtypes.float16, dtypes.float32, dtypes.float64, + dtypes.bfloat16): + np_input = np.arange( + 1.0, 49.0, + dtype=dtype.as_numpy_dtype).reshape([1, 2, 3, 4, + 2]).astype(np.float32) + bias = np.array([1.3, 2.4], dtype=dtype.as_numpy_dtype) + self._testGradient(np_input, bias, dtype, data_format, use_gpu) + + def test1x1Image(self): + for (data_format, use_gpu) in [("NHWC", False), ("NCHW", False)]: + np_input = np.arange(1.0, 129.0).reshape([4, 1, 1, 32]).astype(np.float32) + self._testGradient(np_input, + np.random.rand(32).astype(np.float32), dtypes.float32, + data_format, use_gpu) + + def testEmpty(self): + np.random.seed(7) + for shape in (0, 0), (2, 0), (0, 2), (4, 3, 0), (4, 0, 3), (0, 4, 3): + self._testAll(np.random.randn(*shape), np.random.randn(shape[-1])) + + def testEmptyGradient(self): + for (data_format, use_gpu) in ("NHWC", False), ("NHWC", True): + for shape in (0, 0), (2, 0), (0, 2): + self._testGradient( + np.random.randn(*shape), np.random.randn(shape[-1]), dtypes.float64, + data_format, use_gpu) + + for (data_format, use_gpu) in [("NHWC", False), ("NHWC", True), + ("NCHW", False), ("NCHW", True)]: + for shape in (4, 3, 0), (4, 0, 3), (0, 4, 3): + self._testGradient( + np.random.randn(*shape), np.random.randn(shape[-1]), dtypes.float64, + data_format, use_gpu) diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/cudnn_deterministic_base.py b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/cudnn_deterministic_base.py new file mode 100644 index 0000000000000000000000000000000000000000..0535a1e6af136d9efc1f8be05b93f834572326ae --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/cudnn_deterministic_base.py @@ -0,0 +1,292 @@ +# 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. +# ============================================================================== +"""Tests for deterministic cuDNN functionality.""" + +import collections + +import numpy as np + +from tensorflow.python.eager import backprop +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import test_util +from tensorflow.python.ops import nn_ops +from tensorflow.python.platform import test + +# Notes: +# +# TensorFlow makes cuDNN run deterministically when op determinism is enabled +# via tf.config.experimental.enable_op_determinism(). Additionally, setting the +# environmental variable TF_CUDNN_DETERMINISTIC to 'true' or '1' makes cuDNN run +# deterministically, although this environemtnal variable is deprecated and will +# be removed in a future TensorFlow version. Unlike the enable_op_determinism() +# function, the environmental variable only makes ops using cuDNN deterministic, +# not all TensorFlow ops. +# +# Where both deterministic and non-deterministic cuDNN algorithms are available, +# selecting determinitic operation will lead to only the deterministic +# algorithms being chosen. Additionally, selecting deterministic operation will +# result in a deterministic, or reproducible, selection of algorithms (for any +# given layer configuration) for each of the forward and the two backward paths. +# +# These tests intend to confirm that deterministic algorithms are chosen (for +# the back-prop paths) when desterministic operation is selected. The tested +# configurations were first confirmed to produce non-deterministic results when +# the above-mentioned environment variables are not set. +# +# Even though selecting determinitic operation should ensure that the same +# algorithms, for a given layer configuration, are always used (i.e. that +# algorithm selection is deterministic / reproducible), this is not tested. + +# TODO(duncanriach): Add test for deterministic cuDNN max-pooling + +LayerShapeNHWC = collections.namedtuple('LayerShapeNHWC', + 'batch, height, width, channels') +FilterShape2D = collections.namedtuple( + 'FilterShape2D', 'height, width, in_channels, out_channels') +FilterShape2DTranspose = collections.namedtuple( + 'FilterShape2DTranspose', 'height, width, out_channels, in_channels') + +LayerShapeNCDHW = collections.namedtuple( + 'LayerShapeNCDHW', 'batch, channels, depth, height, width') +FilterShape3D = collections.namedtuple( + 'FilterShape3D', 'depth, height, width, in_channels, out_channels') + + +class ConvolutionTest(test.TestCase): + """Tests for deterministic cuDNN functionality.""" + + def _random_data_op(self, shape): + # np.random.random_sample can properly interpret either tf.TensorShape or + # namedtuple as a list. + return constant_op.constant( + 2 * np.random.random_sample(shape) - 1, dtype=dtypes.float32) + + def _random_out_op(self, in_shape, filter_shape, strides, padding, dilations): + # Choosing not to use array_op.zeros() to prevent possible removal by + # optimization + in_op = self._random_data_op(in_shape) + filter_op = self._random_data_op(filter_shape) + # Use the forward op's shape-inference + conv_op = nn_ops.conv2d( + in_op, filter_op, strides=strides, padding=padding, dilations=dilations) + out_shape = conv_op.get_shape() + out_op = self._random_data_op(out_shape) + return out_op + + def _assert_reproducible(self, operation): + with test_util.force_gpu(): + result_1 = operation() + result_2 = operation() + self.assertAllEqual(result_1, result_2) + + # The default forward algorithm choice, when using cuDNN 7, does not support + # the following layer configuration. This test case intends to confirm that + # an alternative algorithm is selected. Note that, in cuDNN 7, all forward + # algorithms are determnistic. + @test_util.run_cuda_only + def testConvForwardDefaultAlgorithmChoice(self): + in_shape = LayerShapeNCDHW(batch=2, channels=3, depth=5, height=7, width=6) + filter_shape = FilterShape3D( + depth=3, height=3, width=3, in_channels=3, out_channels=2) + in_op = self._random_data_op(in_shape) + filter_op = self._random_data_op(filter_shape) + self._assert_reproducible(lambda: nn_ops.conv3d( + in_op, + filter_op, + strides=[1, 1, 1, 1, 1], + padding='VALID', + data_format='NCDHW', + dilations=[1, 1, 2, 2, 2])) + + # This test is primarily testing XLA since cuDNN forward convolutions are + # always deterministic, even when determinism is not enabled. The convolution + # configuration tested is nondeterministic with XLA when determinism is not + # enabled. + @test_util.run_cuda_only + def testConvForwardXLA(self): + in_shape = LayerShapeNCDHW( + batch=2, channels=8, depth=5, height=12, width=15) + filter_shape = FilterShape3D( + depth=3, height=3, width=3, in_channels=8, out_channels=1) + in_op = self._random_data_op(in_shape) + filter_op = self._random_data_op(filter_shape) + self._assert_reproducible(lambda: nn_ops.conv3d( + in_op, + filter_op, + strides=[1, 1, 1, 1, 1], + padding='VALID', + data_format='NCDHW', + dilations=[1, 1, 2, 2, 2])) + + @test_util.run_cuda_only + def testConvBackwardFilterGradient(self, rate=1): + in_shape = LayerShapeNHWC(batch=8, height=64, width=64, channels=8) + filter_shape = FilterShape2D( + height=3, width=3, in_channels=8, out_channels=8) + in_op = self._random_data_op(in_shape) + strides = [1, 1, 1, 1] + padding = 'SAME' + dilations = [1, rate, rate, 1] + out_op = self._random_out_op(in_shape, filter_shape, strides, padding, + dilations) + self._assert_reproducible(lambda: nn_ops.conv2d_backprop_filter( + in_op, + filter_shape, + out_op, + strides=strides, + padding=padding, + dilations=dilations)) + + # A configuration for this test could not be found that exercises + # nondeterminism when using XLA with determinism not enabled. + @test_util.run_cuda_only + def testConvBackwardFilterGradientWithDilations(self): + self.testConvBackwardFilterGradient(rate=2) + + @test_util.run_cuda_only + def testConvBackwardInputGradient(self, rate=1): + in_shape = LayerShapeNHWC(batch=1, height=16, width=16, channels=1) + filter_shape = FilterShape2D( + height=7, width=7, in_channels=1, out_channels=3) + filter_op = self._random_data_op(filter_shape) + strides = [1, 1, 1, 1] + padding = 'SAME' + dilations = [1, rate, rate, 1] + out_op = self._random_out_op(in_shape, filter_shape, strides, padding, + dilations) + self._assert_reproducible(lambda: nn_ops.conv2d_backprop_input( + in_shape, + filter_op, + out_op, + strides=strides, + padding=padding, + dilations=dilations)) + + # A configuration for this test could not be found that exercises + # nondeterminism when using XLA with determinism not enabled. + @test_util.run_cuda_only + def testConvBackwardInputGradientWithDilations(self): + self.testConvBackwardInputGradient(rate=2) + + @test_util.run_cuda_only + def testConvTransposeForward(self, rate=1): + in_channels = 3 + out_channels = 1 + in_shape = LayerShapeNHWC( + batch=1, height=16, width=16, channels=in_channels) + filter_shape = FilterShape2DTranspose( + height=7, width=7, out_channels=out_channels, in_channels=in_channels) + in_op = self._random_data_op(in_shape) + filter_op = self._random_data_op(filter_shape) + out_shape = LayerShapeNHWC( + batch=in_shape.batch, + height=in_shape.height, + width=in_shape.width, + channels=out_channels) + self._assert_reproducible(lambda: nn_ops.conv2d_transpose_v2( + in_op, + filter_op, + out_shape, + strides=1, + padding='SAME', + data_format='NHWC', + dilations=[1, rate, rate, 1])) + + # A configuration for this test could not be found that exercises + # nondeterminism when using XLA with determinism not enabled. + @test_util.run_cuda_only + def testConvTransposeForwardWithDilations(self): + self.testConvTransposeForward(rate=2) + + @test_util.run_cuda_only + def testConvTransposeBackwardFilterGradient(self, rate=1): + in_channels = 8 + out_channels = 8 + in_shape = LayerShapeNHWC( + batch=8, height=64, width=64, channels=in_channels) + filter_shape = FilterShape2DTranspose( + height=3, width=3, out_channels=out_channels, in_channels=in_channels) + in_op = self._random_data_op(in_shape) + filter_op = self._random_data_op(filter_shape) + out_shape = LayerShapeNHWC( + batch=in_shape.batch, + height=in_shape.height, + width=in_shape.width, + channels=out_channels) + upstream_gradients = self._random_data_op(out_shape) + + def gradient(): + with backprop.GradientTape() as tape: + tape.watch(filter_op) + op_output = nn_ops.conv2d_transpose_v2( + in_op, + filter_op, + out_shape, + strides=1, + padding='SAME', + data_format='NHWC', + dilations=[1, rate, rate, 1]) + gradient_injector_output = op_output * upstream_gradients + return tape.gradient(gradient_injector_output, [filter_op])[0] + + self._assert_reproducible(gradient) + + # A configuration for this test could not be found that exercises + # nondeterminism when using XLA with determinism not enabled. + @test_util.run_cuda_only + def testConvTransposeBackwardFilterGradientWithDilations(self): + self.testConvTransposeBackwardFilterGradient(rate=2) + + # A configuration for this test could not be found that exercises + # nondeterminism when determinism is not enabled (for either XLA or non-XLA). + @test_util.run_cuda_only + def testConvTransposeBackwardInputGradient(self, rate=1): + in_channels = 1 + out_channels = 3 + in_shape = LayerShapeNHWC( + batch=1, height=16, width=16, channels=in_channels) + filter_shape = FilterShape2DTranspose( + height=7, width=7, out_channels=out_channels, in_channels=in_channels) + in_op = self._random_data_op(in_shape) + filter_op = self._random_data_op(filter_shape) + out_shape = LayerShapeNHWC( + batch=in_shape.batch, + height=in_shape.height, + width=in_shape.width, + channels=out_channels) + upstream_gradients = self._random_data_op(out_shape) + + def gradient(): + with backprop.GradientTape() as tape: + tape.watch(in_op) + op_output = nn_ops.conv2d_transpose_v2( + in_op, + filter_op, + out_shape, + strides=1, + padding='SAME', + data_format='NHWC', + dilations=[1, rate, rate, 1]) + gradient_injector_output = op_output * upstream_gradients + return tape.gradient(gradient_injector_output, [in_op])[0] + + self._assert_reproducible(gradient) + + # A configuration for this test could not be found that exercises + # nondeterminism when determinism is not enabled (for either XLA or non-XLA). + @test_util.run_cuda_only + def testConvTransposeBackwardInputGradientWithDilations(self): + self.testConvTransposeBackwardInputGradient(rate=2) diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/depthwise_conv_op_base.py b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/depthwise_conv_op_base.py new file mode 100644 index 0000000000000000000000000000000000000000..4e466a0a1c876a093b79dadd6017b8f59842f776 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/depthwise_conv_op_base.py @@ -0,0 +1,1172 @@ +# 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. +# ============================================================================== +"""Functional tests for depthwise convolutional operations.""" + +import numpy as np + +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.ops import array_ops +from tensorflow.python.ops import gradient_checker +from tensorflow.python.ops import nn_impl +from tensorflow.python.ops import nn_ops +import tensorflow.python.ops.nn_grad # pylint: disable=unused-import +from tensorflow.python.platform import test +from tensorflow.python.platform import tf_logging + + +def _DepthwiseConv2dNumpyBasic(x1, x2, strides): + """Compute depthwise_conv2d using Numpy. + + This allows use to test TensorFlow's depthwise_conv2d by comparing to the + Numpy version. + + Args: + x1: The input Numpy array, in NHWC format. + x2: The filter Numpy array. + strides: A Python list of 4 elements representing the strides. + + Returns: + The depthwise conv2d output as a Numpy array. + """ + n, h, w, c = x1.shape + fh, fw, c2, o = x2.shape + assert c == c2 + _, sh, sw, _ = strides + out_rows = (h - fh + sh) // sh + out_cols = (w - fw + sw) // sw + out = np.zeros([n, out_rows, out_cols, c * o]) + for i in range(out_rows): + for j in range(out_cols): + for k in range(c): + start_height = i * sh + end_height = start_height + fh + start_width = j * sw + end_width = start_width + fw + # multiplied_slice.shape: (b, fh, fw, o) + multiplied_slice = ( + x1[:, start_height:end_height, start_width:end_width, k, np.newaxis] + * x2[:, :, k, :]) + # Set a slice of b * o elements of 'out'. + out[:, i, j, k * o:(k + 1) * o] = np.sum(multiplied_slice, axis=(1, 2)) + return out + + +def _DepthwiseConv2dNumpy(x1, x2, strides, padding, data_format, dilations): + """Compute depthwise_conv2d using Numpy. + + This allows use to test TensorFlow's depthwise_conv2d by comparing to the + Numpy version. + + Unlike `_DepthwiseConv2dNumpyBasic`, this supports more advanced features + like padding. + + Args: + x1: The input Numpy array. + x2: The filter Numpy array. + strides: A Python list of 4 elements representing the strides. + padding: The padding. "SAME", "VALID", or a list of explicit paddings. + data_format: "NHWC" or "NCHW". + dilations: A list of 2 elements, representing the dilations. + + Returns: + The depthwise conv2d as a Numpy array. + """ + if data_format == "NCHW": + # Transpose arguments to NHWC format. + x1 = np.transpose(x1, (0, 3, 1, 2)) + strides = [strides[0], strides[3], strides[1], strides[2]] + if dilations: + dilations = [dilations[0], dilations[3], dilations[1], dilations[2]] + + if dilations: + # Dilate the filter so _DepthwiseConv2dNumpyBasic doesn't have to deal with + # dilations. + fh, fw, c, o = x2.shape + new_fh = (fh - 1) * dilations[0] + 1 + new_fw = (fw - 1) * dilations[1] + 1 + new_x2 = np.zeros((new_fh, new_fw, c, o)) + for i in range(fh): + for j in range(fw): + new_x2[i * dilations[0], j * dilations[1], ::] = x2[i, j, :, :] + x2 = new_x2 + + # Pad input so _DepthwiseConv2dNumpyBasic doesn't have to deal with padding. + if padding == "SAME": + + def PaddingsForDim(input_dim, filter_dim, stride): + """Computes paddings for a single dimension.""" + if input_dim % stride == 0: + total_padding = max(filter_dim - stride, 0) + else: + total_padding = max(filter_dim - (input_dim % stride), 0) + pad_before = total_padding // 2 + pad_after = total_padding - pad_before + return pad_before, pad_after + + padding = [(0, 0), + PaddingsForDim(x1.shape[1], x2.shape[0], strides[1]), + PaddingsForDim(x1.shape[2], x2.shape[1], strides[2]), (0, 0)] + elif padding == "VALID": + padding = [(0, 0)] * 4 + x1 = np.pad(x1, padding, "constant") + + y = _DepthwiseConv2dNumpyBasic(x1, x2, strides) + + if data_format == "NCHW": + # Transpose back to NCHW format. + y = np.transpose(y, (0, 2, 3, 1)) + + return y + + +def ConfigsToTest(): + """Iterator for different convolution shapes, strides and paddings. + + Returns: + List of tuples (input_size, filter_size, out_size, stride, padding, + dilations), the depthwise convolution parameters. + """ + + def Config(input_size, + filter_size, + out_size, + stride=1, + padding="SAME", + dilations=None): + return input_size, filter_size, out_size, stride, padding, dilations + + return [ + Config([4, 5, 5, 48], [1, 1, 48, 2], [4, 5, 5, 96]), + Config([4, 8, 8, 84], [1, 3, 84, 1], [4, 8, 8, 84]), + Config([4, 17, 17, 48], [3, 1, 48, 4], [4, 17, 17, 192]), + Config([4, 9, 27, 8], [3, 3, 8, 1], [4, 9, 27, 8]), + Config([4, 31, 31, 7], [3, 3, 7, 1], [4, 31, 31, 7]), + Config([4, 35, 35, 2], [5, 5, 2, 1], [4, 35, 35, 2]), + Config([4, 147, 147, 2], [3, 3, 2, 8], [4, 49, 49, 16], + 3, + padding="VALID"), + Config([3, 299, 299, 3], [3, 2, 3, 8], [3, 150, 150, 24], 2), + Config([5, 183, 183, 1], [5, 5, 1, 2], [5, 92, 92, 2], 2), + Config([5, 183, 183, 1], [5, 5, 1, 2], [5, 183, 183, 2], dilations=[2, + 2]), + Config([5, 41, 35, 2], [4, 7, 2, 2], [5, 32, 23, 4], + padding="VALID", + dilations=[3, 2]), + ] + + +def ConfigsToTestExplicit(): + """Iterator for different convolution shapes, strides and explicit paddings. + + Returns: + List of tuples (input_size, filter_size, out_size, stride, padding, + dilations), the depthwise convolution parameters. + """ + + def Config(input_size, + filter_size, + out_size, + stride=1, + padding=None, + dilations=None): + return input_size, filter_size, out_size, stride, padding, dilations + + return [ + Config([4, 5, 5, 48], [1, 1, 48, 2], [4, 8, 12, 96], + padding=[[1, 2], [3, 4]]), + Config([4, 1, 1, 3], [3, 3, 3, 2], [4, 29, 39, 6], + padding=[[10, 20], [15, 25]]), + Config([4, 9, 27, 8], [3, 3, 8, 1], [4, 14, 31, 8], + padding=[[3, 4], [4, 2]]), + Config([4, 31, 31, 7], [3, 3, 7, 1], [4, 29, 29, 7], + padding=[[0, 0], [0, 0]]), + Config([3, 299, 299, 3], [3, 2, 3, 8], [3, 150, 153, 24], + 2, + padding=[[1, 2], [3, 5]]), + Config([5, 183, 183, 1], [5, 5, 1, 2], [5, 62, 60, 2], + 3, + padding=[[3, 2], [1, 0]]), + Config([5, 29, 31, 1], [5, 4, 1, 2], [5, 26, 23, 2], + padding=[[3, 2], [1, 0]], + dilations=[2, 3]), + # These cases test the kernels in depthwise_conv_op_gpu.h which are used + # if the input size is small. + Config([4, 5, 5, 48], [3, 3, 48, 1], [4, 5, 5, 48], + padding=[[0, 2], [0, 2]]), + Config([1, 8, 7, 2], [8, 7, 2, 1], [1, 8, 7, 2], padding=[[0, 7], [3, + 3]]), + Config([2, 4, 3, 2], [3, 2, 2, 1], [2, 4, 3, 2], padding=[[2, 0], [1, + 0]]), + ] + + +def CheckGradConfigsToTest(): + """Iterator for different convolution shapes, strides and paddings. + + compute_gradient_error() is very expensive. So the configs should be + relatively small. + + Returns: + List of tuples (input_size, filter_size, out_size, stride, padding, + dilations), the depthwise convolution parameters. + """ + + def Config(input_size, + filter_size, + out_size, + stride=1, + padding="SAME", + dilations=None): + return input_size, filter_size, out_size, stride, padding, dilations + + return [ + Config([2, 5, 8, 1], [4, 4, 1, 2], [2, 5, 8, 2]), + Config([4, 5, 5, 1], [2, 2, 1, 2], [4, 2, 2, 2], 2, padding="VALID"), + Config([2, 4, 4, 2], [3, 1, 2, 2], [2, 4, 4, 4]), + Config([1, 15, 15, 2], [1, 3, 2, 1], [1, 15, 15, 2]), + Config([2, 15, 16, 1], [3, 3, 1, 2], [2, 5, 5, 2], 3, padding="VALID"), + Config([2, 5, 8, 1], [4, 3, 1, 2], [2, 5, 8, 2], dilations=[1, 2]), + # These cases test the kernels in depthwise_conv_op_gpu.h which are used + # if the input size is small. + Config([1, 3, 1, 2], [2, 1, 2, 1], [1, 3, 1, 2]), + Config([2, 2, 3, 2], [2, 1, 2, 1], [2, 2, 3, 2]), + Config([2, 2, 3, 1], [2, 2, 1, 1], [2, 2, 3, 1]), + ] + + +def CheckGradConfigsToTestExplicit(): + """Iterator for different convolution shapes, strides and explicit paddings. + + compute_gradient_error() is very expensive. So the configs should be + relatively small. + + Returns: + List of tuples (input_size, filter_size, out_size, stride, padding, + dilations), the depthwise convolution parameters. + """ + + def Config(input_size, + filter_size, + out_size, + stride=1, + padding=None, + dilations=None): + return input_size, filter_size, out_size, stride, padding, dilations + + return [ + Config([2, 5, 8, 1], [4, 4, 1, 2], [2, 3, 10, 2], + padding=[[0, 1], [2, 3]]), + Config([4, 5, 5, 1], [2, 2, 1, 2], [4, 4, 5, 2], + 2, + padding=[[3, 1], [5, 0]]), + Config([2, 4, 4, 2], [3, 1, 2, 2], [2, 7, 11, 4], + padding=[[4, 1], [3, 4]]), + Config([1, 15, 15, 2], [1, 3, 2, 1], [1, 18, 23, 2], + padding=[[3, 0], [2, 8]]), + Config([2, 15, 16, 1], [3, 3, 1, 2], [2, 5, 8, 2], + 3, + padding=[[0, 0], [10, 0]]), + Config([2, 5, 8, 1], [3, 4, 1, 2], [2, 5, 10, 2], + padding=[[3, 1], [2, 3]], + dilations=[2, 1]), + # These cases test the kernels in depthwise_conv_op_gpu.h which are used + # if the input size is small. + Config([2, 4, 3, 2], [3, 2, 2, 1], [2, 4, 3, 2], padding=[[2, 0], [1, + 0]]), + ] + + +class DepthwiseConv2DBase(test.TestCase): + """Base test class for depthwise Conv2D tests.""" + + # This tests depthwise_conv2d and depthwise_conv2d_native + def _VerifyValues(self, + tensor_in_sizes, + filter_in_sizes, + stride, + padding, + data_type, + use_gpu, + grouped_conv=False, + data_format="NHWC", + dilations=None, + tolerance=None): + """Verifies the output values of the convolution function. + + Args: + tensor_in_sizes: Input tensor dimensions in [batch, input_rows, + input_cols, input_depth]. + filter_in_sizes: Filter tensor dimensions in [filter_rows, filter_cols, + input_depth, depth_multiplier]. + stride: Stride. + padding: Padding type. + data_type: The data type to use. + use_gpu: Whether to use GPU. + grouped_conv: Whether to use cuDNN 7's grouped convolution. + data_format: The data_format of the input. "NHWC" or "NCHW". + dilations: A list of 2 elements, representing the dilations. + tolerance: The absolute and relative tolarance when verifying the output. + """ + input_size = 1 + filter_size = 1 + for s in tensor_in_sizes: + input_size *= s + for s in filter_in_sizes: + filter_size *= s + # Initializes the input and filter tensor with numbers incrementing to 1.0. + x1 = [f * 1.0 / input_size for f in range(1, input_size + 1)] + x1 = np.array(x1).reshape(tensor_in_sizes) + x2 = [f * 1.0 / filter_size for f in range(1, filter_size + 1)] + x2 = np.array(x2).reshape(filter_in_sizes) + # Compute reference result + strides = [1, stride, stride, 1] + if isinstance(padding, list): + padding = [(0, 0)] + padding + [(0, 0)] + np_result = _DepthwiseConv2dNumpy(x1, x2, strides, padding, "NHWC", + dilations) + + ops.reset_default_graph() + graph = ops.get_default_graph() + with self.session(graph=graph, use_gpu=use_gpu) as sess: + tolerance = tolerance or { + dtypes.float16: 4e-2, + dtypes.float32: 1e-5, + dtypes.float64: 1e-12, + dtypes.bfloat16: 1e-2, + }[data_type] + + t1 = constant_op.constant(x1, shape=tensor_in_sizes, dtype=data_type) + t2 = constant_op.constant(x2, shape=filter_in_sizes, dtype=data_type) + + if data_format == "NCHW": + # Transpose from NHWC input to NCHW + # Ex. [4, 5, 5, 48] to [4, 48, 5, 5] + t1 = array_ops.transpose(t1, [0, 3, 1, 2]) + strides = [1, 1, stride, stride] + if isinstance(padding, list): + padding = [padding[0], padding[3], padding[1], padding[2]] + + # depthwise_conv2d_native does not support dilations except on TPUs. + if dilations is None: + with sess.graph._kernel_label_map( # pylint: disable=protected-access + {"DepthwiseConv2dNative": "cudnn_grouped_convolution"} + if grouped_conv else {}): + conv_native = nn_ops.depthwise_conv2d_native( + t1, t2, strides=strides, data_format=data_format, padding=padding) + + if data_format == "NCHW": + # Transpose back from NCHW to NHWC + conv_native = array_ops.transpose(conv_native, [0, 2, 3, 1]) + + try: + # The Numpy array from calling depthwise_conv2d_native + native_result = self.evaluate(conv_native) + except errors.InvalidArgumentError as e: + # Grouped convolution kernel is only registered for cuDNN 7. Silently + # return when we are running on an earlier version or without GPU. + if ("No OpKernel was registered to support Op " + "'DepthwiseConv2dNative'") in e.message: + tf_logging.warn("Skipping grouped convolution test") + return + raise e + + conv_interface = nn_impl.depthwise_conv2d( + t1, + t2, + strides=strides, + padding=padding, + data_format=data_format, + dilations=dilations) + if data_format == "NCHW": + # Transpose back from NCHW to NHWC + conv_interface = array_ops.transpose(conv_interface, [0, 2, 3, 1]) + + # The Numpy array from calling depthwise_conv2d + interface_result = self.evaluate(conv_interface) + + if dilations is None: + self.assertAllClose( + native_result, np_result, atol=tolerance, rtol=tolerance) + self.assertAllClose( + interface_result, np_result, atol=tolerance, rtol=tolerance) + + @test_util.run_v1_only("b/120545219") + @test_util.run_gpu_only + def testDepthwiseConv2DCudnn(self): + for index, (input_size, filter_size, _, stride, padding, + dilations) in enumerate(ConfigsToTest()): + # The CuDNN depthwise conv is turned on only when input/output is NCHW and + # float16(half). See cudnn release note 7.6.3. + tf_logging.info( + "Testing DepthwiseConv2DCudnn, %dth config: %r * %r, stride: %d, " + "padding: %s", index, input_size, filter_size, stride, padding) + data_types = [dtypes.float16, dtypes.bfloat16] + for data_type in data_types: + self._VerifyValues( + input_size, + filter_size, + stride, + padding, + data_type, + use_gpu=True, + data_format="NCHW", + dilations=dilations) + + @test_util.run_v1_only("b/120545219") + def testDepthwiseConv2D(self): + for index, (input_size, filter_size, _, stride, padding, + dilations) in enumerate(ConfigsToTest()): + tf_logging.info( + "Testing DepthwiseConv2D, %dth config: %r * %r, stride: %d, padding: " + "%s", index, input_size, filter_size, stride, padding) + # double datatype is currently not supported for convolution ops + # on the ROCm platform + optional_float64 = [] if test.is_built_with_rocm() else [dtypes.float64] + for data_type in ([dtypes.float32] + optional_float64): + tf_logging.info("Testing without grouped_conv") + tolerance = 1e-4 if data_type == dtypes.float32 else 1e-12 + self._VerifyValues( + input_size, + filter_size, + stride, + padding, + data_type, + use_gpu=True, + dilations=dilations, + tolerance=tolerance) + tf_logging.info("Testing with grouped_conv") + self._VerifyValues( + input_size, + filter_size, + stride, + padding, + data_type, + use_gpu=True, + grouped_conv=True, + dilations=dilations, + tolerance=tolerance) + + @test_util.run_v1_only("b/120545219") + def testDepthwiseConv2DWithUnknownShape(self): + # GitHub issue 22110. + if not test.is_gpu_available(): + return + with self.session(): + x = array_ops.placeholder(dtypes.float32) + f = np.ones([1, 1, 1, 1], np.float32) + v = nn_impl.depthwise_conv2d( + x, f, [1, 1, 1, 1], "VALID", rate=[2, 1], data_format="NCHW") + self.assertAllEqual( + np.ones([1, 1, 1, 1], np.float32), + v.eval(feed_dict={x: np.ones([1, 1, 1, 1], np.float32)})) + + @test_util.run_v1_only("b/120545219") + def testDepthwiseConv2DFormat(self): + if not test.is_gpu_available(): + return + + for index, (input_size, filter_size, _, stride, padding, + dilations) in enumerate(ConfigsToTest()): + tf_logging.info( + "Testing DepthwiseConv2DFormat, %dth config: %r * %r, stride: %d, " + "padding: %s", index, input_size, filter_size, stride, padding) + # double datatype is currently not supported for convolution ops + # on the ROCm platform + optional_float64 = [] if test.is_built_with_rocm() else [dtypes.float64] + for data_type in ([dtypes.float32] + optional_float64): + tolerance = 1e-4 if data_type == dtypes.float32 else 1e-12 + self._VerifyValues( + input_size, + filter_size, + stride, + padding, + data_type, + use_gpu=True, + data_format="NCHW", + dilations=dilations, + tolerance=tolerance) + + @test_util.run_v1_only("b/120545219") + def testDepthwiseConv2DExplicit(self): + for index, (input_size, filter_size, _, stride, padding, + dilations) in enumerate(ConfigsToTestExplicit()): + tf_logging.info( + "Testing DepthwiseConv2D, %dth config: %r * %r, stride: %d, padding: " + "%s", index, input_size, filter_size, stride, padding) + # double datatype is currently not supported for convolution ops + # on the ROCm platform + data_types = [dtypes.float16, dtypes.float32, dtypes.bfloat16] + if not test.is_built_with_rocm(): + data_types.extend([dtypes.float64]) + data_formats = ["NHWC", "NCHW"] if test.is_gpu_available() else ["NHWC"] + for data_type in data_types: + for data_format in data_formats: + tolerance = 2e-2 if data_type == dtypes.bfloat16 else None + self._VerifyValues( + input_size, + filter_size, + stride, + padding, + data_type, + use_gpu=True, + data_format=data_format, + dilations=dilations, + tolerance=tolerance) + + # This is testing against hand calculated results. + + def _VerifyHandValues(self, tensor_in_sizes, filter_in_sizes, stride, padding, + expected, use_gpu): + """Verifies the output values of the depthwise convolution function. + + Args: + tensor_in_sizes: Input tensor dimensions in [batch, input_rows, + input_cols, input_depth]. + filter_in_sizes: Filter tensor dimensions in [filter_rows, filter_cols, + input_depth, depth_multiplier]. + stride: Stride. + padding: Padding type. + expected: An array containing the expected operation outputs. + use_gpu: Whether to use GPU. + """ + total_size_1 = 1 + total_size_2 = 1 + for s in tensor_in_sizes: + total_size_1 *= s + for s in filter_in_sizes: + total_size_2 *= s + # Initializes the input tensor with array containing incrementing + # numbers from 1. + x1 = [f * 1.0 for f in range(1, total_size_1 + 1)] + x2 = [f * 1.0 for f in range(1, total_size_2 + 1)] + with self.cached_session(use_gpu=use_gpu) as sess: + t1 = constant_op.constant(x1, shape=tensor_in_sizes) + t1.set_shape(tensor_in_sizes) + t2 = constant_op.constant(x2, shape=filter_in_sizes) + conv = nn_ops.depthwise_conv2d_native( + t1, t2, strides=[1, stride, stride, 1], padding=padding) + value = self.evaluate(conv) + tf_logging.info("value = %r", value) + self.assertArrayNear(expected, np.ravel(value), 1e-5) + self.assertShapeEqual(value, conv) + + def testConv2D2x2Filter(self): + # The inputs look like this (it's a 3 x 2 matrix, each of depth 2): + # + # [ (1.0, 2.0), (3.0, 4.0), ( 5.0, 6.0) ] + # [ (7.0, 8.0), (9.0, 10.0), (11.0, 12.0) ] + # We can view this as two inputs + # + # input depth 0: + # + # [ 1.0, 3.0, 5.0 ] + # [ 7.0, 9.0, 11.0 ] + # + # input depth 1: + # + # [ 2.0, 4.0, 6.0 ] + # [ 8.0, 10.0, 12.0 ] + # + # The filter looks like this (it has two 2 x 2 patches, each generating 2 + # depths): + # + # filter #0: + # + # [ (1.0, 3.0), ( 5.0, 7.0)] + # [ (9.0, 11.0), (13.0, 15.0)] + # + # filter #1: + # + # [ ( 2.0, 4.0), ( 6.0, 8.0)] + # [ (10.0, 12.0), (14.0, 16.0)] + # + # So the outputs are: + # + # (position 0, 0: in_depth 0, output_depth 0 -- using filter #0) + # 1.0 * 1.0 + 7.0 * 9.0 + 3.0 * 5.0 + 9.0 * 13.0 = 196 + # (position 0, 0: in_depth 0, output_depth 1 -- using filter #1) + # 1.0 * 2.0 + 7.0 * 10.0 + 3.0 * 6.0 + 9.0 * 14.0 = 216 + # (position 0, 0: in_depth 1, output_depth 2 -- using filter #0) + # 2.0 * 3.0 + 8.0 * 11.0 + 4.0 * 7.0 + 10.0 * 15.0 = 272 + # (position 0, 0: in_depth 1, output_depth 3 -- using filter #1) + # 2.0 * 4.0 + 8.0 * 12.0 + 4.0 * 8.0 + 10.0 * 16.0 = 296 + # + # (position 1, 0: in_depth 0, output_depth 0 -- using filter #0) + # 3.0 * 1.0 + 9.0 * 9.0 + 5.0 * 5.0 + 11.0 * 13.0 = 252 + # (position 1, 0: in_depth 0, output_depth 1 -- using filter #1) + # 3.0 * 2.0 + 9.0 * 10.0 + 5.0 * 6.0 + 11.0 * 14.0 = 280 + # (position 1, 0: in_depth 1, output_depth 2 -- using filter #0) + # 4.0 * 3.0 + 10.0 * 11.0 + 6.0 * 7.0 + 12.0 * 15.0 = 344 + # (position 1, 0: in_depth 1, output_depth 3 -- using filter #1) + # 4.0 * 4.0 + 10.0 * 12.0 + 6.0 * 8.0 + 12.0 * 16.0 = 376 + expected_output = [196, 216, 272, 296, 252, 280, 344, 376] + self._VerifyHandValues( + tensor_in_sizes=[1, 2, 3, 2], + filter_in_sizes=[2, 2, 2, 2], + stride=1, + padding="VALID", + expected=expected_output, + use_gpu=False) + + self._VerifyHandValues( + tensor_in_sizes=[1, 2, 3, 2], + filter_in_sizes=[2, 2, 2, 2], + stride=1, + padding="VALID", + expected=expected_output, + use_gpu=True) + + # Gradient checkers. This tests depthwise gradient computations for both + # BackpropFilter and BackpropInput by comparing gradients computed by the + # depthwise gradient ops with the gradients computed numerically (details can + # be found in the compute_gradient_error(). + # Note this check is very expensive so the input should not be too big. + def _ConstructAndTestGradient(self, + input_shape, + filter_shape, + output_shape, + stride, + padding, + data_type, + test_input, + use_gpu, + grouped_conv=False, + data_format="NHWC", + dilations=None): + input_size = 1 + for x in input_shape: + input_size *= x + filter_size = 1 + for x in filter_shape: + filter_size *= x + input_data = [x * 1.0 / input_size for x in range(0, input_size)] + input_np = np.array(input_data).reshape(input_shape) + filter_data = [x * 1.0 / filter_size for x in range(0, filter_size)] + filter_np = np.array(filter_data).reshape(filter_shape) + ops.reset_default_graph() + graph = ops.get_default_graph() + with self.session(graph=graph, use_gpu=use_gpu) as sess: + tolerance = { + dtypes.float16: 4e-0, + dtypes.float32: 8e-4, + dtypes.float64: 1e-12, + dtypes.bfloat16: 1e-0, + }[data_type] + + input_tensor = constant_op.constant( + input_np, shape=input_shape, dtype=data_type, name="input") + filter_tensor = constant_op.constant( + filter_np, shape=filter_shape, dtype=data_type, name="filter") + + native_input = input_tensor + strides = [1, stride, stride, 1] + if isinstance(padding, list): + padding = [(0, 0)] + padding + [(0, 0)] + if data_format == "NCHW": + # Transpose from NHWC input to NCHW + # Ex. [4, 5, 5, 48] to [4, 48, 5, 5] + native_input = array_ops.transpose(input_tensor, [0, 3, 1, 2]) + input_shape = [ + input_shape[0], input_shape[3], input_shape[1], input_shape[2] + ] + output_shape = [ + output_shape[0], output_shape[3], output_shape[1], output_shape[2] + ] + strides = [1, 1, stride, stride] + if isinstance(padding, list): + padding = [padding[0], padding[3], padding[1], padding[2]] + + with sess.graph._kernel_label_map({ # pylint: disable=protected-access,g-long-ternary + "DepthwiseConv2dNative": "cudnn_grouped_convolution", + "DepthwiseConv2dNativeBackpropInput": "cudnn_grouped_convolution", + "DepthwiseConv2dNativeBackpropFilter": "cudnn_grouped_convolution", + } if grouped_conv else {}): + depthwise_conv2d = nn_impl.depthwise_conv2d( + native_input, + filter_tensor, + strides, + padding, + data_format=data_format, + dilations=dilations, + name="depthwise_conv2d") + + self.assertEqual(output_shape, depthwise_conv2d.get_shape()) + + try: + if test_input: + err = gradient_checker.compute_gradient_error(native_input, + input_shape, + depthwise_conv2d, + output_shape) + else: + err = gradient_checker.compute_gradient_error(filter_tensor, + filter_shape, + depthwise_conv2d, + output_shape) + except errors.InvalidArgumentError as e: + # TODO(xjun): Tests depend on error messages could be brittle. + # Grouped convolution kernel is only registered for cuDNN 7. Silently + # return when we are running on an earlier version or without GPU. + if grouped_conv and ("No OpKernel was registered to support Op " + "'DepthwiseConv2dNative'") in e.message: + tf_logging.warn("Skipping grouped convolution test") + return + raise e + + tf_logging.info( + "data_type: %r, use_gpu: %r, grouped_conv: %r, error = %f", data_type, + use_gpu, grouped_conv, err) + self.assertLess(err, tolerance) + + @test_util.run_v1_only("b/120545219") + @test_util.run_gpu_only + def testDepthwiseConv2DInputGradCudnn(self): + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(CheckGradConfigsToTest()): + # The CuDNN depthwise conv (input gradient) is turned on only when + # stride = 1, input/output is NCHW and float16(half). See cudnn release + # note 7.6.3. + if stride != 1: + continue + tf_logging.info( + "Testing DepthwiseConv2DInputGradCudnn, %dth config: %r * %r, " + "stride: %d, padding: %s", index, input_size, filter_size, stride, + padding) + data_types = [dtypes.float16, dtypes.bfloat16] + for data_type in data_types: + self._ConstructAndTestGradient( + input_size, + filter_size, + output_size, + stride, + padding, + data_type, + test_input=True, + use_gpu=True, + data_format="NCHW", + dilations=dilations) + + @test_util.run_v1_only("b/120545219") + def testDepthwiseConv2DInputGrad(self): + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(CheckGradConfigsToTest()): + tf_logging.info( + "Testing DepthwiseConv2DInputGrad, %dth config: %r * %r, stride: %d, " + "padding: %s", index, input_size, filter_size, stride, padding) + # double datatype is currently not supported for convolution ops + # on the ROCm platform + optional_float64 = [] if test.is_built_with_rocm() else [dtypes.float64] + for data_type in ([dtypes.float32] + optional_float64): + self._ConstructAndTestGradient( + input_size, + filter_size, + output_size, + stride, + padding, + data_type, + test_input=True, + use_gpu=True, + dilations=dilations) + self._ConstructAndTestGradient( + input_size, + filter_size, + output_size, + stride, + padding, + data_type, + test_input=True, + use_gpu=True, + grouped_conv=True, + dilations=dilations) + + @test_util.run_v1_only("b/120545219") + def testDepthwiseConv2DInputGradFormat(self): + if not test.is_gpu_available(): + return + + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(CheckGradConfigsToTest()): + tf_logging.info( + "Testing DepthwiseConv2DInputGradFormat, %dth config: %r * %r, " + "stride: %d, padding: %s", index, input_size, filter_size, stride, + padding) + # double datatype is currently not supported for convolution ops + # on the ROCm platform + optional_float64 = [] if test.is_built_with_rocm() else [dtypes.float64] + for data_type in ([dtypes.float32] + optional_float64): + self._ConstructAndTestGradient( + input_size, + filter_size, + output_size, + stride, + padding, + data_type, + test_input=True, + use_gpu=True, + data_format="NCHW", + dilations=dilations) + + @test_util.run_v1_only("b/120545219") + def testDepthwiseConv2DInputGradExplicit(self): + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(CheckGradConfigsToTestExplicit()): + tf_logging.info( + "Testing DepthwiseConv2DInputGradExplicit, %dth config: %r * %r, " + "stride: %d, padding: %s", index, input_size, filter_size, stride, + padding) + # double datatype is currently not supported for convolution ops + # on the ROCm platform + data_types = [dtypes.float16, dtypes.float32, dtypes.bfloat16] + if not test.is_built_with_rocm(): + data_types.extend([dtypes.float64]) + data_formats = ["NHWC", "NCHW"] if test.is_gpu_available() else ["NHWC"] + for data_type in data_types: + for data_format in data_formats: + self._ConstructAndTestGradient( + input_size, + filter_size, + output_size, + stride, + padding, + data_type, + test_input=True, + use_gpu=True, + data_format=data_format, + dilations=dilations) + + @test_util.run_v1_only("b/120545219") + @test_util.run_gpu_only + def testDepthwiseConv2DFilterGradCudnn(self): + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(CheckGradConfigsToTest()): + # The CuDNN depthwise conv (filter gradient) is turned on only when + # input/output is float16(half). See cudnn release note 7.6.3. + tf_logging.info( + "Testing DepthwiseConv2DFilterGradCudnn, %dth config: %r * %r, " + "stride: %d, padding: %s", index, input_size, filter_size, stride, + padding) + data_types = [dtypes.float16, dtypes.bfloat16] + for data_type in data_types: + self._ConstructAndTestGradient( + input_size, + filter_size, + output_size, + stride, + padding, + data_type, + test_input=False, + use_gpu=True, + data_format="NCHW", + dilations=dilations) + self._ConstructAndTestGradient( + input_size, + filter_size, + output_size, + stride, + padding, + data_type, + test_input=False, + use_gpu=True, + data_format="NHWC", + dilations=dilations) + + @test_util.run_v1_only("b/120545219") + def testDepthwiseConv2DFilterGrad(self): + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(CheckGradConfigsToTest()): + tf_logging.info( + "Testing DepthwiseConv2DFilterGrad, %dth config: %r * %r, stride: " + "%d, padding: %s", index, input_size, filter_size, stride, padding) + # double datatype is currently not supported for convolution ops + # on the ROCm platform + optional_float64 = [] if test.is_built_with_rocm() else [dtypes.float64] + for data_type in ([dtypes.float16, dtypes.float32] + optional_float64): + self._ConstructAndTestGradient( + input_size, + filter_size, + output_size, + stride, + padding, + data_type, + test_input=False, + use_gpu=True, + dilations=dilations) + + @test_util.run_v1_only("b/120545219") + def testDepthwiseConv2DFilterGradFormat(self): + if not test.is_gpu_available(): + return + + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(CheckGradConfigsToTest()): + tf_logging.info( + "Testing DepthwiseConv2DFilterGradFormat, %dth config: %r * %r, " + "stride: %d, padding: %s", index, input_size, filter_size, stride, + padding) + # double datatype is currently not supported for convolution ops + # on the ROCm platform + optional_float64 = [] if test.is_built_with_rocm() else [dtypes.float64] + for data_type in ([dtypes.float32] + optional_float64): + self._ConstructAndTestGradient( + input_size, + filter_size, + output_size, + stride, + padding, + data_type, + test_input=False, + use_gpu=True, + data_format="NCHW", + dilations=dilations) + + @test_util.run_v1_only("b/120545219") + def testDepthwiseConv2DFilterGradExplicit(self): + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(CheckGradConfigsToTestExplicit()): + tf_logging.info( + "Testing DepthwiseConv2DFilterGradExplicit, %dth config: %r * %r, " + "stride: %d, padding: %s", index, input_size, filter_size, stride, + padding) + # double datatype is currently not supported for convolution ops + # on the ROCm platform + data_types = [dtypes.float16, dtypes.float32, dtypes.bfloat16] + if not test.is_built_with_rocm(): + data_types.extend([dtypes.float64]) + data_formats = ["NHWC", "NCHW"] if test.is_gpu_available() else ["NHWC"] + for data_type in data_types: + for data_format in data_formats: + self._ConstructAndTestGradient( + input_size, + filter_size, + output_size, + stride, + padding, + data_type, + test_input=False, + use_gpu=True, + data_format=data_format, + dilations=dilations) + + def _CompareBackpropInput(self, input_sizes, filter_sizes, output_sizes, + stride, padding, dtype): + x1 = np.random.rand(*filter_sizes) + x2 = np.random.rand(*output_sizes) + if isinstance(padding, list): + padding = [(0, 0)] + padding + [(0, 0)] + + def _GetVal(use_gpu, dtype): + with self.cached_session(use_gpu=use_gpu): + t0 = constant_op.constant(input_sizes, shape=[len(input_sizes)]) + t1 = constant_op.constant(x1, shape=filter_sizes, dtype=dtype) + t2 = constant_op.constant(x2, shape=output_sizes, dtype=dtype) + backprop = nn_ops.depthwise_conv2d_native_backprop_input( + t0, t1, t2, strides=[1, stride, stride, 1], padding=padding) + ret = self.evaluate(backprop) + self.assertShapeEqual(ret, backprop) + return ret + + rtol, atol = (1e-1, 1e-1) if dtype == "bfloat16" else (1e-4, 1e-4) + gpu_value = _GetVal(use_gpu=True, dtype=dtype) + cpu_value = _GetVal(use_gpu=False, dtype=dtype) + self.assertAllClose(cpu_value, gpu_value, rtol=rtol, atol=atol) + + @test_util.run_gpu_only + def testDepthwiseConv2DInputGradCompare(self): + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(ConfigsToTest()): + if dilations: + continue + tf_logging.info( + "Testing DepthwiseConv2DInputGradCompare, %dth config: %r * %r, " + "stride: %d, padding: %s", index, input_size, filter_size, stride, + padding) + self._CompareBackpropInput(input_size, filter_size, output_size, stride, + padding, "float32") + self._CompareBackpropInput(input_size, filter_size, output_size, stride, + padding, "bfloat16") + # Convolutions on the ROCm platform don't support double dtype. + # So, we skip these tests. + if not test.is_built_with_rocm(): + self._CompareBackpropInput( + input_size, filter_size, output_size, stride, padding, "float64" + ) + + @test_util.run_gpu_only + def testDepthwiseConv2DInputGradExplicitCompare(self): + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(ConfigsToTestExplicit()): + if dilations: + continue + tf_logging.info( + "Testing DepthwiseConv2DInputGradCompare, %dth config: %r * %r, " + "stride: %d, padding: %s", index, input_size, filter_size, stride, + padding) + self._CompareBackpropInput(input_size, filter_size, output_size, stride, + padding, "float32") + self._CompareBackpropInput(input_size, filter_size, output_size, stride, + padding, "bfloat16") + # Convolutions on the ROCm platform don't support double dtype. + if not test.is_built_with_rocm(): + self._CompareBackpropInput( + input_size, filter_size, output_size, stride, padding, "float64" + ) + + def _CompareBackpropFilter(self, input_sizes, filter_sizes, output_sizes, + stride, padding, dtype): + x0 = np.random.rand(*input_sizes) + x2 = np.random.rand(*output_sizes) + padding_nhwc = padding + padding_nchw = padding + if isinstance(padding, list): + padding_nhwc = [(0, 0)] + padding + [(0, 0)] + padding_nchw = [(0, 0)] + [(0, 0)] + padding + + def _GetVal(use_gpu, dtype, data_format="NHWC"): + with self.cached_session(use_gpu=use_gpu): + t0 = constant_op.constant(x0, shape=input_sizes, dtype=dtype) + t1 = constant_op.constant(filter_sizes, shape=[len(filter_sizes)]) + t2 = constant_op.constant(x2, shape=output_sizes, dtype=dtype) + strides = [1, stride, stride, 1] + padding = padding_nhwc + if data_format == "NCHW": + t0 = array_ops.transpose(t0, [0, 3, 1, 2]) + t2 = array_ops.transpose(t2, [0, 3, 1, 2]) + strides = [1, 1, stride, stride] + padding = padding_nchw + backprop = nn_ops.depthwise_conv2d_native_backprop_filter( + t0, + t1, + t2, + strides=strides, + padding=padding, + data_format=data_format) + ret = self.evaluate(backprop) + self.assertShapeEqual(ret, backprop) + return ret + + cpu_value = _GetVal(use_gpu=False, dtype=dtype) + for data_format in ["NHWC", "NCHW"]: + gpu_value = _GetVal(use_gpu=True, dtype=dtype, data_format=data_format) + self.assertAllCloseAccordingToType( + cpu_value, gpu_value, rtol=1e-4, atol=1e-4, bfloat16_rtol=1e-0) + + @test_util.run_gpu_only + def testDepthwiseConv2DFilterGradCompare(self): + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(ConfigsToTest()): + if dilations: + continue + tf_logging.info( + "Testing DepthwiseConv2DFilterGradCompare, %dth config: %r * %r, " + "stride: %d, padding: %s", index, input_size, filter_size, stride, + padding) + self._CompareBackpropFilter(input_size, filter_size, output_size, stride, + padding, "float32") + self._CompareBackpropFilter(input_size, filter_size, output_size, stride, + padding, "bfloat16") + # Convolutions on the ROCm platform don't support double dtype. + if not test.is_built_with_rocm(): + self._CompareBackpropFilter( + input_size, filter_size, output_size, stride, padding, "float64" + ) + + @test_util.run_gpu_only + def testDepthwiseConv2DFilterGradExplicitCompare(self): + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(ConfigsToTestExplicit()): + if dilations: + continue + tf_logging.info( + "Testing DepthwiseConv2DFilterGradCompare, %dth config: %r * %r, " + "stride: %d, padding: %s", index, input_size, filter_size, stride, + padding) + self._CompareBackpropFilter(input_size, filter_size, output_size, stride, + padding, "float32") + self._CompareBackpropFilter(input_size, filter_size, output_size, stride, + padding, "bfloat16") + # Convolutions on the ROCm platform don't support double dtype. + if not test.is_built_with_rocm(): + self._CompareBackpropFilter( + input_size, filter_size, output_size, stride, padding, "float64" + ) + + def _CompareForward(self, input_sizes, filter_sizes, output_sizes, stride, + padding, dtype): + x1 = np.random.rand(*input_sizes) + x2 = np.random.rand(*filter_sizes) + if isinstance(padding, list): + padding = [(0, 0)] + padding + [(0, 0)] + + def _GetVal(use_gpu, dtype): + with self.cached_session(use_gpu=use_gpu): + t1 = constant_op.constant(x1, shape=input_sizes, dtype=dtype) + t2 = constant_op.constant(x2, shape=filter_sizes, dtype=dtype) + output = nn_ops.depthwise_conv2d_native( + t1, t2, strides=[1, stride, stride, 1], padding=padding) + ret = self.evaluate(output) + self.assertShapeEqual(ret, output) + return ret + + gpu_value = _GetVal(use_gpu=True, dtype=dtype) + cpu_value = _GetVal(use_gpu=False, dtype=dtype) + self.assertAllCloseAccordingToType( + cpu_value, gpu_value, rtol=1e-4, atol=1e-4, bfloat16_rtol=1e-1) + + @test_util.run_gpu_only + def testDepthwiseConv2DForwardCompare(self): + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(ConfigsToTest()): + if dilations: + continue + tf_logging.info( + "Testing DepthwiseConv2DForwardCompare, %dth config: %r * %r, " + "stride: %d, padding: %s", index, input_size, filter_size, stride, + padding) + self._CompareForward(input_size, filter_size, output_size, stride, + padding, "float32") + self._CompareForward(input_size, filter_size, output_size, stride, + padding, "bfloat16") + + # Convolutions on the ROCm platform don't support double dtype. + if not test.is_built_with_rocm(): + self._CompareForward( + input_size, filter_size, output_size, stride, padding, "float64" + ) + + @test_util.run_gpu_only + def testDepthwiseConv2DForwardExplicitCompare(self): + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(ConfigsToTestExplicit()): + if dilations: + continue + tf_logging.info( + "Testing DepthwiseConv2DForwardCompare, %dth config: %r * %r, " + "stride: %d, padding: %s", index, input_size, filter_size, stride, + padding) + + self._CompareForward(input_size, filter_size, output_size, stride, + padding, "float32") + self._CompareForward(input_size, filter_size, output_size, stride, + padding, "bfloat16") + + # Convolutions on the ROCm platform don't support double dtype. + if not test.is_built_with_rocm(): + self._CompareForward( + input_size, filter_size, output_size, stride, padding, "float64" + ) diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/xent_op_test_base.py b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/xent_op_test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..80948fa7328d9743d339be07c9f33bd7ddb6e8b0 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/xent_op_test_base.py @@ -0,0 +1,293 @@ +# Copyright 2015-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. +# ============================================================================== +"""Tests for SoftmaxCrossEntropyWithLogits op.""" + +import numpy as np + +from tensorflow.python.eager import backprop +from tensorflow.python.framework import config +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import test_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gradient_checker +from tensorflow.python.ops import gradients_impl +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn_ops +# The following import is required to register the gradient function. +from tensorflow.python.ops.nn_grad import _SoftmaxCrossEntropyWithLogitsGrad # pylint: disable=unused-import +from tensorflow.python.platform import test + + +class XentOpTestBase(test.TestCase): + + def _opFwdBwd(self, labels, logits, axis=-1): + """ Runs the op-under-test both forwards and backwards.""" + logits = ops.convert_to_tensor(logits) # needed for the gradient tape + with backprop.GradientTape() as tape: + tape.watch(logits) + loss = nn_ops.softmax_cross_entropy_with_logits( + labels=labels, logits=logits, dim=axis) + return loss, tape.gradient(loss, logits) + + def _npXent(self, labels, logits, dim=-1): + if dim == -1: + dim = len(logits.shape) - 1 + one_only_on_dim = list(logits.shape) + one_only_on_dim[dim] = 1 + e = np.exp(logits - np.reshape(np.amax(logits, axis=dim), one_only_on_dim)) + probs = e / np.reshape(np.sum(e, axis=dim), one_only_on_dim) + bp = (probs - labels) + l = -np.sum(labels * np.log(probs + 1.0e-20), axis=dim) + return l, bp + + # TODO(b/123860949): The values are constant folded for XLA, so placeholders + # are needed. + def _testXent2D(self, + np_labels, + np_logits, + with_placeholders=False, + expected_gradient=None): + np_loss, np_gradient = self._npXent(labels=np_labels, logits=np_logits) + if expected_gradient is not None: + np_gradient = expected_gradient + with self.cached_session() as sess: + if with_placeholders: + logits_placeholder = array_ops.placeholder(np_logits.dtype) + labels_placeholder = array_ops.placeholder(np_labels.dtype) + loss, gradient = self._opFwdBwd(labels_placeholder, logits_placeholder) + tf_loss, tf_gradient = sess.run([loss, gradient], + feed_dict={ + labels_placeholder: np_labels, + logits_placeholder: np_logits + }) + else: + loss, gradient = self._opFwdBwd(np_labels, np_logits) + tf_loss, tf_gradient = self.evaluate([loss, gradient]) + self.assertAllCloseAccordingToType(np_loss, tf_loss, half_rtol=1e-2) + self.assertAllCloseAccordingToType(np_gradient, tf_gradient) + + def _testXentND(self, np_labels, np_logits, dim=-1): + np_loss, _ = self._npXent(np_labels, np_logits, dim=dim) + loss = nn_ops.softmax_cross_entropy_with_logits( + labels=np_labels, logits=np_logits, dim=dim) + tf_loss = self.evaluate(loss) + self.assertAllCloseAccordingToType(np_loss, tf_loss) + + def _testSingleClass(self, expected_gradient=[[2.0], [1.0], [0.0], [0.0]]): + for dtype in np.float16, np.float32, dtypes.bfloat16.as_numpy_dtype: + loss, gradient = self._opFwdBwd( + labels=np.array([[-1.], [0.], [1.], [1.]]).astype(dtype), + logits=np.array([[1.], [-1.], [0.], [1.]]).astype(dtype)) + self.assertAllClose([0.0, 0.0, 0.0, 0.0], loss) + self.assertAllClose(expected_gradient, gradient) + + def testSingleClass(self): + """This method is structured to be easily overridden by a child class.""" + self._testSingleClass() + + def testNpXent(self): + # We create 2 batches of logits for testing. + # batch 0 is the boring uniform distribution: 1, 1, 1, 1, with target 3. + # batch 1 has a bit of difference: 1, 2, 3, 4, with soft targets (1, 2). + logits = [[1., 1., 1., 1.], [1., 2., 3., 4.]] + labels = [[0., 0., 0., 1.], [0., .5, .5, 0.]] + + # For batch 0, we expect the uniform distribution: 0.25, 0.25, 0.25, 0.25 + # With a hard target 3, the gradient is [0.25, 0.25, 0.25, -0.75] + # The loss for this batch is -log(0.25) = 1.386 + # + # For batch 1, we have: + # exp(0) = 1 + # exp(1) = 2.718 + # exp(2) = 7.389 + # exp(3) = 20.085 + # SUM = 31.192 + # So we have as probabilities: + # exp(0) / SUM = 0.032 + # exp(1) / SUM = 0.087 + # exp(2) / SUM = 0.237 + # exp(3) / SUM = 0.644 + # With a soft target (1, 2), the gradient is + # [0.032, 0.087 - 0.5 = -0.413, 0.237 - 0.5 = -0.263, 0.644] + # The loss for this batch is [0.5 * -log(0.087), 0.5 * -log(0.237)] + # = [1.3862, 1.9401] + np_loss, np_gradient = self._npXent(np.array(labels), np.array(logits)) + self.assertAllClose( + np.array([[0.25, 0.25, 0.25, -0.75], [0.0321, -0.4129, -0.2632, + 0.6439]]), + np_gradient, + rtol=1.e-3, + atol=1.e-3) + self.assertAllClose( + np.array([1.3862, 1.9401]), np_loss, rtol=1.e-3, atol=1.e-3) + + # TODO(b/123860949): The values are constant folded for XLA, so placeholders + # are needed. + @test_util.run_deprecated_v1 + def _testLabelsBroadcast(self, uniform_labels_gradient): + labels = np.array([[0., 0., 0., 1.]]).astype(np.float16) + logits = np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float16) + self._testXent2D(labels, logits, with_placeholders=True) + labels = np.array([[1.]]).astype(np.float16) + logits = np.array([[1.], [2.]]).astype(np.float16) + self._testXent2D(labels, logits, with_placeholders=True) + labels = np.array([[0.], [2.], [0.25]]).astype(np.float16) + logits = np.array([[1., 1., 1., 1.], [1., 2., 3., 4.], + [1., 2., 3., 4.]]).astype(np.float16) + self._testXent2D( + labels, + logits, + with_placeholders=True, + expected_gradient=uniform_labels_gradient) + + def testLabelsBroadcast(self): + """This method is structured to be easily overridden by a child class.""" + self._testLabelsBroadcast(uniform_labels_gradient=[[ + 0.25, 0.25, 0.25, 0.25 + ], [-1.968, -1.913, -1.763, -1.355], [-0.218, -0.163, -0.013, 0.394]]) + + @test_util.run_deprecated_v1 + def testShapeMismatch(self): + with self.cached_session(): + with self.assertRaises(ValueError): + self._opFwdBwd( + labels=[[0., 1., 0.], [1., 0., 0.]], logits=[[0., 1.], [2., 3.]]) + + def testHalf(self): + labels = np.array([[0., 0., 0., 1.], [0., .5, .5, 0.]]).astype(np.float16) + logits = np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float16) + self._testXent2D(labels, logits) + + def testBfloat16(self): + labels = np.array([[0., 0., 0., 1.], + [0., .5, .5, 0.]]).astype(dtypes.bfloat16.as_numpy_dtype) + logits = np.array([[1., 1., 1., 1.], + [1., 2., 3., 4.]]).astype(dtypes.bfloat16.as_numpy_dtype) + self._testXent2D(labels, logits) + + def testFloat(self): + labels = np.array([[0., 0., 0., 1.], [0., .5, .5, 0.]]).astype(np.float32) + logits = np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float32) + self._testXent2D(labels, logits) + + def testDouble(self): + labels = np.array([[0., 0., 0., 1.], [0., .5, .5, 0.]]).astype(np.float64) + logits = np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float64) + self._testXent2D(labels, logits) + + @test_util.run_deprecated_v1 + def testGradient(self): + with self.cached_session() as sess: + labels = constant_op.constant( + [0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5], + shape=[3, 4], + dtype=dtypes.float64, + name="labels") + logits = constant_op.constant( + [0.1, 0.2, 0.3, 0.4, 0.1, 0.4, 0.9, 1.6, 0.1, 0.8, 2.7, 6.4], + shape=[3, 4], + dtype=dtypes.float64, + name="logits") + x = nn_ops.softmax_cross_entropy_with_logits( + labels=labels, logits=logits, name="xent") + err = gradient_checker.compute_gradient_error(logits, [3, 4], x, [3]) + + # Check that no extra computation gets performed. When only the first + # derivative is requested, the second derivative must not be computed. + # So when there is no second derivative, there is no `BatchMatMul` op + # in the graph. + op_names = [ + op.op_def.name for op in sess.graph.get_operations() if op.op_def + ] + self.assertNotIn("BatchMatMul", op_names) + self.assertNotIn("BatchMatMulV2", op_names) + + self.assertLess(err, 5e-8) + + @test_util.run_deprecated_v1 + def testGradientLabelWithV2(self): + with self.cached_session(): + labels = constant_op.constant( + [0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5], + shape=[3, 4], + dtype=dtypes.float64, + name="labels") + logits = constant_op.constant( + [0.1, 0.2, 0.3, 0.4, 0.1, 0.4, 0.9, 1.6, 0.1, 0.8, 2.7, 6.4], + shape=[3, 4], + dtype=dtypes.float64, + name="logits") + x = nn_ops.softmax_cross_entropy_with_logits_v2( + labels=labels, logits=logits, name="xent") + err = gradient_checker.compute_gradient_error(labels, [3, 4], x, [3]) + + self.assertLess(err, 5e-8) + + @test_util.run_deprecated_v1 + def testSecondGradient(self): + with self.cached_session() as sess: + labels = constant_op.constant([ + 0.0, 0.0, 1.0 / 3, 0.0, 1.0 / 3, 0.0, 0.0, 0.0, 0.0, 0.5 / 3, 0.0, + 0.5 / 3 + ], + shape=[12], + dtype=dtypes.float64, + name="labels") + logits = constant_op.constant( + [0.1, 0.2, 0.3, 0.4, 0.1, 0.4, 0.9, 1.6, 0.1, 0.8, 2.7, 6.4], + shape=[12], + dtype=dtypes.float64, + name="logits") + x = nn_ops.softmax_cross_entropy_with_logits( + labels=labels, logits=logits, name="xent") + loss = math_ops.reduce_sum(x) + + gradients = gradients_impl.gradients(loss, [logits])[0] + + err = gradient_checker.compute_gradient_error(logits, [12], gradients, + [12]) + + if not config.is_op_determinism_enabled(): + # Check how second derivative is calculated. + # (it is equivalent to a `BatchMatMul` op being in the graph because of + # the implementation in SoftmaxCrossEntropyWithLogitsGrad) + op_names = [ + op.op_def.name for op in sess.graph.get_operations() if op.op_def + ] + self.assertIn("BatchMatMulV2", op_names) + + self.assertLess(err, 5e-8) + + def test3D(self): + labels = np.array([[[0., 0., 0., 1.], [0., 1., 0., 0.]], + [[0., 0.5, 0.5, 0.], [0.5, 0.5, 0., 0.]], + [[0., 1., 0., 0.], [0., 0., 1., 0.]]]).astype(np.float32) + logits = np.array([[[1., 1., 1., 1.], [1., 2., 3., 4.]], + [[2., 3., 4., 5.], [6., 7., 8., 9.]], + [[5., 4., 3., 2.], [1., 2., 3., 4.]]]).astype(np.float32) + self._testXentND(labels, logits, dim=0) + self._testXentND(labels, logits, dim=1) + self._testXentND(labels, logits, dim=-1) + + def testZeroDimension(self): + labels = np.zeros([0, 2, 4]).astype(np.float32) + logits = np.zeros([0, 2, 4]).astype(np.float32) + np_loss, _ = self._npXent(labels=labels, logits=logits) + loss = nn_ops.softmax_cross_entropy_with_logits( + labels=labels, logits=logits) + tf_loss = self.evaluate(loss) + self.assertAllEqual(np_loss, tf_loss) diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/random/__init__.py b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/random/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/random/__pycache__/__init__.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/random/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac63ec8276e557329f5dedc17b7883cff73bd1e5 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/random/__pycache__/__init__.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/random/__pycache__/util.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/random/__pycache__/util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..385c31e17cc964e407b62efa8e22364d7f88c64b Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/random/__pycache__/util.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/random/util.py b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/random/util.py new file mode 100644 index 0000000000000000000000000000000000000000..7c5a3db560832005ec67ff9942afa6d01ff1d95e --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/random/util.py @@ -0,0 +1,164 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities for testing random variables.""" + +import math + +import numpy as np + +from tensorflow.python.ops.distributions import special_math + + +def test_moment_matching( + samples, + number_moments, + dist, + stride=0): + """Return z-test scores for sample moments to match analytic moments. + + Given `samples`, check that the first sample `number_moments` match + the given `dist` moments by doing a z-test. + + Args: + samples: Samples from target distribution. + number_moments: Python `int` describing how many sample moments to check. + dist: SciPy distribution object that provides analytic moments. + stride: Distance between samples to check for statistical properties. + A stride of 0 means to use all samples, while other strides test for + spatial correlation. + Returns: + Array of z_test scores. + """ + + sample_moments = [] + expected_moments = [] + variance_sample_moments = [] + for i in range(1, number_moments + 1): + if len(samples.shape) == 2: + strided_range = samples.flat[::(i - 1) * stride + 1] + else: + strided_range = samples[::(i - 1) * stride + 1, ...] + sample_moments.append(np.mean(strided_range**i, axis=0)) + expected_moments.append(dist.moment(i)) + variance_sample_moments.append( + (dist.moment(2 * i) - dist.moment(i) ** 2) / len(strided_range)) + + z_test_scores = [] + for i in range(1, number_moments + 1): + # Assume every operation has a small numerical error. + # It takes i multiplications to calculate one i-th moment. + total_variance = ( + variance_sample_moments[i - 1] + + i * np.finfo(samples.dtype).eps) + tiny = np.finfo(samples.dtype).tiny + assert np.all(total_variance > 0) + total_variance = np.where(total_variance < tiny, tiny, total_variance) + # z_test is approximately a unit normal distribution. + z_test_scores.append(abs( + (sample_moments[i - 1] - expected_moments[i - 1]) / np.sqrt( + total_variance))) + return z_test_scores + + +def chi_squared(x, bins): + """Pearson's Chi-squared test.""" + x = np.ravel(x) + n = len(x) + histogram, _ = np.histogram(x, bins=bins, range=(0, 1)) + expected = n / float(bins) + return np.sum(np.square(histogram - expected) / expected) + + +def normal_cdf(x): + """Cumulative distribution function for a standard normal distribution.""" + return 0.5 + 0.5 * np.vectorize(math.erf)(x / math.sqrt(2)) + + +def anderson_darling(x): + """Anderson-Darling test for a standard normal distribution.""" + x = np.sort(np.ravel(x)) + n = len(x) + i = np.linspace(1, n, n) + z = np.sum((2 * i - 1) * np.log(normal_cdf(x)) + + (2 * (n - i) + 1) * np.log(1 - normal_cdf(x))) + return -n - z / n + + +def test_truncated_normal(assert_equal, + assert_all_close, + n, + y, + means=None, + stddevs=None, + minvals=None, + maxvals=None, + mean_atol=5e-4, + median_atol=8e-4, + variance_rtol=1e-3): + """Tests truncated normal distribution's statistics.""" + def _normal_cdf(x): + return .5 * math.erfc(-x / math.sqrt(2)) + + def normal_pdf(x): + return math.exp(-(x**2) / 2.) / math.sqrt(2 * math.pi) + + def probit(x): + return special_math.ndtri(x) + + a = -2. + b = 2. + mu = 0. + sigma = 1. + + if minvals is not None: + a = minvals + + if maxvals is not None: + b = maxvals + + if means is not None: + mu = means + + if stddevs is not None: + sigma = stddevs + + alpha = (a - mu) / sigma + beta = (b - mu) / sigma + z = _normal_cdf(beta) - _normal_cdf(alpha) + + assert_equal((y >= a).sum(), n) + assert_equal((y <= b).sum(), n) + + # For more information on these calculations, see: + # Burkardt, John. "The Truncated Normal Distribution". + # Department of Scientific Computing website. Florida State University. + expected_mean = mu + (normal_pdf(alpha) - normal_pdf(beta)) / z * sigma + y = y.astype(float) + actual_mean = np.mean(y) + assert_all_close(actual_mean, expected_mean, atol=mean_atol) + + expected_median = mu + probit( + (_normal_cdf(alpha) + _normal_cdf(beta)) / 2.) * sigma + actual_median = np.median(y) + assert_all_close(actual_median, expected_median, atol=median_atol) + + expected_variance = sigma**2 * (1 + ( + (alpha * normal_pdf(alpha) - beta * normal_pdf(beta)) / z) - ( + (normal_pdf(alpha) - normal_pdf(beta)) / z)**2) + actual_variance = np.var(y) + assert_all_close( + actual_variance, + expected_variance, + rtol=variance_rtol) diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/signal/__init__.py b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/signal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/signal/__pycache__/__init__.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/signal/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..453952d5c479d0c05d15ef92ee1c2830375c3a62 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/signal/__pycache__/__init__.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/signal/__pycache__/test_util.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/signal/__pycache__/test_util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98a23960f46171434e71fab08a8b0a4a575dc8f1 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/signal/__pycache__/test_util.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/signal/test_util.py b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/signal/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..0d82ca8e6341227ff7df7cd223163db06985e798 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/signal/test_util.py @@ -0,0 +1,96 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.signal.""" + +from tensorflow.core.protobuf import config_pb2 +from tensorflow.lite.python import interpreter +from tensorflow.lite.python import lite +from tensorflow.python.eager import def_function +from tensorflow.python.grappler import tf_optimizer +from tensorflow.python.training import saver + + +def grappler_optimize(graph, fetches=None, config_proto=None): + """Tries to optimize the provided graph using grappler. + + Args: + graph: A `tf.Graph` instance containing the graph to optimize. + fetches: An optional list of `Tensor`s to fetch (i.e. not optimize away). + Grappler uses the 'train_op' collection to look for fetches, so if not + provided this collection should be non-empty. + config_proto: An optional `tf.compat.v1.ConfigProto` to use when rewriting + the graph. + + Returns: + A `tf.compat.v1.GraphDef` containing the rewritten graph. + """ + if config_proto is None: + config_proto = config_pb2.ConfigProto() + config_proto.graph_options.rewrite_options.min_graph_nodes = -1 + if fetches is not None: + for fetch in fetches: + graph.add_to_collection('train_op', fetch) + metagraph = saver.export_meta_graph(graph_def=graph.as_graph_def()) + return tf_optimizer.OptimizeGraph(config_proto, metagraph) + + +def tflite_convert(fn, input_templates): + """Converts the provided fn to tf.lite model. + + Args: + fn: A callable that expects a list of inputs like input_templates that + returns a tensor or structure of tensors. + input_templates: A list of Tensors, ndarrays or TensorSpecs describing the + inputs that fn expects. The actual values of the Tensors or ndarrays are + unused. + + Returns: + The serialized tf.lite model. + """ + fn = def_function.function(fn) + concrete_func = fn.get_concrete_function(*input_templates) + converter = lite.TFLiteConverterV2([concrete_func]) + return converter.convert() + + +def evaluate_tflite_model(tflite_model, input_ndarrays): + """Evaluates the provided tf.lite model with the given input ndarrays. + + Args: + tflite_model: bytes. The serialized tf.lite model. + input_ndarrays: A list of NumPy arrays to feed as input to the model. + + Returns: + A list of ndarrays produced by the model. + + Raises: + ValueError: If the number of input arrays does not match the number of + inputs the model expects. + """ + the_interpreter = interpreter.Interpreter(model_content=tflite_model) + the_interpreter.allocate_tensors() + + input_details = the_interpreter.get_input_details() + output_details = the_interpreter.get_output_details() + + if len(input_details) != len(input_ndarrays): + raise ValueError('Wrong number of inputs: provided=%s, ' + 'input_details=%s output_details=%s' % ( + input_ndarrays, input_details, output_details)) + for input_tensor, data in zip(input_details, input_ndarrays): + the_interpreter.set_tensor(input_tensor['index'], data) + the_interpreter.invoke() + return [the_interpreter.get_tensor(details['index']) + for details in output_details] diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/sparse_ops/__init__.py b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/sparse_ops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/sparse_ops/__pycache__/__init__.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/sparse_ops/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6873f2942038c68bfe3f0d8404e49ee3c7fa965 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/sparse_ops/__pycache__/__init__.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/sparse_ops/__pycache__/sparse_xent_op_test_base.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/sparse_ops/__pycache__/sparse_xent_op_test_base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ba998550bfc11b9b7d1f9c981932a97571e6903 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/sparse_ops/__pycache__/sparse_xent_op_test_base.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/sparse_ops/sparse_xent_op_test_base.py b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/sparse_ops/sparse_xent_op_test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..381e5c093f007ef308e9f93de4661c2f699e70fc --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/python/kernel_tests/sparse_ops/sparse_xent_op_test_base.py @@ -0,0 +1,318 @@ +# Copyright 2015-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. +# ============================================================================== +"""Tests for SparseSoftmaxCrossEntropyWithLogits op.""" + +import numpy as np + +from tensorflow.python.eager import backprop as backprop_lib +from tensorflow.python.eager import context +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_impl +from tensorflow.python.framework import ops as ops_lib +from tensorflow.python.framework import test_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gradient_checker_v2 +from tensorflow.python.ops import nn_ops +import tensorflow.python.ops.nn_grad # pylint: disable=unused-import +from tensorflow.python.platform import test + + +class SparseXentOpTestBase(test.TestCase): + + def _opFwdBwd(self, labels, logits): + """Runs the op-under-test both forwards and backwards""" + logits = ops_lib.convert_to_tensor(logits) # needed for the gradient tape + with backprop_lib.GradientTape() as tape: + tape.watch(logits) + loss = nn_ops.sparse_softmax_cross_entropy_with_logits_v2( + labels=labels, logits=logits) + return loss, tape.gradient(loss, logits) + + def _npXent(self, labels, logits): + logits = np.reshape(logits, [-1, logits.shape[-1]]) + labels = np.reshape(labels, [-1]) + batch_dim = 0 + class_dim = 1 + batch_size = logits.shape[batch_dim] + e = np.exp(logits - + np.reshape(np.amax(logits, axis=class_dim), [batch_size, 1])) + probs = e / np.reshape(np.sum(e, axis=class_dim), [batch_size, 1]) + labels_mat = np.zeros_like(probs).astype(probs.dtype) + labels_mat[np.arange(batch_size), labels] = 1.0 + gradient = (probs - labels_mat) + loss = -np.sum(labels_mat * np.log(probs + 1.0e-20), axis=1) + return loss, gradient + + def _testXent(self, np_labels, np_logits): + np_loss, np_gradient = self._npXent(labels=np_labels, logits=np_logits) + tf_loss, tf_gradient = self._opFwdBwd(labels=np_labels, logits=np_logits) + self.assertAllCloseAccordingToType(np_loss, tf_loss) + self.assertAllCloseAccordingToType(np_gradient, tf_gradient) + + def testSingleClass(self): + for label_dtype in np.int32, np.int64: + tf_loss, tf_gradient = self._opFwdBwd( + labels=np.array([0, 0, 0]).astype(label_dtype), + logits=np.array([[1.], [-1.], [0.]]).astype(np.float32)) + self.assertAllClose([0.0, 0.0, 0.0], tf_loss) + self.assertAllClose([[0.0], [0.0], [0.0]], tf_gradient) + + @test_util.run_gpu_only + def _testInvalidLabelGPU(self, invalid_label_gradient=np.nan): + labels = [4, 3, 0, -1] + logits = [[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 2., 3., 4.], + [1., 2., 3., 4.]] + loss, gradient = self._opFwdBwd(labels=labels, logits=logits) + self.assertAllClose([np.nan, 1.3862, 3.4420, np.nan], + loss, + rtol=1e-3, + atol=1e-3) + self.assertAllClose( + [[invalid_label_gradient] * 4, [0.25, 0.25, 0.25, -0.75], + [-0.968, 0.087, 0.237, 0.6439], [invalid_label_gradient] * 4], + gradient, + rtol=1e-3, + atol=1e-3) + + def testInvalidLabelGPU(self): + """This method is structured to be easily overridden by a child class.""" + self._testInvalidLabelGPU() + + @test_util.run_in_graph_and_eager_modes(use_gpu=False) + @test_util.disable_xla("XLA cannot assert inside of a kernel.") + def _testInvalidLabelCPU(self, expected_regex="Received a label value of"): + labels = [4, 3, 0, -1] + logits = [[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 2., 3., 4.], + [1., 2., 3., 4.]] + with self.assertRaisesRegex( + (errors_impl.InvalidArgumentError, errors_impl.UnknownError), + expected_regex): + self.evaluate( + nn_ops.sparse_softmax_cross_entropy_with_logits_v2( + labels=labels, logits=logits)) + + def testInvalidLabelCPU(self): + """This method is structured to be easily overridden by a child class.""" + self._testInvalidLabelCPU() + + def testNpXent(self): + # We create 2 batches of logits for testing. + # batch 0 is the boring uniform distribution: 1, 1, 1, 1, with target 3. + # batch 1 has a bit of difference: 1, 2, 3, 4, with target 0. + labels = [3, 0] + logits = [[1., 1., 1., 1.], [1., 2., 3., 4.]] + + # For batch 0, we expect the uniform distribution: 0.25, 0.25, 0.25, 0.25 + # With a hard target 3, the gradient is [0.25, 0.25, 0.25, -0.75] + # The loss for this batch is -log(0.25) = 1.386 + # + # For batch 1, we have: + # exp(0) = 1 + # exp(1) = 2.718 + # exp(2) = 7.389 + # exp(3) = 20.085 + # SUM = 31.192 + # So we have as probabilities: + # exp(0) / SUM = 0.032 + # exp(1) / SUM = 0.087 + # exp(2) / SUM = 0.237 + # exp(3) / SUM = 0.644 + # With a hard 1, the gradient is [0.032 - 1.0 = -0.968, 0.087, 0.237, 0.644] + # The loss for this batch is [1.0 * -log(0.25), 1.0 * -log(0.032)] + # = [1.3862, 3.4420] + np_loss, np_gradient = self._npXent( + labels=np.array(labels), logits=np.array(logits)) + self.assertAllClose( + np.array([[0.25, 0.25, 0.25, -0.75], [-0.968, 0.087, 0.237, 0.6439]]), + np_gradient, + rtol=1.e-3, + atol=1.e-3) + self.assertAllClose( + np.array([1.3862, 3.4420]), np_loss, rtol=1.e-3, atol=1.e-3) + + def testShapeMismatch(self): + with self.assertRaisesRegex( + ValueError, "`labels.shape.rank` must equal `logits.shape.rank - 1`"): + nn_ops.sparse_softmax_cross_entropy_with_logits_v2( + labels=[[0, 2]], logits=[[0., 1.], [2., 3.], [2., 3.]]) + + def testScalar(self): + with self.assertRaisesRegex(ValueError, "`logits` cannot be a scalar"): + nn_ops.sparse_softmax_cross_entropy_with_logits_v2( + labels=constant_op.constant(0), logits=constant_op.constant(1.0)) + + def _testLabelsPlaceholderScalar(self, expected_error_message): + with ops_lib.Graph().as_default(), self.session(): + labels = array_ops.placeholder(np.int32) + y = nn_ops.sparse_softmax_cross_entropy_with_logits_v2( + labels=labels, logits=[[7.]]) + with self.assertRaisesOpError(expected_error_message): + y.eval(feed_dict={labels: 0}) + + def testLabelsPlaceholderScalar(self): + """This method is structured to be easily overridden by a child class.""" + self._testLabelsPlaceholderScalar( + expected_error_message="labels must be 1-D") + + def testVector(self): + loss = nn_ops.sparse_softmax_cross_entropy_with_logits_v2( + labels=constant_op.constant(0), logits=constant_op.constant([1.0])) + self.assertAllClose(0.0, loss) + + def testFloat(self): + for label_dtype in np.int32, np.int64: + self._testXent( + np_labels=np.array([3, 0]).astype(label_dtype), + np_logits=np.array([[1., 1., 1., 1.], [1., 2., 3., + 4.]]).astype(np.float32)) + + def testDouble(self): + for label_dtype in np.int32, np.int64: + self._testXent( + np_labels=np.array([0, 3]).astype(label_dtype), + np_logits=np.array([[1., 1., 1., 1.], [1., 2., 3., + 4.]]).astype(np.float64)) + + def testHalf(self): + for label_dtype in np.int32, np.int64: + self._testXent( + np_labels=np.array([3, 0]).astype(label_dtype), + np_logits=np.array([[1., 1., 1., 1.], [1., 2., 3., + 4.]]).astype(np.float16)) + + def testBfloat16(self): + for label_dtype in np.int32, np.int64: + self._testXent( + np_labels=np.array([3, 0]).astype(label_dtype), + np_logits=np.array([[1., 1., 1., 1.], + [1., 2., 3., + 4.]]).astype(dtypes.bfloat16.as_numpy_dtype)) + + def testEmpty(self): + self._testXent( + np_labels=np.zeros((0,), dtype=np.int32), np_logits=np.zeros((0, 3))) + + @test_util.run_in_graph_and_eager_modes() + def testGradient(self): + with self.session() as sess: + labels = constant_op.constant([3, 0, 1], name="labels") + logits = constant_op.constant( + [0.1, 0.2, 0.3, 0.4, 0.1, 0.4, 0.9, 1.6, 0.1, 0.8, 2.7, 6.4], + shape=[3, 4], + dtype=dtypes.float64, + name="logits") + + def xent(logits): + # gradient_checker_v2.computee_gradient doesn't take int32/int64. + # labels must be of type int32/int64, so passing them separately here. + return nn_ops.sparse_softmax_cross_entropy_with_logits_v2( + labels=labels, logits=logits, name="xent") + + analytical, numerical = gradient_checker_v2.compute_gradient( + xent, [logits]) + + if not context.executing_eagerly(): + # Check that no extra computation performed. When only first derivative + # is requested, second derivative must not be computed. So when there is + # no second derivative, there is no `BatchMatMul` op in the graph. + op_names = [ + op.op_def.name for op in sess.graph.get_operations() if op.op_def + ] + self.assertNotIn("BatchMatMul", op_names) + self.assertNotIn("BatchMatMulV2", op_names) + + tol = 5e-8 + self.assertAllClose(analytical, numerical, atol=tol, rtol=tol) + + @test_util.run_in_graph_and_eager_modes() + def testSecondGradient(self): + with self.session() as sess: + labels = constant_op.constant([3, 0, 1], name="labels") + logits = constant_op.constant( + [0.3, 0.4, 0.1, 1.2, 0.1, 1.9, 0.1, 0.7, 0.8, 0.2, 1.3, 1.3], + shape=[3, 4], + dtype=dtypes.float64, + name="logits") + + def xent_grad(logits): + with backprop_lib.GradientTape() as tape: + tape.watch(logits) + return tape.gradient( + nn_ops.sparse_softmax_cross_entropy_with_logits_v2( + labels=labels, logits=logits, name="xent"), [logits])[0] + + analytical, numerical = gradient_checker_v2.compute_gradient( + xent_grad, [logits]) + + if (not context.executing_eagerly() and + not config.is_op_determinism_enabled()): + # Check that second derivative is calculated. + # (it is equivalent to being `BatchMatMul` op in the graph because of + # implementation of xentropy grad) + op_names = [ + op.op_def.name for op in sess.graph.get_operations() if op.op_def + ] + self.assertIn("BatchMatMulV2", op_names) + + tol = 5e-8 + self.assertAllClose(analytical, numerical, atol=tol, rtol=tol) + + @test_util.run_in_graph_and_eager_modes() + def _testHighDim(self, labels, logits): + np_loss, np_gradient = self._npXent( + labels=np.array(labels), logits=np.array(logits)) + # manually reshape loss + np_loss = np.reshape(np_loss, np.array(labels).shape) + tf_loss = nn_ops.sparse_softmax_cross_entropy_with_logits_v2( + labels=labels, logits=logits) + with backprop_lib.GradientTape() as tape: + logits = constant_op.constant(logits) + tape.watch(logits) + tf_gradient = tape.gradient( + nn_ops.sparse_softmax_cross_entropy_with_logits_v2( + labels=labels, logits=logits), [logits])[0] + tf_gradient = array_ops.reshape(tf_gradient, np_gradient.shape) + + self.assertAllCloseAccordingToType(np_loss, tf_loss) + self.assertAllCloseAccordingToType(np_gradient, tf_gradient) + + def testHighDim(self): + labels = [[3], [0]] + logits = [[[1., 1., 1., 1.]], [[1., 2., 3., 4.]]] + self._testHighDim(labels, logits) + + def testHighDim2(self): + labels = [[3, 2], [0, 3]] + logits = [[[1., 1., 1., 1.], [2., 2., 2., 2.]], + [[1., 2., 3., 4.], [5., 6., 7., 8.]]] + self._testHighDim(labels, logits) + + def _testScalarHandling(self, expected_regex): + with ops_lib.Graph().as_default(), self.session(use_gpu=False) as sess: + with self.assertRaisesRegex(errors_impl.InvalidArgumentError, + expected_regex): + labels = array_ops.placeholder(dtypes.int32, shape=[None, 1]) + logits = array_ops.placeholder(dtypes.float32, shape=[None, 3]) + ce = nn_ops.sparse_softmax_cross_entropy_with_logits_v2( + labels=array_ops.squeeze(labels), logits=logits) + labels_v2 = np.zeros((1, 1), dtype=np.int32) + logits_v2 = np.random.randn(1, 3) + sess.run([ce], feed_dict={labels: labels_v2, logits: logits_v2}) + + def testScalarHandling(self): + """This method is structured to be easily overridden by a child class.""" + self._testScalarHandling(expected_regex=".*labels must be 1-D.*") diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/profiler/internal/_pywrap_traceme.so b/videochat2/lib/python3.10/site-packages/tensorflow/python/profiler/internal/_pywrap_traceme.so new file mode 100644 index 0000000000000000000000000000000000000000..c3e7ad0eb0a89059c34fcf330d8a2ad00d285380 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/python/profiler/internal/_pywrap_traceme.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ef8fd8dd6ce0ba707eda4b604b05848c1c0f3d1b3541d094c53a1cb9a6e5d5ac +size 220304 diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/__init__.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4fc4d16cebdc7103b1cb211309d9b829fc7ad0f Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/__init__.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/api.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/api.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8257e947f0942b352fe4389245cb5e9d87fc628e Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/api.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/bfloat16.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/bfloat16.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e00cecb84b45e5d95f23e5329287dcab5d386e5a Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/bfloat16.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/datasets.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/datasets.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d649061e2079a2b574a316a2627c174962e621f Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/datasets.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/device_assignment.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/device_assignment.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..125f237c906010de5f30ee240d4437eb0d17c76d Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/device_assignment.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/feature_column.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/feature_column.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2881740566b74f45dcb32c2051870b8568e39ce0 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/feature_column.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/feature_column_v2.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/feature_column_v2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de23946ec8adddafaa9425ceeecb86f5ce33a990 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/feature_column_v2.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/functional.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/functional.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f329b957b1d5d119973a39736f89266cd5c216a0 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/functional.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tensor_tracer.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tensor_tracer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e389805a225cf3e790f23e34cd324dfeefaa116 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tensor_tracer.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tensor_tracer_flags.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tensor_tracer_flags.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0a1a55750a705678ce24bbde633f0544b4b9b93 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tensor_tracer_flags.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tensor_tracer_pb2.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tensor_tracer_pb2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e4ab49022991f2c96c83882b420ce8d9c940f0e Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tensor_tracer_pb2.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tensor_tracer_report.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tensor_tracer_report.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b1af62d1dc55fb368b5124b759841472242586f Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tensor_tracer_report.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/topology.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/topology.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ef70f4ecb776313424d007f368b37d942e24b12 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/topology.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06e0d536ef62bf0c96e0dd76e147ca6cbdf2e76c Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_embedding_base.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_embedding_base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ddbcd95ae853b62a310c624e72392fe8f361206 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_embedding_base.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_embedding_for_serving.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_embedding_for_serving.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8df0df35d84e3c5075ecc367d55313658decc68 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_embedding_for_serving.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_embedding_v1.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_embedding_v1.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0318a67aaaa5047fe50e8ad9906ab23a8e0b14e6 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_embedding_v1.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_embedding_v2.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_embedding_v2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9177daa178031c721d5fb95f445789b4b7317476 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_embedding_v2.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_embedding_v2_utils.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_embedding_v2_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3e24248f63cb89d9cc64b2edac0427c18c93416 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_embedding_v2_utils.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_embedding_v3.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_embedding_v3.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c39d7a2c6b5b18f76bfab31aea684fca118ffbd Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_embedding_v3.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_embedding_v3_utils.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_embedding_v3_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..835cb2ba826d87c36f471dc708bb83c329ab446d Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_embedding_v3_utils.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_feed.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_feed.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..548d7fdcaf18de3b7ee520d4a5b9927bca7324a3 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_feed.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_function.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_function.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd6f22970b9101a84298be7f3aca19a4e44f29cf Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_function.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_hardware_feature.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_hardware_feature.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..655cb8b4dedf8fb003475d274c3b7089e5bcc905 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_hardware_feature.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_name_util.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_name_util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b671067bf04153f3118155094a298e3c23ebf33 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_name_util.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_optimizer.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_optimizer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69ac64927e2b7409be520c7e5cbb30ebf66af1d1 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_optimizer.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_replication.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_replication.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a815ca91ab1572c9bc08164865403ec9c9877a9 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_replication.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_sharding.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_sharding.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ef2481ac233a75d84b293d4abb1290e847857fc Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_sharding.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_strategy_util.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_strategy_util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8b6aaa961541180082ec1985170d05089624774 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_strategy_util.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_system_metadata.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_system_metadata.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9698762a5df737064f3ce74f1c733562535332ee Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/tpu_system_metadata.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/training_loop.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/training_loop.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d051837d46a0bbc26c79b0410d332b1a5b7fe4ab Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/tensorflow/python/tpu/__pycache__/training_loop.cpython-310.pyc differ