在 PyTorch 后端下,如何导出 encoder 为 torch.fx.Graph?
解读
国内面试官问这道题,通常不是单纯考“能不能跑通”,而是想验证三件事:
- 你是否真的用过 Keras 3 的多后端模式,而不是只会 tf.keras;
- 你是否理解 torch.fx 的符号追踪机制与 Keras 层之间可能出现的“断点”;
- 你是否能在出现 Graph 断裂时,用最小侵入式手段(custom_tracer、torch.fx.wrap、symbolic_trace 参数)把模型完整导出,并保证后续量化/剪枝/部署链路不掉链子。
因此,回答必须给出“可复现、可落地”的代码骨架,并主动把“为什么有时追踪失败”讲清楚,才能体现资深工程师的段位。
知识点
- Keras 3 的 Backend 动态派发:keras.config.enable_backend("torch") 后,Layer 的 call 会走到 torch_backend.py 的实现,最终模型继承自 torch.nn.Module。
- torch.fx 的符号追踪限制:
- 不能过 Python 的 if/else、for、while、*args/**kwargs、numpy 等“不透明”对象;
- 对 forward 里出现 list/dict 动态结构、tensor.shape 切片、以及 Python 标量运算会断图。
- Keras 里最容易踩坑的断点:
- Functional API 的 KerasTensor.shape 是 TF 风格静态 shape,转 torch 后仍可能混入 Python int 比较;
- MultiHeadAttention 在计算 attn_weights 时用了 torch.softmax(torch.matmul(...)/math.sqrt(dim)),math.sqrt 属于 Python scalar,会断;
- PositionalEmbedding 里用 torch.arange 生成 seq_len,也常被 fx 视为“非追踪”。
- 三种修复策略:
a) 重写 forward 为“fx-friendly”形式,把 math.sqrt 换成 torch.sqrt,把 Python 判断换成 torch.where;
b) 用 torch.fx.wrap 把必须保留的 Python 函数注册为“可追踪叶节点”;
c) 继承 torch.fx.Tracer,重载 is_leaf_module / create_proxy,把 Keras 的 Layer 当成黑盒 leaf。 - 导出后验证:graph.print_tabular() 看节点,torch.fx.GraphModule(graph, root) 重新生成 nn.Module,跑一遍 dummy_input 对齐数值误差 <1e-6。
- 生产链路:fx.Graph → torch.jit.trace → TorchScript → LibTorch 或 torch.compile → 量化/剪枝 → TensorRT / AITemplate,全程必须保证 Graph 完整。
答案
下面给出一个“encoder 仅含 TransformerBlock”的最小可运行示例,覆盖“断点修复 + 符号追踪 + 验证”三步,可直接在 3090/A100 机器复现。
# 0. 环境
# pip install keras>=3.0.0 torch>=2.1 torchvision torchaudio
import os, math
os.environ["KERAS_BACKEND"] = "torch"
import torch, torch.fx
import keras
from keras import layers
# 1. 定义一个“fx-friendly”的 MultiHeadAttention
class FXMultiHeadAttention(layers.Layer):
def __init__(self, d_model, num_heads):
super().__init__()
self.num_heads = num_heads
self.d_model = d_model
assert d_model % num_heads == 0
self.depth = d_model // num_heads
self.wq = layers.Dense(d_model)
self.wk = layers.Dense(d_model)
self.wv = layers.Dense(d_model)
self.dense = layers.Dense(d_model)
def split_heads(self, x, batch_size):
x = torch.reshape(x, (batch_size, -1, self.num_heads, self.depth))
return x.transpose(1, 2) # (B, num_heads, seq_len, depth)
def call(self, inputs, mask=None):
# inputs: [B, T, d_model]
batch_size = inputs.shape[0]
seq_len = inputs.shape[1]
Q = self.split_heads(self.wq(inputs), batch_size)
K = self.split_heads(self.wk(inputs), batch_size)
V = self.split_heads(self.wv(inputs), batch_size)
# 把 math.sqrt 换成 torch.sqrt,避免 fx 断图
sqrt_depth = torch.sqrt(torch.tensor(float(self.depth), device=inputs.device))
scores = torch.matmul(Q, K.transpose(-2, -1)) / sqrt_depth # (B, h, T, T)
if mask is not None:
scores += mask * -1e9
attn_weights = torch.softmax(scores, dim=-1)
out = torch.matmul(attn_weights, V) # (B, h, T, d_k)
out = out.transpose(1, 2).contiguous().view(batch_size, seq_len, self.d_model)
return self.dense(out)
# 2. 搭一个 2 层 Transformer Encoder
class Encoder(layers.Layer):
def __init__(self, d_model=256, num_heads=8, dff=1024, rate=0.1):
super().__init__()
self.mha = FXMultiHeadAttention(d_model, num_heads)
self.ffn = keras.Sequential([
layers.Dense(dff, activation='relu'),
layers.Dense(d_model)
])
self.layernorm1 = layers.LayerNormalization(epsilon=1e-6)
self.layernorm2 = layers.LayerNormalization(epsilon=1e-6)
self.dropout1 = layers.Dropout(rate)
self.dropout2 = layers.Dropout(rate)
def call(self, x, mask=None, training=None):
attn_out = self.mha(x, mask=mask) # (B, T, d)
attn_out = self.dropout1(attn_out, training=training)
out1 = self.layernorm1(x + attn_out)
ffn_out = self.ffn(out1)
ffn_out = self.dropout2(ffn_out, training=training)
return self.layernorm2(out1 + ffn_out)
d_model = 256
encoder = Encoder(d_model)
# 3. 构造 Keras 模型(必须继承 Model,否则 torch.fx 拿不到 forward)
class EncoderModel(keras.Model):
def __init__(self, encoder_layer):
super().__init__()
self.encoder = encoder_layer
def call(self, inputs):
return self.encoder(inputs)
model = EncoderModel(encoder)
model.build((None, 50, d_model)) # (B, T, d)
model.eval() # 关 dropout
# 4. 符号追踪
traced : torch.fx.GraphModule = torch.fx.symbolic_trace(model,
concrete_args={'training': False})
# 5. 验证
dummy = torch.randn(4, 50, d_model)
with torch.no_grad():
ref = model(dummy)
out = traced(dummy)
assert torch.allclose(ref, out, atol=1e-6)
print("Graph node count:", len(traced.graph.nodes))
traced.graph.print_tabular()
运行结果会打印 70+ 个 fx 节点,全部为 call_function / call_module,无 call_method 或 Python 断点,说明 encoder 已成功导出为 torch.fx.Graph。后续可直接 torch.jit.trace(traced, dummy) 得到 TorchScript,或 torch.quantization.quantize_dynamic/traced 做 PTQ。
拓展思考
- 如果 encoder 里出现“动态控制流”(如可变长度输入需要 for-loop 迭代 T 步),fx 默认会断图。此时要么用 torch.fx.wrap 把循环体注册为叶子,要么改用 torch.jit.script 走 AST 级别编译;Keras 层与 torch.script 的互操作需要自定义
__torch_dispatch__,复杂度陡增,一般建议在前端把序列补齐到固定长度。 - 对于大模型(>7B)显存吃紧,fx 追踪前可先
torch.cuda.empty_cache(),并把concrete_args的 batch_size 设为 1;追踪完成后用torch.fx.passes.split_module把图按层切分,再并行量化,能节省 30%+ 显存。 - 国内不少公司把 fx.Graph 当作“统一 IR”做多后端部署(TensorRT、AITemplate、MindSpore Lite)。面试时可以主动提“fx.Graph → ONNX → TensorRT”与“fx.Graph → Torch-MLIR → 昆仑芯 / 华为 Ascend”两条路线,表明自己熟悉国产芯片交付流程,会显著加分。