Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132928 views
License: OTHER
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
9
import numpy as np
10
import tensorflow as tf
11
import datetime
12
13
#Processing Units logs
14
log_device_placement = True
15
16
#num of multiplications to perform
17
n = 10
18
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
29
# Creates a graph to store results
30
c1 = []
31
c2 = []
32
33
def matpow(M, n):
34
if n < 1: #Abstract cases where n < 1
35
return M
36
else:
37
return tf.matmul(M, matpow(M, n-1))
38
39
'''
40
Single GPU computing
41
'''
42
with tf.device('/gpu:0'):
43
a = tf.constant(A)
44
b = tf.constant(B)
45
#compute A^n and B^n and store results in c1
46
c1.append(matpow(a, n))
47
c1.append(matpow(b, n))
48
49
with tf.device('/cpu:0'):
50
sum = tf.add_n(c1) #Addition of all elements in c1, i.e. A^n + B^n
51
52
t1_1 = datetime.datetime.now()
53
with tf.Session(config=tf.ConfigProto(log_device_placement=log_device_placement)) as sess:
54
# Runs the op.
55
sess.run(sum)
56
t2_1 = datetime.datetime.now()
57
58
59
'''
60
Multi GPU computing
61
'''
62
#GPU:0 computes A^n
63
with tf.device('/gpu:0'):
64
#compute A^n and store result in c2
65
a = tf.constant(A)
66
c2.append(matpow(a, n))
67
68
#GPU:1 computes B^n
69
with tf.device('/gpu:1'):
70
#compute B^n and store result in c2
71
b = tf.constant(B)
72
c2.append(matpow(b, n))
73
74
with tf.device('/cpu:0'):
75
sum = tf.add_n(c2) #Addition of all elements in c2, i.e. A^n + B^n
76
77
t1_2 = datetime.datetime.now()
78
with tf.Session(config=tf.ConfigProto(log_device_placement=log_device_placement)) as sess:
79
# Runs the op.
80
sess.run(sum)
81
t2_2 = datetime.datetime.now()
82
83
84
print "Single GPU computation time: " + str(t2_1-t1_1)
85
print "Multi GPU computation time: " + str(t2_2-t1_2)
86