import time, torch

# One step of gradient descent on the MLP of examples/train.pl: compare with bench_train.pl.
B, D, H, O = 256, 768, 3072, 768

def best(f, reps, sync):
    f(); f(); sync()
    ts = []
    for _ in range(reps):
        sync(); t0 = time.perf_counter()
        for _ in range(5): f()
        sync(); ts.append((time.perf_counter() - t0) / 5)
    return min(ts) * 1000

for dev in ["cpu", "cuda"] if torch.cuda.is_available() else ["cpu"]:
    x, t = torch.rand(B, D, device=dev), torch.rand(B, O, device=dev)
    ws = [(torch.rand(D, H, device=dev) * 0.02 - 0.01).requires_grad_(), torch.rand(H, device=dev).requires_grad_(),
          (torch.rand(H, O, device=dev) * 0.02 - 0.01).requires_grad_(), torch.rand(O, device=dev).requires_grad_()]
    def step():
        w1, b1, w2, b2 = ws
        h = x @ w1 + b1
        a = h * torch.sigmoid(1.702 * h)
        y = a @ w2 + b2
        loss = ((y - t) ** 2).mean()
        gs = torch.autograd.grad(loss, ws)
        with torch.no_grad():
            for w, g in zip(ws, gs):
                w -= 0.01 * g
        return loss.item()
    sync = torch.cuda.synchronize if dev == "cuda" else (lambda: None)
    print(f"train step {B}x{D}x{H}x{O}  torch {dev}  best={best(step, 5, sync):.3f} ms")
