PyTorch
File size: 11,423 Bytes
bd992b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
328
329
330
331
332
333
334
import argparse
import os
import time
from importlib import util
from pathlib import Path

import torch
import torch.nn as nn
from dotenv import load_dotenv

from benchmarks.registry import ModelEntry, TaskEntry, all_models, all_tasks
from benchmarks.results import TaskResult, StepRecord, result_exists, save_result

load_dotenv()

MLFLOW_TRACKING_URI = os.getenv("MLFLOW_TRACKING_URI")
MLFLOW_ENABLED = MLFLOW_TRACKING_URI is not None

if MLFLOW_ENABLED:
    try:
        import mlflow
        mlflow.set_tracking_uri(MLFLOW_TRACKING_URI)
    except ImportError:
        MLFLOW_ENABLED = False
        print("Warning: mlflow not installed. Disabling MLflow tracking.")


MODELS_DIR = Path(__file__).parent / "models"
TASKS_DIR = Path(__file__).parent / "tasks"

DEFAULT_PARAM_COUNTS = [1_000_000, 10_000_000, 35_000_000, 100_000_000]

DEFAULT_MAX_STEPS = 10_000
DEFAULT_BATCH_SIZE = 64
LOG_EVERY = 10
EVAL_EVERY = 100
TIME_LIMIT_SECONDS = 60 * 60
DEFAULT_SEED = 42


def _import_dir(directory: Path) -> None:
    """
    Import every .py file in the given directory.
    Useful for auto model and task registration.

    :param directory: The directory to import from.
    :return: None
    """
    for path in sorted(directory.glob("*.py")):
        if path.name.startswith("_"):
            continue
        spec = util.spec_from_file_location(path.stem, path)
        mod = util.module_from_spec(spec)
        spec.loader.exec_module(mod)


def _default_optimizer(model: nn.Module) -> torch.optim.Optimizer:
    return torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=1e-2, betas=(0.9, 0.95))


def _default_train_step(
        model: nn.Module,
        optimizer: torch.optim.Optimizer,
        input_ids: torch.Tensor,
        target: torch.Tensor,
        loss_mask: torch.Tensor,
) -> float:
    optimizer.zero_grad()
    logits = model(input_ids)
    B, T, C = logits.shape
    loss = nn.functional.cross_entropy(
        logits.view(B * T, C),
        target.view(B * T),
        reduction="none",
    )
    loss = (loss * loss_mask.view(B * T).float()).sum() / loss_mask.sum().clamp(min=1)
    loss.backward()
    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
    optimizer.step()
    return loss.item()


def _tokens_to_threshold(curve: list[StepRecord], threshold: float = 0.90) -> int | None:
    for r in curve:
        if r.accuracy >= threshold:
            return r.tokens
    return None


