当使用 PyTorch 后端时,如何与 torch.testing 联动?

解读

国内面试官问这道题,通常想验证三件事:

  1. 你是否真的把 Keras 3 的多后端跑通过,而不是只会 model.fit;
  2. 在 PyTorch 后端下,你是否能把 Keras 的“高级”与 torch 的“底层”无缝衔接,写得出单元测试、CI 脚本;
  3. 对数值误差、随机种子、设备一致性这些“坑”有没有工程经验。
    回答时要把“Keras 产生张量 → torch.testing 断言 → 训练/推理一致性验证”这条链路讲完整,并给出可直接落地的代码片段。

知识点

  1. Keras 3 统一后端:通过 KERAS_BACKEND=torch 或 os.environ["KERAS_BACKEND"] = "torch" 切换;keras.ops 自动映射到对应后端。
  2. torch.testing 家族:
    • torch.testing.assert_close(PyTorch ≥1.12,官方推荐,支持 rtol/atol、device、dtype 检查);
    • torch.testing.make_tensor(造随机测试张量);
    • 旧接口 torch.allclose / assert_allclose 已不推荐。
  3. 张量互转:Keras 张量本质是 torch.Tensor 的薄封装,通过 tensor.numpy() 或 torch.tensor(tensor) 即可零拷贝转换;但注意 requires_grad 与 dtype 一致性。
  4. 随机种子:必须同时设置 torch.manual_seed、np.random.seed、keras.utils.set_random_seed,否则 CI 会偶现失败。
  5. 设备一致性:Keras 模型默认与输入同设备;测试代码里要显式 model.to(device) 并把黄金数据也 .to(device),否则 assert_close 会报跨设备比较错误。
  6. 训练步单元测试:重写 train_step 后,用 torch.autograd.gradcheck 或 torch.testing.assert_close(loss, expected) 做回归测试。
  7. 量化/剪枝后的数值容忍:生产环境通常把 rtol=1e-3, atol=1e-5 写进 pytest 的 assert_close 参数,防止量化误差导致流水线红灯。

答案

步骤一:环境确认

export KERAS_BACKEND=torch
pip install keras>=3.0 torch>=2.0 pytest

步骤二:最小可复现实例——验证自定义 Dense 层前向输出

import os, torch, keras
from keras import layers

# 1. 固定随机种子,保证 CI 可复现
_ = torch.manual_seed(42)
keras.utils.set_random_seed(42)

# 2. 构造 Keras 模型
model = keras.Sequential([layers.Dense(4, activation='relu')])
model.build((None, 3))

# 3. 构造输入并前向
x = torch.randn(2, 3)
with torch.no_grad():
    out_keras = model(x)          # Keras 张量,本质是 torch.Tensor

# 4. 手工计算黄金结果(或来自老版本 ckpt)
weight = model.layers[0].kernel.data  # torch.Tensor
bias   = model.layers[0].bias.data
expected = torch.nn.functional.relu(x @ weight + bias)

# 5. torch.testing 断言
torch.testing.assert_close(out_keras, expected, rtol=1e-6, atol=1e-6)
print("✅ 前向数值一致")

步骤三:训练步回归测试

class MyModel(keras.Model):
    def __init__(self):
        super().__init__()
        self.dense = layers.Dense(1)
    def call(self, x):
        return self.dense(x)
    def train_step(self, data):
        x, y = data
        with torch.enable_grad():          # 确保梯度开启
            y_pred = self(x, training=True)
            loss = keras.ops.mean((y_pred - y) ** 2)
        trainable_vars = self.trainable_weights
        grads = torch.autograd.grad(loss, trainable_vars, create_graph=False)
        with torch.no_grad():
            for v, g in zip(trainable_vars, grads):
                v.data.sub_(0.01 * g)      # 手写 SGD
        return {"loss": loss}

model = MyModel()
model.build((None, 10))
opt = keras.optimizers.SGD(learning_rate=0.0)  # 占位,避免 Keras 报错
model.compile(optimizer=opt)

# 造数据
x = torch.randn(32, 10)
y = torch.randn(32, 1)
init_loss = model.evaluate(x, y, verbose=0)

# 训练一步
history = model.fit(x, y, batch_size=32, epochs=1, verbose=0)
final_loss = history.history["loss"][0]

# 断言 loss 下降
assert final_loss < init_loss, "训练步未生效"
torch.testing.assert_close(final_loss, torch.tensor(0.3123), rtol=1e-4)  # 黄金值

步骤四:pytest 集成

# tests/test_keras_torch.py
import torch, pytest, keras
from my_pkg import MyModel

@pytest.mark.parametrize("device", ["cpu", "cuda:0"])
def test_forward_device(device):
    if device.startswith("cuda") and not torch.cuda.is_available():
        pytest.skip("no gpu")
    model = MyModel().to(device)
    x = torch.randn(4, 10, device=device)
    y = model(x)
    assert y.device.type == device.split(":")[0]
    # 数值不做严格校验,仅测设备一致性

运行:

pytest -q tests/test_keras_torch.py

踩坑提示

  1. 若遇到 RuntimeError: Expected object of device type cuda but got device type cpu,99% 是模型或输入忘 .to(device)。
  2. torch.testing.assert_close 默认检查 dtype、device、shape,任何不一致都会抛异常,比 torch.allclose 严格,适合写 CI。
  3. 当模型内含 BatchNormalization 时,训练与推理的 running_mean 更新会导致两次 model(x) 结果不同,测试前务必 model.eval() 或固定 training=False。

拓展思考

  1. 端到端流水线:在 GitHub Actions 里同时跑 TensorFlow 与 PyTorch 两套后端,用 torch.testing 与 tf.test.assert_equal 交叉验证同一 Keras 模型,保证“一份代码、两份信心”。
  2. 动态 shape 场景:对 NLP 可变长输入,用 torch.testing.assert_close 的 equal_nan=True 屏蔽 padding 位,再对比非 mask 部分,实现 token-level 回归测试。
  3. 混合精度:在 torch.cuda.amp.autocast 下训练后,用 assert_close 的 rtol=1e-2 容忍 FP16 误差,防止 CI 误报。
  4. 自定义算子:若重写了 keras.layers.Layer 的 call 并内嵌 torch.nn.functional.xxx,可用 torch.autograd.gradcheck 对算子做梯度正确性检查,再把结果注册成 pytest fixture,实现“白盒”测试。