def masked_loss(model, x0, t, alpha_bar, mask_id):
"""One-draw estimate of the masked bound per sequence, in nats."""
T = len(alpha_bar) - 1
shape = (-1,) + (1,) * (x0.dim() - 1) # broadcast over positions
masked = (torch.rand(x0.shape, device=x0.device)
< (1 - alpha_bar[t]).view(shape)) # with prob. 1 - abar_t
logits = model(torch.where(masked, mask_id, x0), t / T)
nll = -torch.log_softmax(logits, -1).gather(-1, x0[..., None])[..., 0]
w = (alpha_bar[t - 1] - alpha_bar[t]) / (1 - alpha_bar[t]) # 1/t if linear
return (T * w.view(shape) * nll * masked).flatten(1).sum(1)