Tensorflow操作似乎不使用GPU

Tensorflow操作似乎不使用GPU,tensorflow,gpu,cpu,Tensorflow,Gpu,Cpu,我需要执行一项工作,平均大量的长向量多次,我希望这是在我的GPU上完成 在运行时监控nvtop和htop,我发现GPU(在我训练Keras模型时总是显示top活动)在这些操作中根本没有被使用,而CPU使用在这些操作中激增 我在下面的代码片段中模拟了它(尝试最小化非tf工作) 我做错了什么 import tensorflow as tf from tensorflow.math import add_n, add, scalar_mul import numpy as np tf.debuggi

我需要执行一项工作,平均大量的长向量多次,我希望这是在我的GPU上完成

在运行时监控nvtop和htop,我发现GPU(在我训练Keras模型时总是显示top活动)在这些操作中根本没有被使用,而CPU使用在这些操作中激增

我在下面的代码片段中模拟了它(尝试最小化非tf工作)

我做错了什么

import tensorflow as tf
from tensorflow.math import add_n, add, scalar_mul
import numpy as np

tf.debugging.set_log_device_placement(True)
sess = tf.compat.v1.Session(config=config) 
tf.compat.v1.keras.backend.set_session(sess)
os.environ["CUDA_VISIBLE_DEVICES"]="1"

#Make a random numpy matrix
vecs=np.random.rand(100, 300)

with sess.as_default():
    with tf.device('/GPU:0'):
        for _ in range(1000):
            #vecs=np.random.rand(100, 300)
            tf_vecs=tf.Variable(vecs, dtype=tf.float64)
            tf_invlgt=tf.Variable(1/np.shape(vecs)[0],dtype=tf.float64)
            vectors=tf.unstack(tf_vecs)
            sum_vecs=add_n(vectors)
            mean_vec=tf.Variable(scalar_mul(tf_invlgt, sum_vecs))
谢谢


Michael

我可能错了,但cuda_visible_设备应该是“0”型的吗

请参阅github评论

如果仍然无法工作,您还可以添加一小段代码来检查tensorflow是否可以看到gpu设备:

from tensorflow.python.client import device_lib

def get_available_gpus():
    local_device_protos = device_lib.list_local_devices()
    return [x.name for x in local_device_protos if x.device_type == 'GPU']
提到这一点

from tensorflow.python.client import device_lib

def get_available_gpus():
    local_device_protos = device_lib.list_local_devices()
    return [x.name for x in local_device_protos if x.device_type == 'GPU']