1# Copyright 2022 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"""Utility to manipulate CompositeTensors in tf.function."""
16
17from tensorflow.python.framework import composite_tensor
18from tensorflow.python.util import _pywrap_utils
19from tensorflow.python.util import nest
20
21
22# TODO(b/240337581, b/240337099): Remove this function when we de-alias
23# dt_resource tensors or tf.nest support is_leaf.
24def flatten_with_variables(inputs):
25 """Flattens `inputs` but don't expand `ResourceVariable`s."""
26 # We assume that any CompositeTensors have already converted their components
27 # from numpy arrays to Tensors, so we don't need to expand composites here for
28 # the numpy array conversion. Instead, we do so because the flattened inputs
29 # are eventually passed to ConcreteFunction()._call_flat, which requires
30 # expanded composites.
31 flat_inputs = []
32 for value in nest.flatten(inputs):
33 if (isinstance(value, composite_tensor.CompositeTensor) and
34 not _pywrap_utils.IsResourceVariable(value)):
35 components = value._type_spec._to_components(value) # pylint: disable=protected-access
36 flat_inputs.extend(flatten_with_variables(components))
37 else:
38 flat_inputs.append(value)
39 return flat_inputs