第16章 TensorFlow 随机数生成详解
TensorFlow 在 tf.random 模块中提供了一套伪随机数生成器(RNG)。本文介绍如何控制这些随机数生成器,以及它们如何与 TensorFlow 的其他子系统交互。
TensorFlow 提供两种控制随机数生成的方式:
通过显式使用 tf.random.Generator 对象。每个此类对象都维护一个状态(存储在 tf.Variable 中),每次生成随机数后状态都会更新。 通过纯函数式的无状态随机函数,如 tf.random.stateless_uniform。只要传入相同的参数(包括 seed)并在相同设备上调用,这些函数总是返回相同的结果。
设置 import tensorflow as tf
# Creates some virtual devices (cpu:0, cpu:1, etc.) for using distribution strategy physical_devices = tf.config.list_physical_devices("CPU") tf.config.experimental.set_virtual_device_configuration( physical_devices[0], [ tf.config.experimental.VirtualDeviceConfiguration(), tf.config.experimental.VirtualDeviceConfiguration(), tf.config.experimental.VirtualDeviceConfiguration() ])
2024-08-15 01:43:41.157432: 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:43:41.178819: 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:43:41.185039: 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 WARNING: All log messages before absl::InitializeLog() is called are written to STDERR I0000 00:00:1723686223.758551 55391 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
tf.random.Generator 类
当你希望每次 RNG 调用都产生不同结果时,可以使用 tf.random.Generator 类。它维护一个内部状态(由 tf.Variable 对象管理),每次生成随机数时都会更新。由于状态由 tf.Variable 管理,因此可以享受 tf.Variable 的所有便利,例如轻松保存 checkpoint、自动控制依赖和线程安全。
你可以手动创建一个 tf.random.Generator 对象,或者调用 tf.random.get_global_generator() 获取默认的全局生成器: g1 = tf.random.Generator.from_seed(1) print(g1.normal(shape=[2, 3])) g2 = tf.random.get_global_generator() print(g2.normal(shape=[2, 3]))
tf.Tensor( [[ 0.43842277 -0.53439844 -0.07710262] [ 1.5658045 -0.1012345 -0.2744976 ]], shape=(2, 3), dtype=float32) tf.Tensor( [[ 1.3061213 0.6299361 0.52625704] [ 1.3733886 0.29277426 -0.7945693 ]], shape=(2, 3), dtype=float32)
创建生成器对象有多种方式,最简单的是上面示例中的 Generator.from_seed,它根据一个 seed 创建生成器。seed 可以是任意非负整数。from_seed 还接受一个可选参数 alg,用于指定该生成器使用的 RNG 算法: g1 = tf.random.Generator.from_seed(1, alg='philox') print(g1.normal(shape=[2, 3]))
tf.Tensor( [[ 0.43842277 -0.53439844 -0.07710262] [ 1.5658045 -0.1012345 -0.2744976 ]], shape=(2, 3), dtype=float32)
更多细节请参见下文的"算法"部分。
另一种创建方式是 Generator.from_non_deterministic_state。用这种方式创建的生成器会从一个非确定性的状态开始,该状态取决于例如时间和操作系统等因素。 g = tf.random.Generator.from_non_deterministic_state() print(g.normal(shape=[2, 3]))
tf.Tensor( [[ 0.9104948 -0.23143363 -0.09841432] [-0.91448975 0.1579936 1.3923475 ]], shape=(2, 3), dtype=float32)
还有其他创建生成器的方式,比如基于显式状态创建,本指南不作介绍。
使用 tf.random.get_global_generator 获取全局生成器时,需要注意设备放置问题。全局生成器在第一次调用 tf.random.get_global_generator 时(从非确定性状态)创建,并放置在该次调用时的默认设备上。例如,如果第一次调用发生在 tf.device("gpu") 作用域内,全局生成器就会被放在 GPU 上,之后在 CPU 上使用它会产生 GPU 到 CPU 的复制开销。
另外还有一个函数 tf.random.set_global_generator,可以用另一个生成器对象替换全局生成器。但使用时要小心,因为旧的全局生成器可能已被某个 tf.function 以弱引用方式捕获,替换后它会被垃圾回收,从而导致该 tf.function 失效。更好的重置方式是使用某个 "reset" 函数(如 Generator.reset_from_seed),它不会创建新的生成器对象。 g = tf.random.Generator.from_seed(1) print(g.normal([])) print(g.normal([])) g.reset_from_seed(1) print(g.normal([]))
tf.Tensor(0.43842277, shape=(), dtype=float32) tf.Tensor(1.6272374, shape=(), dtype=float32) tf.Tensor(0.43842277, shape=(), dtype=float32)
创建相互独立的随机数流
许多应用需要多条相互独立的随机数流——所谓独立,是指它们互不重叠,也不存在统计上可检测的相关性。这可以通过 Generator.split 实现:它会创建多个生成器,并保证它们彼此独立(即产生相互独立的随机数流)。 g = tf.random.Generator.from_seed(1) print(g.normal([])) new_gs = g.split(3) for new_g in new_gs: print(new_g.normal([])) print(g.normal([]))
tf.Tensor(0.43842277, shape=(), dtype=float32) tf.Tensor(2.536413, shape=(), dtype=float32) tf.Tensor(0.33186463, shape=(), dtype=float32) tf.Tensor(-0.07144657, shape=(), dtype=float32) tf.Tensor(-0.79253083, shape=(), dtype=float32)
split 会改变被调用生成器(上例中的 g)的状态,类似于 normal 这样的 RNG 方法。除了新生成器(new_gs)之间相互独立之外,它们还保证与原生成器(g)相互独立。
当你希望所用生成器与其他计算位于同一设备上、从而避免跨设备复制的开销时,派生新生成器也很有用。例如: with tf.device("cpu"): # change "cpu" to the device you want g = tf.random.get_global_generator().split(1)[0] print(g.normal([])) # use of g won't cause cross-device copy, unlike the global generator
tf.Tensor(-0.66787744, shape=(), dtype=float32)
你还可以递归地进行拆分,即对 split 产生的生成器再调用 split。递归深度没有限制(除非整数溢出)。
与 tf.function 的交互
tf.random.Generator 与 tf.function 一起使用时遵循与 tf.Variable 相同的规则,涉及三个方面。
在 tf.function 外部创建生成器
tf.function 可以使用在其外部创建的生成器。 g = tf.random.Generator.from_seed(1) @tf.function def foo(): return g.normal([]) print(foo())
tf.Tensor(0.43842277, shape=(), dtype=float32)
用户需要确保在函数被调用时生成器对象仍然存活(未被垃圾回收)。
在 tf.function 内部创建生成器
在 tf.function 内部创建生成器只能发生在函数的第一次运行时。 g = None @tf.function def foo(): global g if g is None: g = tf.random.Generator.from_seed(1) return g.normal([]) print(foo()) print(foo())
tf.Tensor(0.43842277, shape=(), dtype=float32) tf.Tensor(1.6272374, shape=(), dtype=float32)
将生成器作为参数传入 tf.function
当生成器作为 tf.function 的参数时,不同的生成器对象会导致 tf.function 重新 tracing。 num_traces = 0 @tf.function def foo(g): global num_traces num_traces += 1 return g.normal([]) foo(tf.random.Generator.from_seed(1)) foo(tf.random.Generator.from_seed(2)) print(num_traces)
2
注意,这种重新 tracing 的行为与 tf.Variable 一致: num_traces = 0 @tf.function def foo(v): global num_traces num_traces += 1 return v.read_value() foo(tf.Variable(1)) foo(tf.Variable(2)) print(num_traces)
1
与分布策略的交互
Generator 与分布策略的交互有两种方式。
在分布策略外部创建生成器
如果生成器是在策略作用域外创建的,所有副本对它的访问会被串行化,因此各副本会得到不同的随机数。 g = tf.random.Generator.from_seed(1) strat = tf.distribute.MirroredStrategy(devices=["cpu:0", "cpu:1"]) with strat.scope(): def f(): print(g.normal([])) results = strat.run(f)
INFO:tensorflow:Using MirroredStrategy with devices ('/job:localhost/replica:0/task:0/device:CPU:0', '/job:localhost/replica:0/task:0/device:CPU:1') tf.Tensor(0.43842274, shape=(), dtype=float32) tf.Tensor(1.6272374, shape=(), dtype=float32)
注意这种用法可能存在性能问题,因为生成器所在设备与副本不同。
在分布策略内部创建生成器
如果生成器是在策略作用域内创建的,每个副本会得到一条不同且相互独立的随机数流。 strat = tf.distribute.MirroredStrategy(devices=["cpu:0", "cpu:1"]) with strat.scope(): g = tf.random.Generator.from_seed(1) print(strat.run(lambda: g.normal([]))) print(strat.run(lambda: g.normal([])))
PerReplica:{ 0: tf.Tensor(-0.87930447, shape=(), dtype=float32), 1: tf.Tensor(0.020661574, shape=(), dtype=float32) } PerReplica:{ 0: tf.Tensor(-1.5822568, shape=(), dtype=float32), 1: tf.Tensor(0.77539235, shape=(), dtype=float32) }
如果生成器指定了 seed(例如通过 Generator.from_seed 创建),随机数就由 seed 决定,即使不同副本得到的是不同且不相关的数。可以把某个副本上生成的随机数理解为:副本 ID 与一个所有副本共享的"主"随机数共同作用的结果(类似哈希)。因此整个系统仍然是确定性的。
tf.random.Generator 也可以在 Strategy.run 内部创建: strat = tf.distribute.MirroredStrategy(devices=["cpu:0", "cpu:1"]) with strat.scope(): def f(): g = tf.random.Generator.from_seed(1) a = g.normal([]) b = g.normal([]) return tf.stack([a, b]) print(strat.run(f)) print(strat.run(f))
PerReplica:{ 0: tf.Tensor([-0.87930447 -1.5822568 ], shape=(2,), dtype=float32), 1: tf.Tensor([0.02066157 0.77539235], shape=(2,), dtype=float32) } PerReplica:{ 0: tf.Tensor([-0.87930447 -1.5822568 ], shape=(2,), dtype=float32), 1: tf.Tensor([0.02066157 0.77539235], shape=(2,), dtype=float32) }
我们不再建议将 tf.random.Generator 作为参数传给 Strategy.run,因为 Strategy.run 通常期望参数是张量而非生成器。
保存生成器
一般来说,保存或序列化 tf.random.Generator 的方式与处理 tf.Variable 或 tf.Module(及其子类)相同。TensorFlow 有两种序列化机制:Checkpoint 和 SavedModel。
Checkpoint
生成器可以通过 tf.train.Checkpoint 自由地保存和恢复。从恢复点继续的随机数流与保存点处完全一致。 filename = "./checkpoint" g = tf.random.Generator.from_seed(1) cp = tf.train.Checkpoint(generator=g) print(g.normal([]))
tf.Tensor(0.43842277, shape=(), dtype=float32)
cp.write(filename) print("RNG stream from saving point:") print(g.normal([])) print(g.normal([]))
RNG stream from saving point: tf.Tensor(1.6272374, shape=(), dtype=float32) tf.Tensor(1.6307176, shape=(), dtype=float32)
cp.restore(filename) print("RNG stream from restoring point:") print(g.normal([])) print(g.normal([]))
RNG stream from restoring point: tf.Tensor(1.6272374, shape=(), dtype=float32) tf.Tensor(1.6307176, shape=(), dtype=float32)
在分布策略中也可以进行保存和恢复: filename = "./checkpoint" strat = tf.distribute.MirroredStrategy(devices=["cpu:0", "cpu:1"]) with strat.scope(): g = tf.random.Generator.from_seed(1) cp = tf.train.Checkpoint(my_generator=g) print(strat.run(lambda: g.normal([])))
PerReplica:{ 0: tf.Tensor(-0.87930447, shape=(), dtype=float32), 1: tf.Tensor(0.020661574, shape=(), dtype=float32) }
with strat.scope(): cp.write(filename) print("RNG stream from saving point:") print(strat.run(lambda: g.normal([]))) print(strat.run(lambda: g.normal([])))
RNG stream from saving point: PerReplica:{ 0: tf.Tensor(-1.5822568, shape=(), dtype=float32), 1: tf.Tensor(0.77539235, shape=(), dtype=float32) } PerReplica:{ 0: tf.Tensor(-0.5039703, shape=(), dtype=float32), 1: tf.Tensor(0.1251838, shape=(), dtype=float32) }
with strat.scope(): cp.restore(filename) print("RNG stream from restoring point:") print(strat.run(lambda: g.normal([]))) print(strat.run(lambda: g.normal([])))
RNG stream from restoring point: PerReplica:{ 0: tf.Tensor(-1.5822568, shape=(), dtype=float32), 1: tf.Tensor(0.77539235, shape=(), dtype=float32) } PerReplica:{ 0: tf.Tensor(-0.5039703, shape=(), dtype=float32), 1: tf.Tensor(0.1251838, shape=(), dtype=float32) }
保存之前,应确保各副本的 RNG 调用历史没有分歧(例如一个副本调用了一次 RNG 而另一个调用了两次)。否则,它们的内部 RNG 状态会产生分歧,而 tf.train.Checkpoint(只保存第一个副本的状态)将无法正确恢复所有副本。
你还可以把保存的 checkpoint 恢复到一个副本数量不同的分布策略中。由于在策略中创建的 tf.random.Generator 对象只能在同一策略中使用,要恢复到另一个策略,必须先在目标策略中创建一个新的 tf.random.Generator 以及对应的 tf.train.Checkpoint,如下例所示: filename = "./checkpoint" strat1 = tf.distribute.MirroredStrategy(devices=["cpu:0", "cpu:1"]) with strat1.scope(): g1 = tf.random.Generator.from_seed(1) cp1 = tf.train.Checkpoint(my_generator=g1) print(strat1.run(lambda: g1.normal([])))
PerReplica:{ 0: tf.Tensor(-0.87930447, shape=(), dtype=float32), 1: tf.Tensor(0.020661574, shape=(), dtype=float32) }
with strat1.scope(): cp1.write(filename) print("RNG stream from saving point:") print(strat1.run(lambda: g1.normal([]))) print(strat1.run(lambda: g1.normal([])))
RNG stream from saving point: PerReplica:{ 0: tf.Tensor(-1.5822568, shape=(), dtype=float32), 1: tf.Tensor(0.77539235, shape=(), dtype=float32) } PerReplica:{ 0: tf.Tensor(-0.5039703, shape=(), dtype=float32), 1: tf.Tensor(0.1251838, shape=(), dtype=float32) }
strat2 = tf.distribute.MirroredStrategy(devices=["cpu:0", "cpu:1", "cpu:2"]) with strat2.scope(): g2 = tf.random.Generator.from_seed(1) cp2 = tf.train.Checkpoint(my_generator=g2) cp2.restore(filename) print("RNG stream from restoring point:") print(strat2.run(lambda: g2.normal([]))) print(strat2.run(lambda: g2.normal([])))
RNG stream from restoring point: PerReplica:{ 0: tf.Tensor(-1.5822568, shape=(), dtype=float32), 1: tf.Tensor(0.77539235, shape=(), dtype=float32), 2: tf.Tensor(0.6851049, shape=(), dtype=float32) } PerReplica:{ 0: tf.Tensor(-0.5039703, shape=(), dtype=float32), 1: tf.Tensor(0.1251838, shape=(), dtype=float32), 2: tf.Tensor(-0.58519536, shape=(), dtype=float32) }
虽然 g1 和 cp1 与 g2 和 cp2 是不同的对象,但它们通过共同的 checkpoint 文件 filename 和对象名 my_generator 关联在一起。两个策略之间重叠的副本(如上例中的 cpu:0 和 cpu:1)会像前面的例子一样被正确恢复各自的随机数流。但这一保证不覆盖以下情况:在某个策略作用域内保存、却在任何策略作用域外恢复(或反之),因为策略外的设备被视为与策略内的任何副本都不相同。
SavedModel
tf.random.Generator 可以保存到 SavedModel 中。生成器可以在策略作用域内创建,保存操作也可以在策略作用域内进行。 filename = "./saved_model"
class MyModule(tf.Module):
def __init__(self): super(MyModule, self).__init__() self.g = tf.random.Generator.from_seed(0)
@tf.function def __call__(self): return self.g.normal([])
@tf.function def state(self): return self.g.state
strat = tf.distribute.MirroredStrategy(devices=["cpu:0", "cpu:1"]) with strat.scope(): m = MyModule() print(strat.run(m)) print("state:", m.state())
PerReplica:{ 0: tf.Tensor(-1.4154755, shape=(), dtype=float32), 1: tf.Tensor(-0.11388441, shape=(), dtype=float32) } state: tf.Tensor([256 0 0], shape=(3,), dtype=int64)
with strat.scope(): tf.saved_model.save(m, filename) print("RNG stream from saving point:") print(strat.run(m)) print("state:", m.state()) print(strat.run(m)) print("state:", m.state())
RNG stream from saving point: PerReplica:{ 0: tf.Tensor(-0.68758255, shape=(), dtype=float32), 1: tf.Tensor(0.8084062, shape=(), dtype=float32) } state: tf.Tensor([512 0 0], shape=(3,), dtype=int64) PerReplica:{ 0: tf.Tensor(-0.27342677, shape=(), dtype=float32), 1: tf.Tensor(-0.53093255, shape=(), dtype=float32) } state: tf.Tensor([768 0 0], shape=(3,), dtype=int64)
imported = tf.saved_model.load(filename) print("RNG stream from loading point:") print("state:", imported.state()) print(imported()) print("state:", imported.state()) print(imported()) print("state:", imported.state())
RNG stream from loading point: state: tf.Tensor([256 0 0], shape=(3,), dtype=int64) tf.Tensor(-1.0359411, shape=(), dtype=float32) state: tf.Tensor([512 0 0], shape=(3,), dtype=int64) tf.Tensor(-0.06425078, shape=(), dtype=float32) state: tf.Tensor([768 0 0], shape=(3,), dtype=int64)
不建议将包含 tf.random.Generator 的 SavedModel 加载到分布策略中使用,因为所有副本会生成完全相同的随机数流(原因是副本 ID 已被固化在 SavedModel 的计算图中)。
把分布式创建的 tf.random.Generator(即在分布策略中创建的生成器)加载到非策略环境(如上例)也有一个注意事项:RNG 状态会被正确恢复,但生成的随机数会与原策略中的原生成器不同(同样是因为策略外的设备被视为与策略内的任何副本都不相同)。
无状态 RNG
无状态 RNG 的使用很简单。它们是纯函数,不涉及任何状态或副作用。 print(tf.random.stateless_normal(shape=[2, 3], seed=[1, 2])) print(tf.random.stateless_normal(shape=[2, 3], seed=[1, 2]))
tf.Tensor( [[ 0.5441101 0.20738031 0.07356433] [ 0.04643455 -1.30159 -0.95385665]], shape=(2, 3), dtype=float32) tf.Tensor( [[ 0.5441101 0.20738031 0.07356433] [ 0.04643455 -1.30159 -0.95385665]], shape=(2, 3), dtype=float32)
每个无状态 RNG 都需要一个 seed 参数,它必须是形状为 [2] 的整数 Tensor。算子的结果完全由这个 seed 决定。
无状态 RNG 使用的算法与设备相关,也就是说,同一个算子在不同设备上运行可能产生不同的输出。
算法
通用说明
tf.random.Generator 类和无状态函数在所有设备上都支持 Philox 算法(写作 "philox" 或 tf.random.Algorithm.PHILOX)。
只要使用相同算法并从相同状态出发,不同设备会生成相同的整数;浮点数也会"几乎相同",只是由于各设备执行浮点计算的方式不同(例如归约顺序),可能出现微小的数值差异。
XLA 设备
在由 XLA 驱动的设备上(如 TPU,以及启用 XLA 的 CPU/GPU),还支持 ThreeFry 算法(写作 "threefry" 或 tf.random.Algorithm.THREEFRY)。与 Philox 相比,该算法在 TPU 上很快,但在 CPU/GPU 上较慢。
关于这些算法的更多细节,请参阅论文 'Parallel Random Numbers: As Easy as 1, 2, 3'。