File size: 10,549 Bytes
b222eb5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02bdb20
 
 
b222eb5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02bdb20
 
b222eb5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02bdb20
 
b222eb5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
"""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