我在TF中看到这样的代码:
from tensorflow.python.eager import function
...
class _PerDeviceGenerator(dataset_ops.DatasetV2):
"""A `dummy` generator dataset."""
def __init__(self, shard_num, multi_device_iterator_resource, incarnation_id,
source_device, element_spec):
...
# TODO(b/124254153): Enable autograph once the overhead is low enough.
@function.defun(autograph=False) # Pure graph code.
def _remote_init_func():
return functional_ops.remote_call(
target=source_device,
args=init_func_concrete.captured_inputs,
Tout=[dtypes.string],
f=init_func_concrete)
self._init_func = _remote_init_func._get_concrete_function_internal() # pylint: disable=protected-access
...
variant_tensor = gen_dataset_ops.generator_dataset(
self._init_captured_args,
self._next_captured_args,
self._finalize_captured_args,
init_func=self._init_func,
next_func=self._next_func,
finalize_func=self._finalize_func,
**self._flat_structure)
super(_PerDeviceGenerator, self).__init__(variant_tensor)
(此代码段来自TF 1.15.0。)
我正在尝试理解代码。
更具体地说,我想知道这里的defun
。我以为defun
适用于急切模式。
但是在这里,此代码似乎同时用于急切模式和图形模式。还是那是错误的,并且这仅适用于渴望模式? (但下面有MultiDeviceIterator
,它的检查类似if context.executing_eagerly()
,后来又在急切模式和图形模式下都使用_PerDeviceGenerator
。或者在图形模式下也被破坏了? {1}}呢?)
executing_eagerly
在图形模式下做什么?
defun
是一些内部API?
答案 0 :(得分:0)
defun
和_get_concrete_function_internal
都是内部API。您应该尽可能使用tf.function
(或在处理内部代码时使用def_function.function
)。 defun
是一个旧的API,在很大程度上复制了function
,将来可能会删除。
也就是说,defun
不仅适用于急切模式(function
也不适用)。它们都创建TF函数,并且在图形模式下,有“函数调用”操作可让您调用这些函数。在渴望模式下,它只允许您调用TF图。但是在图模式下,它们使您可以减小图的大小,就像通过将常用代码分解为函数来减小普通代码的大小一样。