File size: 10,836 Bytes
b662633
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
"""Training loop for Alea-mini on a single GPU.

Speed levers vs v1: dataset pre-packed once; length-bucketed batching (minimal
padding); attention mask built on GPU from segment ids (no per-item [L,L] CPU
build + H2D transfer); optional sdpa attention; selectable trunk freeze mode;
--init-from resumes heads+backbone from a checkpoint.
"""
import argparse
import json
import math
import os
import random
import time

import torch
import torch.nn.functional as F

from .dataset import DecisionDataset, row_to_specs
from .losses import bernoulli_brier, choice_loss, crps_loss, pinball_loss
from .model import AleaModel, collate_segments, mask_from_segments
from .packing import pack_request


def set_freeze(model, mode, tail_k=8):
    bb = model.backbone
    if mode == "full":
        return
    for p in bb.parameters():
        p.requires_grad_(False)
    if mode == "tail":
        n = len(bb.layers)
        for layer in bb.layers[n - tail_k:]:
            for p in layer.parameters():
                p.requires_grad_(True)
        for p in bb.norm.parameters():
            p.requires_grad_(True)
    elif mode == "heads":
        pass
    else:
        raise ValueError(mode)


def load_into(model, ckpt_path):
    ck = torch.load(ckpt_path, map_location="cpu", weights_only=False)
    for name, m in zip(["choice", "score", "noul", "regress"],
                       [model.choice_head, model.score_head, model.noul_head,
                        model.regress_head]):
        if name in ck.get("heads", {}):
            m.load_state_dict(ck["heads"][name])
    if ck.get("backbone"):
        model.backbone.load_state_dict(ck["backbone"])
    aux = ck.get("aux", {})
    if model.aux_embed is not None and "aux_embed" in aux:
        model.aux_embed.load_state_dict(aux["aux_embed"], strict=False)
    if model.ngram is not None and "ngram" in aux:
        try:
            model.ngram.load_state_dict(aux["ngram"])
        except Exception:
            pass
    if model.ngram2 is not None and "ngram2" in aux:
        try:
            model.ngram2.load_state_dict(aux["ngram2"])
        except Exception:
            pass
    return ck.get("args", {})


def question_losses(outputs, targets):
    losses = []
    for qres in outputs:
        for r in qres:
            q = targets[r["qid"]]
            if r["qtype"] == "choice":
                qt = torch.tensor(q, device=r["logits"].device)
                losses.append(choice_loss(r["logits"][None], qt[None]))
            elif r["qtype"] == "score":
                qt = torch.tensor(q, device=r["logits"].device)
                losses.append(crps_loss(r["logits"][None], qt[None]))
            elif r["qtype"] == "noul":
                qt = torch.tensor(q, device=r["p_yes"].device)
                losses.append(bernoulli_brier(
                    torch.logit(r["p_yes"].clamp(1e-6, 1 - 1e-6))[None],
                    qt[None]))
            elif r["qtype"] == "regress":
                from .heads import TAUS
                qt = torch.tensor(q, device=r["quantiles"].device)
                losses.append(pinball_loss(r["quantiles"][None], qt[None], TAUS))
    return losses


