【问题标题】:Tensorflow with GPU slower than expected使用 GPU 的 Tensorflow 比预期的要慢
【发布时间】:2020-12-04 21:42:23
【问题描述】:

所以我最近尝试在具有以下规格的电脑上运行 tensorflow-gpu:

AMD Ryzen 5 2600X 6 核,NVIDIA GeForce RTX 2060,16 GB 内存

我在colab 的教程中使用 Fashion mnist 运行了内置数据集。我运行了以下代码,发现 colab 没有在 gpu 上运行:

print("GPU is", "available" if tf.config.list_physical_devices('GPU') else "NOT AVAILABLE")

所以我浏览了教程并基本上运行了他们的代码:

import tensorflow as tf
import time

print("GPU is", "available" if tf.config.list_physical_devices('GPU') else "NOT AVAILABLE")

mnist = tf.keras.datasets.fashion_mnist
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
training_images  = training_images / 255.0
test_images = test_images / 255.0

model = tf.keras.models.Sequential([tf.keras.layers.Flatten(), 
                                    tf.keras.layers.Dense(128, activation=tf.nn.relu), 
                                    tf.keras.layers.Dense(10, activation=tf.nn.softmax)])



start_time = time.time()
model.compile(optimizer = tf.keras.optimizers.Adam(),
              loss = 'sparse_categorical_crossentropy',
              metrics=['accuracy'])
model.fit(training_images, training_labels, epochs=5)

print("My program took {} seconds to run".format(time.time() - start_time))

我注意到在 colab 上编译和拟合数据需要大约 17 秒。当我在确实检测到 GPU 的计算机上运行它时,执行相同的过程大约需要 13 秒。我的印象是我拥有的 GPU 会快数光年,所以我想知道我的设置出了什么问题,或者我的 GPU 使用是否不正确。

我也在运行 python 3.7.7、tensorflow 版本 2.1.0 和 keras 版本 2.2.4-tf。

【问题讨论】:

标签: python tensorflow keras tensorflow2.0


【解决方案1】:

很高兴为您提供帮助!

我认为问题在于该程序使用的计算资源很少。测试一下我的程序,也许你会看到GPU和CPU的区别~

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
import tensorflow as tf
from datetime import datetime
len=10000 # Set shape(bigger, gpu runs faster and cpu runs slower.)
device_name = gpu  # Choose device from cmd line. Options: gpu or cpu
shape = (int(len), int(len))   
if device_name == "gpu":
    device_name = "/gpu:0"
else:
    device_name = "/cpu:0"
 
with tf.device(device_name):
    # tensorflow 1.x use below:
    # random_matrix = tf.random_uniform(shape=shape, minval=0, maxval=1)
    # tensorflow 2.x use below:
    random_matrix = tf.random.uniform(shape=shape, minval=0, maxval=1)
    dot_operation = tf.matmul(random_matrix, tf.transpose(random_matrix))
    sum_operation = tf.reduce_sum(dot_operation)
 
startTime = datetime.now()

# if tf v1.x, use below:
#with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as session:

# if tf v2.x, use below:
with tf.compat.v1.Session(config=tf.ConfigProto(log_device_placement=True)) as session:
        result = session.run(sum_operation)
        print(result)
 
# It can be hard to see the results on the terminal with lots of output -- add some newlines to improve readability.
print("\n" * 5)
print("Shape:", shape, "Device:", device_name)
print("Time taken:", datetime.now() - startTime)
print("\n" * 5)

希望对你有帮助。

祝你有美好的一天:)

【讨论】:

  • 我收到AttributeError: module 'tensorflow' has no attribute 'random_uniform' 错误。我需要特定版本的 tensorflow 来运行您的代码吗?我正在运行 python 3.7.7、tensorflow 版本 2.1.0 和 keras 版本 2.2.4-tf。
  • 他的代码需要 tf 1.x 但您可以将 tf.random_uniform 更改为 tf.random.uniform 以获得 tf 2.x。
  • 而且我认为 tensorflow 2.0 不再使用 tf.Session
  • 好吧,我的电脑上没有 tf 2.0,请见谅。我将更改代码。
【解决方案2】:

解释:问题是网络不是很大。使用较小的网络,在 CPU 上训练可以正常工作,而且应该很快,这意味着在 GPU 上运行它不会有太大的改进。但是,如果您的网络更大,CPU 会更加努力,让 GPU 真正发挥作用。

类比:如果您要在 CPU 上执行 np.zeros([5]) * np.zeros([5])(乘以 2 个填充为 0 的数组),它应该需要几微秒,因为这是一项非常简单的任务,而且当您在GPU 它也应该花费类似的时间。但是假设数组有 10,000,000 个元素而不是 5 个,那么 GPU 可能会明显更快。

您的回答:真正的改进只有在 CPU 被完全利用后才会出现。对于较大的神经网络,对于 CPU 来说,矩阵乘法开始变得非常困难,以至于它完全用于这一任务。一旦神经网络足够大,CPU 已经达到极限,那么 GPU 可以比 CPU 快 10 倍甚至 20 倍,因为它可以承受更高的负载。

但是,如果您想全面更快地训练您的网络,那么您应该考虑使用图形执行进行训练。这是一种与普通执行(急切执行)不同的执行类型,后者更快(虽然略微),也是 TF 1(默认为图形执行)通常比 TF 2 快的原因。这是一个如何使用它的示例:

import tensorflow as tf
import time

print("GPU is", "available" if tf.config.list_physical_devices('GPU') else "NOT AVAILABLE")

mnist = tf.keras.datasets.fashion_mnist
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
training_images  = training_images / 255.0
test_images = test_images / 255.0

graph = tf.Graph()

with graph.as_default():
  model = tf.keras.models.Sequential([tf.keras.layers.Flatten(), 
                                    tf.keras.layers.Dense(128, activation=tf.nn.relu), 
                                    tf.keras.layers.Dense(10, activation=tf.nn.softmax)])



  start_time = time.time()
  model.compile(optimizer = tf.keras.optimizers.Adam(),
              loss = 'sparse_categorical_crossentropy',
              metrics=['accuracy'])
  model.fit(training_images, training_labels, epochs=5)

print("My program took {} seconds to run".format(time.time() - start_time))

在我的测试期间,它比急切的执行时间减少了大约一秒钟。
渴望执行:17.3 seconds 平均。
图表执行:16.3 seconds on avg

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 2021-10-31
    相关资源
    最近更新 更多