Download benchmarks/run.py from Pulsar-Dynamic-Technologies/Adria: direct link, hf CLI and curl.
- Browser
- Download file 11.4 kB
-
https://huggingface.co/Pulsar-Dynamic-Technologies/Adria/resolve/main/benchmarks/run.py
- Command line
-
hf download hf://Pulsar-Dynamic-Technologies/Adria/benchmarks/run.py
-
curl -L -o run.py https://huggingface.co/Pulsar-Dynamic-Technologies/Adria/resolve/main/benchmarks/run.py
11.4 kB
| 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() | |