W1, b = torch.tensor([[1.0, 2.0], [3.0, -1.0]]), torch.tensor([0.0, -4.0])
w2, x = torch.tensor([2.0, -1.0]), torch.tensor([1.0, 1.0])
def g(x, W1, b, w2): # the 2-2-1 ReLU network
return w2 @ torch.relu(W1 @ x + b)
m = (W1 @ x + b > 0).float() # the ReLU mask
print('by hand :', (w2 @ torch.diag(m) @ W1).numpy())
print('by autograd:', torch.func.grad(g)(x, W1, b, w2).numpy())