1. 程式人生 > 程式設計 >基於tensorflow指定GPU執行及GPU資源分配的幾種方式小結

基於tensorflow指定GPU執行及GPU資源分配的幾種方式小結

1. 在終端執行時設定使用哪些GPU(兩種方式)

(1) 如下(export 語句執行一次就行了,以後再執行程式碼不用執行)

基於tensorflow指定GPU執行及GPU資源分配的幾種方式小結

(2) 如下

基於tensorflow指定GPU執行及GPU資源分配的幾種方式小結

2. 程式碼中指定(兩種方式)

(1)

import os
os.environ["CUDA_VISIBLE_DEVICES"] = "1"

(2)

# Creates a graph.
with tf.device('/gpu:1'):
 a = tf.constant([1.0,2.0,3.0,4.0,5.0,6.0],shape=[2,3],name='a')
 b = tf.constant([1.0,shape=[3,2],name='b')
 c = tf.matmul(a,b)
# Creates a session with log_device_placement set to True.
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
# Runs the op.
print sess.run(c)

若想使用多個GPU,如下

c = []
for d in ['/gpu:0','/gpu:1']:
 with tf.device(d):
  a = tf.constant([1.0,3])
  b = tf.constant([1.0,2])
  c.append(tf.matmul(a,b))
with tf.device('/cpu:0'):
 sum = tf.add_n(c)
# Creates a session with log_device_placement set to True.
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
# Runs the op.
print sess.run(sum)

3.GPU資源分配

(1) 設定允許GPU增長

config = tf.ConfigProto()
config.gpu_options.allow_growth = True
session = tf.Session(config=config,...)

(2) 設定每個GPU記憶體使用多少

config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.4
session = tf.Session(config=config,...)

以上這篇基於tensorflow指定GPU執行及GPU資源分配的幾種方式小結就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。