📚 The CoCalc Library - books, templates and other resources
cocalc-examples / data-science-ipython-notebooks / deep-learning / tensor-flow-examples / multigpu_basics.py
132928 viewsLicense: OTHER
#Multi GPU Basic example1'''2This tutorial requires your machine to have 2 GPUs3"/cpu:0": The CPU of your machine.4"/gpu:0": The first GPU of your machine5"/gpu:1": The second GPU of your machine6'''78import numpy as np9import tensorflow as tf10import datetime1112#Processing Units logs13log_device_placement = True1415#num of multiplications to perform16n = 101718'''19Example: compute A^n + B^n on 2 GPUs20Results on 8 cores with 2 GTX-980:21* Single GPU computation time: 0:00:11.27744922* Multi GPU computation time: 0:00:07.13170123'''24#Create random large matrix25A = np.random.rand(1e4, 1e4).astype('float32')26B = np.random.rand(1e4, 1e4).astype('float32')2728# Creates a graph to store results29c1 = []30c2 = []3132def matpow(M, n):33if n < 1: #Abstract cases where n < 134return M35else:36return tf.matmul(M, matpow(M, n-1))3738'''39Single GPU computing40'''41with tf.device('/gpu:0'):42a = tf.constant(A)43b = tf.constant(B)44#compute A^n and B^n and store results in c145c1.append(matpow(a, n))46c1.append(matpow(b, n))4748with tf.device('/cpu:0'):49sum = tf.add_n(c1) #Addition of all elements in c1, i.e. A^n + B^n5051t1_1 = datetime.datetime.now()52with tf.Session(config=tf.ConfigProto(log_device_placement=log_device_placement)) as sess:53# Runs the op.54sess.run(sum)55t2_1 = datetime.datetime.now()565758'''59Multi GPU computing60'''61#GPU:0 computes A^n62with tf.device('/gpu:0'):63#compute A^n and store result in c264a = tf.constant(A)65c2.append(matpow(a, n))6667#GPU:1 computes B^n68with tf.device('/gpu:1'):69#compute B^n and store result in c270b = tf.constant(B)71c2.append(matpow(b, n))7273with tf.device('/cpu:0'):74sum = tf.add_n(c2) #Addition of all elements in c2, i.e. A^n + B^n7576t1_2 = datetime.datetime.now()77with tf.Session(config=tf.ConfigProto(log_device_placement=log_device_placement)) as sess:78# Runs the op.79sess.run(sum)80t2_2 = datetime.datetime.now()818283print "Single GPU computation time: " + str(t2_1-t1_1)84print "Multi GPU computation time: " + str(t2_2-t1_2)8586