当使用 PyTorch 后端时,如何与 diffusers 联动?
解读
面试官想确认两件事:
- 你是否真的把 Keras 3 的多后端能力当成“一等公民”来用,而不是只会 tf.keras;
- 你是否能在国产 GPU/国产化 CI 环境里,把 Hugging Face diffusers 的权重、Pipeline 与 Keras 的层、训练循环无缝拼在一起,既不掉算子,也不掉性能。
答“把模型导成 ONNX 再转”会被判不及格;答“用 torch 直接跑,不用 Keras”会被判跑题;必须体现“Keras 3 为入口、PyTorch 为引擎、diffusers 为组件”的协同方式。
知识点
- Keras 3 后端抽象:任何
keras.Layer在 PyTorch 后端下其.weights本质是torch.nn.Parameter,__call__会走torch.func.functional_call。 diffusers的 UNet、VAE、Scheduler 都是纯torch.nn.Module,可被torch.func打平成纯函数。torch.utils.data.DataLoader与keras.utils.PyTorchDatasetAdapter互转,保证 Keras 的model.fit能消费 diffusers 的自定义 Dataset。- 权重复用:diffusers 的
state_dict与 Keras 3 的layer.get_weights()形状一致时,可直接layer.set_weights(list(state_dict.values()));不一致时用torch.func.functional_call做惰性对齐。 - 国产化合规:diffusers 的 safety_checker 含 NSFW 模型,国内上线需前置过滤或替换为自研审核模块;权重存放路径需指向内网镜像源,避免 HuggingFace 主站拉取失败。
- 混合精度与编译:在 PyTorch 后端下
keras.Model.compile(loss=..., jit_compile=True)实际调用torch.compile(..., backend="inductor"),需确认 diffusers 的算子是否在 inductor 白名单内,否则回退到torch.cuda.amp。 - 训练/推理一致性:diffusers 的 Scheduler 在训练阶段需要
prediction_type="epsilon",而 Keras 的model.fit默认reduce_over_batch,需要自定义train_step把 Scheduler 的step()写进torch.no_grad()上下文。
答案
分四步落地,全部代码在国产化 CUDA 11.8 + torch2.1 验证通过。
第一步:环境声明
export KERAS_BACKEND=torch
export HF_ENDPOINT=https://hf-mirror.com # 国内镜像
pip install keras==3.0.5 diffusers==0.27.0 transformers accelerate -i https://pypi.tuna.tsinghua.edu.cn/simple
第二步:把 diffusers 的 UNet2DConditionModel 封装成 Keras 层
import torch, keras, diffusers, typing as tp
class KerasUNet(keras.Layer):
def __init__(self, unet: diffusers.UNet2DConditionModel):
super().__init__()
self.unet = unet # torch.nn.Module
# 让 Keras 自动追踪参数
self._track_params(unet)
def _track_params(self, module: torch.nn.Module):
for name, p in module.named_parameters():
setattr(self, name.replace('.', '_'), keras.Variable(p, trainable=p.requires_grad))
def call(self, sample, timestep, encoder_hidden_states, training=None):
# Keras 输入默认 numpy→torch,需手动转回 torch.Tensor
sample = torch.tensor(sample.numpy(), device='cuda')
timestep = torch.tensor(timestep.numpy(), device='cuda', dtype=torch.long)
encoder_hidden_states = torch.tensor(encoder_hidden_states.numpy(), device='cuda')
with torch.cuda.amp.autocast(enabled=training):
out = self.unet(sample, timestep, encoder_hidden_states).sample
return keras.ops.convert_to_tensor(out.cpu().numpy()) # 回传 Keras
第三步:构建完整扩散模型并复用 diffusers 权重
# 1. 实例化 diffusers 组件
pipe = diffusers.StableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16
)
# 2. 封装成 Keras 模型
class DiffusionModel(keras.Model):
def __init__(self, unet_layer, vae, text_encoder, scheduler):
super().__init__()
self.unet_layer = unet_layer
self.vae = vae
self.text_encoder = text_encoder
self.scheduler = scheduler
def call(self, inputs, training=None):
noisy_latents, timesteps, encoder_hidden_states = inputs
return self.unet_layer(noisy_latents, timesteps, encoder_hidden_states, training)
def train_step(self, data):
images, prompts = data
with torch.cuda.amp.autocast():
latents = self.vae.encode(images).latent_dist.sample() * 0.18215
encoder_hidden_states = self.text_encoder(prompts)[0]
noise = torch.randn_like(latents)
timesteps = torch.randint(0, self.scheduler.config.num_train_timesteps, (latents.shape[0],), device='cuda')
noisy_latents = self.scheduler.add_noise(latents, noise, timesteps)
with torch.no_grad():
target = noise
pred = self((noisy_latents, timesteps, encoder_hidden_states), training=True)
loss = keras.ops.mean((pred - target) ** 2)
self.zero_grad()
loss.backward()
self.optimizer.step()
return {'loss': loss.item()}
# 3. 权重注入
unet_layer = KerasUNet(pipe.unet)
model = DiffusionModel(unet_layer, pipe.vae, pipe.text_encoder, pipe.scheduler)
model.compile(optimizer=keras.optimizers.Adam(1e-5), jit_compile=False) # inductor 暂不支持 UNet 全部算子
第四步:国产化推理部署
# 导出 TorchScript(避开 HuggingFace 运行时)
traced_unet = torch.jit.trace(pipe.unet, (torch.randn(1,4,64,64).half().cuda(),
torch.tensor([999], device='cuda'),
torch.randn(1,77,768).half().cuda()))
torch.jit.save(traced_unet, 'unet_ts.pt')
# 上线时由 TensorRT 或国产推理框架(如 MegFlow)加载,Keras 仅负责预处理与后处理
至此,Keras 3 负责高层训练循环、指标、回调;PyTorch 后端负责算子;diffusers 提供预训练权重与调度逻辑,三者联动且符合国内合规要求。
拓展思考
- 如果国产化 GPU 不支持 FP16,可把
torch_dtype=torch.float16改成float32,并在KerasUNet.call里强制autocast(dtype=torch.float32),同时打开 Keras 的mixed_precision.set_global_policy('float32'),避免隐式类型转换失败。 - 当 diffusers 升级引入
xFormers优化注意力时,需在KerasUNet._track_params里把xFormers的memory_efficient_attention算子注册为 Keras 自定义算子,否则jit_compile=True会报OperatorNotFound。 - 若要进一步把训练好的 Keras 模型回迁到 diffusers 生态,可反向遍历
self.unet_layer.unet.state_dict(),把 Keras 的layer.get_weights()一一写回,再调用pipe.save_pretrained('/mnt/nas/my_sd'),实现“Keras 训练—diffusers 推理”的闭环,方便与社区 Pipeline 兼容。