File size: 7,968 Bytes
a0d1de2 | 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 | #!/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()
|