在 Tensorflow 中训练简单模型 GPU 比 CPU 慢

2024-03-27

我在 Tensorflow 中设置了一个简单的线性回归问题,并在 1.13.1 中使用 Tensorflow CPU 和 GPU 创建了简单的 conda 环境(在 NVIDIA Quadro P600 的后端使用 CUDA 10.0)。

然而,GPU 环境似乎总是比 CPU 环境花费更长的时间。我正在运行的代码如下。

import time
import warnings
import numpy as np
import scipy

import tensorflow as tf
import tensorflow_probability as tfp

from tensorflow_probability import edward2 as ed
from tensorflow.python.ops import control_flow_ops
from tensorflow_probability import distributions as tfd



# Handy snippet to reset the global graph and global session.
def reset_g():
    with warnings.catch_warnings():
        warnings.simplefilter('ignore')
        tf.reset_default_graph()
        try:
            sess.close()
        except:
            pass


N = 35000
inttest = np.ones(N).reshape(N, 1)
stddev_raw = 0.09

true_int = 1.
true_b1 = 0.15
true_b2 = 0.7

np.random.seed(69)

X1 = (np.atleast_2d(np.linspace(
    0., 2., num=N)).T).astype(np.float64)
X2 = (np.atleast_2d(np.linspace(
    2., 1., num=N)).T).astype(np.float64)
Ytest = true_int + (true_b1*X1) + (true_b2*X2) + \
    np.random.normal(size=N, scale=stddev_raw).reshape(N, 1)

Ytest = Ytest.reshape(N, )
X1 = X1.reshape(N, )
X2 = X2.reshape(N, )

reset_g()

# Create data and param
model_X1 = tf.placeholder(dtype=tf.float64, shape=[N, ])
model_X2 = tf.placeholder(dtype=tf.float64, shape=[N, ])
model_Y = tf.placeholder(dtype=tf.float64, shape=[N, ])

alpha = tf.get_variable(shape=[1], name='alpha', dtype=tf.float64)
# these two params need shape of one if using trainable distro
beta1 = tf.get_variable(shape=[1], name='beta1', dtype=tf.float64)
beta2 = tf.get_variable(shape=[1], name='beta2', dtype=tf.float64)

# Yhat
tf_pred = (tf.multiply(model_X1, beta1) + tf.multiply(model_X2, beta2) + alpha)


# # Make difference of squares
# resid = tf.square(model_Y - tf_pred)
# loss = tf.reduce_sum(resid)

# # Make a Likelihood function based on simple stuff
stddev = tf.square(tf.get_variable(shape=[1],
                                    name='stddev', dtype=tf.float64))
covar = tfd.Normal(loc=model_Y, scale=stddev)
loss = -1.0*tf.reduce_sum(covar.log_prob(tf_pred))



# Trainer
lr=0.005
N_ITER = 20000

opt = tf.train.AdamOptimizer(lr, beta1=0.95, beta2=0.95)
train = opt.minimize(loss)


with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    start = time.time()
    for step in range(N_ITER):
        out_l, out_b1, out_b2, out_a, laws = sess.run([train, beta1, beta2, alpha, loss],
                                                  feed_dict={model_X1: X1,
                                                             model_X2: X2,
                                                             model_Y: Ytest})

        if step % 500 == 0:
            print('Step: {s}, loss = {l}, alpha = {a:.3f}, beta1 = {b1:.3f}, beta2 = {b2:.3f}'.format(
                s=step, l=laws, a=out_a[0], b1=out_b1[0], b2=out_b2[0]))
    print(f"True: alpha = {true_int}, beta1 = {true_b1}, beta2 = {true_b2}")
    end = time.time()
    print(end-start)

以下是一些打印的输出(如果它们可以指示正在发生的情况):

对于CPU运行:

