multigpu_basics.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #Multi GPU Basic example
  2. '''
  3. This tutorial requires your machine to have 2 GPUs
  4. "/cpu:0": The CPU of your machine.
  5. "/gpu:0": The first GPU of your machine
  6. "/gpu:1": The second GPU of your machine
  7. '''
  8. import numpy as np
  9. import tensorflow as tf
  10. import datetime
  11. #Processing Units logs
  12. log_device_placement = True
  13. #num of multiplications to perform
  14. n = 10
  15. '''
  16. Example: compute A^n + B^n on 2 GPUs
  17. Results on 8 cores with 2 GTX-980:
  18. * Single GPU computation time: 0:00:11.277449
  19. * Multi GPU computation time: 0:00:07.131701
  20. '''
  21. #Create random large matrix
  22. A = np.random.rand(1e4, 1e4).astype('float32')
  23. B = np.random.rand(1e4, 1e4).astype('float32')
  24. # Creates a graph to store results
  25. c1 = []
  26. c2 = []
  27. def matpow(M, n):
  28. if n < 1: #Abstract cases where n < 1
  29. return M
  30. else:
  31. return tf.matmul(M, matpow(M, n-1))
  32. '''
  33. Single GPU computing
  34. '''
  35. with tf.device('/gpu:0'):
  36. a = tf.constant(A)
  37. b = tf.constant(B)
  38. #compute A^n and B^n and store results in c1
  39. c1.append(matpow(a, n))
  40. c1.append(matpow(b, n))
  41. with tf.device('/cpu:0'):
  42. sum = tf.add_n(c1) #Addition of all elements in c1, i.e. A^n + B^n
  43. t1_1 = datetime.datetime.now()
  44. with tf.Session(config=tf.ConfigProto(log_device_placement=log_device_placement)) as sess:
  45. # Runs the op.
  46. sess.run(sum)
  47. t2_1 = datetime.datetime.now()
  48. '''
  49. Multi GPU computing
  50. '''
  51. #GPU:0 computes A^n
  52. with tf.device('/gpu:0'):
  53. #compute A^n and store result in c2
  54. a = tf.constant(A)
  55. c2.append(matpow(a, n))
  56. #GPU:1 computes B^n
  57. with tf.device('/gpu:1'):
  58. #compute B^n and store result in c2
  59. b = tf.constant(B)
  60. c2.append(matpow(b, n))
  61. with tf.device('/cpu:0'):
  62. sum = tf.add_n(c2) #Addition of all elements in c2, i.e. A^n + B^n
  63. t1_2 = datetime.datetime.now()
  64. with tf.Session(config=tf.ConfigProto(log_device_placement=log_device_placement)) as sess:
  65. # Runs the op.
  66. sess.run(sum)
  67. t2_2 = datetime.datetime.now()
  68. print("Single GPU computation time: " + str(t2_1-t1_1))
  69. print("Multi GPU computation time: " + str(t2_2-t1_2))