进阶 tensorflow.org 2026-10-22 02:47:47 · 21 阅读

第7章 图(Graphs)与函数

TensorFlow

TensorFlow Core

指南

图与 tf.function 简介

通过收藏保持有序
根据偏好保存和分类内容。

在 TensorFlow.org 上查看 | 在 Google Colab 中运行 | 在 GitHub 上查看源码 | 下载 Notebook

概述

本指南深入 TensorFlow 和 Keras 的核心,展示 TensorFlow 的工作原理。如果您想立即开始使用 Keras,请查阅 Keras 指南合集。

在本指南中,您将学习如何通过简单修改代码让 TensorFlow 生成图,了解图的存储与表示方式,以及如何利用图来加速模型。

这是一篇宏观概述,涵盖 tf.function 如何让您从即时执行切换到图执行。若需了解 tf.function 的完整规格,请参阅《通过 tf.function 获得更好性能》指南。

什么是图?

在之前的三个指南中,您一直在以即时模式(eager execution)运行 TensorFlow。这意味着 TensorFlow 操作由 Python 逐个执行,并将结果返回给 Python。

虽然即时执行具有独特优势,但图执行支持在非 Python 环境中移植,且通常性能更佳。图执行意味着张量计算作为 TensorFlow 图(有时称为 tf.Graph 或简称“图”)执行。

图是包含一组 tf.Operation 对象(代表计算单元)和 tf.Tensor 对象(代表在操作间流动的数据单元)的数据结构。它们在 tf.Graph 上下文中定义。由于图是数据结构,因此可以保存、运行和恢复,无需原始 Python 代码。

下图展示了在 TensorBoard 中可视化的、表示两层神经网络的 TensorFlow 图:

TensorFlow 图示例

图的优势

使用图可以提供极高的灵活性。您可以在没有 Python 解释器的环境中使用 TensorFlow 图,例如移动应用、嵌入式设备和后端服务器。TensorFlow 导出模型时,即使用图作为保存格式。

图还易于优化,允许编译器执行以下转换:

  • 通过折叠计算中的常量节点静态推断张量值(即“常量折叠”)。
  • 分离独立计算的子部分,并将它们分布在不同的线程或设备上。
  • 通过消除公共子表达式简化算术运算。

有一个完整的优化系统 Grappler 用于执行这些及其他加速任务。

简而言之,图非常有用,能让 TensorFlow 运行得更快、并行化,并高效地在多个设备上运行。

然而,为了方便起见,您仍希望在 Python 中定义机器学习模型(或其他计算),并在需要时自动构建图。

设置

导入必要的库:

import tensorflow as tf
import timeit
from datetime import datetime

日志输出:

2024-08-15 01:23:58.511668: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:485] Unable to register cuFFT factory...

2024-08-15 01:23:58.532403: E external/local_xla/xla/stream_executor/cuda/cuda_dnn.cc:8454] Unable to register cuDNN factory...

2024-08-15 01:23:58.538519: E external/local_xla/xla/stream_executor/cuda/cuda_blas.cc:1452] Unable to register cuBLAS factory...

利用图的优势

在 TensorFlow 中,通过 tf.function 创建和运行图,既可以作为直接调用,也可以作为装饰器。 tf.function 接受一个普通函数作为输入,返回一个 tf.types.experimental.PolymorphicFunction。 PolymorphicFunction 是一个 Python 可调用对象,能从 Python 函数构建 TensorFlow 图。使用 tf.function 的方式与其 Python 等效函数相同。

# 定义一个 Python 函数。
def a_regular_function(x, y, b):
  x = tf.matmul(x, y)
  x = x + b
  return x

# `a_function_that_uses_a_graph` 的 Python 类型现在是
# `PolymorphicFunction`。
a_function_that_uses_a_graph = tf.function(a_regular_function)

# 创建一些张量。
x1 = tf.constant([[1.0, 2.0]])
y1 = tf.constant([[2.0], [3.0]])
b1 = tf.constant(4.0)

orig_value = a_regular_function(x1, y1, b1).numpy()
# 像调用 Python 函数一样调用 `tf.function`。
tf_function_value = a_function_that_uses_a_graph(x1, y1, b1).numpy()
assert(orig_value == tf_function_value)

警告/日志信息:

WARNING: All log messages before absl::InitializeLog() is called are written to STDERR

I0000 00:00:1723685041.078349 ... successful NUMA node read from SysFS had negative value (-1)...