def save_ckpt(model, heads, args, path):
    save = {"heads": {k: m.state_dict() for k, m in
                      zip(["choice", "score", "noul", "regress"], heads)},
            "args": vars(args)}
    if args.train_mode != "heads":
        save["backbone"] = model.backbone.state_dict()
    aux = {}
    if model.aux_embed is not None:
        aux["aux_embed"] = model.aux_embed.state_dict()
    if model.ngram is not None:
        aux["ngram"] = model.ngram.state_dict()
    if getattr(model, "ngram2", None) is not None:
        aux["ngram2"] = model.ngram2.state_dict()
    if aux:
        save["aux"] = aux
    torch.save(save, path)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--train", default="data/train.jsonl")
    ap.add_argument("--dev", default="data/dev.jsonl")
    ap.add_argument("--out", default="runs/alea_mini")
    ap.add_argument("--model", default="Qwen/Qwen3-0.6B")
    ap.add_argument("--init-from", default=None, help="checkpoint to resume")
    ap.add_argument("--epochs", type=float, default=1.0)
    ap.add_argument("--batch", type=int, default=8)
    ap.add_argument("--accum", type=int, default=4)
    ap.add_argument("--lr-head", type=float, default=2e-4)
    ap.add_argument("--lr-backbone", type=float, default=2e-5)
    ap.add_argument("--train-mode", default="tail",
                    choices=["heads", "tail", "full"])
    ap.add_argument("--tail-k", type=int, default=8)
    ap.add_argument("--use-aux-embed", action="store_true",
                    help="add second trainable embedding table (~155M params)")
    ap.add_argument("--use-ngram", action="store_true",
                    help="add hashed n-gram encoder (~100M params)")
    ap.add_argument("--use-ngram2", action="store_true",
                    help="second n-gram bank, orders 5-8, 512k buckets")
    ap.add_argument("--lr-aux", type=float, default=3e-4,
                    help="lr for aux_embed/ngram modules (fresh params)")
    ap.add_argument("--attn", default="sdpa", choices=["eager", "sdpa"])
    ap.add_argument("--max-len", type=int, default=2048)
    ap.add_argument("--token-budget", type=int, default=24576,
                    help="cap batch by tokens: batch_n*max_len <= budget")
    ap.add_argument("--max-items", type=int, default=0)
    ap.add_argument("--save-every", type=int, default=1000)
    ap.add_argument("--seed", type=int, default=0)
    args = ap.parse_args()

    torch.manual_seed(args.seed)
    random.seed(args.seed)
    dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")

    from transformers import AutoTokenizer
    tok = AutoTokenizer.from_pretrained(args.model)
    model = AleaModel(args.model, attn_impl=args.attn,
                      use_aux_embed=args.use_aux_embed,
                      use_ngram=args.use_ngram, use_ngram2=args.use_ngram2).to(dev)
    model.backbone.gradient_checkpointing_enable()
    if args.init_from:
        prev = load_into(model, args.init_from)
        print(f"resumed from {args.init_from}")
    set_freeze(model, args.train_mode, args.tail_k)

    heads = [model.choice_head, model.score_head, model.noul_head,
             model.regress_head]
    head_params = [p for m in heads for p in m.parameters()]
    bb_params = [p for p in model.backbone.parameters() if p.requires_grad]
    groups = [{"params": head_params, "lr": args.lr_head}]
    if bb_params:
        groups.append({"params": bb_params, "lr": args.lr_backbone})
    aux_params = [p for m in (model.aux_embed, model.ngram, model.ngram2) if m is not None
                  for p in m.parameters()]
    if aux_params:
        groups.append({"params": aux_params, "lr": args.lr_aux})
    opt = torch.optim.AdamW(groups, weight_decay=0.01)

    warmup_frac = 0.03
    def lr_lambda(s):
        wu = max(1, int(total_steps * warmup_frac))
        if s < wu:
            return s / wu
        p = (s - wu) / max(1, total_steps - wu)
        return 0.5 * (1 + math.cos(math.pi * min(1.0, p)))

    print("pre-packing dataset...", flush=True)
    ds = DecisionDataset(args.train, tok, max_len=args.max_len)
    if args.max_items:
        ds.rows = ds.rows[: args.max_items]
    items = []
    skipped = 0
    for row in ds.rows:
        try:
            state, qs, targets = row_to_specs(row)
            pk = pack_request(tok, state, qs, max_len=args.max_len)
            items.append((pk, targets))
        except ValueError:
            skipped += 1
    n = len(items)
    print(f"packed {n} (skipped {skipped}) trainable="
          f"{sum(p.numel() for p in model.parameters() if p.requires_grad)/1e6:.1f}M",
          flush=True)

    # token-budget batching: sort by length, then chunk so that
    # batch_size * max_len_in_batch <= token_budget (long items -> small
    # batches, short items -> up to --batch wide)
    lengths = [len(p.input_ids) for p, _ in items]
    order = sorted(range(n), key=lambda i: lengths[i])
    batches, cur, cur_max = [], [], 0
    for i in order:
        new_max = max(cur_max, lengths[i])
        if cur and ((len(cur) + 1) * new_max > args.token_budget
                    or len(cur) >= args.batch):
            batches.append(cur)
            cur, cur_max = [], 0
            new_max = lengths[i]
        cur.append(i)
        cur_max = new_max
    if cur:
        batches.append(cur)
    steps_per_epoch = math.ceil(len(batches) / args.accum)
    total_steps = int(steps_per_epoch * args.epochs)
    sched = torch.optim.lr_scheduler.LambdaLR(opt, lr_lambda)
    pad_id = tok.pad_token_id if tok.pad_token_id is not None else tok.eos_token_id

    os.makedirs(args.out, exist_ok=True)
    step, micro, running = 0, 0, 0.0
    t0 = time.time()
    model.train()

    done = False
    while not done:
        random.shuffle(batches)
        for batch_idx in batches:
            packeds = [items[i][0] for i in batch_idx]
            targs = [items[i][1] for i in batch_idx]
            ids, pos, seg, qof, oof = collate_segments(packeds, pad_id)
            ids, pos = ids.to(dev), pos.to(dev)
            mask = mask_from_segments(seg.to(dev), qof.to(dev),
                                      oof.to(dev)).to(torch.bfloat16)

            out = model(ids, mask, pos, packeds)
            losses = []
            for qi, qres in enumerate(out):
                losses += question_losses([qres], targs[qi])
            loss = torch.stack(losses).mean() / args.accum
            loss.backward()
            running += loss.item() * args.accum
            micro += 1

            if micro % args.accum == 0:
                torch.nn.utils.clip_grad_norm_(
                    [p for g in groups for p in g["params"]], 1.0)
                opt.step()
                sched.step()
                opt.zero_grad(set_to_none=True)
                step += 1
                if step % 50 == 0:
                    el = time.time() - t0
                    mem = torch.cuda.max_memory_allocated() / 2**30
                    print(f"step {step}/{total_steps} "
                          f"loss={running/(50*args.accum):.4f} "
                          f"{el/step:.2f}s/step peak={mem:.1f}GB", flush=True)
                    running = 0.0
                if step % args.save_every == 0 or step == total_steps:
                    ck = os.path.join(args.out, f"step{step}.pt")
                    save_ckpt(model, heads, args, ck)
                    print(f"saved {ck}", flush=True)
                if step >= total_steps:
                    done = True
                    break
        if step >= total_steps:
            break

    save_ckpt(model, heads, args, os.path.join(args.out, "final.pt"))
    print("done")


if __name__ == "__main__":
    main()