Download scripts/bench_finetune_throughput.py from Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs: direct link, hf CLI and curl.
- Browser
- Download file 7.97 kB
-
https://huggingface.co/Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs/resolve/main/scripts/bench_finetune_throughput.py
- Command line
-
hf download hf://Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs/scripts/bench_finetune_throughput.py
-
curl -L -o bench_finetune_throughput.py https://huggingface.co/Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs/resolve/main/scripts/bench_finetune_throughput.py
7.97 kB
| #!/usr/bin/env python | |
| """Benchmark hf_finetune / hf_lora training throughput and project real ETA. | |
| Vanilla fp32 PyTorch throughput for a small transformer like bert-base | |
| varies a lot by GPU count, CUDA/torch version, and whether the batch is | |
| big enough to keep the card busy -- a number pulled from documentation or | |
| guessed from general benchmarks is not reliable here. This script instead | |
| times a handful of *real* training steps (same shapes as | |
| ``scripts/models/train.py``: 3 ``encoder.encode()`` calls per | |
| representation-stage step, 2 per calibration-stage step, real | |
| batch_size/max_length/model from the config, plus a real backward pass | |
| through a small dummy loss) on whatever hardware it's run on, then uses | |
| the *exact* step counts from the real dataset split + config epochs to | |
| project the true run's wall-clock time. | |
| Run this directly on the target machine (e.g. inside the tmux pane with | |
| CUDA_VISIBLE_DEVICES set) for an accurate number: | |
| # single GPU | |
| CUDA_VISIBLE_DEVICES=0 python scripts/bench_finetune_throughput.py \\ | |
| --config gsmic_adv_m9_4omini_bert_finetune | |
| # 4 GPUs (make sure batch_size in the config is a multiple of 4 first -- | |
| # see the printed warning if it isn't) | |
| CUDA_VISIBLE_DEVICES=0,1,2,3 python scripts/bench_finetune_throughput.py \\ | |
| --config gsmic_adv_m9_4omini_bert_finetune | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import time | |
| import torch | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__, | |
| formatter_class=argparse.RawDescriptionHelpFormatter) | |
| parser.add_argument("--config", required=True) | |
| parser.add_argument("--seed", type=int, default=7) | |
| parser.add_argument("--n-bench-steps", type=int, default=15, | |
| help="Real (forward+backward) steps to time per stage. " | |
| "Keep small (10-20) -- this is just for measuring " | |
| "steady-state steps/sec, not a real training run.") | |
| parser.add_argument("--n-warmup-steps", type=int, default=3, | |
| help="Untimed steps first, to absorb cuDNN autotune / " | |
| "first-batch allocator overhead.") | |
| args = parser.parse_args() | |
| from causal_difficulty.config import load_config | |
| from causal_difficulty.encoders import build_encoder | |
| from causal_difficulty.eval.reports import _split | |
| from causal_difficulty.io_utils import read_labeled_pairs | |
| from causal_difficulty.schemas import LabeledPair | |
| from causal_difficulty.models.train import _build_param_groups, build_sce | |
| from causal_difficulty.models import losses | |
| cfg = load_config(args.config) | |
| holdout_frac = cfg.eval.get("holdout_frac", 0.3) | |
| stratified = cfg.eval.get("stratified_split", False) | |
| pairs, pairs_path = read_labeled_pairs(cfg, args.config, LabeledPair) | |
| train_pairs, hold_pairs = _split(pairs, holdout_frac, args.seed, stratified=stratified) | |
| n_train = len(train_pairs) | |
| print(f"[bench] dataset: {pairs_path}") | |
| print(f"[bench] train pairs: {n_train} (holdout: {len(hold_pairs)})") | |
| encoder = build_encoder(cfg) | |
| device = getattr(encoder, "device", "cpu") | |
| n_gpu = torch.cuda.device_count() if str(device).startswith("cuda") else 0 | |
| print(f"[bench] device: {device} (visible CUDA GPUs: {n_gpu})") | |
| sce = build_sce(cfg, encoder, contrast_mode="diff") | |
| sce.heads.train() | |
| rcfg, ccfg = cfg.train.representation, cfg.train.calibration | |
| bs_rep, bs_cal = rcfg.get("batch_size", 64), ccfg.get("batch_size", 64) | |
| for name, bs in [("representation", bs_rep), ("calibration", bs_cal)]: | |
| if n_gpu > 1 and bs % n_gpu != 0: | |
| print(f"[bench] WARNING: {name}.batch_size={bs} is not a multiple of " | |
| f"{n_gpu} visible GPUs -- nn.DataParallel will still work but " | |
| f"splits unevenly and under-fills some GPUs. Consider a batch_size " | |
| f"that is a multiple of {n_gpu} (e.g. {bs_rep * n_gpu}) so each GPU " | |
| f"keeps doing the same per-GPU work as your existing single-GPU runs.") | |
| texts_pool = [p.base_text for p in train_pairs[: max(64, bs_rep * 4)]] or ["placeholder text."] | |
| def _time_steps(step_fn, n_steps: int) -> float: | |
| if str(device).startswith("cuda"): | |
| torch.cuda.synchronize() | |
| t0 = time.perf_counter() | |
| for _ in range(n_steps): | |
| step_fn() | |
| if str(device).startswith("cuda"): | |
| torch.cuda.synchronize() | |
| return time.perf_counter() - t0 | |
| param_groups = _build_param_groups(sce, rcfg.get("lr", 1e-3), rcfg.get("encoder_lr")) | |
| opt_rep = torch.optim.Adam(param_groups) | |
| anchors = [p.base_text for p in train_pairs[:bs_rep]] or texts_pool[:bs_rep] | |
| positives = [p.twin_text for p in train_pairs[:bs_rep]] or texts_pool[:bs_rep] | |
| negatives = texts_pool[:bs_rep] if len(texts_pool) >= bs_rep else (texts_pool * bs_rep)[:bs_rep] | |
| def rep_step(): | |
| a = sce.embed(anchors) | |
| pos = sce.embed(positives) | |
| neg = sce.embed(negatives) | |
| pa, pp, pn = (sce.heads.project_complexity(x) for x in (a, pos, neg)) | |
| loss = losses.triplet(pa, pp, pn, rcfg.get("triplet_margin", 0.3)) | |
| opt_rep.zero_grad() | |
| loss.backward() | |
| opt_rep.step() | |
| _time_steps(rep_step, args.n_warmup_steps) | |
| rep_elapsed = _time_steps(rep_step, args.n_bench_steps) | |
| rep_sec_per_step = rep_elapsed / args.n_bench_steps | |
| rep_seq_per_sec = (3 * bs_rep) / rep_sec_per_step | |
| print(f"[bench] representation: {rep_sec_per_step * 1000:.1f} ms/step " | |
| f"({rep_seq_per_sec:.1f} seq/s, bs={bs_rep}, 3 encode()/step)") | |
| param_groups = _build_param_groups(sce, ccfg.get("lr", 1e-3), ccfg.get("encoder_lr")) | |
| opt_cal = torch.optim.Adam(param_groups) | |
| base_b = [p.base_text for p in train_pairs[:bs_cal]] or texts_pool[:bs_cal] | |
| twin_b = [p.twin_text for p in train_pairs[:bs_cal]] or texts_pool[:bs_cal] | |
| delta_b = torch.zeros(bs_cal, device=device if not str(device).startswith("cuda") or n_gpu <= 1 else "cuda:0") | |
| def cal_step(): | |
| h = sce.embed(base_b) | |
| hp = sce.embed(twin_b) | |
| dhat = sce.heads.contrast(h, hp) | |
| loss = losses.huber(dhat, delta_b[: dhat.shape[0]], ccfg.get("huber_delta", 0.1)) | |
| opt_cal.zero_grad() | |
| loss.backward() | |
| opt_cal.step() | |
| _time_steps(cal_step, args.n_warmup_steps) | |
| cal_elapsed = _time_steps(cal_step, args.n_bench_steps) | |
| cal_sec_per_step = cal_elapsed / args.n_bench_steps | |
| cal_seq_per_sec = (2 * bs_cal) / cal_sec_per_step | |
| print(f"[bench] calibration: {cal_sec_per_step * 1000:.1f} ms/step " | |
| f"({cal_seq_per_sec:.1f} seq/s, bs={bs_cal}, 2 encode()/step)") | |
| steps_per_epoch_rep = (n_train + bs_rep - 1) // bs_rep | |
| steps_per_epoch_cal = (n_train + bs_cal - 1) // bs_cal | |
| n_epochs_rep = rcfg.get("epochs", 30) | |
| n_epochs_cal = ccfg.get("epochs", 60) | |
| total_rep_steps = steps_per_epoch_rep * n_epochs_rep | |
| total_cal_steps = steps_per_epoch_cal * n_epochs_cal | |
| eta_rep_sec = total_rep_steps * rep_sec_per_step | |
| eta_cal_sec = total_cal_steps * cal_sec_per_step | |
| eta_total_sec = eta_rep_sec + eta_cal_sec | |
| def fmt(sec: float) -> str: | |
| m, s = divmod(sec, 60) | |
| h, m = divmod(m, 60) | |
| return f"{int(h)}h {int(m):02d}m {int(s):02d}s" | |
| print() | |
| print(f"[eta] representation: {total_rep_steps} steps ({n_epochs_rep} epochs x " | |
| f"{steps_per_epoch_rep} steps/epoch) -> {fmt(eta_rep_sec)}") | |
| print(f"[eta] calibration: {total_cal_steps} steps ({n_epochs_cal} epochs x " | |
| f"{steps_per_epoch_cal} steps/epoch) -> {fmt(eta_cal_sec)}") | |
| print(f"[eta] TOTAL (this config, this hardware): {fmt(eta_total_sec)}") | |
| print("[eta] (excludes: eval/holdout scoring, baseline training, tokenizer/model " | |
| "download on first run -- add a few minutes for those)") | |
| if __name__ == "__main__": | |
| main() | |