File size: 4,668 Bytes
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
"""Local smoke test: run baseline/CCD/CCD-DS on a tiny randomly-initialised Dream model.

Checks the mechanics of the decoder (Claim 1's machinery) without needing a 7B GPU:
  * every method fully unmasks the response
  * baseline and CCD use exactly `steps` forward passes with budget 1/step
  * CCD-DS uses fewer steps and budgets in [1, V]
  * the documented degeneracy (d=1, V=b_t) makes CCD identical to the baseline
"""
import sys, os
sys.path.insert(0, os.path.dirname(__file__))

import torch
from transformers import AutoConfig, AutoModel
import ccd_decode

MODEL = "Dream-org/Dream-v0-Instruct-7B"
MASK = 151666

def tiny_model():
    cfg = AutoConfig.from_pretrained(MODEL, trust_remote_code=True)
    cfg.num_hidden_layers = 2
    cfg.hidden_size = 128
    cfg.intermediate_size = 256
    cfg.num_attention_heads = 4
    cfg.num_key_value_heads = 2
    cfg.vocab_size = 2000
    cfg.pad_token_id = 0
    cfg.mask_token_id = 1999
    cfg.tie_word_embeddings = True
    torch.manual_seed(0)
    m = AutoModel.from_config(cfg, trust_remote_code=True).eval()
    return NoMaskLogits(m, cfg.mask_token_id)


class NoMaskLogits(torch.nn.Module):
    """Forbid predicting the mask token.

    A trained Dream never emits <|mask|> as a clean-data prediction; a randomly
    initialised tiny model does, which would re-mask positions and corrupt the
    step/budget bookkeeping. This makes the toy model behave like a trained one.
    """
    def __init__(self, inner, mask_id):
        super().__init__()
        self.inner, self.mask_id = inner, mask_id

    def forward(self, *a, **kw):
        out = self.inner(*a, **kw)
        out.logits[..., self.mask_id] = -1e4
        return out

def main():
    m = tiny_model()
    global_mask = 1999  # in-range mask id for the tiny vocab
    prompt = torch.randint(0, 1000, (1, 8))
    N = 32

    results = {}
    for method in ["baseline", "ccd", "ccd_ds"]:
        torch.manual_seed(0)
        x, st = ccd_decode.generate(
            m, prompt, max_new_tokens=N, steps=N, temperature=0.0,
            mask_token_id=global_mask, method=method, buffer_V=4, history_d=3,
        )
        n_left = int((x[0, 8:] == global_mask).sum())
        results[method] = (st, n_left)
        print(f"{method:9s} steps={st['steps']:3d} masks_left={n_left} "
              f"fallbacks={st['fallbacks']:3d} budgets(min/max/mean)="
              f"{min(st['budgets'])}/{max(st['budgets'])}/{sum(st['budgets'])/len(st['budgets']):.2f} "
              f"total_decoded={sum(st['budgets'])}")

    print()
    ok = True
    for method, (st, n_left) in results.items():
        if n_left != 0:
            print(f"FAIL {method}: {n_left} positions left masked"); ok = False
    if results["baseline"][0]["steps"] != N:
        print("FAIL baseline did not use exactly N steps"); ok = False
    if results["ccd"][0]["steps"] != N:
        print("FAIL ccd did not use exactly N steps (fixed budget b_t=1)"); ok = False
    if max(results["ccd"][0]["budgets"]) != 1:
        print("FAIL ccd budget exceeded 1"); ok = False
    if results["ccd_ds"][0]["steps"] >= N:
        print("FAIL ccd_ds did not reduce steps"); ok = False
    if max(results["ccd_ds"][0]["budgets"]) > 4:
        print("FAIL ccd_ds budget exceeded V=4"); ok = False
    print(f"CCD-DS speedup on tiny model: {N / results['ccd_ds'][0]['steps']:.2f}x")

    # Degeneracy to the baseline. The paper (Sec. 4.2) says this happens at
    # "d=1 and V=b_t". Under Eq. (16)/(17) as literally written, the buffer at
    # history length d averages d+1 distributions, so d=1 still mixes the current
    # step with one history step and does NOT reduce to Eq. (1). The degeneracy
    # holds at d=0 (no history). We test both and report the discrepancy.
    torch.manual_seed(0)
    xb, _ = ccd_decode.generate(m, prompt, max_new_tokens=N, steps=N, temperature=0.0,
                                mask_token_id=global_mask, method="baseline")
    for d in (0, 1):
        torch.manual_seed(0)
        xd, _ = ccd_decode.generate(m, prompt, max_new_tokens=N, steps=N, temperature=0.0,
                                    mask_token_id=global_mask, method="ccd",
                                    buffer_V=1, history_d=d)
        same = bool((xb == xd).all())
        print(f"degeneracy check (d={d}, V=b_t=1): CCD == baseline -> {same}")
        if d == 0 and not same:
            print("FAIL degeneracy at d=0"); ok = False
        if d == 1 and same:
            print("NOTE: d=1 also degenerates on this toy model (paper's Sec. 4.2 reading)")

    print("\nSMOKE TEST:", "PASS" if ok else "FAIL")
    return 0 if ok else 1

if __name__ == "__main__":
    sys.exit(main())