multigpu_basics.py 2.1 KB

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