File size: 5,017 Bytes
91ac3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import argparse
import importlib.util
import json
import time

import torch
from transformers import LlamaForCausalLM

from kawk50m.cli import configure_utf8_stdio
from kawk50m.config import build_llama_config, count_unique_parameters, load_yaml


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Benchmark synthetic BF16 pretraining throughput."
    )
    parser.add_argument("--config", default="configs/model_50m.yaml")
    parser.add_argument("--batch-size", type=int, default=8)
    parser.add_argument("--sequence-length", type=int, default=1024)
    parser.add_argument("--gradient-accumulation", type=int, default=16)
    parser.add_argument("--warmup-steps", type=int, default=1)
    parser.add_argument("--steps", type=int, default=3)
    parser.add_argument("--compile", action="store_true", dest="use_compile")
    parser.add_argument("--compile-mode", default="default")
    return parser.parse_args()


def main() -> None:
    configure_utf8_stdio()
    args = parse_args()
    if not torch.cuda.is_available() or not torch.cuda.is_bf16_supported():
        raise RuntimeError("A CUDA GPU with BF16 support is required")
    if args.use_compile and importlib.util.find_spec("triton") is None:
        raise RuntimeError(
            "--compile requires a working Triton installation; none was found"
        )
    for name in (
        "batch_size",
        "sequence_length",
        "gradient_accumulation",
        "warmup_steps",
        "steps",
    ):
        if getattr(args, name) <= 0:
            raise ValueError(f"--{name.replace('_', '-')} must be positive")

    torch.set_float32_matmul_precision("high")
    torch.backends.cuda.matmul.allow_tf32 = True
    device = torch.device("cuda")
    model_config, expected = build_llama_config(load_yaml(args.config))
    if args.sequence_length > model_config.max_position_embeddings:
        raise ValueError("sequence length exceeds the configured context length")

    raw_model = LlamaForCausalLM(model_config).to(device)
    parameter_count = count_unique_parameters(raw_model)
    if expected is not None and parameter_count != expected:
        raise RuntimeError(
            f"Expected {expected} parameters but constructed {parameter_count}"
        )
    model = (
        torch.compile(raw_model, mode=args.compile_mode)
        if args.use_compile
        else raw_model
    )
    optimizer = torch.optim.AdamW(
        model.parameters(),
        lr=6.0e-4,
        betas=(0.9, 0.95),
        weight_decay=0.1,
        fused=True,
    )
    input_ids = torch.randint(
        0,
        model_config.vocab_size,
        (args.batch_size, args.sequence_length),
        device=device,
        dtype=torch.long,
    )

    def optimizer_step() -> float:
        optimizer.zero_grad(set_to_none=True)
        total_loss = 0.0
        for _ in range(args.gradient_accumulation):
            with torch.autocast("cuda", dtype=torch.bfloat16):
                loss = model(
                    input_ids=input_ids,
                    labels=input_ids,
                    use_cache=False,
                ).loss
            (loss / args.gradient_accumulation).backward()
            total_loss += loss.detach().item()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        optimizer.step()
        return total_loss / args.gradient_accumulation

    for _ in range(args.warmup_steps):
        optimizer_step()
    torch.cuda.synchronize()
    torch.cuda.reset_peak_memory_stats()
    started = time.perf_counter()
    final_loss = 0.0
    for _ in range(args.steps):
        final_loss = optimizer_step()
    torch.cuda.synchronize()
    elapsed = time.perf_counter() - started

    tokens = (
        args.steps
        * args.gradient_accumulation
        * args.batch_size
        * args.sequence_length
    )
    tokens_per_second = tokens / elapsed
    result = {
        "gpu": torch.cuda.get_device_name(),
        "parameters": parameter_count,
        "precision": "bf16",
        "compiled": args.use_compile,
        "batch_size": args.batch_size,
        "sequence_length": args.sequence_length,
        "gradient_accumulation": args.gradient_accumulation,
        "timed_optimizer_steps": args.steps,
        "elapsed_seconds": elapsed,
        "tokens": tokens,
        "tokens_per_second": tokens_per_second,
        "seconds_per_optimizer_step": elapsed / args.steps,
        "peak_memory_gib": torch.cuda.max_memory_allocated() / 1024**3,
        "final_synthetic_loss": final_loss,
        "ideal_compute_only_hours": {
            "1B": 1_000_000_000 / tokens_per_second / 3600,
            "5B": 5_000_000_000 / tokens_per_second / 3600,
            "10B": 10_000_000_000 / tokens_per_second / 3600,
        },
        "note": "Synthetic compute-only result; disk I/O, eval, and checkpoints are excluded.",
    }
    print(json.dumps(result, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()