Colocations handled automatically by placer.
2019-04-18 09:00:56.329669: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
2019-04-18 09:00:56.351151: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 2904000000 Hz
2019-04-18 09:00:56.351672: I tensorflow/compiler/xla/service/service.cc:150] XLA service 0x558fefe604c0 executing computations on platform Host. Devices:
2019-04-18 09:00:56.351698: I tensorflow/compiler/xla/service/service.cc:158]   StreamExecutor device (0): <undefined>, <undefined>

对于 GPU 运行:

Instructions for updating:
Call initializer instance with the dtype argument instead of passing it to the constructor
W0418 09:03:21.674947 139956864096064 deprecation.py:506] From /home/sadatnfs/.conda/envs/tf_gpu/lib/python3.6/site-packages/tensorflow/python/training/slot_creator.py:187: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.
Instructions for updating:
Call initializer instance with the dtype argument instead of passing it to the constructor
2019-04-18 09:03:21.712913: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
2019-04-18 09:03:21.717598: I tensorflow/stream_executor/platform/default/dso_loader.cc:42] Successfully opened dynamic library libcuda.so.1
2019-04-18 09:03:21.951277: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:1009] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2019-04-18 09:03:21.952212: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x55e583bc4480 executing computations on platform CUDA. Devices:
2019-04-18 09:03:21.952225: I tensorflow/compiler/xla/service/service.cc:175]   StreamExecutor device (0): Quadro P600, Compute Capability 6.1
2019-04-18 09:03:21.971218: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 2904000000 Hz
2019-04-18 09:03:21.971816: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x55e58577f290 executing computations on platform Host. Devices:
2019-04-18 09:03:21.971842: I tensorflow/compiler/xla/service/service.cc:175]   StreamExecutor device (0): <undefined>, <undefined>
2019-04-18 09:03:21.972102: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1551] Found device 0 with properties:
name: Quadro P600 major: 6 minor: 1 memoryClockRate(GHz): 1.5565
pciBusID: 0000:01:00.0
totalMemory: 1.95GiB freeMemory: 1.91GiB
2019-04-18 09:03:21.972147: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1674] Adding visible gpu devices: 0
2019-04-18 09:03:21.972248: I tensorflow/stream_executor/platform/default/dso_loader.cc:42] Successfully opened dynamic library libcudart.so.10.0
2019-04-18 09:03:21.973094: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1082] Device interconnect StreamExecutor with strength 1 edge matrix:
2019-04-18 09:03:21.973105: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1088]      0
2019-04-18 09:03:21.973110: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1101] 0:   N
2019-04-18 09:03:21.973279: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1222] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 1735 MB memory) -> physical GPU (device: 0, name: Quadro P600, pci bus id: 0000:01:00.0, compute capability: 6.1)

我即将发布另一个关于在 R 中实现 CUBLAS 的问题,因为与 Intel MKL 相比,这给了我较慢的速度时间,但我希望也许有一个明确的原因,为什么即使是像 TF 一样构建良好的东西(与hacky R 和 CUBLAS 补丁)在 GPU 上运行缓慢。


EDIT:下列的弗拉德的建议 https://stackoverflow.com/questions/55749899/training-a-simple-model-in-tensorflow-gpu-slower-than-cpu#comment98177427_55749899,我编写了以下脚本来尝试抛出一些大型对象并对其进行训练,但我认为我可能没有正确设置它,因为在这种情况下,即使矩阵的大小在增加,CPU 也是如此。也许有什么建议吗?

import time
import warnings
import numpy as np
import scipy

import tensorflow as tf
import tensorflow_probability as tfp

from tensorflow_probability import edward2 as ed
from tensorflow.python.ops import control_flow_ops
from tensorflow_probability import distributions as tfd

np.random.seed(69)

# Handy snippet to reset the global graph and global session.
def reset_g():
    with warnings.catch_warnings():
        warnings.simplefilter('ignore')
        tf.reset_default_graph()
        try:
            sess.close()
        except:
            pass