从外部看,tf.function 就像一个使用 TensorFlow 操作编写的普通函数。然而,其内部机制截然不同。底层的 PolymorphicFunction 在一个 API 背后封装了多个 tf.Graph(了解更多内容请参阅多态部分)。这就是 tf.function 能够提供图执行优势(如速度和可部署性)的方式(参见上文《图的优势》)。

tf.function 应用于一个函数及其调用的所有其他函数:

def inner_function(x, y, b):
  x = tf.matmul(x, y)
  x = x + b
  return x

# 使用 `tf.function` 装饰器使 `outer_function` 成为
# `PolymorphicFunction`。
@tf.function
def outer_function(x):
  y = tf.constant([[2.0], [3.0]])
  b = tf.constant(4.0)
  return inner_function(x, y, b)

# 注意:可调用对象将创建一个包含 `inner_function` 和 `outer_function` 的图。
outer_function(tf.constant([[1.0, 2.0]])).numpy()

输出: array([[12.]], dtype=float32)

如果您使用过 TensorFlow 1.x,会注意到全程无需定义 Placeholder 或 tf.Session。

将 Python 函数转换为图

您用 TensorFlow 编写的任何函数都包含内置 TF 操作和 Python 逻辑(如 if-then 语句、循环、break、return、continue 等)的混合。虽然 TensorFlow 操作可轻松被 tf.Graph 捕获,但 Python 特定逻辑需要额外步骤才能成为图的一部分。tf.function 使用名为 AutoGraph (tf.autograph) 的库将 Python 代码转换为生成图的代码。

def simple_relu(x):
  if tf.greater(x, 0):
    return x
  else:
    return 0

# 使用 `tf.function` 使 `tf_simple_relu` 成为包装
# `simple_relu` 的 `PolymorphicFunction`。
tf_simple_relu = tf.function(simple_relu)

print("First branch, with graph:", tf_simple_relu(tf.constant(1)).numpy())
print("Second branch, with graph:", tf_simple_relu(tf.constant(-1)).numpy())

输出: First branch, with graph: 1 Second branch, with graph: 0

虽然您不太需要直接查看图,但可以检查输出以确认确切结果。这些内容不易阅读,因此不必细究!

# 这是 AutoGraph 的生成图输出。
print(tf.autograph.to_code(simple_relu))

# 这是图本身。
print(tf_simple_relu.get_concrete_function(tf.constant(1)).graph.as_graph_def())

(此处省略了生成的 AutoGraph 代码和 protobuf 格式的图定义详细内容,通常在实际文档中会显示完整的代码块和图结构,但在本文翻译中,重点在于解释其逻辑。)

大多数情况下,tf.function 无需特殊考虑即可正常工作。然而存在一些注意事项,tf.function 指南和完整的 AutoGraph 参考可以提供帮助。

多态性:一个 tf.function,多个图

tf.Graph 专门针对特定类型的输入(例如具有特定 dtype 的张量或具有相同 id() 的对象)。

每次调用 tf.function 时,如果传入的参数无法由现有图处理(例如新 dtype 或形状不兼容的参数),它就会创建一个专门针对这些新参数的新 tf.Graph。 tf.Graph 输入的类型规范由 tf.types.experimental.FunctionType 表示,也称为签名(signature)。有关何时生成新 tf.Graph、如何控制该过程以及 FunctionType 用法的更多信息,请参阅《通过 tf.function 获得更好性能》指南中的《追踪规则》部分。

tf.function 将对应于该签名的 tf.Graph 存储在 ConcreteFunction 中。ConcreteFunction 可以被视为 tf.Graph 的封装器。

@tf.function
def my_relu(x):
  return tf.maximum(0., x)

# `my_relu` 在观察到不同输入类型时会创建新图。
print(my_relu(tf.constant(5.5)))
print(my_relu([1, -1]))
print(my_relu(tf.constant([3., -3.])))

输出: tf.Tensor(5.5, shape=(), dtype=float32) tf.Tensor([1. 0.], shape=(2,), dtype=float32) tf.Tensor([3. 0.], shape=(2,), dtype=float32)

如果 tf.function 之前已使用相同的输入类型调用过,它不会创建新的 tf.Graph。

# 这两个调用不会创建新图。
print(my_relu(tf.constant(-2.5))) # 输入类型匹配 `tf.constant(5.5)`。
print(my_relu(tf.constant([-1., 1.]))) # 输入类型匹配 `tf.constant([3., -3.])`。

输出: tf.Tensor(0.0, shape=(), dtype=float32) tf.Tensor([0. 1.], shape=(2,), dtype=float32)

