File size: 7,150 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
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
from __future__ import annotations

import argparse
import glob
import importlib.util
import json
import math
from pathlib import Path
from typing import Any

import numpy as np
import torch
from transformers import AutoTokenizer

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


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Validate model, tokenizer, token binaries, and GPU before training."
    )
    parser.add_argument("--config", default="configs/pretrain_5b_5090.yaml")
    return parser.parse_args()


def binary_info(
    path_value: str | list[str],
    sequence_length: int,
) -> dict[str, Any]:
    values = [path_value] if isinstance(path_value, str) else path_value
    paths: set[Path] = set()
    for value in values:
        matches = [Path(item) for item in glob.glob(value)]
        if matches:
            paths.update(item.resolve() for item in matches if item.is_file())
        else:
            candidate = Path(value)
            if candidate.is_file():
                paths.add(candidate.resolve())
    ordered_paths = sorted(paths)
    if not ordered_paths:
        return {"path": path_value, "exists": False}
    byte_sizes = [path.stat().st_size for path in ordered_paths]
    byte_size = sum(byte_sizes)
    token_count = sum(
        size // np.dtype(np.uint16).itemsize for size in byte_sizes
    )
    sequences = sum(
        max(
            0,
            (size // np.dtype(np.uint16).itemsize - 1) // sequence_length,
        )
        for size in byte_sizes
    )
    return {
        "path": path_value,
        "files": [str(path) for path in ordered_paths],
        "file_count": len(ordered_paths),
        "exists": True,
        "bytes": byte_size,
        "tokens": token_count,
        "sequences": sequences,
        "even_byte_size": all(size % 2 == 0 for size in byte_sizes),
    }


def main() -> None:
    configure_utf8_stdio()
    args = parse_args()
    full_config = load_yaml(args.config)
    data = full_config.get("data")
    training = full_config.get("training")
    if not isinstance(data, dict) or not isinstance(training, dict):
        raise ValueError("Training YAML requires data and training mappings")

    sequence_length = int(data["sequence_length"])
    train_paths = data.get("train_bins", data.get("train_bin"))
    if train_paths is None:
        raise ValueError("data requires train_bin or train_bins")
    train_info = binary_info(train_paths, sequence_length)
    validation_info = binary_info(data["validation_bin"], sequence_length)
    errors: list[str] = []
    warnings: list[str] = []

    tokenizer_path = Path(full_config["tokenizer_dir"])
    tokenizer_info: dict[str, Any] = {
        "path": str(tokenizer_path),
        "exists": tokenizer_path.is_dir(),
    }
    tokenizer = None
    if tokenizer_path.is_dir():
        try:
            tokenizer = AutoTokenizer.from_pretrained(
                tokenizer_path, use_fast=False, legacy=True
            )
            tokenizer_info["vocab_size"] = len(tokenizer)
            tokenizer_info["special_token_ids"] = {
                "bos": tokenizer.bos_token_id,
                "eos": tokenizer.eos_token_id,
                "pad": tokenizer.pad_token_id,
                "unk": tokenizer.unk_token_id,
            }
        except Exception as error:
            errors.append(f"Tokenizer cannot be loaded: {error}")
    else:
        errors.append(f"Missing tokenizer directory: {tokenizer_path}")

    model_config, expected_parameters = build_llama_config(
        load_yaml(full_config["model_config"]),
        tokenizer_vocab_size=len(tokenizer) if tokenizer is not None else None,
    )
    if sequence_length > model_config.max_position_embeddings:
        errors.append("sequence_length exceeds model context length")

    for split, info in (("train", train_info), ("validation", validation_info)):
        if not info["exists"]:
            errors.append(f"Missing {split} token binary: {info['path']}")
        elif not info["even_byte_size"]:
            errors.append(f"{split} binary size is not valid uint16")
        elif info["sequences"] == 0:
            errors.append(f"{split} binary does not contain one full sequence")

    batch_size = int(training["per_device_batch_size"])
    accumulation = int(training["gradient_accumulation_steps"])
    world_size = int(training.get("world_size", 1))
    tokens_per_step = sequence_length * batch_size * accumulation * world_size
    max_steps_value = training.get("max_steps")
    if max_steps_value is None:
        max_tokens = int(training["max_tokens"])
        max_steps = math.ceil(max_tokens / tokens_per_step)
    else:
        max_steps = int(max_steps_value)
        max_tokens = max_steps * tokens_per_step
    if train_info.get("exists") and train_info.get("tokens", 0) < max_tokens:
        warnings.append(
            "The train binary is smaller than the training token budget; "
            "the deterministic sampler will start another pass over the data."
        )

    gpu_info: dict[str, Any] = {
        "available": torch.cuda.is_available(),
        "bf16_supported": (
            torch.cuda.is_available() and torch.cuda.is_bf16_supported()
        ),
        "triton_available": importlib.util.find_spec("triton") is not None,
    }
    if torch.cuda.is_available():
        properties = torch.cuda.get_device_properties(0)
        gpu_info.update(
            {
                "name": properties.name,
                "memory_gib": properties.total_memory / 1024**3,
            }
        )
        if "5090" not in properties.name:
            warnings.append(
                f"Expected an RTX 5090 configuration, detected {properties.name}."
            )
    else:
        warnings.append("No CUDA GPU is visible in this preflight environment.")
    if torch.cuda.is_available() and not gpu_info["bf16_supported"]:
        errors.append("The detected CUDA GPU does not support BF16")
    if not gpu_info["triton_available"]:
        warnings.append("Triton is unavailable; torch.compile will fall back to eager.")

    result = {
        "ok": not errors,
        "config": str(Path(args.config).resolve()),
        "model": {
            "expected_parameters": expected_parameters,
            "vocab_size": model_config.vocab_size,
            "layers": model_config.num_hidden_layers,
            "context_length": model_config.max_position_embeddings,
        },
        "tokenizer": tokenizer_info,
        "data": {"train": train_info, "validation": validation_info},
        "training": {
            "per_device_batch_size": batch_size,
            "gradient_accumulation_steps": accumulation,
            "tokens_per_optimizer_step": tokens_per_step,
            "max_steps": max_steps,
            "planned_tokens": max_steps * tokens_per_step,
        },
        "gpu": gpu_info,
        "warnings": warnings,
        "errors": errors,
    }
    print(json.dumps(result, ensure_ascii=False, indent=2))
    if errors:
        raise SystemExit(1)


if __name__ == "__main__":
    main()