def run_task(
        model_entry: ModelEntry,
        task_entry: TaskEntry,
        n_params: int,
        batch_size: int,
        max_steps: int,
        device: str = "cuda",
        seed: int = DEFAULT_SEED,
) -> TaskResult:
    seq_len = task_entry.seq_len

    vocab_size = (
        task_entry.vocab_size(seq_len)
        if callable(task_entry.vocab_size)
        else task_entry.vocab_size
    )

    torch.manual_seed(seed)
    if device == 'cuda':
        torch.cuda.manual_seed(seed)
    model = model_entry.make_model(n_params, vocab_size, seq_len).to(device)

    make_opt = model_entry.make_optimizer or _default_optimizer
    opt = make_opt(model)

    train_step = model_entry.train_step or _default_train_step

    train_gen = task_entry.batch_generator(seq_len, batch_size, seed + 1)
    test_gen = task_entry.batch_generator(seq_len, batch_size, seed + 2)

    test_batches = [(e_input.to(device), e_target.to(device), e_mask.to(device)) 
                     for e_input, e_target, e_mask in [next(test_gen) for _ in range(10)]]

    actual_params = sum(p.numel() for p in model.parameters())

    mlflow_run = None
    if MLFLOW_ENABLED:
        try:
            mlflow.set_experiment(task_entry.name)
            mlflow_run = mlflow.start_run(run_name=f"{model_entry.name}-{n_params}")
            mlflow.set_tags({
                "model": model_entry.name,
                "task": task_entry.name,
            })
            mlflow.log_params({
                "actual_params": actual_params,
                "target_params": n_params,
                "seq_len": seq_len,
                "batch_size": batch_size,
                "vocab_size": vocab_size,
                "max_steps": max_steps,
                "device": device,
            })
            for param_group in opt.param_groups:
                mlflow.log_param("lr", param_group.get("lr", "unknown"))
                mlflow.log_param("weight_decay", param_group.get("weight_decay", "unknown"))
                break
        except Exception as e:
            print(f"Warning: Failed to connect to MLflow server: {e}")
            mlflow_run = None

    verbose = not MLFLOW_ENABLED or mlflow_run is None
    print(f"Model: {model_entry.name}\n\tTask: {task_entry.name}\n\tParams: {actual_params}\n\tVocabSize: {vocab_size}")

    curve: list[StepRecord] = []
    total_tokens = 0
    t_start = time.time()
    last_log_time = time.time()

    model.train()
    current_eval_acc = 0.0
    exit_reason = "max_steps"

    for step in range(1, max_steps + 1):
        if time.time() - t_start > TIME_LIMIT_SECONDS:
            exit_reason = "time_limit"
            print(f"Time limit reached at step {step}.")
            break

        input_ids, target_ids, loss_mask = next(train_gen)
        input_ids = input_ids.to(device)
        target_ids = target_ids.to(device)
        loss_mask = loss_mask.to(device)

        loss = train_step(model, opt, input_ids, target_ids, loss_mask)
        total_tokens += batch_size * seq_len

        if step % EVAL_EVERY == 0:

            model.eval()

            total_eval_correct = 0
            total_eval_masked = 0
            perfect_batches = 0
            with torch.no_grad():
                for e_input, e_target, e_mask in test_batches:

                    logits = model(e_input)
                    predictions = logits.argmax(dim=-1)
                    correct = (predictions == e_target) & e_mask.bool()

                    batch_correct = correct.sum().item()
                    batch_total = e_mask.sum().clamp(min=1).item()

                    total_eval_correct += batch_correct
                    total_eval_masked += batch_total

                    if batch_correct == batch_total:
                        perfect_batches += 1

            model.train()

            current_eval_acc = total_eval_correct / max(total_eval_masked, 1)
            elapsed = time.time() - t_start
            steps_per_sec = LOG_EVERY / (time.time() - last_log_time)
            last_log_time = time.time()
            
            if mlflow_run:
                mlflow.log_metrics({
                    "eval_accuracy": current_eval_acc,
                    "train_loss": loss,
                    "steps_per_sec": steps_per_sec,
                }, step=step)
            
            if verbose:
                print(f"\n\t[EVAL] Step {step}: {elapsed:.2f}s | Eval Accuracy: {current_eval_acc * 100:.2f}%")
            
            if perfect_batches == 10:
                exit_reason = "early_stop"
                print(f"\tPassed 10/10 evaluation batches with 100% accuracy at step {step}. Exiting early.")
                curve.append(StepRecord(step=step, tokens=total_tokens, loss=loss, accuracy=current_eval_acc))
                break

        if step % LOG_EVERY == 0:
            record = StepRecord(
                step=step,
                tokens=total_tokens,
                loss=loss,
                accuracy=current_eval_acc,
            )
            curve.append(record)

            if mlflow_run and step % EVAL_EVERY != 0:
                mlflow.log_metric("train_loss", loss, step=step)

            if verbose and step % EVAL_EVERY != 0:
                print(f"\tStep {step} | Train Loss: {loss:.4e}")

    final = curve[-1] if curve else StepRecord(0, 0, float("nan"), 0.0)
    elapsed_total = time.time() - t_start
    
    if mlflow_run:
        converged = final.accuracy >= 0.9
        mlflow.set_tags({
            "exit_reason": exit_reason,
            "converged": str(converged).lower(),
        })
        mlflow.log_metrics({
            "final_loss": final.loss,
            "final_accuracy": final.accuracy,
            "total_steps": final.step,
            "total_tokens": total_tokens,
            "total_elapsed_sec": elapsed_total,
            "tokens_to_90pct": _tokens_to_threshold(curve) or 0,
        })
        mlflow.end_run()
    
    if verbose:
        print(f"\tFinal Loss: {final.loss:.4e}")
        print(f"\tFinal Accuracy: {final.accuracy:.2%}")
    
    return TaskResult(
        model_name=model_entry.name,
        task_name=task_entry.name,
        n_params=actual_params,
        seq_len=seq_len,
        batch_size=batch_size,
        total_steps=final.step,
        total_tokens=total_tokens,
        curve=curve,
        final_loss=final.loss,
        final_accuracy=final.accuracy,
        tokens_to_90pct=_tokens_to_threshold(curve),
    )


def main() -> None:
    parser = argparse.ArgumentParser(description="Run model benchmarks on tasks")
    parser.add_argument("--seed", type=int, default=DEFAULT_SEED, help=f"Random seed (default: {DEFAULT_SEED})")
    parser.add_argument("--batch-size", type=int, default=DEFAULT_BATCH_SIZE, help=f"Batch size (default: {DEFAULT_BATCH_SIZE})")
    parser.add_argument("--max-steps", type=int, default=DEFAULT_MAX_STEPS, help=f"Maximum training steps (default: {DEFAULT_MAX_STEPS})")
    parser.add_argument("--device", type=str, default="cuda", help="Device to use (default: cuda)")
    parser.add_argument("--model", type=str, default=None, help="Filter to specific model name")
    parser.add_argument("--task", type=str, default=None, help="Filter to specific task name")
    parser.add_argument("--params", type=int, nargs="+", default=None, help="Filter to specific param counts")
    parser.add_argument("--rerun", action="store_true", help="Rerun tests even if results exist")
    args = parser.parse_args()

    _import_dir(MODELS_DIR)
    _import_dir(TASKS_DIR)

    models = all_models()
    tasks = all_tasks()

    if args.model:
        models = {k: v for k, v in models.items() if args.model.lower() in k.lower()}
    if args.task:
        tasks = {k: v for k, v in tasks.items() if args.task.lower() in k.lower()}

    param_counts = args.params if args.params else DEFAULT_PARAM_COUNTS

    pending = []
    skipped = 0
    for n_params in param_counts:
        for task_name, task_entry in tasks.items():
            for model_name, model_entry in models.items():
                if not args.rerun and result_exists(model_name, task_name, n_params):
                    skipped += 1
                else:
                    pending.append((model_entry, task_entry, n_params))

    total = len(pending) + skipped
    print(f"\nFound {len(models)} models, {len(tasks)} tasks and {len(param_counts)} param sizes.")
    print(f"{total} combinations total, {skipped} skipped, {len(pending)} pending.\n")

    for i, (model_entry, task_entry, n_params) in enumerate(pending):
        print(f"\n{i}/{len(pending)}")
        result = run_task(
            model_entry,
            task_entry,
            n_params,
            args.batch_size,
            args.max_steps,
            device=args.device,
            seed=args.seed,
        )
        save_result(result, n_params)
        print(f"Saved results for {model_entry.name}, task {task_entry.name}.")

    print("\nDone.")


if __name__ == "__main__":
    main()