# Loop over the different number of feature columns
for x_feat in [30, 50, 100, 1000, 10000]:

    y_feat=10;
    # Simulate data
    N = 5000
    inttest = np.ones(N).reshape(N, 1)
    stddev_raw = np.random.uniform(0.01, 0.25, size=y_feat)

    true_int = np.linspace(0.1 ,1., num=y_feat)
    xcols = x_feat
    true_bw = np.random.randn(xcols, y_feat)
    true_X = np.random.randn(N, xcols)
    true_errorcov = np.eye(y_feat)
    np.fill_diagonal(true_errorcov, stddev_raw)

    true_Y = true_int + np.matmul(true_X, true_bw) + \
        np.random.multivariate_normal(mean=np.array([0 for i in range(y_feat)]),
                                      cov=true_errorcov,
                                      size=N)


    ## Our model is:
    ## Y = a + b*X + error where, for N=5000 observations:
    ## Y : 10 outputs;
    ## X : 30,50,100,1000,10000 features
    ## a, b = bias and weights
    ## error: just... error

    # Number of iterations
    N_ITER = 1001

    # Training rate
    lr=0.005

    with tf.device('gpu'):

        # Create data and weights
        model_X = tf.placeholder(dtype=tf.float64, shape=[N, xcols])
        model_Y = tf.placeholder(dtype=tf.float64, shape=[N, y_feat])

        alpha = tf.get_variable(shape=[y_feat], name='alpha', dtype=tf.float64)
        # these two params need shape of one if using trainable distro
        betas = tf.get_variable(shape=[xcols, y_feat], name='beta1', dtype=tf.float64)


        # Yhat
        tf_pred = alpha + tf.matmul(model_X, betas)

        # Make difference of squares (loss fn) [CONVERGES TO TRUTH]
        resid = tf.square(model_Y - tf_pred)
        loss = tf.reduce_sum(resid)

        # Trainer
        opt = tf.train.AdamOptimizer(lr, beta1=0.95, beta2=0.95)
        train = opt.minimize(loss)


    sess = tf.Session()
    sess.run(tf.global_variables_initializer())

    start = time.time()
    for step in range(N_ITER):
        out_l, laws = sess.run([train, loss], feed_dict={model_X: true_X, model_Y: true_Y})

        if step % 500 == 0:
            print('Step: {s}, loss = {l}'.format(
                s=step, l=laws))
    end = time.time()
    print("y_feat: {n}, x_feat: {x2}, Time elapsed: {te}".format(n = y_feat, x2 = x_feat, te = end-start))

    reset_g()

正如我在评论中所说,调用 GPU 内核以及将数据复制到 GPU 或从 GPU 复制数据的开销非常高。对于参数很少的模型的操作,不值得使用 GPU,因为 CPU 核心的频率要高得多。如果比较矩阵乘法(这是深度学习主要做的事情),您会发现对于大型矩阵,GPU 的性能显着优于 CPU。

看看这个情节。 X 轴是两个方阵的大小,y 轴是在 GPU 和 CPU 上将这些矩阵相乘所需的时间。正如您在一开始所看到的,对于小矩阵,蓝线更高,这意味着 CPU 速度更快。但随着我们增加矩阵的大小,使用 GPU 的好处就会显着增加。

要重现的代码:

import tensorflow as tf
import time
cpu_times = []
sizes = [1, 10, 100, 500, 1000, 2000, 3000, 4000, 5000, 8000, 10000]
for size in sizes:
    tf.reset_default_graph()
    start = time.time()
    with tf.device('cpu:0'):
        v1 = tf.Variable(tf.random_normal((size, size)))
        v2 = tf.Variable(tf.random_normal((size, size)))
        op = tf.matmul(v1, v2)

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        sess.run(op)
    cpu_times.append(time.time() - start)
    print('cpu time took: {0:.4f}'.format(time.time() - start))

import tensorflow as tf
import time

