当使用 PyTorch 后端时,如何与 transformers 库联动?
解读
面试官真正想考察的是:
- 候选人是否理解 Keras 3 的「多后端」机制,尤其是 PyTorch 后端在算子、自动微分、权重格式上与原生 PyTorch 的差异。
- 能否把 Hugging Face transformers 的预训练模型无缝嵌入 Keras 训练、推理与部署流程,而不出现 device 冲突、权重格式不匹配、梯度断流等典型坑。
- 是否掌握国内工业界常用的「冻结-微调-量化-导出」四段式落地套路,以及国产化芯片(昇腾、寒武纪、昆仑)适配时的额外注意事项。
一句话:不是问“能不能调”,而是问“怎么调得稳、调得快、调得能上线”。
知识点
- Keras 3 后端切换原理:
os.environ["KERAS_BACKEND"] = "torch"在 import 前生效;- Keras 张量本质是
torch.Tensor的轻量包装,保留requires_grad与device。
- Transformers 库返回的
BaseModelOutput是标准 PyTorch 对象,与 Keras 层之间需要「显式桥接」。 - 权重格式:HF 模型默认
pytorch_model.bin,与 Keras 3 的.weights.h5不通用,但可通过from_pretrained(..., return_dict=False)直接拿nn.Module实例。 - 计算图一致性:Keras 的
Layer.call必须在torch.enable_grad()上下文中执行,否则反向断流。 - 国产化部署:昇腾 ATC 工具链要求
torch_npu与torch>=2.1,量化节点需提前融合,Keras 量化 API 目前只覆盖 TF 后端,因此需在 PyTorch 侧完成 QAT 后再封装成 Keras 模型。 - 数据并行:国内大厂常用
torchrun启动,多卡环境下需保证keras.distribution.set_global_distribution()与torch.distributed的init_method一致,否则出现重复初始化报错。
答案
步骤一:环境初始化
export KERAS_BACKEND=torch
pip install keras>=3.0 transformers torch --upgrade
步骤二:封装 Transformers 模型为 Keras 层
import torch, keras, transformers
from keras import layers
class BertKerasLayer(layers.Layer):
def __init__(self, model_name="bert-base-chinese", trainable=True, **kw):
super().__init__(**kw)
self.bert = transformers.AutoModel.from_pretrained(model_name)
self.trainable = trainable
self.bert.train(trainable) # 控制 dropout 行为
for p in self.bert.parameters():
p.requires_grad = trainable
def call(self, inputs, training=None):
# inputs: dict-like, keys=input_ids, attention_mask, token_type_ids
output = self.bert(**inputs, return_dict=True)
return output.last_hidden_state # shape: (B, L, 768)
def get_config(self):
cfg = super().get_config()
cfg.update({"trainable": self.trainable})
return cfg
步骤三:拼装 Keras 模型
max_len = 128
input_ids = layers.Input(shape=(max_len,), dtype="int32", name="input_ids")
attention_mask = layers.Input(shape=(max_len,), dtype="int32", name="attention_mask")
token_type_ids = layers.Input(shape=(max_len,), dtype="int32", name="token_type_ids")
bert_out = BertKerasLayer(trainable=True)({
"input_ids": input_ids,
"attention_mask": attention_mask,
"token_type_ids": token_type_ids
})
pooled = layers.GlobalAveragePooling1D()(bert_out)
logits = layers.Dense(2, activation="softmax")(pooled)
model = keras.Model(inputs=[input_ids, attention_mask, token_type_ids], outputs=logits)
model.compile(optimizer=keras.optimizers.Adam(2e-5),
loss=keras.losses.SparseCategoricalCrossentropy(),
metrics=["accuracy"])
步骤四:数据管道(以中文文本分类为例)
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("bert-base-chinese")
def gen():
for text, label in zip(train_texts, train_labels):
enc = tokenizer(text, max_length=max_len, truncation=True, padding="max_length")
yield {"input_ids": enc["input_ids"],
"attention_mask": enc["attention_mask"],
"token_type_ids": enc["token_type_ids"]}, label
train_ds = tf.data.Dataset.from_generator(
gen,
output_signature=({
"input_ids": tf.TensorSpec(shape=(max_len,), dtype=tf.int32),
"attention_mask": tf.TensorSpec(shape=(max_len,), dtype=tf.int32),
"token_type_ids": tf.TensorSpec(shape=(max_len,), dtype=tf.int32)
}, tf.TensorSpec(shape=(), dtype=tf.int32))
).batch(32).prefetch(tf.data.AUTOTUNE)
注意:此处用 tf.data 只是国内多数团队已熟悉,其迭代器返回的 tf.Tensor 会在 Keras PyTorch 后端内部自动转 torch.Tensor,无需手写 collate_fn。
步骤五:训练与微调
model.fit(train_ds, epochs=3)
Keras 会自动把 torch.Tensor 的 requires_grad 打开,并调用 torch.autograd 完成反向。
步骤六:量化与导出(国产化场景)
- 由于 Keras 3 的
keras.quantizers目前仅支持 TF 后端,需在 PyTorch 侧做 QAT:
import torch.quantization as quant
self.bert.qconfig = quant.get_default_qconfig('fbgemm')
quant.prepare_qat(self.bert, inplace=True)
# 继续训练 1-2 epoch
quant.convert(self.bert, inplace=True)
- 导出 ONNX:
torch.onnx.export(self.bert, dummy_inputs, "bert_qat.onnx", opset_version=13)
- 昇腾 ATC 转换:
atc --model=bert_qat.onnx --framework=5 --output=bert_om --input_shape="input_ids:1,128" --soc_version=Ascend910B
步骤七:推理服务
import onnxruntime as ort
sess = ort.InferenceSession("bert_om.om")
若仍想保留 Keras 前端,可再包一层 Layer,call 方法内调用 ort.InferenceSession.run,实现“Keras API + 国产芯片”双栈兼容。
拓展思考
- 动态图 vs 静态图:PyTorch 后端下 Keras 仍是 Eager 模式,若业务需要图优化,可尝试
torch.compile(model, mode="max-autotune"),但需验证与 Keras 回调的兼容性。 - 大模型微调:对于 7B+ 参数模型,国内主流做法是先使用
transformers的LoRA+torch.distributed,微调完成后再把merge_and_unload()后的nn.Module封装成 Keras Layer,以复用 Keras serving 框架。 - 安全合规:出海上架 App 需要 GDPR 审计,Keras 的
model.get_weights()在 PyTorch 后端返回的是torch.Tensor,需手动转numpy再copy(),防止内存残留导致权重泄露。 - 版本陷阱:国内镜像源常滞后,
keras 3.2与torch 2.2组合在 Windows 下会出现c10::cuda::CUDAStream析构段错误,降级到torch 2.1可解,面试时可作为“踩坑案例”主动抛出,体现工程经验。