由于 tf.function 由多个图支持,因此它是多态的(正如名称“PolymorphicFunction”所暗示的那样)。这使其能够支持比单个 tf.Graph 能表示更多的输入类型,并针对每个 tf.Graph 进行优化以提升性能。

# `my_relu` 中有三个 `ConcreteFunction`(每个图对应一个)。
# `ConcreteFunction` 还知道返回类型和形状!
print(my_relu.pretty_printed_concrete_signatures())

输出(简化显示):

Input Parameters: x (POSITIONAL_OR_KEYWORD): TensorSpec(shape=(), dtype=tf.float32, name=None)

Output Type: TensorSpec(shape=(), dtype=tf.float32, name=None)

...

使用 tf.function

到目前为止,您已学习如何通过将 tf.function 用作装饰器或包装器将 Python 函数转换为图。但在实践中,让 tf.function 正确工作可能具有挑战性!在以下部分中,您将学习如何让代码按预期与 tf.function 协同工作。

图执行与即时执行

tf.function 中的代码可以即时执行,也可以作为图执行。默认情况下,tf.function 将代码作为图执行:

@tf.function
def get_MSE(y_true, y_pred):
  sq_diff = tf.pow(y_true - y_pred, 2)
  return tf.reduce_mean(sq_diff)
y_true = tf.random.uniform([5], maxval=10, dtype=tf.int32)
y_pred = tf.random.uniform([5], maxval=10, dtype=tf.int32)
print(y_true)
print(y_pred)

get_MSE(y_true, y_pred)

输出: tf.Tensor([2 0 7 2 3], shape=(5,), dtype=int32) tf.Tensor([9 9 1 1 5], shape=(5,), dtype=int32) <tf.Tensor: shape=(), dtype=int32, numpy=34>

为了验证 tf.function 的图是否与等效 Python 函数执行相同的计算,可以使用 tf.config.run_functions_eagerly(True) 让其即时执行。这是一个开关,关闭 tf.function 创建和运行图的能力,改为正常执行代码。

tf.config.run_functions_eagerly(True)
get_MSE(y_true, y_pred)
# 完成后别忘了重置。
tf.config.run_functions_eagerly(False)

然而,tf.function 在图执行和即时执行下可能表现不同。Python 的 print 函数就是这两种模式差异的一个例子。让我们看看在函数中插入 print 语句并反复调用时会发生什么。

@tf.function
def get_MSE(y_true, y_pred):
  print("Calculating MSE!")
  sq_diff = tf.pow(y_true - y_pred, 2)
  return tf.reduce_mean(sq_diff)

# 观察打印的内容:
error = get_MSE(y_true, y_pred)
error = get_MSE(y_true, y_pred)
error = get_MSE(y_true, y_pred)

输出: Calculating MSE!

输出令人惊讶吗?尽管 get_MSE 被调用了三次,但它只打印了一次。

解释如下:当 tf.function 运行原始代码以创建图时,print 语句会执行,这一过程称为“追踪”(refer to the Tracing section of the tf.function guide)。追踪将 TensorFlow 操作捕获到图中,但 print 未被捕获。随后,该图在三处调用中执行,而无需再次运行 Python 代码。

作为合理性检查,让我们关闭图执行以进行对比:

# 现在全局设置所有代码为即时执行,以强制即时执行。
tf.config.run_functions_eagerly(True)
# 观察下面打印的内容。
error = get_MSE(y_true, y_pred)
error = get_MSE(y_true, y_pred)
error = get_MSE(y_true, y_pred)
tf.config.run_functions_eagerly(False)

输出: Calculating MSE! Calculating MSE! Calculating MSE!

print 是 Python 的副作用,将函数转换为 tf.function 时还应注意其他差异。在《通过 tf.function 获得更好性能》指南的《局限性》部分了解更多信息。

非严格执行

图执行仅运行产生可观察效果所必需的操作,这些效果包括:

  • 函数的返回值
  • 文档中已知的副作用,例如:
    • 输入/输出操作,如 tf.print
    • 调试操作,如 tf.debugging 中的 assert 函数
    • tf.Variable 的修改

这种行为通常被称为“非严格执行”,不同于逐步执行所有程序操作(无论是否需要)的即时执行。

特别地,运行时错误检查不算作可观察效果。如果因不必要而跳过了某个操作,它就不会引发任何运行时错误。

在下面的示例中,“不必要”的操作 tf.gather 在图执行期间被跳过,因此不会像即时执行那样引发 InvalidArgumentError 运行时错误。执行图时不要依赖错误会被引发。

