如何使用 tf.test.TestCase 验证模型在不同设备(CPU/GPU)上的行为一致性?
解读
在国内一线/二线互联网公司的 TensorFlow 岗位面试中,这道题常被用来区分“只会跑 GPU 训练脚本”与“真正做过跨设备部署”的候选人。
面试官真正想听的是:
- 你能否用 tf.test.TestCase 把“同一份计算图”在 CPU 与 GPU 上各跑一遍,并拿到可复现的数值结果;
- 你能否规避浮点误差、随机初始化、算子实现差异等“坑”,给出可落地的断言策略;
- 你能否把测试写成 CI 可集成的单元测试,而不是临时脚本。
如果仅回答“用 tf.device 包一下再 assertEqual”只能拿到 60 分;能把随机种子、混合精度、算子黑名单、TF 2.x 的 tf.function 签名缓存机制都考虑进去,才能拿到 90+。
知识点
- tf.test.TestCase:TensorFlow 对 unittest.TestCase 的轻量封装,自动提供 main()、gpu_mode 标志位、assertAllEqual / assertAllClose 等张量级断言。
- device scope 与虚拟设备:tf.device()、tf.config.set_visible_devices、tf.config.set_logical_device_configuration,可在单卡机器上模拟“纯 CPU”与“纯 GPU”两种环境。
- 随机源控制:tf.random.set_seed、np.random.seed、PYTHONHASHSEED,保证权重初始化、dropout、数据打乱一致。
- 浮点误差容忍:assertAllClose(rtol=1e-5, atol=1e-6) 是工业界默认阈值;混合精度(fp16)需放宽到 1e-3。
- 算子差异黑名单:LayerNorm、BatchNorm、Conv 在 GPU 上可能走 cuDNN 路径,CPU 走 generic 实现,允许通过“相对误差 + 绝对误差”双指标白名单机制豁免。
- tf.function 签名缓存:同一 Python 函数在不同 device 下会生成不同 ConcreteFunction,测试里要 force rebuild 或每次新起 Graph。
- CI 集成:pytest + bazel test 都能识别 tf.test.TestCase,GPU 机器需加 tags = ["requires-gpu"],否则会被调度到 CPU 节点导致 skip。
答案
给出一套可直接落地到国内 GitLab-CI 的单元测试模板,支持 TF 2.8+ 单卡机器:
import os
import tensorflow as tf
# 必须在 import 后第一时间执行
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
tf.random.set_seed(42)
np.random.seed(42)
class DeviceConsistencyTest(tf.test.TestCase):
"""验证同一模型在 CPU 与 GPU 上前向 + 反向结果一致。"""
def setUp(self):
super().setUp()
# 构造最小复现网络:一层 Dense + 一层 BN
self.model = tf.keras.Sequential([
tf.keras.layers.Dense(128, activation="relu"),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.Dense(10)
])
self.dummy = tf.random.normal((32, 28))
def _run_forward_backward(self, device_name):
"""在指定 device 上跑一次前向 + 梯度,返回 (logits, 梯度列表)。"""
# 1. 每次重新 build 权重,避免权重复用
self.model.compile(loss="mse", optimizer="sgd")
# 2. 强制新 Graph,规避 tf.function 缓存
with tf.device(device_name):
x = tf.identity(self.dummy) # 显式放到目标设备
with tf.GradientTape() as tape:
tape.watch(x)
logits = self.model(x, training=True)
loss = tf.reduce_mean(logits ** 2)
grads = tape.gradient(loss, self.model.trainable_variables)
return logits, grads
def test_cpu_gpu_consistency(self):
# 若机器无 GPU,自动 skip
if not tf.config.list_physical_devices("GPU"):
self.skipTest("No GPU found")
# 关闭混合精度,排除 fp16 误差
policy = tf.keras.mixed_precision.global_policy()
tf.keras.mixed_precision.set_global_policy("float32")
cpu_logits, cpu_grads = self._run_forward_backward("/CPU:0")
gpu_logits, gpu_grads = self._run_forward_backward("/GPU:0")
# 3. logits 误差容忍
self.assertAllClose(cpu_logits, gpu_logits, rtol=1e-5, atol=1e-6)
# 4. 梯度逐条比较,允许 LayerNorm beta/gamma 略大
for g_cpu, g_gpu in zip(cpu_grads, gpu_grads):
if "norm" in g_cpu.name:
self.assertAllClose(g_cpu, g_gpu, rtol=2e-4, atol=2e-5)
else:
self.assertAllClose(g_cpu, g_gpu, rtol=1e-5, atol=1e-6)
# 5. 恢复全局策略,避免影响后续测试
tf.keras.mixed_precision.set_global_policy(policy)
if __name__ == "__main__":
tf.test.main()
执行方式:
# CPU 环境
python device_test.py
# GPU 环境(CI 镜像需含 nvidia-docker)
CUDA_VISIBLE_DEVICES=0 python device_test.py
要点回顾:
- 每次重新 compile,保证权重初始化一致;
- 用 assertAllClose 而不是 assertEqual,浮点误差可配置;
- 对 BN/LN 这类 device 差异大的算子单独放宽阈值;
- 测试即文档,后续新人加算子直接跑单测就能发现 device 漂移。
拓展思考
- 多卡场景:若业务用到 MirroredStrategy,可把 test 再包一层 strategy.scope(),验证“单 GPU”与“双 GPU 聚合梯度”是否一致;此时需固定 global batch size 并关闭梯度压缩。
- TPU 差异:国内阿里云 TPU 环境需使用 tf.config.connect_to_cluster,assertAllClose 阈值需再放宽一个数量级,且 Conv 的 padding 实现与 GPU 略有差异,建议用 XLA 固定 pass。
- 随机算子:Dropout、Multinomial、RandomCrop 在 CPU/GPU 的随机算法不同,无法 bit-wise 对齐;应把随机节点替换成 deterministic 实现(TF 2.12 起支持 tf.random.stateless_*),或在测试中把随机节点拆出图外。
- 性能回归:在一致性的基础上,可扩展同一个 TestCase 记录 /GPU:0 的 kernel 时间,若某次 MR 导致 GPU 时间上涨 5% 即 fail,实现“正确性 + 性能”双守门。