首页 > 解决方案 > 在图形模式下运行`defun`

问题描述

我在 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用于急切和图形模式。或者图形模式也被破坏了?为什么要检查executing_eagerly呢?)

在图形模式下有什么作用defun

_get_concrete_function_internal是一些内部API?

标签: tensorflow

解决方案


两者都是defun内部_get_concrete_function_internalAPI。您应该尽可能喜欢使用tf.function(或def_function.function在处理内部代码时)。defun是一个大部分重复的旧 API,function将来可能会被删除。

也就是说,defun不仅适用于急切模式(也不是function)。它们都创建了一个 TF 函数,并且在图形模式下,有“函数调用”操作可以让您调用这些函数。在 Eager 模式下,它只允许您调用 TF 图。但是在图形模式下,它们可以让您减小图形的大小,就像您通过将通用代码分解为函数来减小普通代码的大小一样。


推荐阅读