num_workers.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. __author__ = "Christian Heider Nielsen"
  4. __doc__ = r"""
  5. Created on 08-12-2020
  6. """
  7. import time
  8. import numpy
  9. import torch
  10. from draugr.os_utilities import WorkerSession
  11. from draugr.python_utilities import batched_recycle
  12. from draugr.torch_utilities import to_tensor_generator
  13. def test_d3():
  14. channels_in = 3
  15. channels_out = 3
  16. samples = 10
  17. device = "cuda"
  18. batches = 3
  19. batch_size = 32
  20. data_shape = (batches * batch_size, channels_in, 512, 512)
  21. model = torch.nn.Sequential(
  22. torch.nn.Conv2d(channels_in, channels_out, (3, 3)),
  23. torch.nn.ReLU(),
  24. torch.nn.Conv2d(channels_out, channels_out, (3, 3)),
  25. torch.nn.ReLU(),
  26. torch.nn.Conv2d(channels_out, channels_out, (3, 3)),
  27. torch.nn.ReLU(),
  28. ).to(device)
  29. generator = to_tensor_generator(
  30. batched_recycle(numpy.random.sample(data_shape), batch_size), device=device
  31. )
  32. with WorkerSession(0.3) as num_workers:
  33. dataloader = torch.utils.data.DataLoader(
  34. numpy.random.sample(data_shape),
  35. batch_size=batch_size,
  36. shuffle=True,
  37. num_workers=num_workers,
  38. pin_memory=True,
  39. )
  40. for _ in range(samples):
  41. s1 = time.time()
  42. for _, a in zip(range(batches), dataloader):
  43. model(a.to(device, dtype=torch.float))
  44. s2 = time.time()
  45. for _, a in zip(range(batches), generator):
  46. model(a)
  47. s3 = time.time()
  48. print(f"dataloader: {s2 - s1}")
  49. print(f"generator: {s3 - s2}")
  50. if __name__ == "__main__":
  51. test_d3()