Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +3 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/__init__.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/boosted_trees_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/candidate_sampling_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/clip_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/clustering_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/composite_tensor_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/control_flow_state.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/control_flow_v2_toggles.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/filesystem_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_collective_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_control_flow_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_count_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_decode_proto_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_io_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_nccl_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_ragged_array_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_random_index_shuffle_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_resource_variable_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_special_math_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_spectral_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_state_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_stateless_random_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_stateless_random_ops_v2.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_uniform_quant_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gradient_checker.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gradients_impl.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/image_grad.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/linalg_grad.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/nn.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/nn_impl_distribute.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/partitioned_variables.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/random_crop_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/resource_variables_toggle.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/script_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/session_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/sets.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/standard_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/state_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/stateful_random_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/stateless_random_ops.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/summary_ops_v2.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/ragged/__init__.py +28 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/ragged/__pycache__/ragged_autograph.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/ragged/__pycache__/ragged_squeeze_op.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/ragged/dynamic_ragged_shape.py +0 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_array_ops.py +1300 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_autograph.py +73 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_batch_gather_ops.py +60 -0
- videochat2/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_batch_gather_with_default_op.py +179 -0
.gitattributes
CHANGED
|
@@ -856,3 +856,6 @@ videochat2/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_tfprof.so
|
|
| 856 |
videochat2/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_determinism.so filter=lfs diff=lfs merge=lfs -text
|
| 857 |
videochat2/bin/python filter=lfs diff=lfs merge=lfs -text
|
| 858 |
videochat2/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_stat_summarizer.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
| 856 |
videochat2/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_determinism.so filter=lfs diff=lfs merge=lfs -text
|
| 857 |
videochat2/bin/python filter=lfs diff=lfs merge=lfs -text
|
| 858 |
videochat2/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_stat_summarizer.so filter=lfs diff=lfs merge=lfs -text
|
| 859 |
+
videochat2/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_checkpoint_reader.so filter=lfs diff=lfs merge=lfs -text
|
| 860 |
+
videochat2/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_kernel_registry.so filter=lfs diff=lfs merge=lfs -text
|
| 861 |
+
videochat2/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_util_port.so filter=lfs diff=lfs merge=lfs -text
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (177 Bytes). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/boosted_trees_ops.cpython-310.pyc
ADDED
|
Binary file (11.7 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/candidate_sampling_ops.cpython-310.pyc
ADDED
|
Binary file (23.1 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/clip_ops.cpython-310.pyc
ADDED
|
Binary file (13.8 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/clustering_ops.cpython-310.pyc
ADDED
|
Binary file (26.8 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/composite_tensor_ops.cpython-310.pyc
ADDED
|
Binary file (4.05 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/control_flow_state.cpython-310.pyc
ADDED
|
Binary file (21.6 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/control_flow_v2_toggles.cpython-310.pyc
ADDED
|
Binary file (2.16 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/filesystem_ops.cpython-310.pyc
ADDED
|
Binary file (782 Bytes). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_collective_ops.cpython-310.pyc
ADDED
|
Binary file (36.1 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_control_flow_ops.cpython-310.pyc
ADDED
|
Binary file (24.6 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_count_ops.cpython-310.pyc
ADDED
|
Binary file (11.2 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_decode_proto_ops.cpython-310.pyc
ADDED
|
Binary file (10.9 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_io_ops.cpython-310.pyc
ADDED
|
Binary file (61.6 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_nccl_ops.cpython-310.pyc
ADDED
|
Binary file (8.19 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_ragged_array_ops.cpython-310.pyc
ADDED
|
Binary file (16.1 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_random_index_shuffle_ops.cpython-310.pyc
ADDED
|
Binary file (4.69 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_resource_variable_ops.cpython-310.pyc
ADDED
|
Binary file (41.7 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_special_math_ops.cpython-310.pyc
ADDED
|
Binary file (11 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_spectral_ops.cpython-310.pyc
ADDED
|
Binary file (34.1 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_state_ops.cpython-310.pyc
ADDED
|
Binary file (58.3 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_stateless_random_ops.cpython-310.pyc
ADDED
|
Binary file (24.6 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_stateless_random_ops_v2.cpython-310.pyc
ADDED
|
Binary file (23.5 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gen_uniform_quant_ops.cpython-310.pyc
ADDED
|
Binary file (63.7 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gradient_checker.cpython-310.pyc
ADDED
|
Binary file (11.2 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/gradients_impl.cpython-310.pyc
ADDED
|
Binary file (17.7 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/image_grad.cpython-310.pyc
ADDED
|
Binary file (7.21 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/linalg_grad.cpython-310.pyc
ADDED
|
Binary file (26.2 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/nn.cpython-310.pyc
ADDED
|
Binary file (949 Bytes). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/nn_impl_distribute.cpython-310.pyc
ADDED
|
Binary file (4.23 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/partitioned_variables.cpython-310.pyc
ADDED
|
Binary file (12 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/random_crop_ops.cpython-310.pyc
ADDED
|
Binary file (4.24 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/resource_variables_toggle.cpython-310.pyc
ADDED
|
Binary file (2.98 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/script_ops.cpython-310.pyc
ADDED
|
Binary file (34 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/session_ops.cpython-310.pyc
ADDED
|
Binary file (9.79 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/sets.cpython-310.pyc
ADDED
|
Binary file (297 Bytes). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/standard_ops.cpython-310.pyc
ADDED
|
Binary file (4.09 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/state_ops.cpython-310.pyc
ADDED
|
Binary file (35 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/stateful_random_ops.cpython-310.pyc
ADDED
|
Binary file (34.7 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/stateless_random_ops.cpython-310.pyc
ADDED
|
Binary file (34.2 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/__pycache__/summary_ops_v2.cpython-310.pyc
ADDED
|
Binary file (49 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/ragged/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""Ragged Tensors.
|
| 16 |
+
|
| 17 |
+
This package defines ops for manipulating ragged tensors (`tf.RaggedTensor`),
|
| 18 |
+
which are tensors with non-uniform shapes. In particular, each `RaggedTensor`
|
| 19 |
+
has one or more *ragged dimensions*, which are dimensions whose slices may have
|
| 20 |
+
different lengths. For example, the inner (column) dimension of
|
| 21 |
+
`rt=[[3, 1, 4, 1], [], [5, 9, 2], [6], []]` is ragged, since the column slices
|
| 22 |
+
(`rt[0, :]`, ..., `rt[4, :]`) have different lengths. For a more detailed
|
| 23 |
+
description of ragged tensors, see the `tf.RaggedTensor` class documentation
|
| 24 |
+
and the [Ragged Tensor Guide](/guide/ragged_tensor).
|
| 25 |
+
|
| 26 |
+
API docstring: tensorflow.ragged
|
| 27 |
+
"""
|
| 28 |
+
from tensorflow.python.ops.ragged import ragged_tensor
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/ragged/__pycache__/ragged_autograph.cpython-310.pyc
ADDED
|
Binary file (1.96 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/ragged/__pycache__/ragged_squeeze_op.cpython-310.pyc
ADDED
|
Binary file (3.91 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/ragged/dynamic_ragged_shape.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_array_ops.py
ADDED
|
@@ -0,0 +1,1300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""Array operations for RaggedTensors."""
|
| 16 |
+
|
| 17 |
+
from typing import Optional
|
| 18 |
+
from typing import Union
|
| 19 |
+
|
| 20 |
+
from tensorflow.python.framework import dtypes
|
| 21 |
+
from tensorflow.python.framework import ops
|
| 22 |
+
from tensorflow.python.framework import sparse_tensor
|
| 23 |
+
from tensorflow.python.framework import tensor as tensor_lib
|
| 24 |
+
from tensorflow.python.framework import tensor_shape
|
| 25 |
+
from tensorflow.python.framework import tensor_util
|
| 26 |
+
from tensorflow.python.ops import array_ops
|
| 27 |
+
from tensorflow.python.ops import array_ops_stack
|
| 28 |
+
from tensorflow.python.ops import check_ops
|
| 29 |
+
from tensorflow.python.ops import control_flow_ops
|
| 30 |
+
from tensorflow.python.ops import data_flow_ops
|
| 31 |
+
from tensorflow.python.ops import gen_ragged_array_ops
|
| 32 |
+
from tensorflow.python.ops import math_ops
|
| 33 |
+
from tensorflow.python.ops import sort_ops
|
| 34 |
+
from tensorflow.python.ops.ragged import dynamic_ragged_shape
|
| 35 |
+
from tensorflow.python.ops.ragged import ragged_functional_ops
|
| 36 |
+
from tensorflow.python.ops.ragged import ragged_math_ops
|
| 37 |
+
from tensorflow.python.ops.ragged import ragged_tensor
|
| 38 |
+
from tensorflow.python.ops.ragged import ragged_util
|
| 39 |
+
from tensorflow.python.ops.ragged import segment_id_ops
|
| 40 |
+
from tensorflow.python.types import core as core_types
|
| 41 |
+
from tensorflow.python.util import dispatch
|
| 42 |
+
from tensorflow.python.util.tf_export import tf_export
|
| 43 |
+
|
| 44 |
+
# ===============================================================================
|
| 45 |
+
# Masking
|
| 46 |
+
# ===============================================================================
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@tf_export('ragged.boolean_mask')
|
| 50 |
+
@dispatch.add_dispatch_support
|
| 51 |
+
def boolean_mask(data, mask, name=None):
|
| 52 |
+
"""Applies a boolean mask to `data` without flattening the mask dimensions.
|
| 53 |
+
|
| 54 |
+
Returns a potentially ragged tensor that is formed by retaining the elements
|
| 55 |
+
in `data` where the corresponding value in `mask` is `True`.
|
| 56 |
+
|
| 57 |
+
* `output[a1...aA, i, b1...bB] = data[a1...aA, j, b1...bB]`
|
| 58 |
+
|
| 59 |
+
Where `j` is the `i`th `True` entry of `mask[a1...aA]`.
|
| 60 |
+
|
| 61 |
+
Note that `output` preserves the mask dimensions `a1...aA`; this differs
|
| 62 |
+
from `tf.boolean_mask`, which flattens those dimensions.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
data: A potentially ragged tensor.
|
| 66 |
+
mask: A potentially ragged boolean tensor. `mask`'s shape must be a prefix
|
| 67 |
+
of `data`'s shape. `rank(mask)` must be known statically.
|
| 68 |
+
name: A name prefix for the returned tensor (optional).
|
| 69 |
+
|
| 70 |
+
Returns:
|
| 71 |
+
A potentially ragged tensor that is formed by retaining the elements in
|
| 72 |
+
`data` where the corresponding value in `mask` is `True`.
|
| 73 |
+
|
| 74 |
+
* `rank(output) = rank(data)`.
|
| 75 |
+
* `output.ragged_rank = max(data.ragged_rank, rank(mask) - 1)`.
|
| 76 |
+
|
| 77 |
+
Raises:
|
| 78 |
+
ValueError: if `rank(mask)` is not known statically; or if `mask.shape` is
|
| 79 |
+
not a prefix of `data.shape`.
|
| 80 |
+
|
| 81 |
+
#### Examples:
|
| 82 |
+
|
| 83 |
+
>>> # Aliases for True & False so data and mask line up.
|
| 84 |
+
>>> T, F = (True, False)
|
| 85 |
+
|
| 86 |
+
>>> tf.ragged.boolean_mask( # Mask a 2D Tensor.
|
| 87 |
+
... data=[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
|
| 88 |
+
... mask=[[T, F, T], [F, F, F], [T, F, F]]).to_list()
|
| 89 |
+
[[1, 3], [], [7]]
|
| 90 |
+
|
| 91 |
+
>>> tf.ragged.boolean_mask( # Mask a 2D RaggedTensor.
|
| 92 |
+
... tf.ragged.constant([[1, 2, 3], [4], [5, 6]]),
|
| 93 |
+
... tf.ragged.constant([[F, F, T], [F], [T, T]])).to_list()
|
| 94 |
+
[[3], [], [5, 6]]
|
| 95 |
+
|
| 96 |
+
>>> tf.ragged.boolean_mask( # Mask rows of a 2D RaggedTensor.
|
| 97 |
+
... tf.ragged.constant([[1, 2, 3], [4], [5, 6]]),
|
| 98 |
+
... tf.ragged.constant([True, False, True])).to_list()
|
| 99 |
+
[[1, 2, 3], [5, 6]]
|
| 100 |
+
"""
|
| 101 |
+
with ops.name_scope(name, 'RaggedMask', [data, mask]):
|
| 102 |
+
# Convert inputs to tensors.
|
| 103 |
+
data = ragged_tensor.convert_to_tensor_or_ragged_tensor(data, name='data')
|
| 104 |
+
mask = ragged_tensor.convert_to_tensor_or_ragged_tensor(
|
| 105 |
+
mask, dtypes.bool, name='mask')
|
| 106 |
+
row_splits_dtype, (data, mask) = ragged_tensor.match_row_splits_dtypes(
|
| 107 |
+
data, mask, return_dtype=True)
|
| 108 |
+
|
| 109 |
+
# Get static rank of mask.
|
| 110 |
+
if mask.shape.ndims is None:
|
| 111 |
+
raise ValueError('mask.shape.ndims must be known statically.')
|
| 112 |
+
elif mask.shape.ndims == 0:
|
| 113 |
+
raise ValueError('mask cannot be scalar.')
|
| 114 |
+
|
| 115 |
+
# If mask is ragged, then recurse with a non-ragged mask.
|
| 116 |
+
if ragged_tensor.is_ragged(mask):
|
| 117 |
+
if not ragged_tensor.is_ragged(data):
|
| 118 |
+
data = ragged_tensor.RaggedTensor.from_tensor(
|
| 119 |
+
data,
|
| 120 |
+
ragged_rank=mask.ragged_rank,
|
| 121 |
+
row_splits_dtype=mask.row_splits.dtype)
|
| 122 |
+
# Check that mask.nested_row_splits is a prefix of
|
| 123 |
+
# data.nested_row_splits.
|
| 124 |
+
splits_list = [
|
| 125 |
+
mask.nested_row_splits, data.nested_row_splits[:mask.ragged_rank]
|
| 126 |
+
]
|
| 127 |
+
with ops.control_dependencies(
|
| 128 |
+
ragged_util.assert_splits_match(splits_list)):
|
| 129 |
+
# Strip off ragged `splits` until `mask` is non-ragged. Keep the splits
|
| 130 |
+
# that we strip off in `splits`, so we can add them back on after
|
| 131 |
+
# we recursively mask the non-ragged data.
|
| 132 |
+
splits = []
|
| 133 |
+
while ragged_tensor.is_ragged(mask):
|
| 134 |
+
if mask.shape.ndims > 2:
|
| 135 |
+
splits.append(mask.row_splits)
|
| 136 |
+
else:
|
| 137 |
+
# Count the number of True mask values in each row to find the
|
| 138 |
+
# lengths of the filtered rows; then convert to splits.
|
| 139 |
+
int_mask = ragged_functional_ops.map_flat_values(
|
| 140 |
+
math_ops.cast, mask, dtype=row_splits_dtype)
|
| 141 |
+
masked_row_lengths = ragged_math_ops.reduce_sum(int_mask, axis=1)
|
| 142 |
+
splits.append(ragged_util.lengths_to_splits(masked_row_lengths))
|
| 143 |
+
mask = mask.values
|
| 144 |
+
data = data.values
|
| 145 |
+
|
| 146 |
+
# Recursively apply the nested non-ragged mask to the nested data.
|
| 147 |
+
masked_values = boolean_mask(data, mask)
|
| 148 |
+
|
| 149 |
+
# Add the ragged `splits` back to the result.
|
| 150 |
+
masked_values = ragged_tensor.RaggedTensor.from_nested_row_splits(
|
| 151 |
+
masked_values, splits, validate=False)
|
| 152 |
+
|
| 153 |
+
return masked_values
|
| 154 |
+
|
| 155 |
+
# If mask is non-ragged and has rank 1, and data is ragged, then build a
|
| 156 |
+
# ragged tensor with the indicated rows.
|
| 157 |
+
elif ragged_tensor.is_ragged(data) and mask.shape.ndims == 1:
|
| 158 |
+
# Get the masked splits: first get the length of each row, then filter
|
| 159 |
+
# out the rows that we are deleting, and convert that filtered set of
|
| 160 |
+
# masks back to a splits tensor.
|
| 161 |
+
lengths = data.row_lengths()
|
| 162 |
+
masked_lengths = array_ops.boolean_mask(lengths, mask)
|
| 163 |
+
masked_splits = ragged_util.lengths_to_splits(masked_lengths)
|
| 164 |
+
|
| 165 |
+
# Get the masked values: first get row ids corresponding to each
|
| 166 |
+
# value, then use tf.gather to build a boolean mask that's false for
|
| 167 |
+
# values that come from rows that we are deleting, and use that mask to
|
| 168 |
+
# construct the masked values tensor.
|
| 169 |
+
segment_ids = segment_id_ops.row_splits_to_segment_ids(data.row_splits)
|
| 170 |
+
segment_mask = array_ops.gather(mask, segment_ids)
|
| 171 |
+
masked_values = boolean_mask(data.values, segment_mask)
|
| 172 |
+
|
| 173 |
+
return ragged_tensor.RaggedTensor.from_row_splits(
|
| 174 |
+
masked_values, masked_splits, validate=False)
|
| 175 |
+
|
| 176 |
+
# If mask is non-ragged and has rank>1, then convert it to be ragged,
|
| 177 |
+
# with a ragged rank matching data.
|
| 178 |
+
if ragged_tensor.is_ragged(data):
|
| 179 |
+
mask = ragged_tensor.RaggedTensor.from_tensor(
|
| 180 |
+
mask,
|
| 181 |
+
ragged_rank=min(data.ragged_rank, mask.shape.ndims - 1),
|
| 182 |
+
row_splits_dtype=data.row_splits.dtype)
|
| 183 |
+
return boolean_mask(data, mask)
|
| 184 |
+
|
| 185 |
+
# Otherwise, data and mask are both `Tensor`s.
|
| 186 |
+
else:
|
| 187 |
+
# Apply `boolean_mask` to get the masked values.
|
| 188 |
+
masked_values = array_ops.boolean_mask(data, mask)
|
| 189 |
+
|
| 190 |
+
if mask.shape.ndims >= 2:
|
| 191 |
+
# Add the innermost ragged dimension. For each innermost cell, get the
|
| 192 |
+
# number of values it contains. Then flatten that to get a list of
|
| 193 |
+
# cell lengths, and convert it to splits. Finally, combine the splits
|
| 194 |
+
# and values to get the innermost ragged tensor.
|
| 195 |
+
masked_lengths = math_ops.count_nonzero(
|
| 196 |
+
mask, axis=-1, dtype=row_splits_dtype)
|
| 197 |
+
flattened_masked_lengths = array_ops.reshape(masked_lengths, [-1])
|
| 198 |
+
masked_values = ragged_tensor.RaggedTensor.from_row_lengths(
|
| 199 |
+
masked_values, flattened_masked_lengths, validate=False)
|
| 200 |
+
|
| 201 |
+
# Wrap remaining ragged dimensions.
|
| 202 |
+
if mask.shape.ndims > 2:
|
| 203 |
+
mask_shape = array_ops.shape(mask, out_type=row_splits_dtype)
|
| 204 |
+
split_size = math_ops.cumprod(mask_shape) + 1
|
| 205 |
+
for dim in range(mask.shape.ndims - 3, -1, -1):
|
| 206 |
+
elt_size = mask_shape[dim + 1]
|
| 207 |
+
masked_splits = math_ops.range(split_size[dim]) * elt_size
|
| 208 |
+
masked_values = ragged_tensor.RaggedTensor.from_row_splits(
|
| 209 |
+
masked_values, masked_splits, validate=False)
|
| 210 |
+
|
| 211 |
+
return masked_values
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
# ===============================================================================
|
| 215 |
+
# Tiling
|
| 216 |
+
# ===============================================================================
|
| 217 |
+
@dispatch.dispatch_for_api(array_ops.tile)
|
| 218 |
+
def tile(input: ragged_tensor.Ragged, multiples, name=None): # pylint: disable=redefined-builtin
|
| 219 |
+
"""Constructs a `RaggedTensor` by tiling a given `RaggedTensor`.
|
| 220 |
+
|
| 221 |
+
The values of `input` are replicated `multiples[i]` times along the
|
| 222 |
+
`i`th dimension (for each dimension `i`). For every dimension `axis` in
|
| 223 |
+
`input`, the length of each output element in that dimension is the
|
| 224 |
+
length of corresponding input element multiplied by `multiples[axis]`.
|
| 225 |
+
|
| 226 |
+
Args:
|
| 227 |
+
input: A `RaggedTensor`.
|
| 228 |
+
multiples: A 1-D integer `Tensor`. Length must be the same as the number of
|
| 229 |
+
dimensions in `input`.
|
| 230 |
+
name: A name for the operation (optional).
|
| 231 |
+
|
| 232 |
+
Returns:
|
| 233 |
+
A `RaggedTensor` with the same type, rank, and ragged_rank as `input`.
|
| 234 |
+
|
| 235 |
+
#### Example:
|
| 236 |
+
|
| 237 |
+
>>> rt = tf.ragged.constant([[1, 2], [3]])
|
| 238 |
+
>>> tf.tile(rt, [3, 2]).to_list()
|
| 239 |
+
[[1, 2, 1, 2], [3, 3], [1, 2, 1, 2], [3, 3], [1, 2, 1, 2], [3, 3]]
|
| 240 |
+
"""
|
| 241 |
+
with ops.name_scope(name, 'RaggedTile', [input, multiples]):
|
| 242 |
+
input = ragged_tensor.convert_to_tensor_or_ragged_tensor(
|
| 243 |
+
input, name='input')
|
| 244 |
+
if not ragged_tensor.is_ragged(input):
|
| 245 |
+
return array_ops.tile(input, multiples, name)
|
| 246 |
+
multiples = ragged_util.convert_to_int_tensor(
|
| 247 |
+
multiples, name='multiples', dtype=input.row_splits.dtype)
|
| 248 |
+
multiples.shape.assert_has_rank(1)
|
| 249 |
+
|
| 250 |
+
# If the constant value of `multiples` is available, then we can use it
|
| 251 |
+
# to skip tiling dimensions where `multiples=1`.
|
| 252 |
+
const_multiples = tensor_util.constant_value(multiples)
|
| 253 |
+
|
| 254 |
+
return ragged_tensor.RaggedTensor.from_nested_row_splits(
|
| 255 |
+
_tile_ragged_values(input, multiples, const_multiples),
|
| 256 |
+
_tile_ragged_splits(input, multiples, const_multiples),
|
| 257 |
+
validate=False)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def _tile_ragged_values(rt_input, multiples, const_multiples=None):
|
| 261 |
+
"""Builds flat_values tensor for a tiled `RaggedTensor`.
|
| 262 |
+
|
| 263 |
+
Returns a tensor that repeats the values in
|
| 264 |
+
`rt_input.flat_values` in the
|
| 265 |
+
appropriate pattern to construct a `RaggedTensor` that tiles `rt_input` as
|
| 266 |
+
specified by `multiples`.
|
| 267 |
+
|
| 268 |
+
Args:
|
| 269 |
+
rt_input: The `RaggedTensor` whose values should be repeated.
|
| 270 |
+
multiples: A 1-D integer `tensor`, indicating how many times each dimension
|
| 271 |
+
should be repeated.
|
| 272 |
+
const_multiples: Optional constant value for multiples. Used to skip tiling
|
| 273 |
+
dimensions where `multiples=1`.
|
| 274 |
+
|
| 275 |
+
Returns:
|
| 276 |
+
A `Tensor` with the same type and rank as `rt_input.flat_values`.
|
| 277 |
+
|
| 278 |
+
#### Example:
|
| 279 |
+
|
| 280 |
+
>>> rt = tf.ragged.constant([[1, 2], [3]])
|
| 281 |
+
>>> _tile_ragged_values(rt, tf.constant([3, 2])).numpy()
|
| 282 |
+
array([1, 2, 1, 2, 3, 3, 1, 2, 1, 2, 3, 3, 1, 2, 1, 2, 3, 3], dtype=int32)
|
| 283 |
+
"""
|
| 284 |
+
ragged_rank = rt_input.ragged_rank
|
| 285 |
+
nested_splits = rt_input.nested_row_splits
|
| 286 |
+
|
| 287 |
+
# Pointers to the values in `rt_input.flat_values`.
|
| 288 |
+
inner_value_ids = math_ops.range(nested_splits[-1][-1])
|
| 289 |
+
|
| 290 |
+
# For each ragged dimension (working from the innermost to outermost),
|
| 291 |
+
# expand `inner_value_ids` as necessary to tile that dimension.
|
| 292 |
+
prev_splits = None
|
| 293 |
+
for axis in range(ragged_rank, 0, -1):
|
| 294 |
+
# Ragged splits for this dimension.
|
| 295 |
+
splits = nested_splits[axis - 1]
|
| 296 |
+
|
| 297 |
+
# Adjust splits so they point into `inner_value_ids` (instead of just
|
| 298 |
+
# pointing into the next dimension's values).
|
| 299 |
+
if prev_splits is not None: # Not the first pass through the loop.
|
| 300 |
+
splits = array_ops.gather(prev_splits * multiples[axis + 1], splits)
|
| 301 |
+
|
| 302 |
+
# Repeat each element in this ragged dimension `multiples[axis]` times.
|
| 303 |
+
if const_multiples is None or const_multiples[axis] != 1:
|
| 304 |
+
inner_value_ids = ragged_util.repeat_ranges(inner_value_ids, splits,
|
| 305 |
+
multiples[axis])
|
| 306 |
+
|
| 307 |
+
prev_splits = splits
|
| 308 |
+
|
| 309 |
+
# Gather the tiled inner values.
|
| 310 |
+
ragged_tiled_values = array_ops.gather(rt_input.flat_values, inner_value_ids)
|
| 311 |
+
|
| 312 |
+
# Tile the flat_values for the uniform dimensions (i.e., for `axis=0` plus
|
| 313 |
+
# `axis=range(ragged_rank, rank)`).
|
| 314 |
+
inner_repeats = array_ops.concat([multiples[:1], multiples[ragged_rank + 1:]],
|
| 315 |
+
axis=0)
|
| 316 |
+
return array_ops.tile(ragged_tiled_values, inner_repeats)
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def _tile_ragged_splits(rt_input, multiples, const_multiples=None):
|
| 320 |
+
"""Builds nested_split tensors for a tiled `RaggedTensor`.
|
| 321 |
+
|
| 322 |
+
Returns a list of split tensors that can be used to construct the
|
| 323 |
+
`RaggedTensor` that tiles `rt_input` as specified by `multiples`.
|
| 324 |
+
|
| 325 |
+
Args:
|
| 326 |
+
rt_input: The `RaggedTensor` that is being tiled.
|
| 327 |
+
multiples: A 1-D integer `tensor`, indicating how many times each dimension
|
| 328 |
+
should be repeated.
|
| 329 |
+
const_multiples: Optional constant value for multiples. Used to skip tiling
|
| 330 |
+
dimensions where `multiples=1`.
|
| 331 |
+
|
| 332 |
+
Returns:
|
| 333 |
+
A list of 1-D integer `Tensor`s (one for each ragged dimension in
|
| 334 |
+
`rt_input`).
|
| 335 |
+
|
| 336 |
+
#### Example:
|
| 337 |
+
|
| 338 |
+
>>> rt = tf.ragged.constant([[1, 2], [3]])
|
| 339 |
+
>>> _tile_ragged_splits(rt, [3, 2])
|
| 340 |
+
[<tf.Tensor: shape=(7,), dtype=int64,
|
| 341 |
+
numpy=array([ 0, 4, 6, 10, 12, 16, 18])>]
|
| 342 |
+
"""
|
| 343 |
+
ragged_rank = rt_input.ragged_rank
|
| 344 |
+
nested_splits = rt_input.nested_row_splits
|
| 345 |
+
|
| 346 |
+
# projected_splits[src_axis, dst_axis] contains the split points that divide
|
| 347 |
+
# the rows from src_axis in the list of dst_axis values. E.g.,
|
| 348 |
+
# projected_splits[i, i] = nested_splits[i], and
|
| 349 |
+
# projected_splits[i, i+1] = gather(nested_splits[i+1], nested_splits[i]).
|
| 350 |
+
projected_splits = [{i: nested_splits[i]} for i in range(ragged_rank)]
|
| 351 |
+
for src_axis in range(ragged_rank):
|
| 352 |
+
for dst_axis in range(src_axis + 1, ragged_rank - 1):
|
| 353 |
+
projected_splits[src_axis][dst_axis] = array_ops.gather(
|
| 354 |
+
nested_splits[dst_axis], projected_splits[src_axis][dst_axis - 1])
|
| 355 |
+
|
| 356 |
+
# For each ragged dimension: nested_splits[axis] -> result_splits[axis].
|
| 357 |
+
result_splits = []
|
| 358 |
+
for axis in range(ragged_rank):
|
| 359 |
+
# Get the length of each row for the input tensor for this dimension.
|
| 360 |
+
input_lengths = nested_splits[axis][1:] - nested_splits[axis][:-1]
|
| 361 |
+
|
| 362 |
+
# Multiply those lengths by the `multiples` of dimension axis+1, since
|
| 363 |
+
# each value will be repeated that number of times.
|
| 364 |
+
output_lengths = input_lengths * multiples[axis + 1]
|
| 365 |
+
|
| 366 |
+
# Repeat ranges of the row lengths as necessary for them to be tiled in
|
| 367 |
+
# each ragged dimension `d < axis`. (Start with dimension d=axis-1, and
|
| 368 |
+
# work our way up to dimension d=0.)
|
| 369 |
+
repeats = 1
|
| 370 |
+
for d in range(axis - 1, -1, -1):
|
| 371 |
+
if const_multiples is None or const_multiples[d + 1] != 1:
|
| 372 |
+
splits = projected_splits[d][axis - 1] * repeats
|
| 373 |
+
output_lengths = ragged_util.repeat_ranges(output_lengths, splits,
|
| 374 |
+
multiples[d + 1])
|
| 375 |
+
repeats *= multiples[d + 1]
|
| 376 |
+
|
| 377 |
+
# Tile splits for the outermost (uniform) dimension.
|
| 378 |
+
output_lengths = array_ops.tile(output_lengths, multiples[:1])
|
| 379 |
+
|
| 380 |
+
# Convert to splits.
|
| 381 |
+
result_splits.append(ragged_util.lengths_to_splits(output_lengths))
|
| 382 |
+
|
| 383 |
+
return result_splits
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
# ===============================================================================
|
| 387 |
+
# Reshaping
|
| 388 |
+
# ===============================================================================
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
@dispatch.dispatch_for_api(array_ops.expand_dims_v2)
|
| 392 |
+
def expand_dims(input: ragged_tensor.Ragged, axis, name=None): # pylint: disable=redefined-builtin
|
| 393 |
+
"""Inserts a dimension with shape 1 into a potentially ragged tensor's shape.
|
| 394 |
+
|
| 395 |
+
Given a potentially ragged tenor `input`, this operation inserts a
|
| 396 |
+
dimension with size 1 at the dimension `axis` of `input`'s shape.
|
| 397 |
+
|
| 398 |
+
The following table gives some examples showing how `ragged.expand_dims`
|
| 399 |
+
impacts the shapes of different input tensors. Ragged dimensions are
|
| 400 |
+
indicated by enclosing them in parentheses.
|
| 401 |
+
|
| 402 |
+
input.shape | axis | result.shape
|
| 403 |
+
----------------------- | ---- | -----------------------------
|
| 404 |
+
`[D1, D2]` | `0` | `[1, D1, D2]`
|
| 405 |
+
`[D1, D2]` | `1` | `[D1, 1, D2]`
|
| 406 |
+
`[D1, D2]` | `2` | `[D1, D2, 1]`
|
| 407 |
+
`[D1, (D2), (D3), D4]` | `0` | `[1, D1, (D2), (D3), D4]`
|
| 408 |
+
`[D1, (D2), (D3), D4]` | `1` | `[D1, 1, (D2), (D3), D4]`
|
| 409 |
+
`[D1, (D2), (D3), D4]` | `2` | `[D1, (D2), 1, (D3), D4]`
|
| 410 |
+
`[D1, (D2), (D3), D4]` | `3` | `[D1, (D2), (D3), 1, D4]`
|
| 411 |
+
`[D1, (D2), (D3), D4]` | `4` | `[D1, (D2), (D3), D4, 1]`
|
| 412 |
+
|
| 413 |
+
Args:
|
| 414 |
+
input: The potentially tensor that should be expanded with a new dimension.
|
| 415 |
+
axis: An integer constant indicating where the new dimension should be
|
| 416 |
+
inserted.
|
| 417 |
+
name: A name for the operation (optional).
|
| 418 |
+
|
| 419 |
+
Returns:
|
| 420 |
+
A tensor with the same values as `input`, with an added dimension of
|
| 421 |
+
size 1 at `axis`.
|
| 422 |
+
|
| 423 |
+
#### Examples:
|
| 424 |
+
|
| 425 |
+
>>> rt = tf.ragged.constant([[1, 2], [3]])
|
| 426 |
+
>>> print(rt.shape)
|
| 427 |
+
(2, None)
|
| 428 |
+
|
| 429 |
+
>>> expanded = tf.expand_dims(rt, axis=0)
|
| 430 |
+
>>> print(expanded.shape, expanded)
|
| 431 |
+
(1, 2, None) <tf.RaggedTensor [[[1, 2], [3]]]>
|
| 432 |
+
|
| 433 |
+
>>> expanded = tf.expand_dims(rt, axis=1)
|
| 434 |
+
>>> print(expanded.shape, expanded)
|
| 435 |
+
(2, 1, None) <tf.RaggedTensor [[[1, 2]], [[3]]]>
|
| 436 |
+
|
| 437 |
+
>>> expanded = tf.expand_dims(rt, axis=2)
|
| 438 |
+
>>> print(expanded.shape, expanded)
|
| 439 |
+
(2, None, 1) <tf.RaggedTensor [[[1], [2]], [[3]]]>
|
| 440 |
+
"""
|
| 441 |
+
with ops.name_scope(name, 'RaggedExpandDims', [input]):
|
| 442 |
+
input = ragged_tensor.convert_to_tensor_or_ragged_tensor(
|
| 443 |
+
input, name='input')
|
| 444 |
+
|
| 445 |
+
if not ragged_tensor.is_ragged(input):
|
| 446 |
+
return array_ops.expand_dims(input, axis)
|
| 447 |
+
|
| 448 |
+
ndims = None if input.shape.ndims is None else input.shape.ndims + 1
|
| 449 |
+
axis = array_ops.get_positive_axis(axis, ndims, ndims_name='rank(input)')
|
| 450 |
+
|
| 451 |
+
if axis == 0:
|
| 452 |
+
return ragged_tensor.RaggedTensor.from_uniform_row_length(
|
| 453 |
+
input, uniform_row_length=input.nrows(), nrows=1, validate=False)
|
| 454 |
+
elif axis == 1:
|
| 455 |
+
return ragged_tensor.RaggedTensor.from_uniform_row_length(
|
| 456 |
+
input, uniform_row_length=1, nrows=input.nrows(), validate=False)
|
| 457 |
+
else:
|
| 458 |
+
if ragged_tensor.is_ragged(input.values):
|
| 459 |
+
return input.with_values(expand_dims(input.values, axis - 1))
|
| 460 |
+
else:
|
| 461 |
+
return input.with_values(array_ops.expand_dims(input.values, axis - 1))
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
@dispatch.dispatch_for_api(array_ops.expand_dims)
|
| 465 |
+
def _ragged_expand_dims_v1(
|
| 466 |
+
input: ragged_tensor.Ragged, # pylint: disable=redefined-builtin
|
| 467 |
+
axis=None,
|
| 468 |
+
name=None,
|
| 469 |
+
dim=None):
|
| 470 |
+
if dim is not None:
|
| 471 |
+
axis = dim
|
| 472 |
+
return expand_dims(input=input, axis=axis, name=name)
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
# ===============================================================================
|
| 476 |
+
# RaggedTensor Size
|
| 477 |
+
# ===============================================================================
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
@dispatch.dispatch_for_api(array_ops.size_v2)
|
| 481 |
+
def size(input: ragged_tensor.Ragged, out_type=dtypes.int32, name=None): # pylint: disable=redefined-builtin
|
| 482 |
+
"""Returns the size of a potentially ragged tensor.
|
| 483 |
+
|
| 484 |
+
The size of a ragged tensor is the size of its inner values.
|
| 485 |
+
|
| 486 |
+
#### Example:
|
| 487 |
+
|
| 488 |
+
>>> tf.size(tf.ragged.constant([[1, 2], [3]])).numpy()
|
| 489 |
+
3
|
| 490 |
+
|
| 491 |
+
Args:
|
| 492 |
+
input: A potentially ragged `Tensor`.
|
| 493 |
+
out_type: The numeric output type for the operation.
|
| 494 |
+
name: A name for the operation (optional).
|
| 495 |
+
|
| 496 |
+
Returns:
|
| 497 |
+
A Tensor of type `out_type`.
|
| 498 |
+
"""
|
| 499 |
+
if ragged_tensor.is_ragged(input):
|
| 500 |
+
return array_ops.size(input.flat_values, out_type=out_type, name=name)
|
| 501 |
+
else:
|
| 502 |
+
return array_ops.size(input, out_type=out_type, name=name)
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
@dispatch.dispatch_for_api(array_ops.size)
|
| 506 |
+
def _ragged_size_v1(
|
| 507 |
+
input: ragged_tensor.Ragged, # pylint: disable=redefined-builtin
|
| 508 |
+
name=None,
|
| 509 |
+
out_type=dtypes.int32):
|
| 510 |
+
return size(input=input, out_type=out_type, name=name)
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
# ===============================================================================
|
| 514 |
+
# ragged.rank
|
| 515 |
+
# ===============================================================================
|
| 516 |
+
@dispatch.dispatch_for_api(array_ops.rank)
|
| 517 |
+
def rank(input: ragged_tensor.Ragged, name=None): # pylint: disable=redefined-builtin
|
| 518 |
+
"""Returns the rank of a RaggedTensor.
|
| 519 |
+
|
| 520 |
+
Returns a 0-D `int32` `Tensor` representing the rank of `input`.
|
| 521 |
+
|
| 522 |
+
#### Example:
|
| 523 |
+
|
| 524 |
+
>>> # shape of tensor 't' is [2, None, None]
|
| 525 |
+
>>> t = tf.ragged.constant([[[1], [2, 2]], [[3, 3, 3], [4, 4, 4, 4]]])
|
| 526 |
+
>>> tf.rank(t).numpy()
|
| 527 |
+
3
|
| 528 |
+
|
| 529 |
+
Args:
|
| 530 |
+
input: A `RaggedTensor`
|
| 531 |
+
name: A name for the operation (optional).
|
| 532 |
+
|
| 533 |
+
Returns:
|
| 534 |
+
A `Tensor` of type `int32`.
|
| 535 |
+
"""
|
| 536 |
+
with ops.name_scope(name, 'RaggedRank', [input]) as name:
|
| 537 |
+
if not ragged_tensor.is_ragged(input):
|
| 538 |
+
return array_ops.rank(input, name)
|
| 539 |
+
|
| 540 |
+
return input.ragged_rank + array_ops.rank(input.flat_values)
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
# ===============================================================================
|
| 544 |
+
# ragged.one_hot
|
| 545 |
+
# ===============================================================================
|
| 546 |
+
@dispatch.dispatch_for_api(array_ops.one_hot)
|
| 547 |
+
def ragged_one_hot(indices: ragged_tensor.Ragged,
|
| 548 |
+
depth,
|
| 549 |
+
on_value=None,
|
| 550 |
+
off_value=None,
|
| 551 |
+
axis=None,
|
| 552 |
+
dtype=None,
|
| 553 |
+
name=None):
|
| 554 |
+
"""Applies tf.one_hot along the values of a RaggedTensor."""
|
| 555 |
+
# Get the adjusted axis value for the call to array_ops.one_hot.
|
| 556 |
+
# Note: the only negative `axis` value supported by array_ops.one_hot is -1.
|
| 557 |
+
if isinstance(axis, int) and axis >= 0:
|
| 558 |
+
if axis <= indices.ragged_rank:
|
| 559 |
+
raise ValueError('axis (%d) must be greater than indices.ragged_rank '
|
| 560 |
+
'(%d).' % (axis, indices.ragged_rank))
|
| 561 |
+
axis -= indices.ragged_rank
|
| 562 |
+
|
| 563 |
+
with ops.name_scope(name, 'RaggedOneHot',
|
| 564 |
+
[indices, depth, on_value, off_value, axis]):
|
| 565 |
+
indices = ragged_tensor.convert_to_tensor_or_ragged_tensor(
|
| 566 |
+
indices, name='indices')
|
| 567 |
+
return indices.with_flat_values(
|
| 568 |
+
array_ops.one_hot(indices.flat_values, depth, on_value, off_value, axis,
|
| 569 |
+
dtype, name))
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
# ===============================================================================
|
| 573 |
+
# ragged.stack_dynamic_partitions
|
| 574 |
+
# ===============================================================================
|
| 575 |
+
@tf_export('ragged.stack_dynamic_partitions')
|
| 576 |
+
@dispatch.add_dispatch_support
|
| 577 |
+
def stack_dynamic_partitions(data, partitions, num_partitions, name=None):
|
| 578 |
+
"""Stacks dynamic partitions of a Tensor or RaggedTensor.
|
| 579 |
+
|
| 580 |
+
Returns a RaggedTensor `output` with `num_partitions` rows, where the row
|
| 581 |
+
`output[i]` is formed by stacking all slices `data[j1...jN]` such that
|
| 582 |
+
`partitions[j1...jN] = i`. Slices of `data` are stacked in row-major
|
| 583 |
+
order.
|
| 584 |
+
|
| 585 |
+
If `num_partitions` is an `int` (not a `Tensor`), then this is equivalent to
|
| 586 |
+
`tf.ragged.stack(tf.dynamic_partition(data, partitions, num_partitions))`.
|
| 587 |
+
|
| 588 |
+
#### Example:
|
| 589 |
+
|
| 590 |
+
>>> data = ['a', 'b', 'c', 'd', 'e']
|
| 591 |
+
>>> partitions = [ 3, 0, 2, 2, 3]
|
| 592 |
+
>>> num_partitions = 5
|
| 593 |
+
>>> tf.ragged.stack_dynamic_partitions(data, partitions, num_partitions)
|
| 594 |
+
<tf.RaggedTensor [[b'b'], [], [b'c', b'd'], [b'a', b'e'], []]>
|
| 595 |
+
|
| 596 |
+
Args:
|
| 597 |
+
data: A `Tensor` or `RaggedTensor` containing the values to stack.
|
| 598 |
+
partitions: An `int32` or `int64` `Tensor` or `RaggedTensor` specifying the
|
| 599 |
+
partition that each slice of `data` should be added to. `partitions.shape`
|
| 600 |
+
must be a prefix of `data.shape`. Values must be greater than or equal to
|
| 601 |
+
zero, and less than `num_partitions`. `partitions` is not required to be
|
| 602 |
+
sorted.
|
| 603 |
+
num_partitions: An `int32` or `int64` scalar specifying the number of
|
| 604 |
+
partitions to output. This determines the number of rows in `output`.
|
| 605 |
+
name: A name prefix for the returned tensor (optional).
|
| 606 |
+
|
| 607 |
+
Returns:
|
| 608 |
+
A `RaggedTensor` containing the stacked partitions. The returned tensor
|
| 609 |
+
has the same dtype as `data`, and its shape is
|
| 610 |
+
`[num_partitions, (D)] + data.shape[partitions.rank:]`, where `(D)` is a
|
| 611 |
+
ragged dimension whose length is the number of data slices stacked for
|
| 612 |
+
each `partition`.
|
| 613 |
+
"""
|
| 614 |
+
with ops.name_scope(name, 'SegmentStack', [data, partitions, num_partitions]):
|
| 615 |
+
# Convert inputs to tensors.
|
| 616 |
+
data = ragged_tensor.convert_to_tensor_or_ragged_tensor(data, name='data')
|
| 617 |
+
row_splits_dtype = (
|
| 618 |
+
data.row_splits.dtype
|
| 619 |
+
if isinstance(data, ragged_tensor.RaggedTensor) else None)
|
| 620 |
+
partitions = ragged_tensor.convert_to_tensor_or_ragged_tensor(
|
| 621 |
+
partitions, name='partitions', preferred_dtype=row_splits_dtype)
|
| 622 |
+
num_partitions = ops.convert_to_tensor(
|
| 623 |
+
num_partitions, name='num_partitions', preferred_dtype=partitions.dtype)
|
| 624 |
+
if row_splits_dtype is not None:
|
| 625 |
+
partitions = math_ops.cast(partitions, row_splits_dtype)
|
| 626 |
+
num_partitions = math_ops.cast(num_partitions, partitions.dtype)
|
| 627 |
+
|
| 628 |
+
# Sanity-checks for shapes.
|
| 629 |
+
partitions_rank = partitions.shape.ndims
|
| 630 |
+
if partitions_rank is None:
|
| 631 |
+
raise ValueError('partitions must have known rank.')
|
| 632 |
+
num_partitions.shape.assert_has_rank(0)
|
| 633 |
+
partitions.shape.assert_is_compatible_with(data.shape[:partitions_rank])
|
| 634 |
+
|
| 635 |
+
if partitions_rank == 0:
|
| 636 |
+
# If partitions is a scalar, then just create a RaggedTensor containing
|
| 637 |
+
# that single the complete `data` value in the specified row.
|
| 638 |
+
return ragged_tensor.RaggedTensor.from_value_rowids(
|
| 639 |
+
values=array_ops_stack.stack([data]),
|
| 640 |
+
value_rowids=array_ops_stack.stack([partitions]),
|
| 641 |
+
nrows=num_partitions,
|
| 642 |
+
validate=False)
|
| 643 |
+
|
| 644 |
+
elif partitions_rank == 1:
|
| 645 |
+
# If partitions is a vector (the typical case): we can just use data and
|
| 646 |
+
# partitions as the `values` and `value_rowids` for `from_value_rowids`,
|
| 647 |
+
# as long as we sort them first.
|
| 648 |
+
permutation = sort_ops.argsort(partitions, stable=True)
|
| 649 |
+
value_rowids = array_ops.gather(partitions, permutation)
|
| 650 |
+
values = array_ops.gather(data, permutation)
|
| 651 |
+
checks = [
|
| 652 |
+
check_ops.assert_less(
|
| 653 |
+
value_rowids[-1:], num_partitions,
|
| 654 |
+
message='partitions must be less than num_partitions'),
|
| 655 |
+
check_ops.assert_non_negative(
|
| 656 |
+
partitions, message='partitions must be non-negative.')
|
| 657 |
+
]
|
| 658 |
+
with ops.control_dependencies(checks):
|
| 659 |
+
return ragged_tensor.RaggedTensor.from_value_rowids(
|
| 660 |
+
values, value_rowids, nrows=num_partitions, validate=False)
|
| 661 |
+
|
| 662 |
+
else:
|
| 663 |
+
# Handle higher-dimensional partitions via recursion.
|
| 664 |
+
if not isinstance(data, ragged_tensor.RaggedTensor):
|
| 665 |
+
data = ragged_tensor.RaggedTensor.from_tensor(
|
| 666 |
+
data, row_splits_dtype=partitions.dtype, ragged_rank=1)
|
| 667 |
+
if not isinstance(partitions, ragged_tensor.RaggedTensor):
|
| 668 |
+
partitions = ragged_tensor.RaggedTensor.from_tensor(
|
| 669 |
+
partitions,
|
| 670 |
+
row_splits_dtype=partitions.dtype,
|
| 671 |
+
ragged_rank=max(data.ragged_rank, partitions_rank - 1))
|
| 672 |
+
check = check_ops.assert_equal(
|
| 673 |
+
data.row_splits,
|
| 674 |
+
partitions.row_splits,
|
| 675 |
+
message='data and partitions have incompatible ragged shapes')
|
| 676 |
+
with ops.control_dependencies([check]):
|
| 677 |
+
return stack_dynamic_partitions(data.values, partitions.values,
|
| 678 |
+
num_partitions)
|
| 679 |
+
|
| 680 |
+
|
| 681 |
+
# ===============================================================================
|
| 682 |
+
# Reverse
|
| 683 |
+
# ===============================================================================
|
| 684 |
+
@dispatch.dispatch_for_api(array_ops.reverse)
|
| 685 |
+
def reverse(tensor: ragged_tensor.Ragged, axis, name=None):
|
| 686 |
+
"""Reverses a RaggedTensor along the specified axes.
|
| 687 |
+
|
| 688 |
+
#### Example:
|
| 689 |
+
|
| 690 |
+
>>> data = tf.ragged.constant([
|
| 691 |
+
... [[1, 2], [3, 4]], [[5, 6]], [[7, 8], [9, 10], [11, 12]]])
|
| 692 |
+
>>> tf.reverse(data, axis=[0, 2])
|
| 693 |
+
<tf.RaggedTensor [[[8, 7], [10, 9], [12, 11]], [[6, 5]], [[2, 1], [4, 3]]]>
|
| 694 |
+
|
| 695 |
+
Args:
|
| 696 |
+
tensor: A 'RaggedTensor' to reverse.
|
| 697 |
+
axis: A list or tuple of 'int' or a constant 1D 'tf.Tensor'. The indices of
|
| 698 |
+
the axes to reverse.
|
| 699 |
+
name: A name prefix for the returned tensor (optional).
|
| 700 |
+
|
| 701 |
+
Returns:
|
| 702 |
+
A 'RaggedTensor'.
|
| 703 |
+
"""
|
| 704 |
+
type_error_msg = ('`axis` must be a list of int or a constant tensor'
|
| 705 |
+
'when reversing axes in a ragged tensor')
|
| 706 |
+
|
| 707 |
+
with ops.name_scope(name, 'Reverse', [tensor, axis]):
|
| 708 |
+
if isinstance(axis, tensor_lib.Tensor):
|
| 709 |
+
axis = tensor_util.constant_value(axis)
|
| 710 |
+
if axis is None:
|
| 711 |
+
raise TypeError(type_error_msg)
|
| 712 |
+
elif not (isinstance(axis, (list, tuple)) and
|
| 713 |
+
all(isinstance(dim, int) for dim in axis)):
|
| 714 |
+
raise TypeError(type_error_msg)
|
| 715 |
+
|
| 716 |
+
tensor = ragged_tensor.convert_to_tensor_or_ragged_tensor(
|
| 717 |
+
tensor, name='tensor')
|
| 718 |
+
|
| 719 |
+
# Allow usage of negative values to specify innermost axes.
|
| 720 |
+
axis = [
|
| 721 |
+
array_ops.get_positive_axis(dim, tensor.shape.rank, 'axis[%d]' % i,
|
| 722 |
+
'rank(tensor)')
|
| 723 |
+
for i, dim in enumerate(axis)
|
| 724 |
+
]
|
| 725 |
+
|
| 726 |
+
# We only need to slice up to the max axis. If the axis list
|
| 727 |
+
# is empty, it should be 0.
|
| 728 |
+
slices = [slice(None)] * (max(axis) + 1 if axis else 0)
|
| 729 |
+
|
| 730 |
+
for dim in axis:
|
| 731 |
+
slices[dim] = slice(None, None, -1)
|
| 732 |
+
|
| 733 |
+
return tensor[tuple(slices)]
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
# ===============================================================================
|
| 737 |
+
# Cross
|
| 738 |
+
# ===============================================================================
|
| 739 |
+
|
| 740 |
+
|
| 741 |
+
@tf_export('ragged.cross')
|
| 742 |
+
@dispatch.add_dispatch_support
|
| 743 |
+
def cross(inputs, name=None):
|
| 744 |
+
"""Generates feature cross from a list of tensors.
|
| 745 |
+
|
| 746 |
+
The input tensors must have `rank=2`, and must all have the same number of
|
| 747 |
+
rows. The result is a `RaggedTensor` with the same number of rows as the
|
| 748 |
+
inputs, where `result[row]` contains a list of all combinations of values
|
| 749 |
+
formed by taking a single value from each input's corresponding row
|
| 750 |
+
(`inputs[i][row]`). Values are combined by joining their strings with '_X_'.
|
| 751 |
+
E.g.:
|
| 752 |
+
|
| 753 |
+
>>> tf.ragged.cross([tf.ragged.constant([['a'], ['b', 'c']]),
|
| 754 |
+
... tf.ragged.constant([['d'], ['e']]),
|
| 755 |
+
... tf.ragged.constant([['f'], ['g']])])
|
| 756 |
+
<tf.RaggedTensor [[b'a_X_d_X_f'], [b'b_X_e_X_g', b'c_X_e_X_g']]>
|
| 757 |
+
|
| 758 |
+
Args:
|
| 759 |
+
inputs: A list of `RaggedTensor` or `Tensor` or `SparseTensor`.
|
| 760 |
+
name: Optional name for the op.
|
| 761 |
+
|
| 762 |
+
Returns:
|
| 763 |
+
A 2D `RaggedTensor` of type `string`.
|
| 764 |
+
"""
|
| 765 |
+
return _cross_internal(inputs=inputs, hashed_output=False, name=name)
|
| 766 |
+
|
| 767 |
+
|
| 768 |
+
@tf_export('ragged.cross_hashed')
|
| 769 |
+
@dispatch.add_dispatch_support
|
| 770 |
+
def cross_hashed(inputs, num_buckets=0, hash_key=None, name=None):
|
| 771 |
+
"""Generates hashed feature cross from a list of tensors.
|
| 772 |
+
|
| 773 |
+
The input tensors must have `rank=2`, and must all have the same number of
|
| 774 |
+
rows. The result is a `RaggedTensor` with the same number of rows as the
|
| 775 |
+
inputs, where `result[row]` contains a list of all combinations of values
|
| 776 |
+
formed by taking a single value from each input's corresponding row
|
| 777 |
+
(`inputs[i][row]`). Values are combined by hashing together their
|
| 778 |
+
fingerprints. E.g.:
|
| 779 |
+
|
| 780 |
+
>>> tf.ragged.cross_hashed([tf.ragged.constant([['a'], ['b', 'c']]),
|
| 781 |
+
... tf.ragged.constant([['d'], ['e']]),
|
| 782 |
+
... tf.ragged.constant([['f'], ['g']])],
|
| 783 |
+
... num_buckets=100)
|
| 784 |
+
<tf.RaggedTensor [[78], [66, 74]]>
|
| 785 |
+
|
| 786 |
+
Args:
|
| 787 |
+
inputs: A list of `RaggedTensor` or `Tensor` or `SparseTensor`.
|
| 788 |
+
num_buckets: A non-negative `int` that used to bucket the hashed values. If
|
| 789 |
+
`num_buckets != 0`, then `output = hashed_value % num_buckets`.
|
| 790 |
+
hash_key: Integer hash_key that will be used by the `FingerprintCat64`
|
| 791 |
+
function. If not given, a default key is used.
|
| 792 |
+
name: Optional name for the op.
|
| 793 |
+
|
| 794 |
+
Returns:
|
| 795 |
+
A 2D `RaggedTensor` of type `int64`.
|
| 796 |
+
"""
|
| 797 |
+
return _cross_internal(
|
| 798 |
+
inputs=inputs,
|
| 799 |
+
hashed_output=True,
|
| 800 |
+
num_buckets=num_buckets,
|
| 801 |
+
hash_key=hash_key,
|
| 802 |
+
name=name)
|
| 803 |
+
|
| 804 |
+
|
| 805 |
+
_DEFAULT_CROSS_HASH_KEY = 0xDECAFCAFFE
|
| 806 |
+
|
| 807 |
+
|
| 808 |
+
def _cross_internal(inputs,
|
| 809 |
+
hashed_output=False,
|
| 810 |
+
num_buckets=0,
|
| 811 |
+
hash_key=None,
|
| 812 |
+
name=None):
|
| 813 |
+
"""Generates feature cross from a list of ragged and dense tensors."""
|
| 814 |
+
if not isinstance(inputs, (tuple, list)):
|
| 815 |
+
raise TypeError('Inputs must be a list')
|
| 816 |
+
|
| 817 |
+
if hash_key is None:
|
| 818 |
+
hash_key = _DEFAULT_CROSS_HASH_KEY
|
| 819 |
+
|
| 820 |
+
ragged_inputs = []
|
| 821 |
+
sparse_inputs = []
|
| 822 |
+
dense_inputs = []
|
| 823 |
+
input_order = []
|
| 824 |
+
with ops.name_scope(name, 'RaggedCross', inputs):
|
| 825 |
+
for i, t in enumerate(inputs):
|
| 826 |
+
if sparse_tensor.is_sparse(t):
|
| 827 |
+
t = sparse_tensor.SparseTensor.from_value(t)
|
| 828 |
+
else:
|
| 829 |
+
t = ragged_tensor.convert_to_tensor_or_ragged_tensor(t)
|
| 830 |
+
if t.dtype.is_integer:
|
| 831 |
+
t = math_ops.cast(t, dtypes.int64)
|
| 832 |
+
elif t.dtype != dtypes.string:
|
| 833 |
+
raise ValueError('Unexpected dtype for inputs[%d]: %s' % (i, t.dtype))
|
| 834 |
+
if isinstance(t, ragged_tensor.RaggedTensor):
|
| 835 |
+
if t.ragged_rank != 1:
|
| 836 |
+
raise ValueError('tf.ragged.cross only supports inputs with rank=2')
|
| 837 |
+
ragged_inputs.append(t)
|
| 838 |
+
input_order.append('R')
|
| 839 |
+
elif isinstance(t, sparse_tensor.SparseTensor):
|
| 840 |
+
sparse_inputs.append(t)
|
| 841 |
+
input_order.append('S')
|
| 842 |
+
else:
|
| 843 |
+
dense_inputs.append(t)
|
| 844 |
+
input_order.append('D')
|
| 845 |
+
|
| 846 |
+
out_values_type = dtypes.int64 if hashed_output else dtypes.string
|
| 847 |
+
if ragged_inputs and all(
|
| 848 |
+
t.row_splits.dtype == dtypes.int32 for t in ragged_inputs):
|
| 849 |
+
out_row_splits_type = dtypes.int32
|
| 850 |
+
else:
|
| 851 |
+
out_row_splits_type = dtypes.int64
|
| 852 |
+
|
| 853 |
+
# Convert hash_key from uint64 -> int64, since we need to pass it via
|
| 854 |
+
# an int64 attr.
|
| 855 |
+
if hash_key > 2**63:
|
| 856 |
+
hash_key -= 2**64
|
| 857 |
+
|
| 858 |
+
values_out, splits_out = gen_ragged_array_ops.ragged_cross(
|
| 859 |
+
ragged_values=[rt.values for rt in ragged_inputs],
|
| 860 |
+
ragged_row_splits=[rt.row_splits for rt in ragged_inputs],
|
| 861 |
+
sparse_indices=[st.indices for st in sparse_inputs],
|
| 862 |
+
sparse_values=[st.values for st in sparse_inputs],
|
| 863 |
+
sparse_shape=[st.dense_shape for st in sparse_inputs],
|
| 864 |
+
dense_inputs=dense_inputs,
|
| 865 |
+
input_order=''.join(input_order),
|
| 866 |
+
hashed_output=hashed_output,
|
| 867 |
+
num_buckets=num_buckets,
|
| 868 |
+
hash_key=hash_key,
|
| 869 |
+
out_values_type=out_values_type.as_datatype_enum,
|
| 870 |
+
out_row_splits_type=out_row_splits_type.as_datatype_enum,
|
| 871 |
+
name=name)
|
| 872 |
+
|
| 873 |
+
return ragged_tensor.RaggedTensor.from_row_splits(
|
| 874 |
+
values_out, splits_out, validate=False)
|
| 875 |
+
|
| 876 |
+
|
| 877 |
+
def fill_empty_rows(ragged_input, default_value, name=None):
|
| 878 |
+
"""Fills empty rows in the input `RaggedTensor` with rank 2 with a default
|
| 879 |
+
|
| 880 |
+
value.
|
| 881 |
+
|
| 882 |
+
This op adds entries with the specified `default_value` for any row in the
|
| 883 |
+
input that does not already have a value.
|
| 884 |
+
|
| 885 |
+
The op also returns an indicator vector such that
|
| 886 |
+
|
| 887 |
+
empty_row_indicator[i] = True iff row i was an empty row.
|
| 888 |
+
|
| 889 |
+
Args:
|
| 890 |
+
ragged_input: A `RaggedTensor` with rank 2.
|
| 891 |
+
default_value: The value to fill for empty rows, with the same type as
|
| 892 |
+
`ragged_input.`
|
| 893 |
+
name: A name prefix for the returned tensors (optional)
|
| 894 |
+
|
| 895 |
+
Returns:
|
| 896 |
+
ragged_ordered_output: A `RaggedTensor`with all empty rows filled in with
|
| 897 |
+
`default_value`.
|
| 898 |
+
empty_row_indicator: A bool vector indicating whether each input row was
|
| 899 |
+
empty.
|
| 900 |
+
|
| 901 |
+
Raises:
|
| 902 |
+
TypeError: If `ragged_input` is not a `RaggedTensor`.
|
| 903 |
+
"""
|
| 904 |
+
with ops.name_scope(name, 'RaggedFillEmptyRows', [ragged_input]):
|
| 905 |
+
if not isinstance(ragged_input, ragged_tensor.RaggedTensor):
|
| 906 |
+
raise TypeError(
|
| 907 |
+
'ragged_input must be RaggedTensor, got'
|
| 908 |
+
f' {type(ragged_input)}'
|
| 909 |
+
)
|
| 910 |
+
default_value = ops.convert_to_tensor(
|
| 911 |
+
default_value, dtype=ragged_input.dtype
|
| 912 |
+
)
|
| 913 |
+
(
|
| 914 |
+
output_value_rowids,
|
| 915 |
+
output_values,
|
| 916 |
+
empty_row_indicator,
|
| 917 |
+
unused_reverse_index_map,
|
| 918 |
+
) = gen_ragged_array_ops.ragged_fill_empty_rows(
|
| 919 |
+
value_rowids=ragged_input.value_rowids(),
|
| 920 |
+
values=ragged_input.values,
|
| 921 |
+
nrows=ragged_input.nrows(),
|
| 922 |
+
default_value=default_value,
|
| 923 |
+
)
|
| 924 |
+
return (
|
| 925 |
+
ragged_tensor.RaggedTensor.from_value_rowids(
|
| 926 |
+
values=output_values,
|
| 927 |
+
value_rowids=output_value_rowids,
|
| 928 |
+
validate=False,
|
| 929 |
+
),
|
| 930 |
+
empty_row_indicator,
|
| 931 |
+
)
|
| 932 |
+
|
| 933 |
+
|
| 934 |
+
@ops.RegisterGradient('RaggedFillEmptyRows')
|
| 935 |
+
def _ragged_fill_empty_rows_grad(
|
| 936 |
+
op,
|
| 937 |
+
unused_grad_output_indices,
|
| 938 |
+
output_grad_values,
|
| 939 |
+
unused_grad_empty_row_indicator,
|
| 940 |
+
unused_grad_reverse_index_map,
|
| 941 |
+
):
|
| 942 |
+
"""Gradients for RaggedFillEmptyRows."""
|
| 943 |
+
reverse_index_map = op.outputs[3]
|
| 944 |
+
|
| 945 |
+
d_values, d_default_value = gen_ragged_array_ops.ragged_fill_empty_rows_grad(
|
| 946 |
+
reverse_index_map=reverse_index_map, grad_values=output_grad_values
|
| 947 |
+
)
|
| 948 |
+
|
| 949 |
+
# d_value_rowids, d_values, d_nrows, d_default_value.
|
| 950 |
+
return [None, d_values, None, d_default_value]
|
| 951 |
+
|
| 952 |
+
|
| 953 |
+
# ===============================================================================
|
| 954 |
+
# dynamic_partition
|
| 955 |
+
# ===============================================================================
|
| 956 |
+
@dispatch.dispatch_for_api(data_flow_ops.dynamic_partition)
|
| 957 |
+
def dynamic_partition(data: ragged_tensor.RaggedOrDense,
|
| 958 |
+
partitions: ragged_tensor.RaggedOrDense,
|
| 959 |
+
num_partitions,
|
| 960 |
+
name=None):
|
| 961 |
+
"""RaggedTensor dispatch override for tf.dynamic_partition."""
|
| 962 |
+
if not isinstance(num_partitions, int) or num_partitions < 0:
|
| 963 |
+
raise TypeError('num_partitions must be a non-negative integer')
|
| 964 |
+
result = stack_dynamic_partitions(data, partitions, num_partitions, name)
|
| 965 |
+
return [result[i] for i in range(num_partitions)]
|
| 966 |
+
|
| 967 |
+
|
| 968 |
+
# ===============================================================================
|
| 969 |
+
# split
|
| 970 |
+
# ===============================================================================
|
| 971 |
+
@dispatch.dispatch_for_api(array_ops.split)
|
| 972 |
+
def split(value: ragged_tensor.Ragged,
|
| 973 |
+
num_or_size_splits,
|
| 974 |
+
axis=0,
|
| 975 |
+
num=None,
|
| 976 |
+
name=None):
|
| 977 |
+
"""Splits a RaggedTensor `value` into a list of sub RaggedTensors.
|
| 978 |
+
|
| 979 |
+
If `num_or_size_splits` is an `int`, then it splits `value` along the
|
| 980 |
+
dimension `axis` into `num_or_size_splits` smaller RaggedTensors. This
|
| 981 |
+
requires that `value.shape[axis]` is divisible by `num_or_size_splits`.
|
| 982 |
+
|
| 983 |
+
If `num_or_size_splits` is a 1-D Tensor (or list), then `value` is split into
|
| 984 |
+
`len(num_or_size_splits)` elements. The shape of the `i`-th element has the
|
| 985 |
+
same size as the `value` except along dimension `axis` where the size is
|
| 986 |
+
`num_or_size_splits[i]`.
|
| 987 |
+
|
| 988 |
+
Splits along a ragged dimension is not allowed.
|
| 989 |
+
|
| 990 |
+
For example:
|
| 991 |
+
|
| 992 |
+
>>> rt = tf.RaggedTensor.from_row_lengths(
|
| 993 |
+
... np.arange(6 * 3).reshape(6, 3), row_lengths=[1, 2, 2, 1])
|
| 994 |
+
>>> rt.shape
|
| 995 |
+
TensorShape([4, None, 3])
|
| 996 |
+
>>>
|
| 997 |
+
>>> rt1, rt2 = tf.split(rt, 2) # uniform splits
|
| 998 |
+
>>> rt1.shape
|
| 999 |
+
TensorShape([2, None, 3])
|
| 1000 |
+
>>> rt2.shape
|
| 1001 |
+
TensorShape([2, None, 3])
|
| 1002 |
+
>>>
|
| 1003 |
+
>>> rt3, rt4, rt5 = tf.split(rt, [1, 2, 1]) # ragged splits
|
| 1004 |
+
>>> rt3.shape
|
| 1005 |
+
TensorShape([1, None, 3])
|
| 1006 |
+
>>> rt4.shape
|
| 1007 |
+
TensorShape([2, None, 3])
|
| 1008 |
+
>>> rt5.shape
|
| 1009 |
+
TensorShape([1, None, 3])
|
| 1010 |
+
>>>
|
| 1011 |
+
>>> rt6, rt7 = tf.split(rt, [1, 2], axis=2) # splits along axis 2
|
| 1012 |
+
>>> rt6.shape
|
| 1013 |
+
TensorShape([4, None, 1])
|
| 1014 |
+
>>> rt7.shape
|
| 1015 |
+
TensorShape([4, None, 2])
|
| 1016 |
+
|
| 1017 |
+
Args:
|
| 1018 |
+
value: The `RaggedTensor` to split.
|
| 1019 |
+
num_or_size_splits: Either an `int` indicating the number of splits
|
| 1020 |
+
along `axis` or a 1-D integer `Tensor` or Python list containing the sizes
|
| 1021 |
+
of each output tensor along `axis`. If a Python int, then it must evenly
|
| 1022 |
+
divide `value.shape[axis]`; otherwise the sum of sizes along the split
|
| 1023 |
+
axis must match that of the `value`.
|
| 1024 |
+
axis: An `int` or scalar `int32` `Tensor`. The dimension along which
|
| 1025 |
+
to split. Must be in the range `[-rank(value), rank(value))`. Defaults to
|
| 1026 |
+
0.
|
| 1027 |
+
num: An `int` used to specify the number of outputs when
|
| 1028 |
+
`num_or_size_splits` is a 1-D list or `Tensor` and its length is
|
| 1029 |
+
statically unknown, e.g., specifying `tf.TensorSepc(None)` with
|
| 1030 |
+
the `input_signature` argument of `tf.function` (optional).
|
| 1031 |
+
name: A name for the operation (optional).
|
| 1032 |
+
|
| 1033 |
+
Returns:
|
| 1034 |
+
if `num_or_size_splits` is an `int` returns a list of `num_or_size_splits`
|
| 1035 |
+
`RaggedTensor` objects; if `num_or_size_splits` is a 1-D Tensor returns
|
| 1036 |
+
`num_or_size_splits.get_shape[0]` `RaggedTensor` objects resulting from
|
| 1037 |
+
splitting `value`.
|
| 1038 |
+
|
| 1039 |
+
Raises:
|
| 1040 |
+
ValueError: If the dimension `axis` of `value` is a ragged dimension.
|
| 1041 |
+
ValueError: If `num` is unspecified and cannot be inferred.
|
| 1042 |
+
ValueError: If `num` is specified but doesn't match the length of
|
| 1043 |
+
`num_or_size_splits`.
|
| 1044 |
+
ValueError: If `num_or_size_splits` is an `int` and less than 1.
|
| 1045 |
+
TypeError: If `num_or_size_splits` is not an `int` or 1-D
|
| 1046 |
+
list or 1-D `Tensor`.
|
| 1047 |
+
InvalidArgumentError: If the `axis` of `value` cannot be exactly splitted
|
| 1048 |
+
by `num_or_size_splits`.
|
| 1049 |
+
InvalidArgumentError: If `num_or_size_splits` is contains negative integers.
|
| 1050 |
+
InvalidArgumentError: If `num_or_size_splits`'s static shape is unknown and
|
| 1051 |
+
its dynamic shape is inconsistent `num`.
|
| 1052 |
+
InvalidArgumentError: If `num_or_size_splits`'s static rank is unknown and
|
| 1053 |
+
`axis` is a negative integer.
|
| 1054 |
+
"""
|
| 1055 |
+
with ops.name_scope(name, 'RaggedSplit'):
|
| 1056 |
+
value = ragged_tensor.convert_to_tensor_or_ragged_tensor(
|
| 1057 |
+
value, name='value')
|
| 1058 |
+
if isinstance(num_or_size_splits, int) and num_or_size_splits == 1:
|
| 1059 |
+
return [value]
|
| 1060 |
+
|
| 1061 |
+
# static assert
|
| 1062 |
+
check_ops.assert_integer_v2(
|
| 1063 |
+
num_or_size_splits,
|
| 1064 |
+
message=('`num_or_size_splits` must be an `int` or 1-D list or '
|
| 1065 |
+
'`Tensor` of integers.'))
|
| 1066 |
+
value_shape = dynamic_ragged_shape.DynamicRaggedShape.from_tensor(value)
|
| 1067 |
+
axis = array_ops.get_positive_axis(axis, value_shape.rank)
|
| 1068 |
+
try:
|
| 1069 |
+
dim_size = value_shape[axis]
|
| 1070 |
+
except ValueError:
|
| 1071 |
+
raise ValueError('Cannot split a ragged dimension. Got `value` with '
|
| 1072 |
+
f'shape {value_shape} and `axis` {axis}.')
|
| 1073 |
+
if isinstance(num_or_size_splits, int):
|
| 1074 |
+
# Uniform split
|
| 1075 |
+
num_splits = num_or_size_splits
|
| 1076 |
+
if num_splits < 1:
|
| 1077 |
+
raise ValueError('`num_or_size_splits` must be >=1 if it is an `int`.'
|
| 1078 |
+
f'Received {num_or_size_splits}.')
|
| 1079 |
+
split_length = math_ops.floordiv(dim_size, num_splits)
|
| 1080 |
+
split_lengths = array_ops.repeat(split_length, num_splits)
|
| 1081 |
+
else:
|
| 1082 |
+
# Ragged split
|
| 1083 |
+
num_splits = None
|
| 1084 |
+
split_lengths = ops.convert_to_tensor(num_or_size_splits)
|
| 1085 |
+
if split_lengths.shape.ndims is not None:
|
| 1086 |
+
if split_lengths.shape.ndims != 1:
|
| 1087 |
+
raise TypeError('`num_or_size_splits` must be an `int` or 1-D list '
|
| 1088 |
+
f'or `Tensor`. Received {num_or_size_splits}.')
|
| 1089 |
+
num_splits = tensor_shape.dimension_value(split_lengths.shape[0])
|
| 1090 |
+
|
| 1091 |
+
if num_splits is None:
|
| 1092 |
+
if num is None:
|
| 1093 |
+
raise ValueError('`num` must be specified as an `int` when the '
|
| 1094 |
+
'size of `num_or_size_split` is statically '
|
| 1095 |
+
f'unknown. Received `num`: {num} and '
|
| 1096 |
+
f'`num_or_size_split`: {num_or_size_splits}.')
|
| 1097 |
+
num_splits = num
|
| 1098 |
+
else:
|
| 1099 |
+
if num is not None and num != num_splits:
|
| 1100 |
+
raise ValueError('`num` does not match the size of '
|
| 1101 |
+
f'`num_or_size_split`. Received `num`: {num} and '
|
| 1102 |
+
f'size of `num_or_size_split`: {num_splits}.')
|
| 1103 |
+
|
| 1104 |
+
splits = array_ops.concat([[0], math_ops.cumsum(split_lengths)], axis=0)
|
| 1105 |
+
checks = []
|
| 1106 |
+
checks.append(
|
| 1107 |
+
check_ops.assert_non_negative_v2(
|
| 1108 |
+
num_or_size_splits,
|
| 1109 |
+
message='`num_or_size_splits` must be non-negative.'))
|
| 1110 |
+
checks.append(
|
| 1111 |
+
check_ops.assert_equal_v2(
|
| 1112 |
+
num_splits,
|
| 1113 |
+
array_ops.shape(split_lengths)[0],
|
| 1114 |
+
message='`num` is inconsistent with `num_or_size_split.shape[0]`.'))
|
| 1115 |
+
checks.append(
|
| 1116 |
+
check_ops.assert_equal_v2(
|
| 1117 |
+
math_ops.cast(dim_size, splits.dtype),
|
| 1118 |
+
splits[-1],
|
| 1119 |
+
message=('Cannot exactly split the `axis` dimension of `value` '
|
| 1120 |
+
'with the given `num_or_size_split`.')))
|
| 1121 |
+
splits = control_flow_ops.with_dependencies(checks, splits)
|
| 1122 |
+
splited_rts = []
|
| 1123 |
+
slices = [slice(None)] * (axis + 1)
|
| 1124 |
+
for i in range(num_splits):
|
| 1125 |
+
slices[-1] = slice(splits[i], splits[i + 1])
|
| 1126 |
+
splited_rts.append(value[tuple(slices)])
|
| 1127 |
+
return splited_rts
|
| 1128 |
+
|
| 1129 |
+
|
| 1130 |
+
# ===============================================================================
|
| 1131 |
+
# RaggedTensor shape operations
|
| 1132 |
+
# ===============================================================================
|
| 1133 |
+
|
| 1134 |
+
|
| 1135 |
+
@dispatch.dispatch_for_api(array_ops.reshape)
|
| 1136 |
+
def ragged_reshape(
|
| 1137 |
+
tensor: ragged_tensor.RaggedOrDense,
|
| 1138 |
+
shape: dynamic_ragged_shape.DenseOrRaggedShape
|
| 1139 |
+
) -> Union[ragged_tensor.RaggedTensor, tensor_lib.Tensor]:
|
| 1140 |
+
"""Reshapes a tensor or ragged tensor."""
|
| 1141 |
+
tensor = ragged_tensor.convert_to_tensor_or_ragged_tensor(
|
| 1142 |
+
tensor, name='tensor')
|
| 1143 |
+
if isinstance(tensor, ragged_tensor.RaggedTensor):
|
| 1144 |
+
tensor = tensor.values
|
| 1145 |
+
|
| 1146 |
+
if isinstance(shape, dynamic_ragged_shape.DynamicRaggedShape):
|
| 1147 |
+
flat_values = array_ops.reshape(tensor, shape.inner_shape)
|
| 1148 |
+
return ragged_tensor.RaggedTensor._from_nested_row_partitions( # pylint: disable=protected-access
|
| 1149 |
+
flat_values,
|
| 1150 |
+
shape.row_partitions,
|
| 1151 |
+
validate=False)
|
| 1152 |
+
else:
|
| 1153 |
+
shape = ops.convert_to_tensor(shape, name='shape')
|
| 1154 |
+
return array_ops.reshape(tensor, shape)
|
| 1155 |
+
|
| 1156 |
+
|
| 1157 |
+
@dispatch.dispatch_for_api(array_ops.broadcast_to)
|
| 1158 |
+
def broadcast_to(
|
| 1159 |
+
input: ragged_tensor.RaggedOrDense, # pylint: disable=redefined-builtin
|
| 1160 |
+
shape: dynamic_ragged_shape.DynamicRaggedShape
|
| 1161 |
+
) -> Union[ragged_tensor.RaggedTensor, tensor_lib.Tensor]:
|
| 1162 |
+
"""Broadcasts a potentially ragged tensor to a ragged shape.
|
| 1163 |
+
|
| 1164 |
+
Tiles `input` as necessary to match the given shape.
|
| 1165 |
+
|
| 1166 |
+
Behavior is undefined if `input` is not broadcast-compatible with `shape`.
|
| 1167 |
+
|
| 1168 |
+
Args:
|
| 1169 |
+
input: The potentially ragged tensor to broadcast.
|
| 1170 |
+
shape: A `DynamicRaggedShape`
|
| 1171 |
+
|
| 1172 |
+
Returns:
|
| 1173 |
+
A potentially ragged tensor whose values are taken from
|
| 1174 |
+
`input`, and whose shape matches `shape`.
|
| 1175 |
+
"""
|
| 1176 |
+
return dynamic_ragged_shape.broadcast_to(input, shape)
|
| 1177 |
+
|
| 1178 |
+
|
| 1179 |
+
# Note: default value for out_type needs to be int32, to match the
|
| 1180 |
+
# default for tf.shape's out_type parameter.
|
| 1181 |
+
@dispatch.dispatch_for_api(array_ops.shape)
|
| 1182 |
+
def ragged_shape(
|
| 1183 |
+
input: ragged_tensor.Ragged, # pylint: disable=redefined-builtin
|
| 1184 |
+
name: Optional[str] = None,
|
| 1185 |
+
out_type=dtypes.int32) -> dynamic_ragged_shape.DynamicRaggedShape:
|
| 1186 |
+
"""Returns the shape of a RaggedTensor.
|
| 1187 |
+
|
| 1188 |
+
Args:
|
| 1189 |
+
input: A `RaggedTensor`
|
| 1190 |
+
name: A name for the operation (optional).
|
| 1191 |
+
out_type: dtype used to encode the shape.
|
| 1192 |
+
|
| 1193 |
+
Returns:
|
| 1194 |
+
A `tf.experimental.DynamicRaggedShape`
|
| 1195 |
+
"""
|
| 1196 |
+
with ops.name_scope(name, 'RaggedShape', [input]):
|
| 1197 |
+
return dynamic_ragged_shape.DynamicRaggedShape.from_tensor(input, out_type)
|
| 1198 |
+
|
| 1199 |
+
|
| 1200 |
+
@dispatch.dispatch_for_api(array_ops.broadcast_dynamic_shape)
|
| 1201 |
+
def broadcast_dynamic_shape(
|
| 1202 |
+
shape_x: dynamic_ragged_shape.DenseOrRaggedShape,
|
| 1203 |
+
shape_y: dynamic_ragged_shape.DenseOrRaggedShape
|
| 1204 |
+
) -> dynamic_ragged_shape.DynamicRaggedShape:
|
| 1205 |
+
"""Returns the shape formed by broadcasting two shapes to be compatible.
|
| 1206 |
+
|
| 1207 |
+
1. If shape_x and shape_y both have row_partitions, then fail if their dtypes
|
| 1208 |
+
don't match.
|
| 1209 |
+
2. If neither has row_partitions and they have different dtypes,
|
| 1210 |
+
go with int64.
|
| 1211 |
+
3. If one has row_partitions, go with that dtype.
|
| 1212 |
+
|
| 1213 |
+
Args:
|
| 1214 |
+
shape_x: A `DynamicRaggedShape`
|
| 1215 |
+
shape_y: A `DynamicRaggedShape`
|
| 1216 |
+
|
| 1217 |
+
Returns:
|
| 1218 |
+
A `DynamicRaggedShape`.
|
| 1219 |
+
Raises:
|
| 1220 |
+
ValueError: If `shape_x` and `shape_y` are not broadcast-compatible.
|
| 1221 |
+
"""
|
| 1222 |
+
if not isinstance(shape_x, dynamic_ragged_shape.DynamicRaggedShape):
|
| 1223 |
+
shape_x = dynamic_ragged_shape.DynamicRaggedShape([], shape_x)
|
| 1224 |
+
if not isinstance(shape_y, dynamic_ragged_shape.DynamicRaggedShape):
|
| 1225 |
+
shape_y = dynamic_ragged_shape.DynamicRaggedShape([], shape_y)
|
| 1226 |
+
return dynamic_ragged_shape.broadcast_dynamic_shape(shape_x, shape_y)
|
| 1227 |
+
|
| 1228 |
+
|
| 1229 |
+
@dispatch.dispatch_for_api(array_ops.ones)
|
| 1230 |
+
def ones(
|
| 1231 |
+
shape: dynamic_ragged_shape.DynamicRaggedShape,
|
| 1232 |
+
dtype=dtypes.float32,
|
| 1233 |
+
name=None,
|
| 1234 |
+
layout=None,
|
| 1235 |
+
) -> ragged_tensor.RaggedOrDense:
|
| 1236 |
+
"""Returns ones shaped like x."""
|
| 1237 |
+
if layout is not None and not layout.is_fully_replicated():
|
| 1238 |
+
raise ValueError(
|
| 1239 |
+
f'RaggedTensor only allows replicated layout. got {layout}'
|
| 1240 |
+
)
|
| 1241 |
+
flat_values = array_ops.ones(
|
| 1242 |
+
shape.inner_shape, dtype=dtype, name=name, layout=layout
|
| 1243 |
+
)
|
| 1244 |
+
return shape._add_row_partitions(flat_values) # pylint: disable=protected-access
|
| 1245 |
+
|
| 1246 |
+
|
| 1247 |
+
@dispatch.dispatch_for_api(array_ops.zeros)
|
| 1248 |
+
def zeros(
|
| 1249 |
+
shape: dynamic_ragged_shape.DynamicRaggedShape,
|
| 1250 |
+
dtype=dtypes.float32,
|
| 1251 |
+
name=None,
|
| 1252 |
+
layout=None,
|
| 1253 |
+
) -> ragged_tensor.RaggedOrDense:
|
| 1254 |
+
"""Returns ones shaped like x."""
|
| 1255 |
+
if layout is not None and not layout.is_fully_replicated():
|
| 1256 |
+
raise ValueError(
|
| 1257 |
+
f'RaggedTensor only allows replicated layout. got {layout}'
|
| 1258 |
+
)
|
| 1259 |
+
flat_values = array_ops.zeros(
|
| 1260 |
+
shape.inner_shape, dtype=dtype, name=name, layout=layout
|
| 1261 |
+
)
|
| 1262 |
+
return shape._add_row_partitions(flat_values) # pylint: disable=protected-access
|
| 1263 |
+
|
| 1264 |
+
|
| 1265 |
+
@dispatch.dispatch_for_api(array_ops.fill)
|
| 1266 |
+
def fill(
|
| 1267 |
+
dims: dynamic_ragged_shape.DynamicRaggedShape,
|
| 1268 |
+
value: core_types.TensorLike,
|
| 1269 |
+
name: Optional[str] = None,
|
| 1270 |
+
layout=None,
|
| 1271 |
+
) -> ragged_tensor.RaggedOrDense:
|
| 1272 |
+
"""Creates a tensor with shape `dims` and fills it with `value`."""
|
| 1273 |
+
if layout is not None and not layout.is_fully_replicated():
|
| 1274 |
+
raise ValueError(
|
| 1275 |
+
f'RaggedTensor only allows replicated layout. got {layout}'
|
| 1276 |
+
)
|
| 1277 |
+
flat_values = array_ops.fill(
|
| 1278 |
+
dims.inner_shape, value, name=name, layout=layout
|
| 1279 |
+
)
|
| 1280 |
+
return dims._add_row_partitions(flat_values) # pylint: disable=protected-access
|
| 1281 |
+
|
| 1282 |
+
|
| 1283 |
+
# ===============================================================================
|
| 1284 |
+
# bitcast
|
| 1285 |
+
# ===============================================================================
|
| 1286 |
+
@dispatch.dispatch_for_api(array_ops.bitcast)
|
| 1287 |
+
def bitcast(
|
| 1288 |
+
input: ragged_tensor.RaggedOrDense, # pylint: disable=redefined-builtin
|
| 1289 |
+
type, # pylint: disable=redefined-builtin
|
| 1290 |
+
name=None) -> ragged_tensor.RaggedOrDense:
|
| 1291 |
+
"""RaggedTensor dispatch override for tf.bitcast."""
|
| 1292 |
+
type = dtypes.as_dtype(type)
|
| 1293 |
+
with ops.name_scope(name, 'Bitcast', [input]):
|
| 1294 |
+
input = ragged_tensor.convert_to_tensor_or_ragged_tensor(
|
| 1295 |
+
input, name='input')
|
| 1296 |
+
if (input.dtype.size < type.size and input.flat_values.shape.rank < 2):
|
| 1297 |
+
raise ValueError('`input.flat_values` is required to have rank >= 2 when '
|
| 1298 |
+
'input.dtype.size < type.size. Actual rank: '
|
| 1299 |
+
f'{input.flat_values.shape.rank}')
|
| 1300 |
+
return input.with_flat_values(array_ops.bitcast(input.flat_values, type))
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_autograph.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""Autograph-specific overrides for ragged_tensor."""
|
| 16 |
+
from tensorflow.python.autograph.operators import control_flow
|
| 17 |
+
from tensorflow.python.ops import cond as tf_cond
|
| 18 |
+
from tensorflow.python.ops.ragged import ragged_tensor
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _tf_ragged_for_stmt(
|
| 22 |
+
iter_, extra_test, body, get_state, set_state, symbol_names, opts
|
| 23 |
+
):
|
| 24 |
+
"""Overload of for_stmt that iterates over TF ragged tensors."""
|
| 25 |
+
init_vars = get_state()
|
| 26 |
+
control_flow.verify_loop_init_vars(init_vars, symbol_names)
|
| 27 |
+
|
| 28 |
+
# TODO(mdan): Move this into len()? Requires eager support.
|
| 29 |
+
if iter_.shape and iter_.shape[0] is not None:
|
| 30 |
+
n = iter_.shape[0]
|
| 31 |
+
else:
|
| 32 |
+
n = iter_.row_lengths()[0]
|
| 33 |
+
|
| 34 |
+
iterate_index = 0
|
| 35 |
+
|
| 36 |
+
def aug_get_state():
|
| 37 |
+
return (iterate_index,) + get_state()
|
| 38 |
+
|
| 39 |
+
def aug_set_state(aug_loop_vars):
|
| 40 |
+
nonlocal iterate_index
|
| 41 |
+
# TODO(b/171479293): Drop the lint override.
|
| 42 |
+
iterate_index, *loop_vars = aug_loop_vars # pylint:disable=unused-variable
|
| 43 |
+
# The iteration index is not "output" by the for loop. If the iteration
|
| 44 |
+
# index is used outside the loop, it will appear
|
| 45 |
+
# in the loop vars separately.
|
| 46 |
+
set_state(loop_vars)
|
| 47 |
+
|
| 48 |
+
def aug_body():
|
| 49 |
+
nonlocal iterate_index
|
| 50 |
+
body(iter_[iterate_index])
|
| 51 |
+
iterate_index += 1
|
| 52 |
+
|
| 53 |
+
def aug_test():
|
| 54 |
+
main_test = iterate_index < n
|
| 55 |
+
if extra_test is not None:
|
| 56 |
+
return tf_cond.cond(main_test, extra_test, lambda: False)
|
| 57 |
+
return main_test
|
| 58 |
+
|
| 59 |
+
control_flow._add_max_iterations_hint(opts, n) # pylint: disable=protected-access
|
| 60 |
+
|
| 61 |
+
control_flow._tf_while_stmt( # pylint: disable=protected-access
|
| 62 |
+
aug_test,
|
| 63 |
+
aug_body,
|
| 64 |
+
aug_get_state,
|
| 65 |
+
aug_set_state,
|
| 66 |
+
('<internal iterate>',) + symbol_names,
|
| 67 |
+
opts,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
control_flow.for_loop_registry.register(
|
| 72 |
+
ragged_tensor.RaggedTensor, _tf_ragged_for_stmt
|
| 73 |
+
)
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_batch_gather_ops.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""Batch gather operations for RaggedTensors."""
|
| 16 |
+
|
| 17 |
+
from tensorflow.python.ops import array_ops
|
| 18 |
+
from tensorflow.python.ops.ragged import ragged_gather_ops
|
| 19 |
+
from tensorflow.python.ops.ragged import ragged_tensor
|
| 20 |
+
from tensorflow.python.util import dispatch
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
#===============================================================================
|
| 24 |
+
# ragged.batch_gather
|
| 25 |
+
#===============================================================================
|
| 26 |
+
@dispatch.dispatch_for_api(array_ops.batch_gather)
|
| 27 |
+
def batch_gather(params: ragged_tensor.RaggedOrDense,
|
| 28 |
+
indices: ragged_tensor.RaggedOrDense,
|
| 29 |
+
name=None):
|
| 30 |
+
"""Gathers slices from `params` according to `indices` with batch dims.
|
| 31 |
+
|
| 32 |
+
This operation is similar to `gather`, but it assumes that the leading `N`
|
| 33 |
+
dimensions of `indices` and `params` are batch dimensions, and performs a
|
| 34 |
+
gather within each batch. In particular, when using this operation with `N`
|
| 35 |
+
batch dimensions `B1...BN`:
|
| 36 |
+
|
| 37 |
+
* `indices` has shape `[B1...BN, I]`
|
| 38 |
+
* `params` has shape `[B1...BN, P1...PM]`.
|
| 39 |
+
* `result` has shape `[B1...BN, I, P2...PM]`.
|
| 40 |
+
* `result[b1...bN, i, p2...pM] =
|
| 41 |
+
params[b1...bN, indices[b1...bN, i], p2...pM]`
|
| 42 |
+
|
| 43 |
+
Args:
|
| 44 |
+
params: A potentially ragged tensor with shape `[B1...BN, P1...PM]` (`N>=0`,
|
| 45 |
+
`M>0`).
|
| 46 |
+
indices: A potentially ragged tensor with shape `[B1...BN, I]` (`N>=0`).
|
| 47 |
+
name: A name for the operation (optional).
|
| 48 |
+
|
| 49 |
+
Returns:
|
| 50 |
+
A potentially ragged tensor with shape `[B1...BN, I, P2...PM]`.
|
| 51 |
+
`result.ragged_rank = max(indices.ragged_rank, params.ragged_rank)`.
|
| 52 |
+
|
| 53 |
+
#### Example:
|
| 54 |
+
|
| 55 |
+
>>> params = tf.ragged.constant([['a', 'b', 'c'], ['d'], [], ['e']])
|
| 56 |
+
>>> indices = tf.ragged.constant([[1, 2, 0], [], [], [0, 0]])
|
| 57 |
+
>>> tf.compat.v1.batch_gather(params, indices)
|
| 58 |
+
<tf.RaggedTensor [[b'b', b'c', b'a'], [], [], [b'e', b'e']]>
|
| 59 |
+
"""
|
| 60 |
+
return ragged_gather_ops.gather(params, indices, batch_dims=-1, name=name)
|
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_batch_gather_with_default_op.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""Array operations for RaggedTensors."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
from tensorflow.python.framework import constant_op
|
| 19 |
+
from tensorflow.python.framework import ops
|
| 20 |
+
from tensorflow.python.ops import array_ops
|
| 21 |
+
from tensorflow.python.ops import check_ops
|
| 22 |
+
from tensorflow.python.ops import math_ops
|
| 23 |
+
from tensorflow.python.ops.ragged import ragged_array_ops
|
| 24 |
+
from tensorflow.python.ops.ragged import ragged_dispatch # pylint: disable=unused-import
|
| 25 |
+
from tensorflow.python.ops.ragged import ragged_operators # pylint: disable=unused-import
|
| 26 |
+
from tensorflow.python.ops.ragged import ragged_tensor
|
| 27 |
+
from tensorflow.python.ops.ragged import ragged_tensor_shape
|
| 28 |
+
from tensorflow.python.ops.ragged import ragged_where_op
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
#===============================================================================
|
| 32 |
+
# ragged.batch_gather_with_default
|
| 33 |
+
#===============================================================================
|
| 34 |
+
def batch_gather_with_default(params,
|
| 35 |
+
indices,
|
| 36 |
+
default_value='',
|
| 37 |
+
name=None):
|
| 38 |
+
"""Same as `batch_gather` but inserts `default_value` for invalid indices.
|
| 39 |
+
|
| 40 |
+
This operation is similar to `batch_gather` except that it will substitute
|
| 41 |
+
the value for invalid indices with `default_value` as the contents.
|
| 42 |
+
See `batch_gather` for more details.
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
Args:
|
| 46 |
+
params: A potentially ragged tensor with shape `[B1...BN, P1...PM]` (`N>=0`,
|
| 47 |
+
`M>0`).
|
| 48 |
+
indices: A potentially ragged tensor with shape `[B1...BN, I]` (`N>=0`).
|
| 49 |
+
default_value: A value to be inserted in places where `indices` are out of
|
| 50 |
+
bounds. Must be the same dtype as params and either a scalar or rank 1.
|
| 51 |
+
name: A name for the operation (optional).
|
| 52 |
+
|
| 53 |
+
Returns:
|
| 54 |
+
A potentially ragged tensor with shape `[B1...BN, I, P2...PM]`.
|
| 55 |
+
`result.ragged_rank = max(indices.ragged_rank, params.ragged_rank)`.
|
| 56 |
+
|
| 57 |
+
#### Example:
|
| 58 |
+
|
| 59 |
+
>>> params = tf.ragged.constant([['a', 'b', 'c'], ['d'], [], ['e']])
|
| 60 |
+
>>> indices = tf.ragged.constant([[1, 2, -1], [], [], [0, 10]])
|
| 61 |
+
>>> batch_gather_with_default(params, indices, 'FOO')
|
| 62 |
+
<tf.RaggedTensor [[b'b', b'c', b'FOO'], [], [], [b'e', b'FOO']]>
|
| 63 |
+
|
| 64 |
+
"""
|
| 65 |
+
with ops.name_scope(name, 'RaggedBatchGatherWithDefault'):
|
| 66 |
+
params = ragged_tensor.convert_to_tensor_or_ragged_tensor(
|
| 67 |
+
params, name='params',
|
| 68 |
+
)
|
| 69 |
+
indices = ragged_tensor.convert_to_tensor_or_ragged_tensor(
|
| 70 |
+
indices, name='indices',
|
| 71 |
+
)
|
| 72 |
+
default_value = ragged_tensor.convert_to_tensor_or_ragged_tensor(
|
| 73 |
+
default_value, name='default_value',
|
| 74 |
+
)
|
| 75 |
+
row_splits_dtype, (params, indices, default_value) = (
|
| 76 |
+
ragged_tensor.match_row_splits_dtypes(params, indices, default_value,
|
| 77 |
+
return_dtype=True))
|
| 78 |
+
# TODO(hterry): lift this restriction and support default_values of
|
| 79 |
+
# of rank > 1
|
| 80 |
+
if default_value.shape.ndims not in (0, 1):
|
| 81 |
+
raise ValueError('"default_value" must be a scalar or vector')
|
| 82 |
+
upper_bounds = None
|
| 83 |
+
if indices.shape.ndims is None:
|
| 84 |
+
raise ValueError('Indices must have a known rank.')
|
| 85 |
+
if params.shape.ndims is None:
|
| 86 |
+
raise ValueError('Params must have a known rank.')
|
| 87 |
+
|
| 88 |
+
num_batch_dimensions = indices.shape.ndims - 1
|
| 89 |
+
pad = None
|
| 90 |
+
# The logic for this works as follows:
|
| 91 |
+
# - create a padded params, where:
|
| 92 |
+
# padded_params[b1...bn, 0] = default_value
|
| 93 |
+
# padded_params[b1...bn, i] = params[b1...bn, i-1] (i>0)
|
| 94 |
+
# - create an `upper_bounds` Tensor that contains the number of elements
|
| 95 |
+
# in each innermost rank. Broadcast `upper_bounds` to be the same shape
|
| 96 |
+
# as `indices`.
|
| 97 |
+
# - check to see which index in `indices` are out of bounds and substitute
|
| 98 |
+
# it with the index containing `default_value` (the first).
|
| 99 |
+
# - call batch_gather with the indices adjusted.
|
| 100 |
+
with ops.control_dependencies([
|
| 101 |
+
check_ops.assert_greater_equal(array_ops.rank(params),
|
| 102 |
+
array_ops.rank(indices))]):
|
| 103 |
+
if ragged_tensor.is_ragged(params):
|
| 104 |
+
row_lengths = ragged_array_ops.expand_dims(
|
| 105 |
+
params.row_lengths(axis=num_batch_dimensions),
|
| 106 |
+
axis=-1)
|
| 107 |
+
upper_bounds = math_ops.cast(row_lengths, indices.dtype)
|
| 108 |
+
|
| 109 |
+
pad_shape = _get_pad_shape(params, indices, row_splits_dtype)
|
| 110 |
+
|
| 111 |
+
pad = ragged_tensor_shape.broadcast_to(
|
| 112 |
+
default_value, pad_shape)
|
| 113 |
+
else:
|
| 114 |
+
params_shape = array_ops.shape(params)
|
| 115 |
+
pad_shape = array_ops.concat([
|
| 116 |
+
params_shape[:num_batch_dimensions],
|
| 117 |
+
[1],
|
| 118 |
+
params_shape[num_batch_dimensions + 1:params.shape.ndims]
|
| 119 |
+
], 0)
|
| 120 |
+
upper_bounds = params_shape[num_batch_dimensions]
|
| 121 |
+
pad = array_ops.broadcast_to(default_value, pad_shape)
|
| 122 |
+
|
| 123 |
+
# Add `default_value` as the first value in the innermost (ragged) rank.
|
| 124 |
+
pad = math_ops.cast(pad, params.dtype)
|
| 125 |
+
padded_params = array_ops.concat(
|
| 126 |
+
[pad, params], axis=num_batch_dimensions)
|
| 127 |
+
|
| 128 |
+
# Adjust the indices by substituting out-of-bound indices to the
|
| 129 |
+
# default-value index (which is the first element)
|
| 130 |
+
shifted_indices = indices + 1
|
| 131 |
+
is_out_of_bounds = (indices < 0) | (indices > upper_bounds)
|
| 132 |
+
adjusted_indices = ragged_where_op.where(
|
| 133 |
+
is_out_of_bounds,
|
| 134 |
+
x=array_ops.zeros_like(indices), y=shifted_indices,
|
| 135 |
+
)
|
| 136 |
+
return array_ops.batch_gather(
|
| 137 |
+
params=padded_params, indices=adjusted_indices, name=name)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _get_pad_shape(params, indices, row_splits_dtype):
|
| 141 |
+
"""Gets the RaggedTensorDynamicShape for the pad tensor."""
|
| 142 |
+
num_batch_dimensions = indices.shape.ndims - 1
|
| 143 |
+
params_shape = ragged_tensor_shape.RaggedTensorDynamicShape.from_tensor(
|
| 144 |
+
params, dim_size_dtype=row_splits_dtype)
|
| 145 |
+
|
| 146 |
+
# We want to create a pad tensor that can be concatenated with the params.
|
| 147 |
+
if params.shape.ndims == indices.shape.ndims:
|
| 148 |
+
# When params and indices are the same rank, the shape of the pad tensor is
|
| 149 |
+
# almost identical to params, except the last dimension which has size = 1.
|
| 150 |
+
if params_shape.num_inner_dimensions == 0:
|
| 151 |
+
pad_dims = params_shape.partitioned_dim_sizes[:-1] + (
|
| 152 |
+
array_ops.ones_like(params_shape.partitioned_dim_sizes[-1]),)
|
| 153 |
+
return ragged_tensor_shape.RaggedTensorDynamicShape(
|
| 154 |
+
pad_dims, [])
|
| 155 |
+
else:
|
| 156 |
+
return ragged_tensor_shape.RaggedTensorDynamicShape(
|
| 157 |
+
params_shape.partitioned_dim_sizes,
|
| 158 |
+
array_ops.concat([params_shape.inner_dim_sizes[:-1], [1]], axis=0))
|
| 159 |
+
else:
|
| 160 |
+
# When the rank of indices < params, the pad has the same dimension as
|
| 161 |
+
# params up to the 'num_batch_dimensions' rank. Every dimension after that
|
| 162 |
+
# has size 1.
|
| 163 |
+
pad_dims = None
|
| 164 |
+
if num_batch_dimensions == 0:
|
| 165 |
+
pad_dims = (constant_op.constant(1, dtype=row_splits_dtype),) + (
|
| 166 |
+
constant_op.constant([1], dtype=row_splits_dtype),) * (
|
| 167 |
+
params_shape.num_partitioned_dimensions -
|
| 168 |
+
num_batch_dimensions - 1)
|
| 169 |
+
else:
|
| 170 |
+
batch_dimensions = params_shape.partitioned_dim_sizes[
|
| 171 |
+
:num_batch_dimensions]
|
| 172 |
+
gather_dimension = params_shape.partitioned_dim_sizes[
|
| 173 |
+
num_batch_dimensions]
|
| 174 |
+
pad_dims = batch_dimensions + (
|
| 175 |
+
array_ops.ones_like(gather_dimension),) * (
|
| 176 |
+
params_shape.num_partitioned_dimensions - num_batch_dimensions)
|
| 177 |
+
|
| 178 |
+
return ragged_tensor_shape.RaggedTensorDynamicShape(
|
| 179 |
+
pad_dims, params_shape.inner_dim_sizes)
|