第17章 TensorFlow 中的 NumPy API
NumPy API on TensorFlow
在 TensorFlow.org 上查看 | 在 Google Colab 中运行 | 在 GitHub 上查看源代码 | 下载笔记本
概述
TensorFlow 实现了 NumPy API 的一个子集,可通过 tf.experimental.numpy 访问。这使得你可以在 TensorFlow 加速下运行 NumPy 代码,同时还能访问 TensorFlow 的所有 API。
环境搭建
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import tensorflow.experimental.numpy as tnp
import timeit
print("Using TensorFlow version %s" % tf.__version__)
2024-08-15 01:31:55.452313: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:485] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered 2024-08-15 01:31:55.473711: E external/local_xla/xla/stream_executor/cuda/cuda_dnn.cc:8454] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered 2024-08-15 01:31:55.480014: E external/local_xla/xla/stream_executor/cuda/cuda_blas.cc:1452] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered Using TensorFlow version 2.17.0
启用 NumPy 行为
若要将 tnp 作为 NumPy 使用,需为 TensorFlow 启用 NumPy 行为:
tnp.experimental_enable_numpy_behavior()
此调用会在 TensorFlow 中启用类型提升(type promotion),并改变字面量转换为张量时的类型推断,使其更严格地遵循 NumPy 标准。
TensorFlow NumPy ND 数组
tf.experimental.numpy.ndarray 的实例(称为 ND 数组)表示放置在特定设备上的、具有指定 dtype 的多维稠密数组。它是 tf.Tensor 的别名。请查看 ND array 类以了解诸如 ndarray.T、ndarray.reshape、ndarray.ravel 等实用方法。
首先创建 ND 数组对象,然后调用不同方法。
# 创建 ND 数组并查看不同属性。
ones = tnp.ones([5, 3], dtype=tnp.float32)
print("Created ND array with shape = %s, rank = %s, "
"dtype = %s on device = %s\n" % (
ones.shape, ones.ndim, ones.dtype, ones.device))
# `ndarray` 只是 `tf.Tensor` 的别名。
print("Is `ones` an instance of tf.Tensor: %s\n" % isinstance(ones, tf.Tensor))
# 尝试常用的成员函数。
print("ndarray.T has shape %s" % str(ones.T.shape))
print("narray.reshape(-1) has shape %s" % ones.reshape(-1).shape)
Created ND array with shape = (5, 3), rank = 2, dtype = <dtype: 'float32'> on device = /job:localhost/replica:0/task:0/device:GPU:0
Is `ones` an instance of tf.Tensor: True
ndarray.T has shape (3, 5)
narray.reshape(-1) has shape (15,)
WARNING: All log messages before absl::InitializeLog() is called are written to STDERR
I0000 00:00:1723685517.895102 23752 cuda_executor.cc:1015] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero. See more at https://github.com/torvalds/linux/blob/v6.0/Documentation/ABI/testing/sysfs-bus-pci#L344-L355
... [日志信息略] ...
类型提升
TensorFlow 中有 4 种类型提升选项。
- 默认情况下,TensorFlow 对混合类型操作会引发错误,而不是提升类型。
- 运行 tf.numpy.experimental_enable_numpy_behavior() 会使 TensorFlow 切换为使用 NumPy 类型提升规则(详见下文)。
- TensorFlow 2.15 之后,新增了两个选项(详见 TF NumPy Type Promotion):
- tf.numpy.experimental_enable_numpy_behavior(dtype_conversion_mode="all") 使用 Jax 类型提升规则。
- tf.numpy.experimental_enable_numpy_behavior(dtype_conversion_mode="safe") 使用 Jax 类型提升规则,但禁止某些不安全的提升。
NumPy 类型提升
TensorFlow NumPy API 对将字面量转换为 ND 数组以及在对 ND 数组输入执行类型提升时,具有明确定义语义。详情请见 np.result_type。
TensorFlow API 会保持 tf.Tensor 输入不变,不对它们执行类型提升;而 TensorFlow NumPy API 会根据 NumPy 类型提升规则对所有输入进行提升。在下一个示例中,我们将执行类型提升。首先,对不同类型的 ND 数组输入执行加法,并注意输出类型。这些类型提升在 TensorFlow API 中都是不允许的。
print("Type promotion for operations")
values = [tnp.asarray(1, dtype=d) for d in
(tnp.int32, tnp.int64, tnp.float32, tnp.float64)]
for i, v1 in enumerate(values):
for v2 in values[i + 1:]:
print("%s + %s => %s" %
(v1.dtype.name, v2.dtype.name, (v1 + v2).dtype.name))
Type promotion for operations
int32 + int64 => int64
int32 + float32 => float64
int32 + float64 => float64
int64 + float32 => float64
int64 + float64 => float64
float32 + float64 => float64
最后,使用 ndarray.asarray 将字面量转换为 ND 数组,并注意生成的类型。
print("Type inference during array creation")
print("tnp.asarray(1).dtype == tnp.%s" % tnp.asarray(1).dtype.name)
print("tnp.asarray(1.).dtype == tnp.%s\n" % tnp.asarray(1.).dtype.name)
Type inference during array creation
tnp.asarray(1).dtype == tnp.int64
tnp.asarray(1.).dtype == tnp.float64
将字面量转换为 ND 数组时,NumPy 优先选择较宽的类型,如 tnp.int64 和 tnp.float64。相比之下,tf.convert_to_tensor 在将常量转换为 tf.Tensor 时优先使用 tf.int32 和 tf.float32。TensorFlow NumPy API 对整数遵循 NumPy 的行为。对于浮点数,experimental_enable_numpy_behavior 的 prefer_float32 参数允许你控制是否优先使用 tf.float32 而非 tf.float64(默认为 False)。例如:
tnp.experimental_enable_numpy_behavior(prefer_float32=True)
print("When prefer_float32 is True:")
print("tnp.asarray(1.).dtype == tnp.%s" % tnp.asarray(1.).dtype.name)
print("tnp.add(1., 2.).dtype == tnp.%s" % tnp.add(1., 2.).dtype.name)
tnp.experimental_enable_numpy_behavior(prefer_float32=False)
print("When prefer_float32 is False:")
print("tnp.asarray(1.).dtype == tnp.%s" % tnp.asarray(1.).dtype.name)
print("tnp.add(1., 2.).dtype == tnp.%s" % tnp.add(1., 2.).dtype.name)
When prefer_float32 is True:
tnp.asarray(1.).dtype == tnp.float32
tnp.add(1., 2.).dtype == tnp.float32
When prefer_float32 is False:
tnp.asarray(1.).dtype == tnp.float64
tnp.add(1., 2.).dtype == tnp.float64
广播
与 TensorFlow 类似,NumPy 为“广播”值定义了丰富的语义。
你可以查阅 NumPy broadcasting guide 获取更多信息,并将其与 TensorFlow 广播语义进行比较。
x = tnp.ones([2, 3])
y = tnp.ones([3])
z = tnp.ones([1, 2, 1])
print("Broadcasting shapes %s, %s and %s gives shape %s" % (
x.shape, y.shape, z.shape, (x + y + z).shape))
Broadcasting shapes (2, 3), (3,) and (1, 2, 1) gives shape (1, 2, 3)
索引
NumPy 定义了非常复杂的索引规则。参见 NumPy Indexing guide。注意下文将 ND 数组用作索引的用法。
x = tnp.arange(24).reshape(2, 3, 4)
print("Basic indexing")
print(x[1, tnp.newaxis, 1:3, ...], "\n")
print("Boolean indexing")
print(x[:, (True, False, True)], "\n")
print("Advanced indexing")
print(x[1, (0, 0, 1), tnp.asarray([0, 1, 1])])
Basic indexing
tf.Tensor(
[[[16 17 18 19]
[20 21 22 23]]], shape=(1, 2, 4), dtype=int64)
Boolean indexing
tf.Tensor(
[[[ 0 1 2 3]
[ 8 9 10 11]]
[[12 13 14 15]
[20 21 22 23]]], shape=(2, 2, 4), dtype=int64)
Advanced indexing
tf.Tensor([12 13 17], shape=(3,), dtype=int64)
# 目前不支持变更
try:
tnp.arange(6)[1] = -1
except TypeError:
print("Currently, TensorFlow NumPy does not support mutation.")
Currently, TensorFlow NumPy does not support mutation.
示例模型
接下来,我们将展示如何创建模型并对其进行推理。这个简单模型先应用一个 relu 层,然后进行线性投影。后续章节将展示如何使用 TensorFlow 的 GradientTape 为此模型计算梯度。
class Model(object):
"""Model with a dense and a linear layer."""
def __init__(self):
self.weights = None
def predict(self, inputs):
if self.weights is None:
size = inputs.shape[1]
# 注意,为了性能使用类型 `tnp.float32`。
stddev = tnp.sqrt(size).astype(tnp.float32)
w1 = tnp.random.randn(size, 64).astype(tnp.float32) / stddev
bias = tnp.random.randn(64).astype(tnp.float32)
w2 = tnp.random.randn(64, 2).astype(tnp.float32) / 8
self.weights = (w1, bias, w2)
else:
w1, bias, w2 = self.weights
y = tnp.matmul(inputs, w1) + bias
y = tnp.maximum(y, 0) # Relu
return tnp.matmul(y, w2) # 线性投影
model = Model()
# 创建输入数据并计算预测值。
print(model.predict(tnp.ones([2, 32], dtype=tnp.float32)))
tf.Tensor(
[[-0.8292594 0.75780904]
[-0.8292594 0.75780904]], shape=(2, 2), dtype=float32)
TensorFlow NumPy 与 NumPy
TensorFlow NumPy 实现了完整 NumPy 规范的一个子集。虽然随着时间的推移会添加更多符号,但有一些系统性功能在近期将不被支持。这包括 NumPy C API 支持、Swig 集成、Fortran 存储顺序、视图和 stride_tricks,以及一些 dtype(如 np.recarray 和 np.object)。更多细节请参阅 TensorFlow NumPy API Documentation。
NumPy 互操作性
TensorFlow ND 数组可以与 NumPy 函数互操作。这些对象实现了 __array__ 接口。NumPy 使用此接口在处理函数参数之前将其转换为 np.ndarray 值。
同样,TensorFlow NumPy 函数可以接受不同类型的输入,包括 np.ndarray。这些输入通过调用 ndarray.asarray 转换为 ND 数组。
ND 数组与 np.ndarray 之间的转换可能会触发实际的数据复制。更多细节请参阅关于 buffer copies 的章节。
# ND array passed into NumPy function.
np_sum = np.sum(tnp.ones([2, 3]))
print("sum = %s. Class: %s" % (float(np_sum), np_sum.__class__))
# `np.ndarray` passed into TensorFlow NumPy function.
tnp_sum = tnp.sum(np.ones([2, 3]))
print("sum = %s. Class: %s" % (float(tnp_sum), tnp_sum.__class__))
sum = 6.0. Class: <class 'numpy.float64'>
sum = 6.0. Class: <class 'tensorflow.python.framework.ops.EagerTensor'>
# 给定 __array__ 接口,绘制 ND 数组很容易。
labels = 15 + 2 * tnp.random.randn(1, 1000)
_ = plt.hist(labels)
Buffer 复制
将 TensorFlow NumPy 与 NumPy 代码混合使用可能会触发数据复制。这是因为 TensorFlow NumPy 对内存对齐的要求比 NumPy 更严格。
当 np.ndarray 传递给 TensorFlow NumPy 时,它会检查对齐要求并在必要时触发复制。当将 ND 数组 CPU 缓冲区传递给 NumPy 时,通常缓冲区满足对齐要求,NumPy 无需创建副本。
ND 数组可以引用放置在本地 CPU 内存之外的设备上的缓冲区。在这种情况下,调用 NumPy 函数将根据需要在网络或设备间触发复制。
鉴于此,混合使用 NumPy API 调用通常应谨慎进行,用户应注意数据复制带来的开销。交错使用 TensorFlow NumPy 调用和 TensorFlow 调用通常是安全的,可以避免数据复制。更多细节请参阅关于 TensorFlow 互操作性的章节。
运算符优先级
TensorFlow NumPy 定义了比 NumPy 更高的 __array_priority__。这意味着对于涉及 ND 数组和 np.ndarray 的运算符,前者将优先,即 np.ndarray 输入将转换为 ND 数组,并调用 TensorFlow NumPy 的运算符实现。
x = tnp.ones([2]) + np.ones([2])
print("x = %s\nclass = %s" % (x, x.__class__))
x = tf.Tensor([2. 2.], shape=(2,), dtype=float64)
class = <class 'tensorflow.python.framework.ops.EagerTensor'>
TF NumPy 与 TensorFlow
TensorFlow NumPy 构建在 TensorFlow 之上,因此与 TensorFlow 无缝互操作。
tf.Tensor 与 ND 数组
ND 数组是 tf.Tensor 的别名,因此显然可以混合使用而不会触发实际的数据复制。
x = tf.constant([1, 2])
print(x)
# 这里的 `asarray` 和 `convert_to_tensor` 都是无操作。
tnp_x = tnp.asarray(x)
print(tnp_x)
print(tf.convert_to_tensor(tnp_x))
# 注意 `tf.Tensor.numpy()` 将继续返回 `np.ndarray`。
print(x.numpy(), x.numpy().__class__)
tf.Tensor([1 2], shape=(2,), dtype=int32)
tf.Tensor([1 2], shape=(2,), dtype=int32)
tf.Tensor([1 2], shape=(2,), dtype=int32)
[1 2] <class 'numpy.ndarray'>
TensorFlow 互操作性
由于 ND 数组只是 tf.Tensor 的别名,因此可以传递给 TensorFlow API。如前所述,这种互操作即使对于放置在加速器或远程设备上的数据,也不会进行数据复制。
反过来,tf.Tensor 对象也可以传递给 tf.experimental.numpy API,而无需进行数据复制。
# ND array passed into TensorFlow function.
tf_sum = tf.reduce_sum(tnp.ones([2, 3], tnp.float32))
print("Output = %s" % tf_sum)
# `tf.Tensor` passed into TensorFlow NumPy function.
tnp_sum = tnp.sum(tf.ones([2, 3]))
print("Output = %s" % tnp_sum)
Output = tf.Tensor(6.0, shape=(), dtype=float32)
Output = tf.Tensor(6.0, shape=(), dtype=float32)
梯度和雅可比矩阵:tf.GradientTape
TensorFlow 的 GradientTape 可用于通过 TensorFlow 和 TensorFlow NumPy 代码进行反向传播。
使用“示例模型”章节中创建的模型,计算梯度和雅可比矩阵。
def create_batch(batch_size=32):
"""Creates a batch of input and labels."""
return (tnp.random.randn(batch_size, 32).astype(tnp.float32),
tnp.random.randn(batch_size, 2).astype(tnp.float32))
def compute_gradients(model, inputs, labels):
"""Computes gradients of squared loss between model prediction and labels."""
with tf.GradientTape() as tape:
assert model.weights is not None
# 注意,由于 `model.weights` 不是 tf.Variable,需要明确监视它们。
tape.watch(model.weights)
# 计算预测值和损失
prediction = model.predict(inputs)
loss = tnp.sum(tnp.square(prediction - labels))
# 此调用计算上述计算的梯度。
return tape.gradient(loss, model.weights)
inputs, labels = create_batch()
gradients = compute_gradients(model, inputs, labels)
# 检查返回梯度的形状,验证其与参数形状匹配。
print("Parameter shapes:", [w.shape for w in model.weights])
print("Gradient shapes:", [g.shape for g in gradients])
# 验证梯度类型为 ND array。
assert isinstance(gradients[0], tnp.ndarray)
Parameter shapes: [TensorShape([32, 64]), TensorShape([64]), TensorShape([64, 2])]
Gradient shapes: [TensorShape([32, 64]), TensorShape([64]), TensorShape([64, 2])]
# 计算一批雅可比矩阵。每一行是批次中输出元素相对于相应输入批次元素的雅可比矩阵。
def prediction_batch_jacobian(inputs):
with tf.GradientTape() as tape:
tape.watch(inputs)
prediction = model.predict(inputs)
return prediction, tape.batch_jacobian(prediction, inputs)
inp_batch = tnp.ones([16, 32], tnp.float32)
output, batch_jacobian = prediction_batch_jacobian(inp_batch)
# 注意批次雅可比矩阵的形状如何与输入和输出形状相关联。
print("Output shape: %s, input shape: %s" % (output.shape, inp_batch.shape))
print("Batch jacobian shape:", batch_jacobian.shape)
Output shape: (16, 2), input shape: (16, 32)
Batch jacobian shape: (16, 2, 32)
追踪编译:tf.function
TensorFlow 的 tf.function 通过“追踪编译”代码,然后优化这些追踪以获得更快的性能。参见 Introduction to Graphs and Functions。
tf.function 也可以用于优化 TensorFlow NumPy 代码。这里有一个简单的示例来展示速度提升。注意 tf.function 代码体包含对 TensorFlow NumPy API 的调用。
inputs, labels = create_batch(512)
print("Eager performance")
compute_gradients(model, inputs, labels)
print(timeit.timeit(lambda: compute_gradients(model, inputs, labels),
number=10) * 100, "ms")
print("\ntf.function compiled performance")
compiled_compute_gradients = tf.function(compute_gradients)
compiled_compute_gradients(model, inputs, labels) # 热身
print(timeit.timeit(lambda: compiled_compute_gradients(model, inputs, labels),
number=10) * 100, "ms")
Eager performance
2.710705300000882 ms
tf.function compiled performance
0.7041131000050882 ms
向量化:tf.vectorized_map
TensorFlow 内置支持向量化并行循环,这可以实现一到两个数量级的速度提升。这些速度提升可通过 tf.vectorized_map API 访问,也适用于 TensorFlow NumPy 代码。
有时计算批次中每个输出相对于相应输入批次元素的梯度会很有用。如下所示,使用 tf.vectorized_map 可以高效地完成这种计算。
@tf.function
def vectorized_per_example_gradients(inputs, labels):
def single_example_gradient(arg):
inp, label = arg
return compute_gradients(model,
tnp.expand_dims(inp, 0),
tnp.expand_dims(label, 0))
# 注意,对 `tf.vectorized_map` 的调用在语义上将
# `single_example_gradient` 映射到 `inputs` 和 `labels` 的每一行。
# 接口类似于 `tf.map_fn`。
# 底层机制向量化了这个映射循环,从而带来
# 不错的速度提升。
return tf.vectorized_map(single_example_gradient, (inputs, labels))
batch_size = 128
inputs, labels = create_batch(batch_size)
per_example_gradients = vectorized_per_example_gradients(inputs, labels)
for w, p in zip(model.weights, per_example_gradients):
print("Weight shape: %s, batch size: %s, per example gradient shape: %s " % (
w.shape, batch_size, p.shape))
Weight shape: (32, 64), batch size: 128, per example gradient shape: (128, 32, 64)
Weight shape: (64,), batch size: 128, per example gradient shape: (128, 64)
Weight shape: (64, 2), batch size: 128, per example gradient shape: (128, 64, 2)
# 对上面的向量化计算进行基准测试,并与使用 `tf.map_fn` 的非向量化顺序计算进行比较。
@tf.function
def unvectorized_per_example_gradients(inputs, labels):
def single_example_gradient(arg):
inp, label = arg
return compute_gradients(model,
tnp.expand_dims(inp, 0),
tnp.expand_dims(label, 0))
return tf.map_fn(single_example_gradient, (inputs, labels),
fn_output_signature=(tf.float32, tf.float32, tf.float32))
print("Running vectorized computation")
print(timeit.timeit(lambda: vectorized_per_example_gradients(inputs, labels),
number=10) * 100, "ms")
print("\nRunning unvectorized computation")
per_example_gradients = unvectorized_per_example_gradients(inputs, labels)
print(timeit.timeit(lambda: unvectorized_per_example_gradients(inputs, labels),
number=10) * 100, "ms")
Running vectorized computation
0.659675699989748 ms
Running unvectorized computation
29.259711299982882 ms
设备放置
TensorFlow NumPy 可以将操作放置在 CPU、GPU、TPU 和远程设备上。它使用标准的 TensorFlow 机制进行设备放置。下面一个简单的示例展示了如何列出所有设备,然后将某些计算放置在特定设备上。
TensorFlow 还有用于在设备间复制计算和执行集体归约(collective reductions)的 API,这里将不予涉及。
列出设备
可以使用 tf.config.list_logical_devices 和 tf.config.list_physical_devices 查找要使用哪些设备。
print("All logical devices:", tf.config.list_logical_devices())
print("All physical devices:", tf.config.list_physical_devices())
# 尝试获取 GPU 设备。如果不可用,则回退到 CPU。
try:
device = tf.config.list_logical_devices(device_type="GPU")[0]
except IndexError:
device = "/device:CPU:0"
All logical devices: [LogicalDevice(name='/device:CPU:0', device_type='CPU'), LogicalDevice(name='/device:GPU:0', device_type='GPU'), LogicalDevice(name='/device:GPU:1', device_type='GPU'), LogicalDevice(name='/device:GPU:2', device_type='GPU'), LogicalDevice(name='/device:GPU:3', device_type='GPU')]
All physical devices: [PhysicalDevice(name='/physical_device:CPU:0', device_type='CPU'), PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU'), PhysicalDevice(name='/physical_device:GPU:1', device_type='GPU'), PhysicalDevice(name='/physical_device:GPU:2', device_type='GPU'), PhysicalDevice(name='/physical_device:GPU:3', device_type='GPU')]
放置操作:tf.device
通过调用 tf.device 范围可以放置在设备上。
print("Using device: %s" % str(device))
# 在 `tf.device` 范围中运行操作。
# 如果有可用的 GPU,这些操作将在 GPU 上执行,输出
# 将放置在 GPU 内存中。
with tf.device(device):
prediction = model.predict(create_batch(5)[0])
print("prediction is placed on %s" % prediction.device)
Using device: LogicalDevice(name='/device:GPU:0', device_type='GPU')
prediction is placed on /job:localhost/replica:0/task:0/device:GPU:0
跨设备复制 ND 数组:tnp.copy
放置在特定设备范围内的 tnp.copy 调用将数据复制到该设备,除非数据已经在该设备上。
with tf.device("/device:CPU:0"):
prediction_cpu = tnp.copy(prediction)
print(prediction.device)
print(prediction_cpu.device)
/job:localhost/replica:0/task:0/device:GPU:0
/job:localhost/replica:0/task:0/device:CPU:0
性能比较
TensorFlow NumPy 使用高度优化的 TensorFlow 内核,可以分派到 CPU、GPU 和 TPU。TensorFlow 还执行许多编译器优化,如操作融合(operation fusion),这会带来性能和内存方面的改进。请参阅 TensorFlow graph optimization with Grappler 以了解更多。
但是,与 NumPy 相比,TensorFlow 在分派操作时具有更高的开销。对于由小操作(大约小于 10 微秒)组成的工作负载,这些开销可能会主导运行时间,此时 NumPy 可能提供更好的性能。在其他情况下,TensorFlow 通常应提供更好的性能。
运行下面的基准测试以比较不同输入大小下 NumPy 和 TensorFlow NumPy 的性能。
def benchmark(f, inputs, number=30, force_gpu_sync=False):
"""Utility to benchmark `f` on each value in `inputs`."""
times = []
for inp in inputs:
def _g():
if force_gpu_sync:
one = tnp.asarray(1)
f(inp)
if force_gpu_sync:
with tf.device("CPU:0"):
tnp.copy(one) # 强制 GPU 情况下的同步
_g() # 热身
t = timeit.timeit(_g, number=number)
times.append(t * 1000. / number)
return times
def plot(np_times, tnp_times, compiled_tnp_times, has_gpu, tnp_times_gpu):
"""Plot the different runtimes."""
plt.xlabel("size")
plt.ylabel("time (ms)")
plt.title("Sigmoid benchmark: TF NumPy vs NumPy")
plt.plot(sizes, np_times, label="NumPy")
plt.plot(sizes, tnp_times, label="TF NumPy (CPU)")
plt.plot(sizes, compiled_tnp_times, label="Compiled TF NumPy (CPU)")
if has_gpu:
plt.plot(sizes, tnp_times_gpu, label="TF NumPy (GPU)")
plt.legend()
# 定义一个简单的 `sigmoid` 实现,并使用
# NumPy 和 TensorFlow NumPy 针对不同输入大小进行基准测试。
def np_sigmoid(y):
return 1. / (1. + np.exp(-y))
def tnp_sigmoid(y):
return 1. / (1. + tnp.exp(-y))
@tf.function
def compiled_tnp_sigmoid(y):
return tnp_sigmoid(y)
sizes = (2 ** 0, 2 ** 5, 2 ** 10, 2 ** 15, 2 ** 20)
np_inputs = [np.random.randn(size).astype(np.float32) for size in sizes]
np_times = benchmark(np_sigmoid, np_inputs)
with tf.device("/device:CPU:0"):
tnp_inputs = [tnp.random.randn(size).astype(np.float32) for size in sizes]
tnp_times = benchmark(tnp_sigmoid, tnp_inputs)
compiled_tnp_times = benchmark(compiled_tnp_sigmoid, tnp_inputs)
has_gpu = len(tf.config.list_logical_devices("GPU"))
if has_gpu:
with tf.device("/device:GPU:0"):
tnp_inputs = [tnp.random.randn(size).astype(np.float32) for size in sizes]
tnp_times_gpu = benchmark(compiled_tnp_sigmoid, tnp_inputs, 100, True)
else:
tnp_times_gpu = None
plot(np_times, tnp_times, compiled_tnp_times, has_gpu, tnp_times_gpu)
延伸阅读
- TensorFlow NumPy: 分布式图像分类教程
- TensorFlow NumPy: Keras 和分布式策略
- 使用 Trax 和 TensorFlow NumPy 进行情感分析