ccd-repro-code / scripts /ccd_decode.py
ashishk1331's picture
Eq20 budget diagnostics
02bdb20 verified
Raw
History Blame Contribute Delete
10.5 kB
"""Coherent Contextual Decoding (CCD) and CCD-DS for Dream diffusion language models.
Independent reimplementation of:
"Beyond Confidence: Adaptive and Coherent Decoding for Diffusion Language Models"
(arXiv 2512.02044 / OpenReview b0O96emqNj), Section 3.
No official code was released; this follows the equations in the paper.
Equation map
------------
Eq. (1) baseline single-step sampling (Dream `alg="entropy"`)
Eq. (6) p_bar(x_i|s) = (1/(T-t+1)) sum_k p_theta(x_i | c_{T-k,i}, s) -- marginalized target
Eq. (16) H_t : sliding-window historical buffer, last d iters, top-V per iter,
I_t = intersection of the top-V position sets over those d iters
Eq. (17) I^c_t = (current top-V set) intersect (positions present in H_t)
Eq. (18) CCD sampling: p_{t,i} = p_bar over the d+1 buffer entries; J_t = top-b_t by -H(p_bar)
Eq. (20) CCD-DS adaptive budget:
|I^c_t| <= b_t -> J_t = I^c_t
|I^c_t| > b_t -> J_t = top-b_t U {i : H(p_bar_i) < eps}
with the paper's Sec. 4.2 stability heuristic standing in for eps:
argmax token index identical across all d+1 buffer entries.
Implementation decisions where the paper is silent (documented in the logbook):
* Buffer warm-up: at the first iteration no history exists (Eq. 16 gives
j in {1..min(d, T-t)} = empty), so I^c_t is unconstrained and p_bar is the
single-step distribution (Monte-Carlo count 1). The buffer fills over the
first d iterations.
* Empty-intersection fallback: if I^c_t is empty the step would decode nothing
and stall forever. We fall back to the baseline rule (Eq. 1): decode the
top-b_t positions by single-step confidence. This is the natural reading of
the paper's claim that CCD "degrades to the existing single-context method",
and it guarantees CCD-DS never needs more steps than the baseline.
"""
import torch
import torch.nn.functional as F
import torch.distributions as dists
# ---------------------------------------------------------------- distributions
def _apply_filters(logits, temperature=0.0, top_p=None, top_k=None):
"""Dream's logit preprocessing (verbatim from Dream generation_utils.sample_tokens)."""
if temperature > 0:
logits = logits / temperature
if top_p is not None and top_p < 1:
logits = _top_p_logits(logits, top_p)
if top_k is not None:
logits = _top_k_logits(logits, top_k)
return torch.softmax(logits.float(), dim=-1)
def _top_p_logits(logits, top_p=None):
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
sorted_indices_to_remove = cumulative_probs > top_p
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
sorted_indices_to_remove[..., 0] = 0
mask = torch.zeros_like(logits, dtype=torch.bool, device=logits.device)
mask = mask.scatter_(-1, sorted_indices, sorted_indices_to_remove)
return logits.masked_fill(mask, torch.finfo(logits.dtype).min)
def _top_k_logits(logits, top_k=None):
top_k = min(top_k, logits.size(-1))
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
return logits.masked_fill(indices_to_remove, torch.finfo(logits.dtype).min)
def _neg_entropy(probs):
"""Dream's confidence surrogate for alg='entropy': -H(p) (higher = more confident)."""
return torch.sum(probs * torch.log(probs + 1e-10), dim=-1)
def _pick_token(probs, temperature):
"""Token value from a distribution: argmax at temp 0, categorical sample otherwise.
Mirrors Dream's sample_tokens so CCD and the baseline differ only in *which*
distribution is used, never in how a token is drawn from it.
"""
if temperature > 0:
try:
return dists.Categorical(probs=probs).sample()
except Exception:
return probs.argmax(dim=-1)
return probs.argmax(dim=-1)
# ---------------------------------------------------------------- the decoder
@torch.no_grad()
def generate(
model,
input_ids,
attention_mask=None,
max_new_tokens=256,
steps=256,
temperature=0.0,
top_p=None,
top_k=None,
mask_token_id=151666,
eps=1e-3,
method="baseline", # 'baseline' | 'ccd' | 'ccd_ds'
buffer_V=4, # top-V confident tokens retained per iteration
history_d=3, # history length d (Dream default in the paper)
eos_token_id=None,
):
"""Decode one sequence (batch size 1) and return (sequence, stats).
stats: {'steps': forward passes actually run, 'budgets': tokens decoded per step,
'fallbacks': steps that used the empty-intersection fallback}
"""
assert input_ids.shape[0] == 1, "batch size 1 (per-sequence buffer bookkeeping)"
device = input_ids.device
prompt_len = input_ids.shape[1]
max_length = prompt_len + max_new_tokens
x = F.pad(input_ids, (0, max_new_tokens), value=mask_token_id)
if attention_mask is not None and torch.any(attention_mask == 0.0):
attention_mask = F.pad(attention_mask, (0, max_new_tokens), value=1.0)
tok_idx = attention_mask.long().cumsum(-1) - 1
tok_idx.masked_fill_(attention_mask == 0, 1)
attention_mask = torch.logical_and(
attention_mask.unsqueeze(1).unsqueeze(-2),
attention_mask.unsqueeze(1).unsqueeze(-1),
)
else:
tok_idx = None
attention_mask = "full"
timesteps = torch.linspace(1, eps, steps + 1, device=device)
# sliding-window historical buffer: list of (positions[V], probs[V, |X|]),
# most recent last, at most `history_d` entries.
buffer = []
stats = {"steps": 0, "budgets": [], "fallbacks": 0,
# diagnostics: what actually gates the adaptive budget (Eq. 20)
"ic_sizes": [], "n_stable": []}
for i in range(steps):
mask_index = (x == mask_token_id)
if not mask_index.any():
break # early stop: every position decoded (CCD-DS)
logits = model(x, attention_mask, tok_idx).logits
logits = torch.cat([logits[:, :1], logits[:, :-1]], dim=1) # Dream's shift
stats["steps"] += 1
mask_pos = mask_index[0].nonzero(as_tuple=True)[0] # [M]
probs_cur = _apply_filters(logits[0, mask_pos], temperature, top_p, top_k) # [M, |X|]
conf_cur = _neg_entropy(probs_cur) # [M]
# baseline uniform budget b_t (Dream's schedule)
num_mask = mask_pos.numel()
t, s = timesteps[i], timesteps[i + 1]
b_t = int(num_mask * (1 - s / t)) if i < steps - 1 else num_mask
b_t = max(b_t, 1)
if method == "baseline":
k = min(b_t, num_mask)
sel = torch.topk(conf_cur, k).indices
x[0, mask_pos[sel]] = _pick_token(probs_cur[sel], temperature)
stats["budgets"].append(int(k))
continue
# ---- Eq. (16): current top-V confident positions
V = min(buffer_V, num_mask)
topv_local = torch.topk(conf_cur, V).indices
topv_pos = mask_pos[topv_local]
# ---- Eq. (16)/(17): I_t = intersection of buffered top-V position sets,
# I^c_t = current top-V intersect I_t
cur_set = set(topv_pos.tolist())
inter = cur_set
for pos_b, _ in buffer:
inter = inter & set(pos_b.tolist())
ic_t = sorted(inter)
if len(ic_t) == 0:
# fallback -> baseline rule (Eq. 1)
stats["fallbacks"] += 1
stats["ic_sizes"].append(0)
stats["n_stable"].append(0)
k = min(b_t, num_mask)
sel = torch.topk(conf_cur, k).indices
x[0, mask_pos[sel]] = _pick_token(probs_cur[sel], temperature)
stats["budgets"].append(int(k))
else:
# ---- Eq. (6): p_bar = mean over the d+1 buffer entries (history + current)
pos_index_cur = {int(p): j for j, p in enumerate(mask_pos.tolist())}
p_bars, stable = [], []
for pos in ic_t:
dists_i = [probs_cur[pos_index_cur[pos]]]
for pos_b, prob_b in buffer:
j = (pos_b == pos).nonzero(as_tuple=True)[0]
if j.numel() > 0:
dists_i.append(prob_b[j[0]])
stacked = torch.stack(dists_i, dim=0) # [d+1, |X|]
p_bars.append(stacked.mean(dim=0))
# Sec. 4.2 stability heuristic standing in for H(p_bar) < eps
argmaxes = stacked.argmax(dim=-1)
stable.append(bool((argmaxes == argmaxes[0]).all()) and stacked.shape[0] > 1)
stats["ic_sizes"].append(len(ic_t))
stats["n_stable"].append(int(sum(stable)))
p_bar = torch.stack(p_bars, dim=0) # [|I^c_t|, |X|]
marg_conf = _neg_entropy(p_bar) # -H(p_bar)
ic_pos = torch.tensor(ic_t, device=device)
# ---- Eq. (18) / Eq. (20): choose J_t
if method == "ccd":
k = min(b_t, len(ic_t))
sel = torch.topk(marg_conf, k).indices
elif method == "ccd_ds":
if len(ic_t) <= b_t:
sel = torch.arange(len(ic_t), device=device)
else:
sel = torch.topk(marg_conf, b_t).indices
extra = [j for j in range(len(ic_t))
if stable[j] and j not in set(sel.tolist())]
if extra:
sel = torch.cat([sel, torch.tensor(extra, device=device)])
else:
raise ValueError(f"unknown method: {method}")
x[0, ic_pos[sel]] = _pick_token(p_bar[sel], temperature)
stats["budgets"].append(int(sel.numel()))
# ---- update the sliding window (store only still-masked top-V positions)
still_masked = (x[0, topv_pos] == mask_token_id)
keep_pos = topv_pos[still_masked]
if keep_pos.numel() > 0:
keep_local = topv_local[still_masked]
buffer.append((keep_pos.clone(), probs_cur[keep_local].clone()))
else:
buffer.append((torch.empty(0, dtype=torch.long, device=device),
torch.empty(0, probs_cur.shape[-1], device=device)))
if len(buffer) > history_d:
buffer.pop(0)
return x, stats