gpu_times = []
for size in sizes:
    tf.reset_default_graph()
    start = time.time()
    with tf.device('gpu:0'):
        v1 = tf.Variable(tf.random_normal((size, size)))
        v2 = tf.Variable(tf.random_normal((size, size)))
        op = tf.matmul(v1, v2)

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        sess.run(op)
    gpu_times.append(time.time() - start)
    print('gpu time took: {0:.4f}'.format(time.time() - start))

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(8, 6))
ax.plot(sizes, gpu_times, label='GPU')
ax.plot(sizes, cpu_times, label='CPU')
plt.xlabel('MATRIX SIZE')
plt.ylabel('TIME (sec)')
plt.legend()
plt.show()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Tensorflow 中训练简单模型 GPU 比 CPU 慢 的相关文章

  • 静态文件配置不正确

    我已经在 Heroku 上部署了简单的博客应用程序 它运行在Django 1 8 4 我在静态文件方面遇到了一些问题 当打开我的应用程序时 我看到Application Error页面 所以我尝试调试它并发现当我提交到 Heroku 时它无
  • 创建圆形图像 PIL Tkinter

    Currently I have a zoom feature in my application that works very well however I d like the actual zoom box to be a circ
  • 如何在Python中的BeautifulSoup4中使用.next_sibling时忽略空行

    由于我想删除 html 网站中重复的占位符 因此我使用 BeautifulSoup 的 next sibling 运算符 只要重复项位于同一行 就可以正常工作 参见数据 但有时它们之间有一个空行 所以我希望 next sibling 忽略它
  • 通过鼻子测试检查某个函数是否发出警告

    我正在使用编写单元测试nose http somethingaboutorange com mrl projects nose 0 11 2 我想检查函数是否引发警告 该函数使用warnings warn 这是很容易就能做到的事情吗 def
  • 十六进制数的按位异或

    我们如何在 Python 中对十六进制数进行异或 例如 我想要异或 ABCD and 12EF 答案应该是 B922 我使用了下面的代码 但它给出了错误的结果 xor two strings of different lengths def
  • 在加载“cv2”二进制扩展期间检测到递归

    我有一个小程序 在 pyinstaller 编译后返回 opencv 错误 但无需编译即可工作 我在 Windows 10 上使用 Python 3 8 10 Program 导入 pyautogui将 numpy 导入为 np导入CV2
  • 在 keras 中使用自定义张量流操作

    我在张量流中有一个脚本 其中包含自定义张量流操作 我想将代码移植到 keras 但我不确定如何在 keras 代码中调用自定义操作 我想在 keras 中使用tensorflow 所以到目前为止我发现的教程描述了与我想要的相反的内容 htt
  • 使用 Python 的文本中的词频但忽略停用词

    这给了我文本中单词的频率 fullWords re findall r w allText d defaultdict int for word in fullWords d word 1 finalFreq sorted d iterit
  • 在函数调用之间保存数据的Pythonic方式是什么?

    对我来说 上下文是我需要在调用修改该值的函数之间保留的单个 int 的信息 我可以使用全局 但我知道这是不鼓励的 现在 我使用了包含 int 的列表形式的默认参数 并利用了可变性 以便在调用之间保留对值的更改 如下所示 def increm
  • 如何使用 python 操作系统更改驱动器?

    我正在尝试更改当前目录C to Y 我试过 import os os chdir Y 但我不断收到错误消息 提示无法找到驱动器 本质上我正在寻找相当于 cd d cmd 中的命令 你确定吗Y 确实是有效的驱动器号吗 Try os chdir
  • 如何使用 jira-python 设置 fixVersions 字段

    我正在尝试使用 jira python 模块 http jira python readthedocs org en latest 更新现有的 JIRA 具体来说 我正在尝试设置问题的fixesVersion 列表 我已经尝试了一段时间但没
  • Floyd-Warshall 算法:获取最短路径

    假设一个图由一个表示n x n维数邻接矩阵 我知道如何获得所有对的最短路径矩阵 但我想知道有没有办法追踪所有最短路径 Blow是python代码实现 v len graph for k in range 0 v for i in range
  • 为 Python 2.4 改进“with”语句的直接替换

    您能否建议一种方法来编写可在 Python 2 4 中使用的 with 语句的直接替换代码 这将是一个 hack 但它可以让我更好地将我的项目移植到 Python 2 4 EDIT 删除了不相关的元类草图 只需使用 try finally
  • 如何在 Python 中执行相当于预处理器指令的操作?

    有没有办法在 Python 中执行以下预处理器指令 if DEBUG lt do some code gt else lt do some other code gt endif There s debug 这是编译器预处理的特殊值 if
  • PyQt - 如何检查 QDialog 是否可见?

    我有个问题 我有这个代码 balls Ball for i in range 1 10 因此 当我说 Ball 时 这将在 QDialog 上绘制一个球 然后当这完成后 我正在移动球QDialog无限循环中 我想说类似的话while QDi
  • 向量化 numpy bincount

    我有一个 2d numpy 数组 A我要申请np bincount 到矩阵的每一列A生成另一个二维数组B由原始矩阵每列的 bincounts 组成A 我的问题是 np bincount 是一个采用一维数组的函数 它不是像这样的数组方法B A
  • 网页抓取 - 如何识别网页上的主要内容

    给定一个新闻文章网页 来自任何主要新闻来源 例如时报或彭博社 我想识别该页面上的主要文章内容 并丢弃其他杂项元素 例如广告 菜单 侧边栏 用户评论 在大多数主要新闻网站上都可以使用的通用方法是什么 有哪些好的数据挖掘工具或库 最好是基于Py
  • 测试中的模型 - Django 1.7 问题

    我正在尝试将我的项目移植为使用 Django 1 7 除了一件事之外 一切都很好 测试文件夹内的模型 Django 1 7 新迁移在内部运行 migrate 命令 在运行syncdb之前 这意味着如果模型未包含在迁移中 它将不会填充到数据库
  • 如何使用 Python 将我的 GoPro Hero 4 相机直播连接到 openCV?

    我在尝试从我的新 GoPro Hero 4 相机捕获实时流并使用 openCV 对其进行一些图像处理时遇到麻烦 这是我的试用 创建的窗口上没有显示任何内容 import cv2 import argparse import time imp
  • 在读/写二进制数据结构时访问位域

    我正在为二进制格式编写一个解析器 这种二进制格式涉及不同的表 这些表同样采用二进制格式 通常包含不同的字段大小 其中 50 100 个之间 大多数这些结构都有位域 并且在 C 语言中表示时看起来像这样 struct myHeader uns

