File size: 12,012 Bytes
b16b327
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""One optimizer step (or a few, with minibatches) on a round's data. Run under torchrun, one rank per GPU.



    torchrun --nproc_per_node 2 -m pocket_math.train --spec spec.json

    python -m pocket_math.train --merge-only --base B --adapter A --out DIR



Each rank loads the frozen fp16 base with the LoRA adapter, takes a length-balanced share of

the sequences (batch size 1, no padding), and accumulates gradients. Gradients are summed

across ranks before the step, so every rank applies the identical update; rank 0 saves.

"""

from __future__ import annotations

import argparse
import json
import math
import os
import random
import sys
import time
from pathlib import Path
from typing import Any

import torch
import torch.distributed as dist

from .io import read_jsonl, write_json
from .losses import PGConfig, dpo_loss, pg_loss_sum, sft_loss_sum, token_advantages
from .modeling import attach_lora, load_model, pick_dtype, save_adapter, save_merged, train_logprobs

# Losses are backpropagated divided by GRAD_UNIT instead of the batch's token count (up to ~2M),
# so fp16 activation gradients stay far from underflow; gradients are rescaled after unscale_.
GRAD_UNIT = 4096.0


def _setup() -> tuple[int, int, str]:
    world, rank = int(os.environ.get("WORLD_SIZE", 1)), int(os.environ.get("RANK", 0))
    local = int(os.environ.get("LOCAL_RANK", 0))
    cuda = torch.cuda.is_available()
    if world > 1:
        dist.init_process_group("nccl" if cuda else "gloo")
    if cuda:
        torch.cuda.set_device(local)
    return world, rank, f"cuda:{local}" if cuda else "cpu"


def _length(row: dict[str, Any]) -> int:
    return len(row["prompt_ids"]) + len(row.get("response_ids") or row.get("chosen_ids", [])) + \
        len(row.get("rejected_ids", []))


def partition(rows: list[dict[str, Any]], world: int, minibatches: int, seed: int) -> list[list[list[int]]]:
    """parts[m][rank] = row indices; minibatches by seeded shuffle, ranks balanced by token count."""
    order = list(range(len(rows)))
    random.Random(seed).shuffle(order)
    parts = []
    for m in range(minibatches):
        idx = sorted(order[m::minibatches], key=lambda i: -_length(rows[i]))
        loads, buckets = [0] * world, [[] for _ in range(world)]
        for i in idx:
            r = loads.index(min(loads))
            buckets[r].append(i)
            loads[r] += _length(rows[i])
        parts.append(buckets)
    return parts


def _loss_tokens(row: dict[str, Any]) -> int:
    mask = row.get("loss_mask")
    return sum(mask) if mask else len(row["response_ids"])


def _all_reduce_(tensors: list[torch.Tensor], world: int) -> None:
    if world > 1:
        for t in tensors:
            dist.all_reduce(t)


def train_step(spec: dict[str, Any]) -> dict[str, Any]:
    world, rank, device = _setup()
    torch.manual_seed(int(spec.get("seed", 0)))
    dtype = pick_dtype(spec.get("dtype", "fp16"), device)
    model = load_model(spec["base_dir"], dtype, device, spec.get("trust_remote_code", False))
    model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
    model.config.use_cache = False
    adapter_in = Path(spec["adapter_in"]) if spec.get("adapter_in") else None
    model = attach_lora(model, spec.get("lora", {}), adapter_in, trainable=True)
    model.train()
    params = [p for p in model.parameters() if p.requires_grad]
    opt = torch.optim.AdamW(params, lr=float(spec["lr"]), betas=tuple(spec.get("betas", (0.9, 0.999))),
                            weight_decay=float(spec.get("weight_decay", 0.0)), eps=1e-8)
    use_scaler = device.startswith("cuda") and dtype == torch.float16
    scaler = torch.amp.GradScaler("cuda", enabled=use_scaler, init_scale=2.0 ** 14, growth_interval=20)
    optim_in = spec.get("optim_in")
    if optim_in and Path(optim_in).exists():
        state = torch.load(optim_in, map_location=device, weights_only=False)
        opt.load_state_dict(state["optimizer"])
        if use_scaler and state.get("scaler"):
            scaler.load_state_dict(state["scaler"])
    for g in opt.param_groups:
        g["lr"] = float(spec["lr"])

    kind = spec.get("kind", "pg")
    unit = 1.0 if kind == "dpo" else GRAD_UNIT
    rows = list(read_jsonl(spec["data"]))
    # The longest sequence a T4 can train on is measured by the smoke job (bench train-mem). Longer
    # ones are left out of this step and counted, instead of crashing the step with out-of-memory.
    max_tokens = int(spec.get("max_seq_tokens") or 0)
    if max_tokens:
        kept = [r for r in rows if _length(r) <= max_tokens]
        too_long, rows = len(rows) - len(kept), kept
    else:
        too_long = 0
    minibatches = max(1, min(int(spec.get("minibatches", 1)), len(rows)))
    parts = partition(rows, world, minibatches, int(spec.get("seed", 0)))
    cfg = PGConfig(**spec.get("loss", {}))
    chunk = int(spec.get("chunk", 1024))
    autocast = torch.autocast("cuda", dtype=dtype, enabled=device.startswith("cuda") and dtype != torch.float32)
    # loss, tokens, kl, entropy, adv, tis_mean, tis_capped, ratio_clipped, seqs, skipped_steps, grad_norm, pairs
    sums = torch.zeros(12, dtype=torch.float64, device=device)
    t0 = time.time()

    def logprobs(ids_list: list[int], start: int) -> tuple[torch.Tensor, torch.Tensor]:
        ids = torch.tensor(ids_list, device=device)
        with autocast:
            return train_logprobs(model, ids, start, chunk)

    lp_old: dict[int, torch.Tensor] = {}
    if kind == "pg" and minibatches > 1:
        with torch.no_grad():
            for i in (i for part in parts for i in part[rank]):
                r = rows[i]
                lp_old[i] = logprobs(r["prompt_ids"] + r["response_ids"], len(r["prompt_ids"]))[0].float()

    for part in parts:
        mine = part[rank]
        if kind == "dpo":
            norm = float(sum(len(b) for b in part))
        else:
            norm = float(sum(_loss_tokens(rows[i]) for b in part for i in b))
        for i in mine:
            r = rows[i]
            if kind == "dpo":
                start = len(r["prompt_ids"])
                chosen, rejected = r["prompt_ids"] + r["chosen_ids"], r["prompt_ids"] + r["rejected_ids"]
                beta = float(spec.get("dpo_beta", 0.1))
                with torch.no_grad():
                    lp_c0 = logprobs(chosen, start)[0].float().sum()
                    lp_r0 = logprobs(rejected, start)[0].float().sum()
                    with model.disable_adapter():
                        ref_c = logprobs(chosen, start)[0].float().sum()
                        ref_r = logprobs(rejected, start)[0].float().sum()
                    loss = dpo_loss(lp_c0, lp_r0, ref_c, ref_r, beta)
                    coef = -beta * torch.sigmoid(-beta * ((lp_c0 - ref_c) - (lp_r0 - ref_r)))
                # d loss / d lp_chosen = coef and d loss / d lp_rejected = -coef. Two backward passes
                # keep only one long sequence's graph in memory at a time.
                for ids, sign in ((chosen, 1.0), (rejected, -1.0)):
                    lp_seq = logprobs(ids, start)[0].float().sum()
                    scaler.scale(sign * coef * lp_seq / unit).backward()
                sums[0] += float(loss)
                sums[11] += 1
                continue
            start = len(r["prompt_ids"])
            lp, ent = logprobs(r["prompt_ids"] + r["response_ids"], start)
            lp = lp.float()
            mask = torch.tensor(r["loss_mask"] if r.get("loss_mask") else [1] * len(lp), device=device)
            if kind == "sft":
                loss = sft_loss_sum(lp, mask)
                stats: dict[str, float] = {}
            else:
                teacher = torch.tensor(r["teacher_logprobs"], device=device) if r.get("teacher_logprobs") else None
                sampler = torch.tensor([math.nan if x is None else x for x in r["sampler_logprobs"]], device=device,
                                       dtype=torch.float32)
                adv = token_advantages(cfg, lp, teacher, r.get("seq_adv"))
                loss, stats = pg_loss_sum(cfg, lp, adv, sampler, mask, lp_old.get(i))
                with torch.no_grad():
                    mf = mask.float()
                    n = float(mf.sum())
                    if teacher is not None:
                        sums[2] += float(((lp.detach() - teacher) * mf).sum())
                    sums[4] += float((adv * mf).sum())
                    for k, name in ((5, "tis_mean"), (6, "tis_capped"), (7, "ratio_clipped")):
                        sums[k] += stats[name] * n
            scaler.scale(loss / unit).backward()
            with torch.no_grad():
                sums[0] += float(loss)
                sums[1] += float(mask.sum())
                sums[3] += float((ent * mask).sum())
                sums[8] += 1
        for p in params:
            if p.grad is None:
                p.grad = torch.zeros_like(p)
        _all_reduce_([p.grad for p in params], world)
        scaler.unscale_(opt)
        for p in params:
            p.grad.mul_(unit / max(norm, 1.0))
        gn = torch.nn.utils.clip_grad_norm_(params, float(spec.get("grad_clip", 1.0)))
        if not torch.isfinite(gn):
            sums[9] += 1
        sums[10] += float(gn) if torch.isfinite(gn) else 0.0
        scaler.step(opt)
        scaler.update()
        opt.zero_grad(set_to_none=True)

    _all_reduce_([sums[:9], sums[11:]], world)
    tok = max(float(sums[1]), 1.0)
    metrics = {
        "loss": float(sums[0]) / max(tok if kind != "dpo" else float(sums[11]), 1.0),
        "tokens": int(sums[1]), "seqs": int(sums[8]), "pairs": int(sums[11]),
        "kl": float(sums[2]) / tok, "entropy": float(sums[3]) / tok, "adv_mean": float(sums[4]) / tok,
        "tis_mean": float(sums[5]) / tok, "tis_capped": float(sums[6]) / tok, "ratio_clipped": float(sums[7]) / tok,
        "grad_norm": float(sums[10]) / minibatches, "skipped_steps": int(sums[9]),
        "train_seconds": time.time() - t0, "world": world, "too_long_skipped": too_long,
    }
    if device.startswith("cuda"):
        metrics["peak_mem_gb"] = torch.cuda.max_memory_allocated() / 2 ** 30
    if rank == 0:
        save_adapter(model, Path(spec["adapter_out"]), extra=spec.get("base_info"))
        tmp = Path(spec["optim_out"]).with_suffix(".tmp")
        torch.save({"optimizer": opt.state_dict(), "scaler": scaler.state_dict() if use_scaler else None,
                    "step": spec.get("step")}, tmp)
        os.replace(tmp, spec["optim_out"])
        if spec.get("merge_out"):
            save_merged(model, Path(spec["base_dir"]), Path(spec["merge_out"]))
        write_json(spec["metrics_out"], metrics)
    if world > 1:
        dist.barrier()
        dist.destroy_process_group()
    return metrics


def merge_only(base: str, adapter: str, out: str, trust_remote_code: bool = False) -> None:
    device = "cuda" if torch.cuda.is_available() else "cpu"
    model = load_model(base, pick_dtype("fp16", device), device, trust_remote_code)
    model = attach_lora(model, {}, Path(adapter), trainable=False)
    save_merged(model, Path(base), Path(out))


def main(argv: list[str] | None = None) -> int:
    p = argparse.ArgumentParser()
    p.add_argument("--spec")
    p.add_argument("--merge-only", action="store_true")
    p.add_argument("--base")
    p.add_argument("--adapter")
    p.add_argument("--out")
    p.add_argument("--trust-remote-code", action="store_true")
    a = p.parse_args(argv)
    if a.merge_only:
        merge_only(a.base, a.adapter, a.out, a.trust_remote_code)
        return 0
    metrics = train_step(json.loads(Path(a.spec).read_text()))
    if int(os.environ.get("RANK", 0)) == 0:
        print(json.dumps(metrics), flush=True)
    return 0


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