File size: 16,590 Bytes
6071ec5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
"""Full-parameter SFT of Slayer1B-1.09 (native checkpoint) on the rendered data from prepare.py.



  torchrun --nproc_per_node 8 train.py --ckpt wagi_95000.pt --data data/s1_toolcall --out runs/s1 [options]

  python train.py ... --smoke            (single GPU, few steps, SGD: checks shapes, masks, loss, save/load)



Design

- No packing: the native attention is plain causal SDPA without document masks, so packed examples would attend to

  each other. Microbatches are padded, length-bucketed, under a token budget (--mb-tokens, padded tokens).

- Tool calling in every batch: every microbatch holds >= --min-tool-per-mb tool-use examples (deterministic swap).

- Loss: cross-entropy on assistant targets only (loss_mask), normalised by the number of target tokens of the whole

  optimizer step (known in advance on every rank, no extra communication). Separate tool/chat losses are logged.

- FSDP2 (fully_shard per block + root) with bf16 compute / fp32 master weights and reduce; activation checkpointing.

- Saves checkpoints in the native wagi_*.pt format (same keys as the base) + run metadata.

"""
from __future__ import annotations

import argparse
import hashlib
import json
import math
import os
import random
import sys
import time
from pathlib import Path

import numpy as np
import pyarrow.parquet as pq
import torch
import torch.distributed as dist
import torch.nn.functional as F

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
from model_io import load, save, sha256  # noqa: E402


def log(*a):
    if not dist.is_initialized() or dist.get_rank() == 0:
        print(time.strftime("%H:%M:%S"), *a, flush=True)


def read_examples(path):
    t = pq.read_table(path, columns=["id", "input_ids", "loss_mask", "is_tool", "n_tokens"]).to_pylist()
    return [{"id": r["id"], "x": np.frombuffer(r["input_ids"], dtype=np.uint16), "m": np.frombuffer(r["loss_mask"], dtype=np.uint8),
             "tool": bool(r["is_tool"]), "n": r["n_tokens"]} for r in t]


def microbatches(ex, budget, seed, epoch, min_tool, chunk=8192):
    """Length-bucketed microbatches under a padded-token budget, each with >= min_tool tool examples."""
    rng = random.Random(f"{seed}|{epoch}")
    idx = list(range(len(ex)))
    rng.shuffle(idx)
    mbs = []
    for a in range(0, len(idx), chunk):
        part = sorted(idx[a:a + chunk], key=lambda i: ex[i]["n"])
        cur, mx = [], 0
        for i in part:
            n = ex[i]["n"]
            if cur and max(mx, n) * (len(cur) + 1) > budget:
                mbs.append(cur)
                cur, mx = [], 0
            cur.append(i)
            mx = max(mx, n)
        if cur:
            mbs.append(cur)
    if min_tool:
        # deficient microbatches swap their shortest chat example for a surplus tool example of similar length
        # from another microbatch; a swap is done only if both padded sizes stay within the budget
        import bisect
        surplus = []                                   # (n, mb index, example index)
        for bi, b in enumerate(mbs):
            tools = sorted((i for i in b if ex[i]["tool"]), key=lambda i: ex[i]["n"])
            for i in tools[min_tool:]:
                surplus.append((ex[i]["n"], bi, i))
        surplus.sort()
        keys = [s[0] for s in surplus]
        used = set()
        for bi, b in enumerate(mbs):
            while sum(ex[i]["tool"] for i in b) < min_tool:
                chats = [i for i in b if not ex[i]["tool"]]
                if not chats:
                    break
                mx = max(ex[i]["n"] for i in b)
                c = min(chats, key=lambda i: ex[i]["n"])
                k = bisect.bisect_right(keys, mx) - 1
                while k >= 0 and (k in used or surplus[k][1] == bi):
                    k -= 1
                if k < 0:
                    break
                n_t, dbi, ti = surplus[k]
                d = mbs[dbi]
                if max([ex[j]["n"] for j in d if j != ti] + [ex[c]["n"]]) * len(d) > budget:
                    used.add(k)
                    continue
                used.add(k)
                d[d.index(ti)] = c
                b[b.index(c)] = ti
    rng.shuffle(mbs)
    return mbs