随机推荐

  • Pygame 缩放精灵

    如何将精灵的图像放大或缩小 我可以更改矩形和所有内容 但不能更改图像 代码 虽然我不确定为什么你需要它 class test pygame sprite Sprite def init self pygame sprite Sprite i
  • .net - C# 2.0 应用程序中的玻璃效果

    如何在 net 2 0 中的 Windows 窗体应用程序上提供 Vista 或 Mac OS X 风格的玻璃效果 这是通过使用 Vista DWM 桌面窗口管理器 API 的互操作来完成的 例如 导入这些函数 DllImport dwma
  • @BeanProperty 具有 PropertyChangeListener 支持吗?

    BeanProperty生成简单的get set方法 有没有办法自动生成此类方法并支持触发属性更改事件 例如 我想将其与 JFace 数据绑定一起使用 我也有同样的问题 并一直在密切关注可能的答案 我想我刚刚偶然发现了一个 尽管我还没有尝试
  • 类路径中的 Flutter 运行时 JAR 文件应具有相同的版本

    Building without sound null safety For more information see https dart dev null safety unsound null safety w Runtime JAR
  • 小阴谋家 - 从哪里开始?

    我刚刚打开 小阴谋家 我觉得我错过了一些东西 第一个问题问 这是一个原子吗 但我没有看到原子是什么的任何定义 我想我可以通过问题的答案推导出什么是原子 但随后它继续问 l 的 car 是什么 l 的 cdr 是什么 我不知道在问什么 这本书
  • AngularJS:工厂 $http 服务

    我试图理解 Angular 中工厂和服务的概念 我在控制器下有以下代码 init function init http post services type getSource ID TP001 success function data
  • Java:具有重复键的 Json 可以使用 Jackson 进行映射

    我有一个具有相同键但不同值的 json 文件 如下所示 domains A name a type a1 B name r type g1 A name b type b1 这是来自外部系统 如何转换json 到 java 映射对象并访问不
  • JQuery 如何 .find() 不区分大小写?

  • Fabric.loadSVGFromString 导致结果扭曲

    我用 inkscape 编辑了 SVG
  • 如何在xtable表格中放置颜色间距?

    如何在xtable表格中放置颜色间距 我使用以下说明生成表格 test table lt xtable summary test caption test floating FALSE align test table lt c l pri
  • DataGridView 中明显的内存泄漏

    如何强制 DataGridView 释放其对绑定 DataSet 的引用 我们有一个相当大的数据集显示在 DataGridView 中 并注意到 DataGridView 关闭后资源没有被释放 如果用户重复查看此报告 他们最终会收到内存不足
  • 我在 intellij 中的 jar 资源文件是只读的,我需要编辑它们

    我已经尝试了几个小时来编辑我用作库的 jar 中的 java 文件 但没有成功 我已将资源标记为内容根和源根 但我仍然无法编辑 jar 中的代码 该项目编译并运行正确 但我需要对资源文件进行调整 但不能 我尝试了所有我能想到的项目结构 难道
  • kotlin如何通过delegate使用this来实例化viewmodel

    我正在阅读 google android 架构示例并遇到了这个 有人可以向我解释这个代表是如何工作的吗 private val viewModel by viewModels
  • 如何在C++中“返回一个对象”?

    我知道这个标题听起来很熟悉 因为有很多类似的问题 但我要求问题的不同方面 我知道将东西放在堆栈上和将它们放在堆上之间的区别 在Java中我总是可以返回对 本地 对象的引用 public Thing calculateThing Thing
  • Mono 可以在 rdlc 中创建/运行报告吗?

    我从未使用过 mono 很好奇 mono 是否可以创建 运行 rdlc 报告 我正在寻找实现的是一个单声道 asp net mvc 应用程序 用于使用 rdlc 创建报告并导出为 pdf 单声道可以吗 有一些开源项目尝试在 NET 中实现
  • twitter 没有重定向到 android 应用程序中的回调 url

    我的目标是允许使用 twitter4j 登录 Twitter 我用这个作为参考 https github com Sheikh Aman Android Samples blob master 1 20Sign inWithTwitterT
  • Jsoup:忽略 SSL 错误

    我正在尝试下载https www deviantart com https www deviantart com使用 Jsoup v1 10 3 以及validateTLSCertificates false Java 8 已安装 Unli
  • 使用 OpenTok 暂停视频通话

    我一直在研究 webRTC 平台 发现 OpenTok 似乎提供了最可定制的功能 在深入研究之前 我想确保它可以满足一项关键要求 在两个用户 A 和 B 之间的 1 1 视频通话期间 我希望其中一个用户 让我们与用户 A 一起 能够接收来自
  • Django - 无法获取 highchart 来显示数据

    我尝试按照以下解决方案在 Highchart 的帮助下显示图表 通过 JSON 将 Django 数据库查询集传递到 Highcharts https stackoverflow com questions 27810087 passing
  • 在 Tensorflow 中训练简单模型 GPU 比 CPU 慢

    我在 Tensorflow 中设置了一个简单的线性回归问题 并在 1 13 1 中使用 Tensorflow CPU 和 GPU 创建了简单的 conda 环境 在 NVIDIA Quadro P600 的后端使用 CUDA 10 0 然而