首页 > 解决方案 > 在 Google Colab 上为 cpu 和 gpu 获取相同的运行时

问题描述

所以我一直在使用 Colab,以便为我的学士学位开展我的深度学习项目。当我在 colab 上运行提供的示例以测试 cpu 和 gpu 之间的比较速度时,它工作正常,但是当我尝试使用自己的代码时,两者的运行时间相同。我正在执行的任务只是使用PIL.Image包将 1000 幅 jpg 图像转换为 RGB 值。使用 gpu 时的运行时不应该更快吗?还是只有在运行深度学习模型时才会出现这种情况?请在下面找到我使用的代码:

import pandas as pd
import tensorflow as tf
import timeit

device_name = tf.test.gpu_device_name()
if device_name != '/device:GPU:0':
  raise SystemError('GPU device not found')
print('Found GPU at: {}'.format(device_name))

def cpu():
  dataset = pd.read_excel("/content/drive/My Drive/BachelorProject/labels/user_01.xlsx")
  classes = pd.read_excel("/content/drive/My Drive/BachelorProject/labels/Classes.xlsx")
  classes = list(np.array(classes).flatten())
  labels = np.array(dataset["Class"])
  labels = [classes.index(x) for x in labels]

  '''
  All the photos filename in an array
  '''
  files = np.array(dataset["Photo"])
  imgDir = "/content/drive/My Drive/BachelorProject/images_routine_users/user_01/user1_01/"
  with tf.device('/cpu:0'):
    files = np.array([convertToRGB(imgDir+x) for x in files[0:100]])

  img_width, img_height = 32, 32
  input_shape = (img_width, img_height, 3)

def gpu():
  dataset = pd.read_excel("/content/drive/My Drive/BachelorProject/labels/user_01.xlsx")
  classes = pd.read_excel("/content/drive/My Drive/BachelorProject/labels/Classes.xlsx")
  classes = list(np.array(classes).flatten())
  labels = np.array(dataset["Class"])
  labels = [classes.index(x) for x in labels]

  '''
  All the photos filename in an array
  '''
  files = np.array(dataset["Photo"])
  imgDir = "/content/drive/My Drive/BachelorProject/images_routine_users/user_01/user1_01/"
  with tf.device('/device:GPU:0'):
    files = np.array([convertToRGB(imgDir+x) for x in files[0:100]])

  img_width, img_height = 32, 32
  input_shape = (img_width, img_height, 3)

cpu()
gpu()

print('CPU (s):')
cpu_time = timeit.timeit('cpu()', number=10, setup="from __main__ import cpu")
print(cpu_time)
print('GPU (s):')
gpu_time = timeit.timeit('gpu()', number=10, setup="from __main__ import gpu")
print(gpu_time)
print('GPU speedup over CPU: {}x'.format(int(cpu_time/gpu_time)))

我得到的输出如下:

Found GPU at: /device:GPU:0
CPU (s):
167.21270494400005
GPU (s):
166.9953728999999
GPU speedup over CPU: 1x

这本质上是说 cpu 和 gpu 的运行时是相同的。希望听到你对此有什么看法。谢谢

标签: pythontensorflowgoogle-colaboratory

解决方案


TensorFlow 设备设置不会影响非 TensorFlow 操作。

也就是说,Tensorflow 现在拥有自己的numpy API,可以使用为 Tensorflow 设置的设备,例如with tf.device('/device:GPU:0').

新的 api 可以与 numpy 类似地使用

import tensorflow.experimental.numpy as tnp

这也是一篇关于新 api 与普通(cpu)numpy 性能比较的不错的博客文章。

这是一个关于在 colab 上使用 gpu 和普通 python 的相关问题。


推荐阅读