simple_conv.py 1.3 KB

123456789101112131415161718192021222324252627282930313233
  1. from tinygrad.helpers import getenv
  2. from tinygrad import dtypes, Tensor
  3. dtype_in = dtypes.half if getenv("HALF") else dtypes.bfloat16 if getenv("BFLOAT16") else dtypes.float
  4. acc_dtype = dtypes.half if getenv("ACC_HALF") else dtypes.bfloat16 if getenv("ACC_BFLOAT16") else None
  5. CNT = getenv("CNT", 8)
  6. BS = getenv("BS", 16)
  7. CIN = getenv("CIN", 128)
  8. COUT = getenv("COUT", 128)
  9. HW = getenv("HW", 128)
  10. K = getenv("K", 3)
  11. PADDING = getenv("PADDING", 1)
  12. COMP = getenv("COMP", 0)
  13. ATOL = getenv("ATOL", 1e-4)
  14. RTOL = getenv("RTOL", 3e-2)
  15. FLOPS = BS*K*K*CIN*HW*HW*COUT*2
  16. def rand_input(): return Tensor.rand(BS, CIN, HW, HW, dtype=dtype_in).realize(), Tensor.rand(COUT, CIN, K, K, dtype=dtype_in).realize()
  17. if __name__ == "__main__":
  18. a, b = rand_input()
  19. for i in range(CNT):
  20. if i > 0 and getenv("RAND", 0) != 0:
  21. a, b = rand_input()
  22. c = a.conv2d(b, padding=PADDING, acc_dtype=acc_dtype).realize()
  23. if COMP:
  24. import numpy as np, time, torch
  25. torch_device = "cuda:0" if torch.cuda.is_available() else ("mps" if getenv("MPS", 0) else "cpu")
  26. ta, tb = torch.from_numpy(a.numpy()).to(torch_device), torch.from_numpy(b.numpy()).to(torch_device)
  27. tc = torch.nn.functional.conv2d(ta, tb, padding=PADDING)
  28. np.testing.assert_allclose(c.numpy(), tc.cpu(), atol=ATOL, rtol=RTOL)