File size: 8,593 Bytes
c953ec4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Train a ~6M-parameter bidirectional masked-diffusion model (GPT-2 style, no causal
mask) on FORMULA[SEP]ASSIGNMENT for random 3-SAT, per paper Sec 6.2.

Deviation note: minimal MDLM-style absorbing diffusion (linear schedule), since the
author repo ships no symbolic code; the paper gives only "standard masked diffusion
objective" for a GPT-2-style bidirectional denoiser.
"""
import argparse
import json
import math
import os
import random
import time

import torch
import torch.nn as nn
import torch.nn.functional as F

import sat_core as S

D, LAYERS, HEADS, FF, SEQ = 224, 6, 8, 1792, S.SEQ_LEN


class Block(nn.Module):
    def __init__(self):
        super().__init__()
        self.ln1 = nn.LayerNorm(D)
        self.qkv = nn.Linear(D, 3 * D)
        self.proj = nn.Linear(D, D)
        self.ln2 = nn.LayerNorm(D)
        self.fc1 = nn.Linear(D, FF)
        self.fc2 = nn.Linear(FF, D)

    def forward(self, x, pad_mask):
        B, T, _ = x.shape
        h = self.ln1(x)
        q, k, v = self.qkv(h).chunk(3, dim=-1)
        q = q.view(B, T, HEADS, -1).transpose(1, 2)
        k = k.view(B, T, HEADS, -1).transpose(1, 2)
        v = v.view(B, T, HEADS, -1).transpose(1, 2)
        att = (q @ k.transpose(-2, -1)) / math.sqrt(q.size(-1))
        att = att.masked_fill(~pad_mask[:, None, None, :], float("-inf"))
        att = att.softmax(dim=-1)
        o = (att @ v).transpose(1, 2).reshape(B, T, D)
        x = x + self.proj(o)
        x = x + self.fc2(F.gelu(self.fc1(self.ln2(x))))
        return x


class MDM(nn.Module):
    def __init__(self):
        super().__init__()
        self.emb = nn.Embedding(len(S.VOCAB), D)
        self.pos = nn.Embedding(SEQ, D)
        self.blocks = nn.ModuleList(Block() for _ in range(LAYERS))
        self.ln_f = nn.LayerNorm(D)
        self.head = nn.Linear(D, len(S.VOCAB), bias=False)
        self.head.weight = self.emb.weight  # tied

    def forward(self, ids, pad_mask):
        x = self.emb(ids) + self.pos(torch.arange(SEQ, device=ids.device))[None]
        for b in self.blocks:
            x = b(x, pad_mask)
        return self.head(self.ln_f(x))


def encode_batch(rows, targets, device):
    ids = torch.tensor([S.encode_row(r, t) for r, t in zip(rows, targets)], device=device)
    pad_mask = ids.ne(S.TOK["PAD"])
    return ids, pad_mask


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--train", default="/work/data/train_sat.jsonl")
    ap.add_argument("--val", default="/work/data/val_sat.jsonl")
    ap.add_argument("--out", default="/work/mdm_sat.pt")
    ap.add_argument("--steps", type=int, default=25000)
    ap.add_argument("--batch", type=int, default=512)
    ap.add_argument("--lr", type=float, default=3e-4)
    ap.add_argument("--seed", type=int, default=0)
    args = ap.parse_args()

    torch.manual_seed(args.seed)
    random.seed(args.seed)
    torch.backends.cuda.matmul.allow_tf32 = True
    torch.backends.cudnn.allow_tf32 = True
    dev = "cuda" if torch.cuda.is_available() else "cpu"
    print("device:", dev, flush=True)

    train = [json.loads(l) for l in open(args.train)]
    val = [json.loads(l) for l in open(args.val)]
    assert len(train) > 0 and all(r["is_sat"] and r["train_target"] for r in train)
    print(f"train {len(train)} sat formulas, val {len(val)}", flush=True)

    model = MDM().to(dev)
    n_params = sum(p.numel() for p in model.parameters())
    print(f"params: {n_params/1e6:.2f}M", flush=True)

    opt = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=0.01)
    sched = torch.optim.lr_scheduler.LambdaLR(
        opt, lambda s: min(1.0, s / 500) * (1 if s < args.steps * 0.9 else max(0.05, (args.steps - s) / (args.steps * 0.1))))

    import trackio
    trackio.init(project="searchdiff-sat-repro", space_id="Rami/searchdiff-sat-repro-trackio",
                 config={"steps": args.steps, "batch": args.batch, "params_M": round(n_params / 1e6, 2)})

    n = len(train)
    t0 = time.time()

    def build(rows):
        ids_list, lab_list = [], []
        for r in rows:
            tgt = r["train_target"]
            toks = S.encode_formula(r["text"]) + [S.TOK[b] for b in tgt]
            toks += [S.TOK["PAD"]] * (SEQ - len(toks))
            labs = ([-100] * S.ASSIGN_START + [S.TOK[b] for b in tgt]
                    + [-100] * (SEQ - S.ASSIGN_START - S.N_ASSIGN))
            ids_list.append(toks)
            lab_list.append(labs)
        return torch.tensor(ids_list, device=dev), torch.tensor(lab_list, device=dev)

    train_ids, train_labs = build(train)  # clean ids; masked on-GPU per step
    val_ids, val_labs = build(val)

    for step in range(1, args.steps + 1):
        idx = torch.randint(0, n, (args.batch,), device=dev)
        ids = train_ids[idx].clone()
        labs = train_labs[idx]
        t = torch.rand(args.batch, device=dev).clamp_min(0.02)  # mask prob per sample
        drop = torch.rand(args.batch, S.N_ASSIGN, device=dev) < t[:, None]
        assign = ids[:, S.ASSIGN_START:S.ASSIGN_START + S.N_ASSIGN]
        assign = torch.where(drop, torch.full_like(assign, S.TOK["MASK"]), assign)
        ids[:, S.ASSIGN_START:S.ASSIGN_START + S.N_ASSIGN] = assign
        labels = torch.where(drop, labs[:, S.ASSIGN_START:S.ASSIGN_START + S.N_ASSIGN],
                             torch.full_like(labs[:, S.ASSIGN_START:S.ASSIGN_START + S.N_ASSIGN], -100))
        pad_mask = ids.ne(S.TOK["PAD"])
        logits = model(ids, pad_mask)
        assign_logits = logits[:, S.ASSIGN_START:S.ASSIGN_START + S.N_ASSIGN, :]
        ce = F.cross_entropy(assign_logits.reshape(-1, len(S.VOCAB)), labels.reshape(-1),
                             reduction="none", ignore_index=-100).view(args.batch, S.N_ASSIGN)
        denom = ce.ne(0).sum()
        if denom.item() == 0:
            continue
        # MDLM-style 1/t weighting on masked positions (per-sample NELBO estimate)
        w = 1.0 / t
        loss = (ce.sum(dim=1) * w).mean() / S.N_ASSIGN
        opt.zero_grad(set_to_none=True)
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        opt.step()
        sched.step()

        if step % 200 == 0:
            print(f"step {step} loss {loss.item():.4f} lr {sched.get_last_lr()[0]:.2e} "
                  f"({(time.time()-t0)/step:.3f}s/step)", flush=True)
            trackio.log({"train/loss": loss.item(), "train/lr": sched.get_last_lr()[0]}, step=step)
        if step % 2000 == 0:
            torch.save({"state_dict": model.state_dict(), "config": {"D": D, "LAYERS": LAYERS,
                        "HEADS": HEADS, "FF": FF, "SEQ": SEQ, "vocab": S.VOCAB}}, args.out)
            print(f"checkpoint saved at step {step}", flush=True)
        if step % 1000 == 0:
            model.eval()
            with torch.no_grad():
                # val CE under the SAME masking process (t=0.5), unweighted,
                # over held-out formulas never trained on
                vg = torch.Generator(device=dev).manual_seed(123)
                vloss, vtot = 0.0, 0
                for i in range(0, len(val_ids), 256):
                    vid = val_ids[i:i + 256].clone()
                    vlab = val_labs[i:i + 256, S.ASSIGN_START:S.ASSIGN_START + S.N_ASSIGN]
                    Bv = vid.shape[0]
                    dropv = torch.rand(Bv, S.N_ASSIGN, device=dev, generator=vg) < 0.5
                    assign_v = vid[:, S.ASSIGN_START:S.ASSIGN_START + S.N_ASSIGN]
                    vid[:, S.ASSIGN_START:S.ASSIGN_START + S.N_ASSIGN] = torch.where(
                        dropv, torch.full_like(assign_v, S.TOK["MASK"]), assign_v)
                    lg = model(vid, vid.ne(S.TOK["PAD"]))
                    al = lg[:, S.ASSIGN_START:S.ASSIGN_START + S.N_ASSIGN, :]
                    ce_v = F.cross_entropy(al.reshape(-1, len(S.VOCAB)), vlab.reshape(-1),
                                           reduction="none", ignore_index=-100).view(Bv, S.N_ASSIGN)
                    vloss += ce_v.sum().item()
                    vtot += dropv.float().sum().item()
                vloss /= max(vtot, 1)
            print(f"step {step} val_ce {vloss:.4f}", flush=True)
            trackio.log({"val/ce": vloss}, step=step)
            model.train()

    os.makedirs(os.path.dirname(args.out), exist_ok=True)
    torch.save({"state_dict": model.state_dict(), "config": {"D": D, "LAYERS": LAYERS,
                "HEADS": HEADS, "FF": FF, "SEQ": SEQ, "vocab": S.VOCAB}}, args.out)
    print("saved", args.out, flush=True)
    if "vloss" in locals():
        trackio.log({"final/val_ce": vloss})
    trackio.finish()


if __name__ == "__main__":
    main()