Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-helix/blob/main/tests/bench_pytorch_h2h.py # omega-helix This project has not described itself yet. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omega-helix / tests / bench_pytorch_h2h.py` 228 lines ยท 8764 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Reproducible PyTorch + CUDA Head-to-Head Benchmark on the Exact Omega Helix v2 Shape. 3 4 Matches `native/model.om` v2 shape (`V=4096, T=256, D=384, H=12, F=1536, L=8, B=64`, `P=15,833,472`): 5 - Token embedding (tied w_tok / lm_head): V * D 6 - Positional embedding (w_pos): T * D 7 - L decoder blocks, each with pre-attn RMSNorm (D), Q/K/V/O linear projections (4 * D^2, no bias), 8 causal SDPA attention, pre-MLP RMSNorm (D), 2-layer ReLU MLP D -> F -> D (2 * D * F, no bias) 9 - Final RMSNorm (D) 10 Total parameters: 4096*384 + 256*384 + 8*(4*384^2 + 2*384*1536 + 2*384) + 384 = 15,833,472. 11 12 Usage: 13 python3 tests/bench_pytorch_h2h.py --mode eager --steps 30 --warmup 5 --out receipt.json 14 python3 tests/bench_pytorch_h2h.py --mode both --steps 30 --warmup 5 --out receipt.json 15 """ 16 17 from __future__ import annotations 18 19 import argparse 20 import importlib.util 21 import json 22 import os 23 import subprocess 24 import sys 25 import time 26 from pathlib import Path 27 28 29 def _pkg_tree_bytes(pkg_names: list[str]) -> dict[str, int]: 30 """Compute installed byte footprint of Python/CUDA wheel directories cleanly.""" 31 seen: set[Path] = set() 32 roots: list[Path] = [] 33 for sp in sys.path: 34 p = Path(sp) 35 if p.is_dir() and p.name == "site-packages" and p not in seen: 36 seen.add(p) 37 roots.append(p) 38 totals: dict[str, int] = {} 39 for root in roots: 40 for entry in root.iterdir(): 41 low = entry.name.lower() 42 if any(low == n or low.startswith(n + "-") or low.startswith(n + "_") for n in pkg_names): 43 sz = 0 44 if entry.is_file(): 45 sz = entry.stat().st_size 46 elif entry.is_dir(): 47 for dp, _, fns in os.walk(entry): 48 for fn in fns: 49 fp = Path(dp) / fn 50 try: 51 sz += fp.stat().st_size 52 except OSError: 53 pass 54 totals[entry.name] = sz 55 return {"packages": totals, "total_bytes": sum(totals.values())} 56 57 58 def run_benchmark(mode: str, steps: int, warmup: int) -> dict[str, object]: 59 import torch 60 import torch.nn as nn 61 import torch.nn.functional as F 62 63 if not torch.cuda.is_available(): 64 raise RuntimeError("CUDA GPU not available in this Python environment") 65 66 V, T, D, H, F_dim, L, B = 4096, 256, 384, 12, 1536, 8, 64 67 head_dim = D // H 68 69 class RMSNormNoBias(nn.Module): 70 def __init__(self, dim: int, eps: float = 1e-5) -> None: 71 super().__init__() 72 self.weight = nn.Parameter(torch.ones(dim)) 73 self.eps = eps 74 75 def forward(self, x: torch.Tensor) -> torch.Tensor: 76 xf = x.float() 77 inv = torch.rsqrt(xf.pow(2).mean(dim=-1, keepdim=True) + self.eps) 78 return (xf * inv).to(x.dtype) * self.weight 79 80 class Block(nn.Module): 81 def __init__(self) -> None: 82 super().__init__() 83 self.norm1 = RMSNormNoBias(D) 84 self.wq = nn.Linear(D, D, bias=False) 85 self.wk = nn.Linear(D, D, bias=False) 86 self.wv = nn.Linear(D, D, bias=False) 87 self.wo = nn.Linear(D, D, bias=False) 88 self.norm2 = RMSNormNoBias(D) 89 self.w1 = nn.Linear(D, F_dim, bias=False) 90 self.w2 = nn.Linear(F_dim, D, bias=False) 91 92 def forward(self, x: torch.Tensor) -> torch.Tensor: 93 h = self.norm1(x) 94 bsz, seq, _ = h.shape 95 q = self.wq(h).view(bsz, seq, H, head_dim).transpose(1, 2) 96 k = self.wk(h).view(bsz, seq, H, head_dim).transpose(1, 2) 97 v = self.wv(h).view(bsz, seq, H, head_dim).transpose(1, 2) 98 att = F.scaled_dot_product_attention(q, k, v, is_causal=True) 99 att = att.transpose(1, 2).contiguous().view(bsz, seq, D) 100 x = x + self.wo(att) 101 m = self.norm2(x) 102 x = x + self.w2(F.relu(self.w1(m))) 103 return x 104 105 class OmegaV2Ref(nn.Module): 106 def __init__(self) -> None: 107 super().__init__() 108 self.tok_emb = nn.Embedding(V, D) 109 self.pos_emb = nn.Embedding(T, D) 110 self.blocks = nn.ModuleList([Block() for _ in range(L)]) 111 self.norm_f = RMSNormNoBias(D) 112 113 def forward(self, idx: torch.Tensor, targets: torch.Tensor) -> torch.Tensor: 114 pos = torch.arange(T, device=idx.device) 115 x = self.tok_emb(idx) + self.pos_emb(pos) 116 for blk in self.blocks: 117 x = blk(x) 118 x = self.norm_f(x) 119 logits = F.linear(x, self.tok_emb.weight) 120 return F.cross_entropy(logits.view(-1, V), targets.view(-1)) 121 122 torch.manual_seed(42) 123 device = torch.device("cuda") 124 model = OmegaV2Ref().to(device=device, dtype=torch.bfloat16) 125 param_count = sum(p.numel() for p in model.parameters()) 126 assert param_count == 15_833_472, f"unexpected param count {param_count}" 127 128 opt = torch.optim.AdamW(model.parameters(), lr=3e-4, betas=(0.9, 0.999), eps=1e-8, weight_decay=0.0) 129 idx = torch.randint(0, V, (B, T), device=device, dtype=torch.long) 130 targets = torch.randint(0, V, (B, T), device=device, dtype=torch.long) 131 132 fn = model if mode == "eager" else torch.compile(model) 133 torch.cuda.reset_peak_memory_stats(device) 134 torch.cuda.synchronize(device) 135 136 for _ in range(max(1, warmup)): 137 opt.zero_grad(set_to_none=True) 138 loss = fn(idx, targets) 139 loss.backward() 140 opt.step() 141 torch.cuda.synchronize(device) 142 143 t0 = time.perf_counter() 144 for _ in range(steps): 145 opt.zero_grad(set_to_none=True) 146 loss = fn(idx, targets) 147 loss.backward() 148 opt.step() 149 torch.cuda.synchronize(device) 150 dt = time.perf_counter() - t0 151 152 tokens_per_step = B * T 153 total_tokens = steps * tokens_per_step 154 step_ms = (dt / steps) * 1000.0 155 tok_per_s = total_tokens / dt 156 peak_alloc = int(torch.cuda.max_memory_allocated(device)) 157 peak_reserved = int(torch.cuda.max_memory_reserved(device)) 158 159 return { 160 "mode": mode, 161 "param_count": param_count, 162 "shape": {"V": V, "T": T, "D": D, "H": H, "F": F_dim, "L": L, "B": B}, 163 "steps": steps, 164 "warmup": warmup, 165 "elapsed_s": round(dt, 4), 166 "step_ms": round(step_ms, 2), 167 "tok_per_s": round(tok_per_s, 1), 168 "last_loss": round(float(loss.detach().cpu()), 6), 169 "peak_cuda_alloc_bytes": peak_alloc, 170 "peak_cuda_reserved_bytes": peak_reserved, 171 "torch_version": torch.__version__, 172 "cuda_version": torch.version.cuda, 173 "device_name": torch.cuda.get_device_name(0), 174 } 175 176 177 def measure_cold_start(script_path: str, mode: str) -> float: 178 """Spawn a clean subprocess and time from process launch through step 1 GPU sync.""" 179 t0 = time.perf_counter() 180 subprocess.run( 181 [sys.executable, script_path, "--mode", mode, "--steps", "1", "--warmup", "0", "--quiet"], 182 check=True, 183 ) 184 return round((time.perf_counter() - t0) * 1000.0, 1) 185 186 187 def main() -> int: 188 ap = argparse.ArgumentParser(description="Reproducible PyTorch BF16 H2H benchmark for Omega Helix v2 (15.83M).") 189 ap.add_argument("--mode", choices=["eager", "compile", "both"], default="eager") 190 ap.add_argument("--steps", type=int, default=30) 191 ap.add_argument("--warmup", type=int, default=5) 192 ap.add_argument("--measure-cold-start", action="store_true") 193 ap.add_argument("--out", default=None) 194 ap.add_argument("--quiet", action="store_true") 195 args = ap.parse_args() 196 197 if importlib.util.find_spec("torch") is None: 198 print(json.dumps({"ok": False, "error": "torch is not installed in this Python interpreter"})) 199 return 2 200 201 modes = ["eager", "compile"] if args.mode == "both" else [args.mode] 202 results: dict[str, object] = {} 203 for m in modes: 204 try: 205 res = run_benchmark(m, args.steps, args.warmup) 206 if args.measure_cold_start: 207 res["cold_start_to_step1_ms"] = measure_cold_start(__file__, m) 208 results[m] = res 209 except Exception as exc: 210 results[m] = {"mode": m, "error": str(exc)} 211 212 out_doc = { 213 "kind": "omega-helix-pytorch-h2h", 214 "schema": 1, 215 "footprint": _pkg_tree_bytes(["torch", "nvidia", "triton"]), 216 "runs": results, 217 } 218 if not args.quiet: 219 print(json.dumps(out_doc, indent=2)) 220 if args.out: 221 op = Path(args.out).expanduser().resolve() 222 op.parent.mkdir(parents=True, exist_ok=True) 223 op.write_text(json.dumps(out_doc, indent=2) + "\n", encoding="utf-8") 224 return 0 225 226 227 if __name__ == "__main__": 228 raise SystemExit(main())