Guest User

Untitled

a guest
Dec 4th, 2025
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. import time
  2. import torch
  3.  
  4. B, C, H, W = 8, 3, 1080, 1920
  5. device = "cuda"
  6.  
  7. print("torch version:", torch.__version__)
  8. print("device:", device)
  9.  
  10. imgs = torch.randint(
  11. 0, 256, (B, C, H, W),
  12. dtype=torch.uint8,
  13. device="cpu",
  14. )
  15. imgs_pinned = imgs.pin_memory()
  16. cpu_pinned_float = torch.empty((B, C, H, W), dtype=torch.float32, device="cpu", pin_memory=True)
  17. gpu_float = torch.empty((B, C, H, W), dtype=torch.float32, device=device)
  18.  
  19.  
  20. def benchmark(name, fn, iters=50):
  21. fn()
  22. torch.cuda.synchronize()
  23.  
  24. t0 = time.perf_counter()
  25. for _ in range(iters):
  26. fn()
  27. torch.cuda.synchronize()
  28. t1 = time.perf_counter()
  29.  
  30. print(f"{name:35s}: {(t1 - t0) * 1000 / iters:.3f} ms/iter")
  31.  
  32.  
  33. def cpu_uint8_to_float32():
  34. return imgs.to(dtype=torch.float32)
  35.  
  36.  
  37. def cpu_uint8_to_cuda_float32_combined():
  38. return imgs.to(device=device, dtype=torch.float32).div_(255.0)
  39.  
  40.  
  41. def cpu_uint8_to_cuda_then_dtype():
  42. return imgs.to(device=device).to(dtype=torch.float32).div_(255.0)
  43.  
  44.  
  45. def cpu_uint8_to_float32_then_cuda():
  46. x = imgs.to(dtype=torch.float32)
  47. return x.to(device=device).div_(255.0)
  48.  
  49.  
  50. def cpu_uint8_pinned_to_cuda_float32_combined_nonblocking():
  51. return imgs_pinned.to(device=device, dtype=torch.float32, non_blocking=True).div_(255.0)
  52.  
  53.  
  54. def cpu_uint8_pinned_to_cuda_then_dtype_nonblocking():
  55. return imgs_pinned.to(device=device, non_blocking=True).to(dtype=torch.float32).div_(255.0)
  56.  
  57.  
  58. def cpu_uint8_copy_to_pinned_float_then_gpu_nonblocking():
  59. cpu_pinned_float.copy_(imgs)
  60. gpu_float.copy_(cpu_pinned_float, non_blocking=True)
  61. return gpu_float
  62.  
  63.  
  64. if __name__ == "__main__":
  65. benchmark("cpu uint8 -> float32", cpu_uint8_to_float32)
  66. benchmark("cpu uint8 -> cuda float32 (combined)", cpu_uint8_to_cuda_float32_combined)
  67. benchmark("cpu uint8 -> cuda -> float32", cpu_uint8_to_cuda_then_dtype)
  68. benchmark("cpu uint8 -> float32 -> cuda", cpu_uint8_to_float32_then_cuda)
  69. benchmark("cpu uint8 pinned -> cuda float32 (combined, nb)", cpu_uint8_pinned_to_cuda_float32_combined_nonblocking)
  70. benchmark("cpu uint8 pinned -> cuda -> float32 (nb)", cpu_uint8_pinned_to_cuda_then_dtype_nonblocking)
  71. benchmark("cpu uint8 -> pinned float32 -> cuda (nb, copy_)", cpu_uint8_copy_to_pinned_float_then_gpu_nonblocking)
Advertisement
Add Comment
Please, Sign In to add comment