Summary

DFlash is a speculative decoding technique that uses a diffusion-based draft model to rapidly generate draft tokens. It resolves the issue with autoregressive drafting, which is that the cost grows linearly with the speculation budget.

Input Tensors: Suppose a batch contains:

  • input_ids (token IDs), [batch, sequence]
  • target_hidden (target_model features), [batch, sequence, target_dim]
  • anchor_pos (location to start drafting from)
  • block_size (number of draft slots, including the anchor)

Get the target features without training the target:

target.eval()
for p in target.parameters():
   p.requires_grad_(False)
 
with torch.no_grad():
   out = target(
       input_ids=input_ids,
       output_hidden_states=True,
       use_cache=False,
   )
 
   # Pick several layers, for example early, middle, and late.
   hs = out.hidden_states
   target_features = torch.cat(
       [hs[4], hs[12], hs[-1]],
       dim=-1,
   )

Shapes:

hs[layer]:       [batch, sequence, hidden_dim]
target_features: [batch, sequence, 3 * hidden_dim]

Then build the masked block (as the drafter needs an embedding for the anchor and a learned representation for masked slots):

anchor_emb = token_embedding(anchor_ids)           # [B, 1, D]
mask_emb = mask_token.expand(B, block_size - 1, D)
 
draft_input = torch.cat([anchor_emb, mask_emb], dim=1)
# [B, block_size, D]

For the block:

x = torch.cat([context, draft_input], dim=1)
# [B, seq + block Size, D]
draft_states = draft_transformer(
    x,
    mask=None,
)
draft_states = draft_states[:, context_len:, :]  # [B, block_size, D]
logits = lm_head(draft_states)                   # [B, block_size, vocab]
 
# Slot 0 is the anchor. Predict slots 1...block_size-1.
future_logits = logits[:, 1:, :]
future_labels = target_ids[:, anchor_pos + 1 : anchor_pos + block_size]
 
loss = torch.nn.functional.cross_entropy(
    future_logits.reshape(-1, future_logits.size(-1)),
    future_labels.reshape(-1),
)
optimizer.zero_grad(set_to_none=True)
loss.backward()
optimizer.step()