Coding困难
手撕 Diffusion Policy 训练 step(DDPM ε-prediction)
;
简要回答
标准答案
考察点:
常见错误
- 漏掉视觉 cond 进 UNet
- 把 action 当图像 spatial 维
- 推理 K 步太多(DDIM 10-50 即可)
- 不用 EMA 生成抖。
c-2.7,0,-7.17,-2.7,-13.5,-8c-5.8,-5.3,-9.5,-10,-9.5,-14
c0,-2,0.3,-3.3,1,-4c1.3,-2.7,23.83,-20.7,67.5,-54
c44.2,-33.3,65.8,-50.3,66.5,-51c1.3,-1.3,3,-2,5,-2c4.7,0,8.7,3.3,12,10
s173,378,173,378c0.7,0,35.3,-71,104,-213c68.7,-142,137.5,-285,206.5,-429
c69,-144,104.5,-217.7,106.5,-221
l0 -0
c5.3,-9.3,12,-14,20,-14
H400000v40H845.2724
s-225.272,467,-225.272,467s-235,486,-235,486c-2.7,4.7,-9,7,-19,7
c-6,0,-10,-1,-12,-3s-194,-422,-194,-422s-65,47,-65,47z
M834 80h400000v40h-400000z"/>⋅ϵ‘;ε-prediction 目标;视觉 obs 作为 cross-attn condition。
c-2.7,0,-7.17,-2.7,-13.5,-8c-5.8,-5.3,-9.5,-10,-9.5,-14
c0,-2,0.3,-3.3,1,-4c1.3,-2.7,23.83,-20.7,67.5,-54
c44.2,-33.3,65.8,-50.3,66.5,-51c1.3,-1.3,3,-2,5,-2c4.7,0,8.7,3.3,12,10
s173,378,173,378c0.7,0,35.3,-71,104,-213c68.7,-142,137.5,-285,206.5,-429
c69,-144,104.5,-217.7,106.5,-221
l0 -0
c5.3,-9.3,12,-14,20,-14
H400000v40H845.2724
s-225.272,467,-225.272,467s-235,486,-235,486c-2.7,4.7,-9,7,-19,7
c-6,0,-10,-1,-12,-3s-194,-422,-194,-422s-65,47,-65,47z
M834 80h400000v40h-400000z"/>⋅ϵ‘;ε-prediction 目标;视觉 obs 作为 cross-attn condition。
实现:
import torchimport torch.nn.functional as F
def make_alpha_bar(T=1000):
# cosine schedule (Nichol & Dhariwal):ᾱ_t = f(t)/f(0),比 linear 末段更稳
steps = torch.arange(T + 1) / T
f = torch.cos((steps + 0.008) / 1.008 * torch.pi / 2).pow(2)
return (f / f[0])[1:] # 长度 T,单调递减,保证 1-ᾱ_t ∈ (0,1)
def dp_train_step(model, x0, cond, alpha_bar):
# x0: [B, H, action_dim] 未来 H 步 action chunk
# cond: [B, D_cond] 视觉特征(不能漏,否则退化为无条件采样)
B = x0.size(0)
t = torch.randint(0, len(alpha_bar), (B,), device=x0.device)
ab = alpha_bar[t].view(B, 1, 1) # 广播到 [B,H,action_dim]
eps = torch.randn_like(x0)
xt = ab.sqrt() * x0 + (1 - ab).sqrt() * eps # forward q(x_t|x_0)
eps_pred = model(xt, t, cond=cond)
return F.mse_loss(eps_pred, eps) # ε-prediction 目标