def unused_return_eager(x):
  # 当 `len(x) == 1` 时,获取索引 1 会失败
  tf.gather(x, [1]) # 未使用 
  return x

try:
  print(unused_return_eager(tf.constant([0.0])))
except tf.errors.InvalidArgumentError as e:
  # 即时执行期间所有操作都会运行,因此会引发错误。
  print(f'{type(e).__name__}: {e}')

@tf.function
def unused_return_graph(x):
  tf.gather(x, [1]) # 未使用
  return x

# 图执行期间只运行必要的操作。错误未被引发。
print(unused_return_graph(tf.constant([0.0])))

tf.function 最佳实践

可能需要一些时间来适应 tf.function 的行为。为了快速入门,首次使用者应尝试用 @tf.function 装饰玩具函数,以积累从即时到图执行的经验。

为 tf.function 进行设计可能是编写兼容图的 TensorFlow 程序的最佳方法。以下是一些建议:

  • 早期且频繁地使用 tf.config.run_functions_eagerly 在即时和图执行之间切换,以定位两种模式分叉的情况/时间。
  • 在 Python 函数外部创建 tf.Variable,并在内部修改它们。对于使用 tf.Variable 的对象(如 tf.keras.layers、tf.keras.Models 和 tf.keras.optimizers)也是如此。
  • 避免编写依赖外部 Python 变量的函数(tf.Variable 和 Keras 对象除外)。在 tf.function 指南的《依赖 Python 全局和自由变量》部分了解更多。
  • 优先编写以张量和其他 TensorFlow 类型为输入的函数。可以传入其他对象类型,但需小心!在 tf.function 指南的《依赖 Python 对象》部分了解更多。
  • 将尽可能多的计算包含在 tf.function 下以最大化性能提升。例如,装饰整个训练步骤或整个训练循环。

观察加速效果

tf.function 通常会提高代码性能,但加速程度取决于运行的计算类型。小型计算可能被调用图的开销所主导。您可以这样测量性能差异:

x = tf.random.uniform(shape=[10, 10], minval=-1, maxval=2, dtype=tf.dtypes.int32)

def power(x, y):
  result = tf.eye(10, dtype=tf.dtypes.int32)
  for _ in range(y):
    result = tf.matmul(x, result)
  return result

print("Eager execution:", timeit.timeit(lambda: power(x, 100), number=1000), "seconds")

power_as_graph = tf.function(power)
print("Graph execution:", timeit.timeit(lambda: power_as_graph(x, 100), number=1000), "seconds")

输出: Eager execution: 4.1027931490000356 seconds Graph execution: 0.7951284349999241 seconds

tf.function 常用于加速训练循环,您可以参考《从零开始使用 Keras 编写训练循环》指南中的《使用 tf.function 加速训练步骤》部分了解更多信息。

性能与权衡

图可以加速代码,但创建图的过程存在一些开销。对于某些函数,创建图所需的时间可能超过执行图的时间。这种投入通常很快通过后续执行的性能提升得到回报,但重要的是要意识到,由于追踪,任何大型模型训练的前几步可能会较慢。

无论模型多大,您都希望避免频繁追踪。在 tf.function 指南的《控制重新追踪》部分,讨论了如何设置输入规范和使用张量参数以避免重新追踪。如果发现性能异常差,检查是否意外发生了重新追踪是个好主意。

tf.function 何时在追踪?

要弄清 tf.function 何时在追踪,请在其代码中添加 print 语句。作为经验法则,tf.function 每次追踪时都会执行该 print 语句。

@tf.function
def a_function_with_python_side_effect(x):
  print("Tracing!") # 仅即时执行的副作用。
  return x * x + tf.constant(2)

# 第一次会追踪。
print(a_function_with_python_side_effect(tf.constant(2)))
# 第二次不会看到副作用。
print(a_function_with_python_side_effect(tf.constant(3)))

输出: Tracing! tf.Tensor(6, shape=(), dtype=int32) tf.Tensor(11, shape=(), dtype=int32)

# Python 参数每次改变时都会重新追踪,
# 因为 Python 参数可能是 epoch 计数或其他超参数。
print(a_function_with_python_side_effect(2))
print(a_function_with_python_side_effect(3))

输出: Tracing! tf.Tensor(6, shape=(), dtype=int32) Tracing! tf.Tensor(11, shape=(), dtype=int32)

新的 Python 参数总是触发新图的创建,因此产生额外的追踪。

下一步

您可以在 API 参考页面以及《通过 tf.function 获得更好性能》指南中了解更多关于 tf.function 的信息。

评论 (0)