File size: 8,055 Bytes
3bbd5dd | 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 | """Phase 0 hardware sanity check for the MTP-under-fertility experiments.
Confirms, on this Pascal cluster: CUDA arch/capability, a real forward pass
through the frozen backbone, a real training step through an MTP head, and
scratch disk space. Run before any training code; numbers here calibrate
every later time budget.
"""
import argparse
import logging
import os
import shutil
import sys
import time
from dataclasses import dataclass
from pathlib import Path
# must be set before `import torch`: without it, torch orders CUDA devices
# fastest-first, so torch's cuda:0 is the Quadro P6000, not nvidia-smi's GPU 0
os.environ.setdefault("CUDA_DEVICE_ORDER", "PCI_BUS_ID")
import torch # noqa: E402
import torch.nn as nn # noqa: E402
from transformers import AutoModelForCausalLM, AutoTokenizer # noqa: E402
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from src.models.heads import MTPHead # noqa: E402
EXPECTED_CAPABILITY = (6, 1)
DEFAULT_MODEL = "meta-llama/Llama-3.2-1B"
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("huggingface_hub").setLevel(logging.WARNING)
logger = logging.getLogger("phase0")
@dataclass
class Phase0Config:
model: str
device: str
batch_size: int
seq_len: int
warmup_iters: int
timed_iters: int
scratch_dir: str
def parse_args() -> Phase0Config:
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--model", default=DEFAULT_MODEL)
p.add_argument("--device", default="cuda:0")
p.add_argument("--batch-size", type=int, default=4)
p.add_argument("--seq-len", type=int, default=512)
p.add_argument("--warmup-iters", type=int, default=5)
p.add_argument("--timed-iters", type=int, default=20)
p.add_argument("--scratch-dir", default="/data/cs769_mtp/scratch")
args = p.parse_args()
return Phase0Config(
model=args.model,
device=args.device,
batch_size=args.batch_size,
seq_len=args.seq_len,
warmup_iters=args.warmup_iters,
timed_iters=args.timed_iters,
scratch_dir=args.scratch_dir,
)
def check_arch_and_capability() -> None:
"""Report get_arch_list() and per-device capability; capability is the pass criterion.
Newer torch cuXXX wheels can omit the literal 'sm_61' string from
get_arch_list() while still running correctly on Pascal via PTX JIT from
a lower virtual architecture (e.g. sm_60). The capability tuple is the
ground truth for whether the hardware is actually usable, so that -- not
the arch-list substring -- is what this check enforces.
"""
arch_list = torch.cuda.get_arch_list()
has_literal_sm61 = "sm_61" in arch_list
logger.info("torch.cuda.get_arch_list() = %s", arch_list)
logger.info("literal 'sm_61' present: %s", has_literal_sm61)
device_count = torch.cuda.device_count()
caps = [torch.cuda.get_device_capability(i) for i in range(device_count)]
names = [torch.cuda.get_device_name(i) for i in range(device_count)]
for i, (cap, name) in enumerate(zip(caps, names)):
logger.info("device %d: %s capability=%s", i, name, cap)
assert all(c == EXPECTED_CAPABILITY for c in caps), (
f"expected capability {EXPECTED_CAPABILITY} on all devices, got {caps}"
)
if not has_literal_sm61:
logger.warning(
"arch list lacks literal 'sm_61'; relying on PTX JIT to sm_60. "
"First use of any new kernel shape pays a one-time compile cost."
)
def check_forward_pass(cfg: Phase0Config) -> dict:
"""Load the backbone in fp32, run a real forward pass, report memory and wall time."""
tokenizer = AutoTokenizer.from_pretrained(cfg.model)
model = AutoModelForCausalLM.from_pretrained(cfg.model, dtype=torch.float32)
model.to(cfg.device)
model.eval()
text = "The quick brown fox jumps over the lazy dog. " * 4
inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=cfg.seq_len).to(cfg.device)
with torch.no_grad():
for _ in range(cfg.warmup_iters):
model(**inputs)
torch.cuda.synchronize(cfg.device)
torch.cuda.reset_peak_memory_stats(cfg.device)
torch.cuda.synchronize(cfg.device)
start = time.perf_counter()
with torch.no_grad():
for _ in range(cfg.timed_iters):
out = model(**inputs)
torch.cuda.synchronize(cfg.device)
elapsed = time.perf_counter() - start
peak_mem_mib = torch.cuda.max_memory_allocated(cfg.device) / (1024**2)
avg_ms = elapsed / cfg.timed_iters * 1000
logger.info("forward pass: logits shape %s", tuple(out.logits.shape))
logger.info("forward pass: peak memory %.1f MiB", peak_mem_mib)
logger.info("forward pass: avg wall time %.2f ms/iter over %d iters", avg_ms, cfg.timed_iters)
del model
torch.cuda.empty_cache()
return {"peak_mem_mib": peak_mem_mib, "avg_ms": avg_ms}
def check_training_step(cfg: Phase0Config) -> dict:
"""Time a real training step: frozen backbone forward + backward through one MTP head."""
model = AutoModelForCausalLM.from_pretrained(cfg.model, dtype=torch.float32)
model.to(cfg.device)
for param in model.parameters():
param.requires_grad = False
hidden_size = model.config.hidden_size
vocab_size = model.config.vocab_size
head = MTPHead(hidden_size, unembedding=model.lm_head).to(cfg.device)
optimizer = torch.optim.AdamW(head.trainable_parameters(), lr=1e-4)
loss_fn = nn.CrossEntropyLoss()
torch.manual_seed(0)
input_ids = torch.randint(0, vocab_size, (cfg.batch_size, cfg.seq_len), device=cfg.device)
targets = torch.randint(0, vocab_size, (cfg.batch_size, cfg.seq_len), device=cfg.device)
def step() -> None:
with torch.no_grad():
hidden_states = model.model(input_ids=input_ids).last_hidden_state
logits = head(hidden_states)
loss = loss_fn(logits.reshape(-1, vocab_size), targets.reshape(-1))
optimizer.zero_grad(set_to_none=True)
loss.backward()
optimizer.step()
for _ in range(cfg.warmup_iters):
step()
torch.cuda.synchronize(cfg.device)
start = time.perf_counter()
for _ in range(cfg.timed_iters):
step()
torch.cuda.synchronize(cfg.device)
elapsed = time.perf_counter() - start
tokens_per_iter = cfg.batch_size * cfg.seq_len
tokens_per_sec = tokens_per_iter * cfg.timed_iters / elapsed
avg_ms = elapsed / cfg.timed_iters * 1000
logger.info(
"training step: batch=%d seq=%d -> %.1f tokens/sec (%.2f ms/step)",
cfg.batch_size, cfg.seq_len, tokens_per_sec, avg_ms,
)
del model, head, optimizer
torch.cuda.empty_cache()
return {"tokens_per_sec": tokens_per_sec, "avg_ms": avg_ms}
def check_disk_space(scratch_dir: str) -> dict:
"""Confirm the scratch path exists and is writable; report free space."""
path = Path(scratch_dir)
path.mkdir(parents=True, exist_ok=True)
probe = path / ".phase0_write_probe"
probe.write_text("ok")
probe.unlink()
usage = shutil.disk_usage(scratch_dir)
free_gib = usage.free / (1024**3)
logger.info("scratch dir %s: %.1f GiB free, writable", scratch_dir, free_gib)
return {"scratch_dir": scratch_dir, "free_gib": free_gib}
def main() -> None:
cfg = parse_args()
logger.info("config: %s", cfg)
check_arch_and_capability()
forward_result = check_forward_pass(cfg)
training_result = check_training_step(cfg)
disk_result = check_disk_space(cfg.scratch_dir)
logger.info("=== PHASE 0 SUMMARY ===")
logger.info("forward pass: %.1f MiB peak, %.2f ms/iter", forward_result["peak_mem_mib"], forward_result["avg_ms"])
logger.info("training step: %.1f tokens/sec, %.2f ms/step", training_result["tokens_per_sec"], training_result["avg_ms"])
logger.info("scratch: %s (%.1f GiB free)", disk_result["scratch_dir"], disk_result["free_gib"])
if __name__ == "__main__":
main()
|