mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
Compare every rank payload with the expected float32 contents. Exercise the public CLI verdict with deterministic offline fixtures.
304 lines
11 KiB
Python
304 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
"""Real-world PyTorch 2.5 + cuDNN 9 + NCCL 2.21 parity harness.
|
|
|
|
Runs deterministic single-GPU (cuBLAS, FP16 Tensor Cores, cuDNN Conv2d/BN/SDPA,
|
|
Transformer autograd + AdamW, CUDA Graph capture/replay) and multi-GPU NCCL
|
|
collectives (all_reduce, all_gather, broadcast, reduce_scatter, DDP training)
|
|
across all visible CUDA GPUs, emitting bit-exact SHA-256 digests for stock vs
|
|
nvidia_rs.ko comparison.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import socket
|
|
import struct
|
|
import sys
|
|
import torch
|
|
import torch.distributed as dist
|
|
import torch.multiprocessing as mp
|
|
import torch.nn as nn
|
|
import torch.nn.functional as F
|
|
|
|
|
|
ALL_REDUCE_SIZE = 1024
|
|
BROADCAST_SIZE = 256
|
|
ALL_GATHER_CHUNK_SIZE = 128
|
|
REDUCE_SCATTER_CHUNK_SIZE = 64
|
|
|
|
|
|
def _pick_master_port() -> str:
|
|
override = os.environ.get("MASTER_PORT")
|
|
if override:
|
|
return override
|
|
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
|
sock.bind(("127.0.0.1", 0))
|
|
return str(sock.getsockname()[1])
|
|
|
|
|
|
def _payload_digest(raw: bytes) -> str:
|
|
return hashlib.sha256(raw).hexdigest()[:16]
|
|
|
|
|
|
def tensor_digest(t: torch.Tensor) -> str:
|
|
arr = t.detach().to("cpu", non_blocking=False).contiguous()
|
|
if arr.dtype == torch.float16:
|
|
raw = arr.view(torch.uint16).numpy().tobytes()
|
|
elif arr.dtype == torch.float32:
|
|
raw = arr.view(torch.int32).numpy().tobytes()
|
|
else:
|
|
raw = arr.numpy().tobytes()
|
|
return _payload_digest(raw)
|
|
|
|
|
|
def set_deterministic(seed: int = 42) -> None:
|
|
torch.manual_seed(seed)
|
|
torch.cuda.manual_seed_all(seed)
|
|
torch.backends.cudnn.deterministic = True
|
|
torch.backends.cudnn.benchmark = False
|
|
torch.backends.cuda.matmul.allow_tf32 = False
|
|
torch.backends.cudnn.allow_tf32 = False
|
|
|
|
|
|
def run_single_gpu_suite(device_idx: int = 0) -> dict:
|
|
set_deterministic(42)
|
|
dev = torch.device(f"cuda:{device_idx}")
|
|
torch.cuda.set_device(dev)
|
|
|
|
# 1. cuBLAS FP32 & FP16 Tensor Core GEMM
|
|
a32 = torch.randn(256, 256, device=dev, dtype=torch.float32)
|
|
b32 = torch.randn(256, 256, device=dev, dtype=torch.float32)
|
|
c32 = a32 @ b32
|
|
a16 = a32.half()
|
|
b16 = b32.half()
|
|
c16 = a16 @ b16
|
|
|
|
# 2. cuDNN 9 Conv2d + BatchNorm2d + ReLU forward + backward
|
|
conv = nn.Sequential(
|
|
nn.Conv2d(16, 32, kernel_size=3, padding=1),
|
|
nn.BatchNorm2d(32),
|
|
nn.ReLU(),
|
|
nn.Conv2d(32, 32, kernel_size=3, padding=1),
|
|
).to(dev)
|
|
x_img = torch.randn(8, 16, 32, 32, device=dev, requires_grad=True)
|
|
y_img = conv(x_img)
|
|
loss_img = (y_img ** 2).mean()
|
|
loss_img.backward()
|
|
cudnn_out_digest = tensor_digest(y_img)
|
|
cudnn_grad_digest = tensor_digest(x_img.grad)
|
|
|
|
# 3. Transformer block (LayerNorm + SDPA + SwiGLU MLP) + AdamW 3 steps
|
|
class MiniTransformer(nn.Module):
|
|
def __init__(self, d=128, heads=4):
|
|
super().__init__()
|
|
self.ln1 = nn.LayerNorm(d)
|
|
self.qkv = nn.Linear(d, 3 * d, bias=False)
|
|
self.proj = nn.Linear(d, d, bias=False)
|
|
self.ln2 = nn.LayerNorm(d)
|
|
self.w1 = nn.Linear(d, 4 * d, bias=False)
|
|
self.w2 = nn.Linear(4 * d, d, bias=False)
|
|
self.heads = heads
|
|
|
|
def forward(self, x):
|
|
B, T, C = x.shape
|
|
h = self.ln1(x)
|
|
qkv = self.qkv(h).view(B, T, 3, self.heads, C // self.heads)
|
|
q, k, v = qkv.unbind(dim=2)
|
|
q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
|
|
attn = F.scaled_dot_product_attention(q, k, v, is_causal=True)
|
|
attn = attn.transpose(1, 2).contiguous().view(B, T, C)
|
|
x = x + self.proj(attn)
|
|
x = x + self.w2(F.silu(self.w1(self.ln2(x))))
|
|
return x
|
|
|
|
set_deterministic(123)
|
|
model = MiniTransformer().to(dev)
|
|
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
|
|
x_seq = torch.randn(4, 32, 128, device=dev)
|
|
target = torch.randn(4, 32, 128, device=dev)
|
|
losses = []
|
|
for _ in range(3):
|
|
opt.zero_grad(set_to_none=True)
|
|
out = model(x_seq)
|
|
loss = F.mse_loss(out, target)
|
|
loss.backward()
|
|
opt.step()
|
|
losses.append(round(float(loss.item()), 6))
|
|
transformer_weight_digest = tensor_digest(model.proj.weight)
|
|
|
|
# 4. CUDA Graph capture & replay
|
|
g_in = torch.randn(128, 128, device=dev)
|
|
g_w = torch.randn(128, 128, device=dev)
|
|
g_out = torch.empty(128, 128, device=dev)
|
|
s = torch.cuda.Stream(device=dev)
|
|
s.wait_stream(torch.cuda.current_stream(dev))
|
|
with torch.cuda.stream(s):
|
|
for _ in range(2):
|
|
g_out.copy_(torch.relu(g_in @ g_w))
|
|
torch.cuda.current_stream(dev).wait_stream(s)
|
|
graph = torch.cuda.CUDAGraph()
|
|
with torch.cuda.graph(graph, stream=s):
|
|
g_out.copy_(torch.relu(g_in @ g_w))
|
|
g_in.fill_(0.5)
|
|
graph.replay()
|
|
torch.cuda.synchronize(dev)
|
|
graph_digest = tensor_digest(g_out)
|
|
|
|
return {
|
|
"fp32_gemm_digest": tensor_digest(c32),
|
|
"fp16_gemm_digest": tensor_digest(c16),
|
|
"cudnn_out_digest": cudnn_out_digest,
|
|
"cudnn_grad_digest": cudnn_grad_digest,
|
|
"transformer_losses": losses,
|
|
"transformer_weight_digest": transformer_weight_digest,
|
|
"cuda_graph_digest": graph_digest,
|
|
}
|
|
|
|
|
|
def _expected_f32_digest(values: list[int]) -> str:
|
|
"""Hash the known-good payload in the same native float32 format as tensor_digest."""
|
|
return _payload_digest(struct.pack(f"={len(values)}f", *values))
|
|
|
|
|
|
def _collectives_match_expected(items: list[dict], world_size: int) -> bool:
|
|
rank_sum = world_size * (world_size + 1) // 2
|
|
all_reduce = _expected_f32_digest([rank_sum] * ALL_REDUCE_SIZE)
|
|
broadcast = _expected_f32_digest(list(range(BROADCAST_SIZE)))
|
|
all_gather = _expected_f32_digest(
|
|
[rank * 10 + 3 for rank in range(world_size) for _ in range(ALL_GATHER_CHUNK_SIZE)]
|
|
)
|
|
return len(items) == world_size and all(
|
|
result["rank"] == rank
|
|
and result["all_reduce_digest"] == all_reduce
|
|
and result["broadcast_digest"] == broadcast
|
|
and result["all_gather_digest"] == all_gather
|
|
and result["reduce_scatter_digest"] == _expected_f32_digest(
|
|
[rank_sum * (rank + 1)] * REDUCE_SCATTER_CHUNK_SIZE
|
|
)
|
|
for rank, result in enumerate(items)
|
|
)
|
|
|
|
|
|
def _nccl_worker(rank: int, world_size: int, ret_queue: mp.Queue, master_port: str) -> None:
|
|
os.environ.setdefault("MASTER_ADDR", "127.0.0.1")
|
|
os.environ["MASTER_PORT"] = master_port
|
|
os.environ.setdefault("NCCL_IB_DISABLE", "1")
|
|
os.environ.setdefault("NCCL_SOCKET_IFNAME", "lo")
|
|
os.environ.setdefault("NCCL_ALGO", "Ring")
|
|
torch.cuda.set_device(rank)
|
|
dist.init_process_group(backend="nccl", rank=rank, world_size=world_size)
|
|
try:
|
|
dev = torch.device(f"cuda:{rank}")
|
|
|
|
# 1. AllReduce (SUM)
|
|
t_ar = torch.full((ALL_REDUCE_SIZE,), float(rank + 1), device=dev, dtype=torch.float32)
|
|
dist.all_reduce(t_ar, op=dist.ReduceOp.SUM)
|
|
|
|
# 2. Broadcast from rank 0
|
|
t_bc = torch.arange(BROADCAST_SIZE, device=dev, dtype=torch.float32) * (
|
|
1.0 if rank == 0 else 0.0
|
|
)
|
|
dist.broadcast(t_bc, src=0)
|
|
|
|
# 3. AllGather
|
|
t_ag_in = torch.full(
|
|
(ALL_GATHER_CHUNK_SIZE,), float(rank * 10 + 3), device=dev, dtype=torch.float32
|
|
)
|
|
t_ag_out = [
|
|
torch.empty(ALL_GATHER_CHUNK_SIZE, device=dev, dtype=torch.float32)
|
|
for _ in range(world_size)
|
|
]
|
|
dist.all_gather(t_ag_out, t_ag_in)
|
|
ag_cat = torch.cat(t_ag_out, dim=0)
|
|
|
|
# 4. ReduceScatter
|
|
rs_in = [
|
|
torch.full(
|
|
(REDUCE_SCATTER_CHUNK_SIZE,),
|
|
float((rank + 1) * (i + 1)),
|
|
device=dev,
|
|
dtype=torch.float32,
|
|
)
|
|
for i in range(world_size)
|
|
]
|
|
rs_out = torch.empty(REDUCE_SCATTER_CHUNK_SIZE, device=dev, dtype=torch.float32)
|
|
dist.reduce_scatter(rs_out, rs_in, op=dist.ReduceOp.SUM)
|
|
|
|
# 5. Real DistributedDataParallel training step
|
|
set_deterministic(77)
|
|
base = nn.Sequential(nn.Linear(64, 128), nn.GELU(), nn.Linear(128, 64)).to(dev)
|
|
ddp = nn.parallel.DistributedDataParallel(base, device_ids=[rank])
|
|
opt = torch.optim.SGD(ddp.parameters(), lr=0.05)
|
|
set_deterministic(1000 + rank)
|
|
x = torch.randn(16, 64, device=dev)
|
|
y = torch.randn(16, 64, device=dev)
|
|
for _ in range(2):
|
|
opt.zero_grad(set_to_none=True)
|
|
loss = F.mse_loss(ddp(x), y)
|
|
loss.backward()
|
|
opt.step()
|
|
|
|
torch.cuda.synchronize(dev)
|
|
res = {
|
|
"rank": rank,
|
|
"all_reduce_digest": tensor_digest(t_ar),
|
|
"broadcast_digest": tensor_digest(t_bc),
|
|
"all_gather_digest": tensor_digest(ag_cat),
|
|
"reduce_scatter_val": float(rs_out[0].item()),
|
|
"reduce_scatter_digest": tensor_digest(rs_out),
|
|
"ddp_weight_digest": tensor_digest(ddp.module[0].weight),
|
|
}
|
|
dist.barrier()
|
|
ret_queue.put(res)
|
|
finally:
|
|
if dist.is_initialized():
|
|
dist.destroy_process_group()
|
|
|
|
|
|
def main() -> int:
|
|
n_gpus = torch.cuda.device_count()
|
|
if n_gpus < 1:
|
|
print(json.dumps({"passed": False, "error": "no CUDA GPUs detected"}))
|
|
return 1
|
|
|
|
single = run_single_gpu_suite(0)
|
|
nccl_results = None
|
|
if n_gpus > 1:
|
|
master_port = _pick_master_port()
|
|
ctx = mp.get_context("spawn")
|
|
q = ctx.Queue()
|
|
mp.spawn(_nccl_worker, args=(n_gpus, q, master_port), nprocs=n_gpus, join=True)
|
|
items = sorted([q.get() for _ in range(n_gpus)], key=lambda d: d["rank"])
|
|
all_synced = (
|
|
_collectives_match_expected(items, n_gpus)
|
|
and len({r["ddp_weight_digest"] for r in items}) == 1
|
|
)
|
|
nccl_results = {
|
|
"world_size": n_gpus,
|
|
"all_synced": all_synced,
|
|
"all_reduce_digest": items[0]["all_reduce_digest"],
|
|
"broadcast_digest": items[0]["broadcast_digest"],
|
|
"all_gather_digest": items[0]["all_gather_digest"],
|
|
"reduce_scatter_vals": [r["reduce_scatter_val"] for r in items],
|
|
"ddp_weight_digest": items[0]["ddp_weight_digest"],
|
|
}
|
|
|
|
out = {
|
|
"passed": True if (nccl_results is None or nccl_results["all_synced"]) else False,
|
|
"torch_version": torch.__version__,
|
|
"cuda_version": torch.version.cuda,
|
|
"cudnn_version": torch.backends.cudnn.version(),
|
|
"nccl_version": list(torch.cuda.nccl.version()),
|
|
"device_count": n_gpus,
|
|
"device_name": torch.cuda.get_device_name(0),
|
|
"single_gpu": single,
|
|
"nccl": nccl_results,
|
|
}
|
|
print(json.dumps(out))
|
|
return 0 if out["passed"] else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|