File size: 13,939 Bytes
643267a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Train PAT or FA with CUDA BF16, using one device or torchrun."""

from __future__ import annotations

import argparse
import hashlib
import json
import os
import random
import signal
import tempfile
import time
from pathlib import Path

import numpy as np
import torch
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel

from .checkpoint import load_checkpoint, save_checkpoint, sha256, verify_checkpoint
from .config import PATConfig
from .data import PieceDataset, training_batches, validation_batches
from .model import PATModel
from .tokenizer import TOKENIZER_SHA256
from .training import (
    TrainingConfig,
    backward_loss,
    optimizer_for,
    validate_resume_plan,
    validate_resume_state,
)


def _sum(values: torch.Tensor, world_size: int) -> torch.Tensor:
    if world_size > 1:
        dist.all_reduce(values, op=dist.ReduceOp.SUM)
    return values


def _plan_hash(plan: list[list[int]]) -> str:
    return hashlib.sha256(json.dumps(plan, separators=(",", ":")).encode()).hexdigest()


@torch.no_grad()
def validate(model, data: PieceDataset, budget: int, device, rank: int, world: int) -> dict:
    model.eval()
    totals = torch.zeros(4, device=device, dtype=torch.float64)
    for index, batch in enumerate(validation_batches(data, budget, seed=model.config.seed)):
        if index % world != rank:
            continue
        pieces = [data[item].to(device) for item in batch]
        with torch.autocast("cuda", dtype=torch.bfloat16):
            output = model(pieces)
        totals += torch.tensor([
            output.loss_sum.item(), output.token_count,
            output.lexical_loss_sum.item(), output.lexical_token_count,
        ], device=device, dtype=torch.float64)
    _sum(totals, world)
    if totals[1].item() <= 0 or totals[3].item() <= 0:
        raise ValueError("Validation corpus contains no supervised lexical tokens")
    model.train()
    return {"loss": (totals[0] / totals[1]).item(),
            "lexical_loss": (totals[2] / totals[3]).item(),
            "targets": int(totals[1].item()), "lexical_targets": int(totals[3].item())}


def _save(model, optimizer, directory: Path, state: dict, rank: int, world: int) -> None:
    rng = {"cpu": torch.get_rng_state(), "cuda": torch.cuda.get_rng_state().cpu()}
    states = [None] * world if rank == 0 else None
    if world > 1:
        dist.gather_object(rng, states, dst=0)
    else:
        states = [rng]
    if rank == 0:
        # The outer directory is published only after both weights and resume
        # state have been written and hashed; interrupted saves are never latest.
        stage_root = Path(tempfile.mkdtemp(prefix=".saving-", dir=directory.parent))
        stage = stage_root / "checkpoint"
        save_checkpoint(model, stage, metadata={"tokens": state["seen_tokens"], "step": state["step"]})
        torch.save({**state, "optimizer": optimizer.state_dict(), "rng_by_rank": states}, stage / "training.pt")
        manifest = json.loads((stage / "manifest.json").read_text())
        manifest["files"]["training.pt"] = {
            "sha256": sha256(stage / "training.pt"), "size_bytes": (stage / "training.pt").stat().st_size,
        }
        (stage / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
        stage.rename(directory)
        stage_root.rmdir()
    if world > 1:
        dist.barrier()


def run(args) -> None:
    if not torch.cuda.is_available():
        raise RuntimeError("Training requires a CUDA GPU; no alternate attention implementation is provided")
    rank, world = int(os.environ.get("RANK", "0")), int(os.environ.get("WORLD_SIZE", "1"))
    device = torch.device("cuda", int(os.environ.get("LOCAL_RANK", "0")))
    torch.cuda.set_device(device)
    if not torch.cuda.is_bf16_supported():
        raise RuntimeError("Training requires BF16 support")
    if world > 1:
        dist.init_process_group("nccl", device_id=device)
    document = json.loads(args.config.read_text())
    if set(document) != {"model", "training"}:
        raise ValueError("Training config must contain exactly 'model' and 'training'")
    model_config = PATConfig.from_dict(document["model"])
    training_values = dict(document["training"])
    if args.tokens is not None:
        training_values["tokens"] = args.tokens
    config = TrainingConfig(**training_values)
    if config.seed != model_config.seed:
        raise ValueError("Model and training initialization seeds must agree")
    random.seed(config.seed)
    np.random.seed(config.seed)
    torch.manual_seed(config.seed)
    torch.cuda.manual_seed_all(config.seed)
    torch.backends.cuda.matmul.allow_tf32 = False
    torch._dynamo.config.optimize_ddp = False
    dataset = PieceDataset(args.data)
    val_dataset = PieceDataset(args.validation) if args.validation else None
    for data in (dataset, val_dataset):
        if data is None:
            continue
        if data.manifest["tokenizer_sha256"] != TOKENIZER_SHA256:
            raise ValueError("Dataset tokenizer differs from the model tokenizer")
        if data.manifest["context_length"] != model_config.context_length:
            raise ValueError("Dataset context length differs from model configuration")
    if config.microbatch_tokens < model_config.context_length:
        raise ValueError("Microbatch token budget must fit one maximum-length piece")
    if args.resume and args.init_checkpoint:
        raise ValueError("Choose resume or initialize from weights, not both")
    source = args.resume or args.init_checkpoint
    model = load_checkpoint(source, device=device) if source else PATModel(model_config).to(device)
    if model.config.to_dict() != model_config.to_dict():
        raise ValueError("Checkpoint architecture differs from the training configuration")
    model.train()
    optimizer = optimizer_for(model, config)
    state = {"format": "pat-training-state-1", "seen_tokens": 0, "step": 0,
             "epoch": 0, "cursor": 0, "data_fingerprint": dataset.fingerprint,
             "validation_fingerprint": val_dataset.fingerprint if val_dataset else None,
             "training_config": config.to_dict(), "world_size": world, "plan_sha256": None}
    if args.resume:
        verify_checkpoint(args.resume)
        restored = torch.load(args.resume / "training.pt", map_location="cpu", weights_only=True)
        validate_resume_state(restored, state)
        optimizer.load_state_dict(restored.pop("optimizer"))
        rng = restored.pop("rng_by_rank")[rank]
        torch.set_rng_state(rng["cpu"])
        torch.cuda.set_rng_state(rng["cuda"], device)
        state = restored
    if args.output.exists() and any(args.output.iterdir()) and not args.resume:
        raise FileExistsError("Use a new output directory for a new training run")
    args.output.mkdir(parents=True, exist_ok=True)
    wrapped = (
        DistributedDataParallel(model, device_ids=[device.index], find_unused_parameters=True)
        if world > 1 else model
    )
    stopping = False

    def request_stop(_signal, _frame):
        nonlocal stopping
        stopping = True

    for number in (signal.SIGTERM, signal.SIGINT, signal.SIGUSR1):
        signal.signal(number, request_stop)
    log = (args.output / "metrics.jsonl").open("a", buffering=1) if rank == 0 else None
    last_save = state["seen_tokens"]
    last_eval = state["seen_tokens"]
    quantum = world * config.accumulation_steps
    try:
        while state["seen_tokens"] < config.tokens:
            plan = training_batches(dataset.routed_lengths, dataset.lexical_lengths,
                                    budget=config.microbatch_tokens, seed=config.seed,
                                    epoch=state["epoch"], quantum=quantum)
            if not plan:
                raise ValueError("Dataset is too small for one distributed optimizer window")
            identity = _plan_hash(plan)
            validate_resume_plan(state, len(plan), identity)
            state["plan_sha256"] = identity
            while state["cursor"] < len(plan) and state["seen_tokens"] < config.tokens:
                started = time.perf_counter()
                batches = plan[state["cursor"]:state["cursor"] + quantum]
                # With explicit next-token labels, each routed token has exactly
                # one predecessor (including BOS->first token and lexical->EOD).
                lexical = [int(dataset.lexical_lengths[batch].sum()) for batch in batches]
                targets = [int(dataset.routed_lengths[batch].sum()) for batch in batches]
                total_lexical, total_targets = sum(lexical), sum(targets)
                optimizer.zero_grad(set_to_none=True)
                lr = config.lr_at(state["seen_tokens"])
                for group in optimizer.param_groups:
                    group["lr"] = lr
                metrics = torch.zeros(4, device=device, dtype=torch.float64)
                for microstep in range(config.accumulation_steps):
                    position = microstep * world + rank
                    batch = batches[position]
                    pieces = [dataset[item].to(device) for item in batch]
                    with torch.autocast("cuda", dtype=torch.bfloat16):
                        result = wrapped(pieces)
                        if result.token_count != targets[position]:
                            raise RuntimeError("Model target count differs from the planned objective")
                        loss_sum = result.loss_sum.to(dtype=next(model.parameters()).dtype)
                        global_loss_sum = (
                            _sum(result.loss_sum.detach().to(torch.float64), world)
                            if world > 1 else None
                        )
                        loss = backward_loss(
                            loss_sum, model_config.architecture, world_size=world,
                            local_lexical=lexical[position],
                            global_microbatch_targets=sum(targets[microstep * world:(microstep + 1) * world]),
                            global_window_targets=total_targets,
                            global_window_lexical=total_lexical,
                            global_loss_sum=global_loss_sum,
                        )
                    # DDP reduces every microstep, preserving accumulation and
                    # reduction order even when multiple microsteps form an update.
                    loss.backward()
                    metrics += torch.tensor([result.loss_sum.item(), result.token_count,
                                             result.lexical_loss_sum.item(), result.lexical_token_count],
                                            device=device, dtype=torch.float64)
                grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0, error_if_nonfinite=True)
                if not torch.isfinite(metrics).all():
                    raise FloatingPointError("Nonfinite loss; optimizer update was not performed")
                optimizer.step()
                state["step"] += 1
                state["cursor"] += quantum
                state["seen_tokens"] += total_lexical
                _sum(metrics, world)
                stop_flag = torch.tensor(int(stopping), device=device)
                _sum(stop_flag, world)
                stopping = stop_flag.item() > 0
                row = {"step": state["step"], "tokens": state["seen_tokens"], "lr": lr,
                       "loss": (metrics[0] / metrics[1]).item(),
                       "lexical_loss": (metrics[2] / metrics[3]).item(),
                       "grad_norm": float(grad_norm),
                       "tokens_per_second": total_lexical / (time.perf_counter() - started)}
                finished = state["seen_tokens"] >= config.tokens
                if val_dataset and (finished or state["seen_tokens"] - last_eval >= config.validate_every):
                    row["validation"] = validate(model, val_dataset, config.microbatch_tokens, device, rank, world)
                    last_eval = state["seen_tokens"]
                if rank == 0:
                    log.write(json.dumps(row) + "\n")
                    if state["step"] % 10 == 0 or finished or stopping:
                        print(json.dumps(row), flush=True)
                if finished or stopping or state["seen_tokens"] - last_save >= config.checkpoint_every:
                    path = args.output / f"step-{state['step']:08d}"
                    _save(model, optimizer, path, state, rank, world)
                    last_save = state["seen_tokens"]
                    if rank == 0:
                        (args.output / "latest.txt").write_text(path.name + "\n")
                if stopping:
                    return
            if state["cursor"] == len(plan):
                state["epoch"] += 1
                state["cursor"] = 0
                state["plan_sha256"] = None
    finally:
        if log:
            log.close()
        if world > 1:
            dist.destroy_process_group()


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--config", type=Path, required=True, help="Model and training JSON recipe")
    parser.add_argument("--data", type=Path, required=True, help="Prepared training dataset")
    parser.add_argument("--validation", type=Path, help="Prepared held-out validation dataset")
    parser.add_argument("--output", type=Path, required=True, help="Run directory for metrics and checkpoints")
    parser.add_argument("--resume", type=Path, help="Complete checkpoint from this trainer, including training.pt")
    parser.add_argument("--init-checkpoint", type=Path, help="Initialize weights; start a NEW optimizer and token clock")
    parser.add_argument("--tokens", type=int, help="Override lexical training horizon; complete the final optimizer window")
    run(parser.parse_args())


if __name__ == "__main__":
    main()