def collate(ex, b, device):
    L = max(ex[i]["n"] for i in b)
    x = torch.zeros((len(b), L), dtype=torch.long)
    y = torch.full((len(b), L), -100, dtype=torch.long)
    is_tool = torch.zeros(len(b), dtype=torch.bool)
    for k, i in enumerate(b):
        ids = torch.from_numpy(ex[i]["x"].astype(np.int64))
        m = torch.from_numpy(ex[i]["m"].astype(np.bool_))
        n = len(ids)
        x[k, :n] = ids
        tgt = torch.full((n,), -100, dtype=torch.long)
        tgt[:-1] = torch.where(m[1:], ids[1:], torch.tensor(-100))      # predict token t+1 where t+1 is a target
        y[k, :n] = tgt
        is_tool[k] = ex[i]["tool"]
    return x.to(device, non_blocking=True), y.to(device, non_blocking=True), is_tool.to(device)


def n_targets(ex, b):
    return int(sum(int(ex[i]["m"][1:].sum()) for i in b))


def _ce_chunk(lg, y):
    return F.cross_entropy(lg.float(), y, ignore_index=-100, reduction="none")


def loss_parts(model, x, y, is_tool, tool_w, chunk=4096):
    from torch.utils.checkpoint import checkpoint
    logits, _ = model(x)
    lg, yy = logits.reshape(-1, logits.size(-1)), y.reshape(-1)
    # fp32 CE per chunk, recomputed in backward: never materialises the full fp32 logits
    ce = torch.cat([checkpoint(_ce_chunk, lg[i:i + chunk], yy[i:i + chunk], use_reentrant=False) for i in range(0, lg.size(0), chunk)]).view(y.shape)
    valid = (y != -100).float()
    per_ex = (ce * valid).sum(1)
    w = torch.where(is_tool, torch.full_like(per_ex, tool_w), torch.ones_like(per_ex))
    return (per_ex * w).sum(), per_ex[is_tool].sum().detach(), valid[is_tool].sum().detach(), per_ex[~is_tool].sum().detach(), valid[~is_tool].sum().detach()


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--ckpt", required=True)
    ap.add_argument("--ckpt-sha256", default=None)
    ap.add_argument("--data", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--epochs", type=float, default=1.0)
    ap.add_argument("--lr", type=float, default=2e-5)
    ap.add_argument("--min-lr-ratio", type=float, default=0.1)
    ap.add_argument("--warmup", type=float, default=0.03)
    ap.add_argument("--schedule", choices=["cosine", "wsd"], default="cosine",
                    help="wsd: warmup -> constant peak -> linear decay to min-lr over the last --decay-frac of the steps")
    ap.add_argument("--decay-frac", type=float, default=0.25)
    ap.add_argument("--save-before-decay", action="store_true", help="also save the checkpoint at the end of the constant phase")
    ap.add_argument("--wd", type=float, default=0.01)
    ap.add_argument("--mb-tokens", type=int, default=16384, help="padded tokens per microbatch per GPU")
    ap.add_argument("--accum", type=int, default=2)
    ap.add_argument("--min-tool-per-mb", type=int, default=1)
    ap.add_argument("--tool-loss-weight", type=float, default=1.0)
    ap.add_argument("--eval-every", type=int, default=200)
    ap.add_argument("--save-every", type=int, default=0)
    ap.add_argument("--seed", default="slayer1b-sft-1")
    ap.add_argument("--act-ckpt", action=argparse.BooleanOptionalAction, default=True, help="--no-act-ckpt: keep activations (faster, more memory)")
    ap.add_argument("--smoke", action="store_true")
    ap.add_argument("--max-steps", type=int, default=0)
    ap.add_argument("--no-save", action="store_true")
    ap.add_argument("--dist", choices=["ddp", "fsdp"], default="ddp",
                    help="ddp: full replica per GPU, one bf16-compressed all-reduce per step (fits 1B + AdamW on 24-32 GB); fsdp: sharded")
    ap.add_argument("--no-eval", action="store_true")
    a = ap.parse_args()
    out = Path(a.out)
    out.mkdir(parents=True, exist_ok=True)
    distributed = "RANK" in os.environ and not a.smoke
    if distributed:
        dist.init_process_group("nccl")
        rank, world = dist.get_rank(), dist.get_world_size()
        torch.cuda.set_device(int(os.environ["LOCAL_RANK"]))
    else:
        rank, world = 0, 1
    dev = "cuda"
    torch.manual_seed(int(hashlib.sha256(a.seed.encode()).hexdigest()[:8], 16))
    base_sd_keys = set(torch.load(a.ckpt, map_location="cpu", weights_only=True, mmap=True)["model"].keys())
    model, cfg, base_step = load(a.ckpt, device="cpu" if distributed else dev, dtype=torch.float32, expect_sha256=a.ckpt_sha256)
    model.cfg.act_ckpt = bool(a.act_ckpt)
    if a.smoke:
        model = model.to(torch.bfloat16)          # local smoke on a 16 GB card: bf16 weights + SGD (no optimizer state)
    model.train()
    raw = model
    if distributed and a.dist == "fsdp":
        from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard
        mp = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32)
        model = model.to(dev)
        for b in model.blocks:
            fully_shard(b, mp_policy=mp)
        fully_shard(model, mp_policy=mp)
    elif distributed:
        from torch.distributed.algorithms.ddp_comm_hooks.default_hooks import bf16_compress_hook
        from torch.nn.parallel import DistributedDataParallel as DDP
        model = model.to(dev)
        model = DDP(model, device_ids=[torch.cuda.current_device()], gradient_as_bucket_view=True, bucket_cap_mb=100)
        model.register_comm_hook(None, bf16_compress_hook)
    train = read_examples(Path(a.data) / "train.parquet")
    val = read_examples(Path(a.data) / "val.parquet")
    decay, no_decay = [], []
    for n, p in model.named_parameters():
        (decay if p.ndim >= 2 and "tok" not in n else no_decay).append(p)
    if a.smoke:
        opt = torch.optim.SGD(model.parameters(), lr=a.lr)
    else:
        opt = torch.optim.AdamW([{"params": decay, "weight_decay": a.wd}, {"params": no_decay, "weight_decay": 0.0}],
                                lr=a.lr, betas=(0.9, 0.95), eps=1e-8, fused=True)
    per_step = world * a.accum
    epochs = math.ceil(a.epochs)
    plan = []
    for e in range(epochs):
        mbs = microbatches(train, a.mb_tokens, a.seed, e, a.min_tool_per_mb)
        if e == epochs - 1 and a.epochs != epochs:
            mbs = mbs[: int(len(mbs) * (a.epochs - (epochs - 1)))]
        plan += mbs[: len(mbs) // per_step * per_step]
    steps = len(plan) // per_step
    if a.max_steps:
        steps = min(steps, a.max_steps)
    warm = max(1, int(steps * a.warmup))
    decay_start = steps - max(1, int(steps * a.decay_frac))

    def lr_at(s):
        if s < warm:
            return a.lr * (s + 1) / warm
        if a.schedule == "wsd":
            if s < decay_start:
                return a.lr
            return a.lr * (a.min_lr_ratio + (1 - a.min_lr_ratio) * (1 - (s - decay_start + 1) / max(1, steps - decay_start)))
        return a.lr * (a.min_lr_ratio + (1 - a.min_lr_ratio) * 0.5 * (1 + math.cos(math.pi * (s - warm) / max(1, steps - warm))))
    tool_mb = sum(1 for b in plan if any(train[i]["tool"] for i in b))
    tool_steps = sum(1 for s in range(steps) if any(train[i]["tool"] for b in plan[s * per_step:(s + 1) * per_step] for i in b))
    meta = {"base_ckpt": a.ckpt, "base_step": base_step, "args": vars(a), "world": world, "steps": steps, "microbatches": len(plan),
            "microbatches_with_tool_example": tool_mb, "optimizer_steps_with_tool_example": tool_steps, "train_examples": len(train), "val_examples": len(val),
            "data_manifest": json.loads((Path(a.data) / "manifest.json").read_text(encoding="utf-8")).get("files") if (Path(a.data) / "manifest.json").exists() else None}
    log(json.dumps({k: meta[k] for k in ("steps", "microbatches", "microbatches_with_tool_example", "optimizer_steps_with_tool_example", "train_examples", "world")}))
    if rank == 0:
        (out / "run_meta.json").write_text(json.dumps(meta, indent=1, default=str), encoding="utf-8")
    logf = open(out / "train_log.jsonl", "a", encoding="utf-8") if rank == 0 else None

    def evaluate():
        model.eval()
        sums = torch.zeros(4, device=dev)
        vb = microbatches(val, a.mb_tokens, "val", 0, 0)
        vb = vb[: len(vb) // world * world]
        with torch.no_grad():
            for b in vb[rank::world]:
                x, y, it = collate(val, b, dev)
                with torch.autocast("cuda", dtype=torch.bfloat16):
                    _, ts, tn, cs, cn = loss_parts(model, x, y, it, 1.0)
                sums += torch.stack([ts, tn, cs, cn])
        if distributed:
            dist.all_reduce(sums)
        model.train()
        ts, tn, cs, cn = sums.tolist()
        return {"val_tool_loss": ts / max(tn, 1), "val_chat_loss": cs / max(cn, 1)}

    if not a.smoke and not a.no_eval:
        ev = evaluate()
        log("step 0", json.dumps(ev))
        if logf:
            logf.write(json.dumps({"step": 0, **ev}) + "\n")
    t0, tok_seen = time.time(), 0
    for s in range(steps):
        group = plan[s * per_step:(s + 1) * per_step]
        denom = sum(n_targets(train, b) for b in group)
        mine = group[rank::world]
        for g in opt.param_groups:
            g["lr"] = lr_at(s)
        stats = torch.zeros(5, device=dev)
        import contextlib
        for k, b in enumerate(mine):
            x, y, it = collate(train, b, dev)
            sync = contextlib.nullcontext() if (not distributed or a.dist == "fsdp" or k == len(mine) - 1) else model.no_sync()
            with sync:
                with torch.autocast("cuda", dtype=torch.bfloat16):
                    lsum, ts, tn, cs, cn = loss_parts(model, x, y, it, a.tool_loss_weight)
                (lsum / denom * world).backward()       # DDP/FSDP average grads over ranks: * world restores the sum
            stats += torch.stack([lsum.detach(), ts, tn, cs, cn])
            tok_seen += x.numel()
        gn = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        opt.step()
        opt.zero_grad(set_to_none=True)
        if distributed:
            dist.all_reduce(stats)
        if s % 10 == 0 or s == steps - 1 or a.max_steps:
            l, ts, tn, cs, cn = stats.tolist()
            rec = {"step": s + 1, "lr": lr_at(s), "loss": l / max(denom, 1), "tool_loss": ts / max(tn, 1), "chat_loss": cs / max(cn, 1),
                   "grad_norm": float(gn), "tok_per_s_per_gpu": tok_seen / (time.time() - t0)}
            log(json.dumps(rec))
            if logf:
                logf.write(json.dumps(rec) + "\n")
                logf.flush()
        last = s == steps - 1
        if (not a.smoke) and (not a.no_eval) and ((a.eval_every and (s + 1) % a.eval_every == 0) or last):
            ev = evaluate()
            log(f"step {s + 1}", json.dumps(ev))
            if logf:
                logf.write(json.dumps({"step": s + 1, **ev}) + "\n")
        if not a.no_save and ((a.save_every and (s + 1) % a.save_every == 0) or last or (a.save_before_decay and a.schedule == "wsd" and s + 1 == decay_start)):
            if distributed and a.dist == "fsdp":
                from torch.distributed.checkpoint.state_dict import StateDictOptions, get_model_state_dict
                sd = get_model_state_dict(model, options=StateDictOptions(full_state_dict=True, cpu_offload=True))
            elif distributed:
                sd = {k: v.detach().float().cpu() for k, v in raw.state_dict().items()} if rank == 0 else {}
            else:
                sd = {k: v.detach().float().cpu() for k, v in model.state_dict().items()}
            if rank == 0:
                sd = {k: v.float() for k, v in sd.items() if k in base_sd_keys}
                if "head.weight" in sd and "tok.weight" in sd:
                    sd["head.weight"] = sd["tok.weight"]          # tied: one storage, same file size as the base
                missing = base_sd_keys - set(sd)
                assert not missing, f"missing keys {sorted(missing)[:5]}"
                p = out / f"sft_step{s + 1}.pt"
                save(None, cfg, p, base_step, extra={"sft_step": s + 1, **{k: meta[k] for k in ("args", "steps")}}, state_dict=sd)
                log("saved", p, sha256(p))
            if distributed:
                dist.barrier()
    if distributed:
        dist.destroy_process_group()


if __name__ == "__main__":
    main()