Datasets:
Download kernel_bench/candidates/shared_mega_moe/check_backward.py from code-roamer/gpu-kernel-benchmark: direct link, hf CLI and curl.
- Browser
- Download file 8.3 kB
-
https://huggingface.co/datasets/code-roamer/gpu-kernel-benchmark/resolve/main/kernel_bench/candidates/shared_mega_moe/check_backward.py
- Command line
-
hf download hf://datasets/code-roamer/gpu-kernel-benchmark/kernel_bench/candidates/shared_mega_moe/check_backward.py
-
curl -L -o check_backward.py https://huggingface.co/datasets/code-roamer/gpu-kernel-benchmark/resolve/main/kernel_bench/candidates/shared_mega_moe/check_backward.py
8.3 kB
| """Distributed MoE VJP qualification with an independent global-loss autograd oracle.""" | |
| import argparse | |
| import json | |
| import os | |
| from pathlib import Path | |
| import sys | |
| import torch | |
| import torch.distributed as dist | |
| import torch.nn.functional as F | |
| HERE = Path(__file__).resolve().parent | |
| sys.path.insert(0, str(HERE.parent)) | |
| from backward_eval import load, qualify | |
| from check import init_ep_group | |
| # E, hidden, intermediate, capacity per rank, shared count, routing fixture | |
| CASES = {"masked": (8, 128, 64, 15, 1, "masked"), | |
| "shared_only": (8, 128, 64, 15, 2, "shared_only"), | |
| "t32_s1": (64, 4096, 2048, 32, 1, "hot"), | |
| "t128_s1": (64, 4096, 2048, 128, 1, "hot"), | |
| "t512_s2": (64, 4096, 2048, 512, 2, "hot")} | |
| def make_state(x, gate, w1): | |
| z = F.linear(x.float(), w1.float()).bfloat16() | |
| a, b = z.float().chunk(2, -1) | |
| hidden = (F.silu(a.clamp_max(10)) * b.clamp(-10, 10) * gate[:, None]).bfloat16() | |
| return x, gate, z, hidden | |
| def make(case, rank, world, seed=137): | |
| e, h, i, cap, n_shared, pattern = CASES[case] | |
| if e % world or world > cap: | |
| raise ValueError("EP degree must divide expert count and fit the token capacity") | |
| gen = torch.Generator(device="cuda").manual_seed(seed) | |
| def rand(shape): | |
| return torch.randn(shape, device="cuda", dtype=torch.bfloat16, generator=gen) | |
| x = rand((world * cap, h)) | |
| x[::cap] *= 12 # Exercise clamp derivatives in both branches. | |
| ids = torch.rand((len(x), e), device="cuda", generator=gen) | |
| ids[:, 0] += 2 | |
| ids = ids.topk(6).indices | |
| coeff = torch.rand((len(x), 6), device="cuda", generator=gen) | |
| valid = (torch.arange(cap, device="cuda")[None, :] < cap - torch.arange(world, device="cuda")[:, None]).flatten() | |
| ids[~valid] = -1 | |
| if pattern == "shared_only": | |
| ids.fill_(-1) | |
| elif pattern == "masked": | |
| ids[::4, 1:] = -1 | |
| ids[1::4] = -1 | |
| coeff[2::4, 0] = 0 # A valid routed weight of zero can have a nonzero gradient. | |
| sw1 = rand((2*n_shared*i, h)) * h**-.5 | |
| sw2 = rand((h, n_shared*i)) * (n_shared*i)**-.5 | |
| gen.manual_seed(seed + 55 + rank) | |
| w1 = rand((e//world, 2*i, h)) * h**-.5 | |
| w2 = rand((e//world, h, i)) * i**-.5 | |
| weights = w1, w2, sw1, sw2 | |
| local = slice(rank*cap, rank*cap + cap-rank) | |
| shared = make_state(x[local], x.new_ones(cap-rank, dtype=torch.float32), sw1) | |
| experts = [] | |
| for ex in range(e//world): | |
| rows, slots = (ids == rank*(e//world) + ex).nonzero(as_tuple=True) | |
| experts.append((rows, slots, make_state(x[rows], coeff[rows, slots], w1[ex]))) | |
| return x, ids, coeff, valid, local, shared, experts, weights, cap | |
| def routing_stats(ids, capacity, experts_per_rank, world): | |
| # The fixture stores every source rank's tokens in consecutive capacity-sized blocks. | |
| rows, slots = torch.where(ids >= 0) | |
| src = rows // capacity | |
| dst = ids[rows, slots] // experts_per_rank | |
| counts = torch.bincount(src * world + dst, minlength=world**2).view(world, world) | |
| counts.fill_diagonal_(0) | |
| return dict(valid_routes=rows.numel(), cross_rank_routes=int(counts.sum()), | |
| cross_rank_pairs=int(counts.count_nonzero())) | |
| def oracle_mlp(x, coeff, dy, w1, w2): | |
| # Straight-through BF16 rounding in the primal, FP32 master gradients. | |
| def rounded(v): | |
| return (v - v.detach()) + v.detach().bfloat16().float() | |
| x, coeff, a, b = [t.detach().float().requires_grad_() for t in (x, coeff, w1, w2)] | |
| gate, up = rounded(F.linear(x, a)).chunk(2, -1) | |
| act = F.silu(gate.clamp(max=10)) * up.clamp(-10, 10) | |
| out = F.linear(rounded(act * coeff[:, None]), b) | |
| return torch.autograd.grad(out, (x, coeff, a, b), grad_outputs=dy.float()) | |
| def oracle(data, dy): | |
| x, ids, coeff, valid, local, _, _, weights, cap = data | |
| w1, w2, sw1, sw2 = weights | |
| rank = dist.get_rank() | |
| # Reconstruct a full-token objective on each expert owner. The shared oracle | |
| # sees every real token once, independently of the candidate's shared all-reduces. | |
| chunks = [torch.empty((cap, x.shape[1]), dtype=dy.dtype, device=x.device) | |
| for _ in range(dist.get_world_size())] | |
| dist.all_gather(chunks, F.pad(dy, (0, 0, 0, cap-len(dy)))) | |
| all_dy = torch.cat(chunks) | |
| dx = torch.zeros_like(x, dtype=torch.float32) | |
| dc = torch.zeros_like(coeff) | |
| dw1, dw2 = (torch.zeros_like(v, dtype=torch.float32) for v in (w1, w2)) | |
| for ex in range(len(w1)): | |
| rows, slots = torch.where(ids == rank * len(w1) + ex) | |
| if len(rows): | |
| gx, gc, a, b = oracle_mlp(x[rows], coeff[rows, slots], all_dy[rows], w1[ex], w2[ex]) | |
| dx[rows] += gx | |
| dc[rows, slots] = gc | |
| dw1[ex].copy_(a) | |
| dw2[ex].copy_(b) | |
| dist.all_reduce(dx) | |
| dist.all_reduce(dc) | |
| ds1, ds2 = (torch.zeros_like(w, dtype=torch.float32) for w in (sw1, sw2)) | |
| for src in range(dist.get_world_size()): | |
| # Preserve the forward BF16 rounding points for each source batch. | |
| sl = slice(src * cap, src * cap + cap - src) | |
| sx, _, a, b = oracle_mlp(x[sl], coeff.new_ones(cap - src), all_dy[sl], sw1, sw2) | |
| dx[sl] += sx | |
| ds1 += a | |
| ds2 += b | |
| return dx[local].bfloat16(), dc[local], dw1, dw2, ds1, ds2 | |
| def main(): | |
| p = argparse.ArgumentParser(description=__doc__) | |
| p.add_argument("--candidate", type=Path, default=HERE / "backward.py") | |
| p.add_argument("--baseline", help="public for the frozen per-case baseline, or a Python path") | |
| p.add_argument("--case", choices=[*CASES, "all"], default="all") | |
| p.add_argument("--seed", type=int, default=137, help="seed for inputs, weights, routes and upstream gradients") | |
| p.add_argument("--capacity", type=int) | |
| args = p.parse_args() | |
| if args.capacity is not None: | |
| if args.case == "all" or args.capacity < 8: | |
| p.error("capacity override requires one case and at least 8 tokens") | |
| e, h, width, _, shared, pattern = CASES[args.case] | |
| CASES[args.case] = (e, h, width, args.capacity, shared, pattern) | |
| 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("run with at least two GPUs on one node") | |
| torch.cuda.set_device(rank) | |
| init_ep_group(torch.device("cuda", rank)) | |
| torch.backends.cuda.matmul.allow_tf32 = False | |
| torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction = False | |
| public_file = "backward_tensorcore.py" | |
| if world == 8 and any(name in torch.cuda.get_device_name(rank) for name in ("H100", "B200")): | |
| public_file = "backward_fused.py" | |
| candidate = load(args.candidate) | |
| for case in CASES if args.case == "all" else [args.case]: | |
| paths, modules = [args.candidate], [candidate] | |
| if args.baseline: | |
| public_baseline = HERE / public_file | |
| baseline = public_baseline if args.baseline == "public" else Path(args.baseline) | |
| paths.append(baseline) | |
| modules.append(load(baseline)) | |
| data = make(case, rank, world, args.seed) | |
| x, _, _, _, local, shared, experts, weights, cap = data | |
| dy = torch.empty_like(x[local]) | |
| def refresh(check_seed): | |
| gen = torch.Generator(device="cuda").manual_seed(args.seed + (check_seed - 137) + rank) | |
| dy.normal_(generator=gen) | |
| if check_seed == 153 and rank == 0: | |
| dy.zero_() # Shared gradients must still include other ranks. | |
| calls = [lambda m=m: m.moe_backward(dy, shared, experts, weights, cap, 6, dist.group.WORLD) | |
| for m in modules] | |
| tolerances = [(2e-3, .012), (.003, .002)] + [(.002, .002)]*4 | |
| result = qualify(calls, refresh, lambda: oracle(data, dy), tolerances, repeats=3, | |
| names=("dx", "droute", "dW1", "dW2", "dSharedW1", "dSharedW2")) | |
| if rank == 0: | |
| routes = routing_stats(data[1], cap, len(experts), world) | |
| print(json.dumps(dict(task="shared_mega_moe", phase="backward", case=case, ranks=world, seed=args.seed, | |
| implementations=[p.name for p in paths], **routes, **result)), flush=True) | |
| del calls, data, x, shared, experts, weights, dy | |
| dist.destroy_process_group() | |
| if __name__ == "__main__": | |
| main() | |