code-roamer's picture
Publish GPU Kernel Benchmark v0.8.1 public edition
5d12def verified
Raw History Blame Contribute Delete
10.3 kB
"""Run with torchrun on peer-connected SM100 GPUs with pinned DeepGEMM installed."""
import argparse
import importlib.util
import sys
import json
import os
from pathlib import Path
import statistics
import torch
import torch.distributed as dist
import torch.nn.functional as F
from native import pack_weights, run as native
def init_ep_group(device):
# This benchmark uses one torchrun node. On the frozen devbox stack the
# IPv6/eth0 bootstrap leaves NCCL proxy service threads in commFree.
if (torch.cuda.nccl.version() == (2, 27, 5)
and os.environ.get("NCCL_SOCKET_FAMILY") == "AF_INET6"
and os.environ.get("NCCL_SOCKET_IFNAME") == "=eth0"):
os.environ["NCCL_SOCKET_FAMILY"] = "AF_INET"
os.environ["NCCL_SOCKET_IFNAME"] = "lo"
dist.init_process_group("nccl", device_id=device)
def load(path):
directory = str(path.resolve().parent)
if directory not in sys.path:
sys.path.append(directory)
spec = importlib.util.spec_from_file_location("mega_candidate", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module.run
def check_rank(y, expected, label):
rank, world = dist.get_rank(), dist.get_world_size()
delta = y.float() - expected.float()
power = expected.float().square().mean().clamp_min(1e-12)
rms_rel = (delta.square().mean() / power).sqrt()
try:
torch.testing.assert_close(y, expected, atol=.025, rtol=.025, check_dtype=True)
bad = rms_rel.item() > .01
except AssertionError:
bad = True
failing_rank = torch.tensor(rank if bad else world, device=y.device, dtype=torch.int32)
dist.all_reduce(failing_rank, op=dist.ReduceOp.MIN)
source = failing_rank.item()
if source != world:
metrics = torch.stack(((~y.isfinite()).sum(), (~expected.isfinite()).sum(),
delta.abs().max(), rms_rel)).double()
dist.broadcast(metrics, src=source)
nonfinite, ref_nonfinite, maximum, relative = metrics.tolist()
raise ValueError(f"{label} failing_rank={source} nonfinite={int(nonfinite)} "
f"expected_nonfinite={int(ref_nonfinite)} max_abs={maximum:.6g} "
f"rms_rel={relative:.6g} (atol=0.025 rtol=0.025 rms_rel_limit=0.01)")
def local_shared(x, gate_up, down):
gate, up = F.linear(x, gate_up).float().chunk(2, dim=-1)
activated = F.silu(gate.clamp_max(10)) * up.clamp(-10, 10)
return F.linear(activated.bfloat16(), down)
def verify_single_launch(fn, y, buf, weights, device):
from torch.profiler import ProfilerActivity, profile
dist.barrier()
torch.cuda.synchronize()
with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof:
fn(y, buf, *weights)
torch.cuda.synchronize()
# CPU-side annotations and cudaDeviceSynchronize do not count as GPU work.
device_events = [e.name for e in prof.events()
if e.device_type == torch.autograd.DeviceType.CUDA]
ok = torch.tensor(int(len(device_events) == 1), device=device)
dist.all_reduce(ok, op=dist.ReduceOp.MIN)
if not ok.item():
raise ValueError(f"expected one GPU activity per rank; rank {dist.get_rank()} saw {device_events}")
return device_events[0]
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--candidate", type=Path, required=True)
p.add_argument("--tokens", type=int, default=128)
p.add_argument("--shared", type=int, choices=(1, 2), default=1)
p.add_argument("--seed", type=int, default=137)
p.add_argument("--public-feedback", action="store_true")
args = p.parse_args()
rank = int(os.environ["LOCAL_RANK"])
world = int(os.environ["WORLD_SIZE"])
if world < 2 or world != int(os.environ["LOCAL_WORLD_SIZE"]):
p.error("this EP profile requires multiple GPUs on one node")
torch.cuda.set_device(rank)
if torch.cuda.get_device_capability()[0] != 10:
p.error("the pinned native Mega MoE implementation requires SM major 10")
if args.tokens < world or 64 % world:
p.error("require tokens >= ranks and an EP degree dividing 64")
import deep_gemm as dg
device = torch.device("cuda", rank)
init_ep_group(device)
group = dist.group.WORLD
dg.use_deterministic_algorithms(True)
h, width, experts, topk = 4096, 2048, 64, 6
count = args.tokens - rank
gen = torch.Generator(device=device).manual_seed(args.seed + rank)
shared_gen = torch.Generator(device=device).manual_seed(args.seed + world)
def weights(shape, generator):
return (torch.randn(shape, generator=generator, device=device) / shape[-1]**.5).bfloat16()
shared_gate_up = weights((2 * width * args.shared, h), shared_gen)
shared_down = weights((h, width * args.shared), shared_gen)
weights4 = pack_weights(weights((experts // world, 2 * width, h), gen),
weights((experts // world, h, width), gen),
shared_gate_up, shared_down)
def split(y, buf, r1, r2, s1, s2):
dg.bf16_mega_moe(y, r1, r2, buf, activation_clamp=10.)
y.add_(local_shared(buf.x[:count], shared_gate_up, shared_down))
fns = (native, load(args.candidate), split)
buffers = [dg.get_symm_buffer_for_mega_moe(group, experts, args.tokens, topk, h, width,
num_shared_experts=s, mma_type="bf16xbf16") for s in (args.shared, args.shared, 0)]
ys = [torch.empty((count, h), device=device, dtype=torch.bfloat16) for _ in buffers]
def refresh(pattern, seed):
gen.manual_seed(seed + rank)
x = torch.randn(count, h, device=device, generator=gen, dtype=torch.bfloat16)
ids = torch.rand(count, experts, device=device, generator=gen)
if pattern == "hot":
ids[:, seed % experts] += 1
ids = ids.topk(topk).indices
gates = torch.rand(count, topk, device=device, generator=gen)
if pattern == "shared_only":
ids.fill_(-1)
elif pattern == "partial":
ids[::2, 1:] = -1
gates.masked_fill_(ids < 0, 0)
for buf in buffers:
buf.x[:count].copy_(x)
buf.topk_idx[:count].copy_(ids)
buf.topk_weights[:count].copy_(gates)
# Remote SMs can read peer inputs directly. Publish every rank's new inputs
# before letting the first persistent launch enter the fixture.
torch.cuda.synchronize()
dist.barrier()
patterns = ("hot", "shared_only", "partial")
eager_errors = []
for i, pattern in enumerate(patterns):
refresh(pattern, args.seed + 176 * i)
for fn, y, buf in zip(fns, ys, buffers):
y.fill_(torch.nan)
fn(y, buf, *weights4)
check_rank(ys[2], ys[0], f"eager split {pattern}")
try:
check_rank(ys[1], ys[0], f"eager candidate {pattern}")
except ValueError as exc:
if not args.public_feedback:
raise
eager_errors.append(str(exc))
if eager_errors:
raise ValueError("\n".join(eager_errors))
refresh("hot", args.seed + 499)
# Attribute direct reuse of the pinned API outside timing. A separately
# compiled kernel may retain the upstream symbol and still be a new implementation.
from unittest.mock import patch
with patch.object(dg, "bf16_mega_moe", wraps=dg.bf16_mega_moe) as native_call:
probe = load(args.candidate)
candidate_kernel = verify_single_launch(probe, ys[1], buffers[1], weights4, device)
reused = torch.tensor(int(native_call.called), device=device)
dist.all_reduce(reused, op=dist.ReduceOp.MAX)
native_api_reused = bool(reused.item())
graphs = []
graph_outputs = []
for fn, y, buf in zip(fns, ys, buffers):
outputs = (y, torch.empty_like(y))
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
# The native combine readiness tag comes from the launch grid ID.
# Alternate two distinct nodes so consecutive uses of a symmetric
# buffer cannot observe a readiness tag from its previous replay.
for output in outputs:
fn(output, buf, *weights4)
graphs.append(graph)
graph_outputs.append(outputs)
for i, pattern in enumerate(patterns):
refresh(pattern, args.seed + 500 + i)
native(ys[0], buffers[0], *weights4)
expected = ys[0].clone()
for label, graph, outputs in zip(("native", "candidate", "split"), graphs, graph_outputs):
for output in outputs:
output.fill_(torch.nan)
graph.replay()
for node, output in enumerate(outputs):
check_rank(output, expected, f"graph {label} {pattern} node={node}")
refresh("hot", args.seed + 900)
samples = [[], [], []]
for rnd in range(9):
for offset in range(3):
i = (rnd + offset) % 3
dist.barrier()
torch.cuda.synchronize()
start, end = (torch.cuda.Event(enable_timing=True) for _ in range(2))
start.record()
for _ in range(8):
graphs[i].replay()
end.record()
end.synchronize()
value = torch.tensor(start.elapsed_time(end) * 1000 / 16, device=device)
dist.all_reduce(value, op=dist.ReduceOp.MAX)
samples[i].append(value.item())
if rank == 0:
speed = statistics.median(a/b for a, b in zip(samples[0], samples[1]))
fusion_gain = statistics.median(a/b for a, b in zip(samples[2], samples[1]))
print(json.dumps(dict(ranks=world, tokens=args.tokens, shared=args.shared,
candidate_kernel=candidate_kernel, native_api_reused=native_api_reused, native_us=samples[0], candidate_us=samples[1], split_us=samples[2],
speedup_vs_native=speed, speedup_vs_split=fusion_gain)))
dist.barrier()
for graph in graphs:
graph.reset()
del graph
graphs.clear()
for buf in buffers:
buf.destroy()
dg.destroy_localizer()
torch.cuda.synchronize()
dist.destroy_process_group()
if __name__ == "__main__":
main()