Coding中等
手撕 OpenVLA 风格 action token CE loss
连续动作离散到 256 bin → LM head next-token CE;
简要回答
连续动作离散到 256 bin → LM head next-token CE;用 quantile 切分(非 min/max)匹配数据分布。
标准答案
考察点:连续动作离散到 256 bin → LM head next-token CE;用 quantile 切分(非 min/max)匹配数据分布。
实现:
import torchimport torch.nn.functional as F
def fit_bins_quantile(actions, n_bin=256):
# actions: [N, D];按 quantile 而非 min/max 切分,防长尾压缩
qs = torch.linspace(0, 1, n_bin + 1, device=actions.device)
# 每维独立切:返回 [D, n_bin+1] 的边界
return torch.stack([torch.quantile(actions[:, d], qs) for d in range(actions.size(1))])
def discretize(action, bins, vocab_offset):
# action: [B, D];bins: [D, n_bin+1]
# 用 bucketize 找落在哪个区间 → token id(偏移到词表预留段)
token_ids = torch.stack([
torch.bucketize(action[:, d], bins[d, 1:-1]) # 去掉首尾哨兵
for d in range(action.size(1))
], dim=1)
return token_ids + vocab_offset # 落到词表预留的 action token 段
def openvla_loss(logits, target_ids, action_mask):
# logits: [B, L, V];target_ids: [B, L];action_mask 仅在 action token 处为 1
# 屏蔽 prompt/image token 的 loss,只学 action 段
return F.cross_entropy(logits.transpose(1, 2), target_ids,
reduction='none').mul(action_mask).sum() / action_mask.sum().clamp(min=1)
常见错误
- 用全局 min/max 切 bin 长尾压缩
- mask 后仍要是合法 vocab id(用时改写法)
- 推理用 sampling 而非 argmax 致动作抖。