如何在 GPU 上强制使用 tensorflow 和 Keras 运行?
How to force tensorflow and Keras run on GPU?
我在 Linux Ubuntu 中有 TensorFlow、NVIDIA GPU (CUDA)/CPU、Keras 和 Python 3.7。
我按照本教程执行了所有步骤:
https://www.youtube.com/watch?v=dj-Jntz-74g
当我运行以下代码时:
# What version of Python do you have?
import sys
import tensorflow.keras
import pandas as pd
import sklearn as sk
import tensorflow as tf
print(f"Tensor Flow Version: {tf.__version__}")
print(f"Keras Version: {tensorflow.keras.__version__}")
print()
print(f"Python {sys.version}")
print(f"Pandas {pd.__version__}")
print(f"Scikit-Learn {sk.__version__}")
gpu = len(tf.config.list_physical_devices('GPU'))>0
print("GPU is", "available" if gpu else "NOT AVAILABLE")
我得到了这些结果:
Tensor Flow Version: 2.4.1
Keras Version: 2.4.0
Python 3.7.10 (default, Feb 26 2021, 18:47:35)
[GCC 7.3.0]
Pandas 1.2.3
Scikit-Learn 0.24.1
GPU is available
但是;我不知道如何在 GPU 上 运行 我的 Keras 模型。当我 运行 我的模型时,我得到 $ nvidia-smi -l 1
,GPU 使用率在 运行 期间几乎是 %0。
from keras import layers
from keras.models import Sequential
from keras.layers import Dense, Conv1D, Flatten
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
from sklearn.metrics import r2_score
from keras.callbacks import EarlyStopping
model = Sequential()
model.add(Conv1D(100, 3, activation="relu", input_shape=(32, 1)))
model.add(Flatten())
model.add(Dense(64, activation="relu"))
model.add(Dense(1, activation="linear"))
model.compile(loss="mse", optimizer="adam", metrics=['mean_squared_error'])
model.summary()
es = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=70)
history = model.fit(partial_xtrain_CNN, partial_ytrain_CNN, batch_size=100, epochs=1000,\
verbose=0, validation_data=(xval_CNN, yval_CNN), callbacks = [es])
我是否需要更改代码的任何部分或添加部分以在 GPU 上强制执行 运行?
要在 GPU 上运行 tensorflow,有几个步骤需要完成,而且比较困难。
首先,这些框架与 NVIDIA 的兼容性比其他框架要好得多,因此如果 GPU 是 NVIDIA 并且应该在此 list。
第二件事是您需要安装所有要求:
1- GPU 驱动程序的最新版本
2- 显示 CUDA 安装 here
3- 然后安装 Anaconda 在安装时将 anaconda 添加到环境中。
所有安装完成后运行在命令提示符下执行以下命令。
conda install numba & conda install cudatoolkit
现在使用此代码评估结果:
from numba import jit, cuda
import numpy as np
# to measure exec time
from timeit import default_timer as timer
# normal function to run on cpu
def func(a):
for i in range(10000000):
a[i]+= 1
# function optimized to run on gpu
@jit(target ="cuda")
def func2(a):
for i in range(10000000):
a[i]+= 1
if __name__=="__main__":
n = 10000000
a = np.ones(n, dtype = np.float64)
b = np.ones(n, dtype = np.float32)
start = timer()
func(a)
print("without GPU:", timer()-start)
start = timer()
func2(a)
print("with GPU:", timer()-start)
此答案的部分内容来自 here,您可以阅读更多内容。
我找到了我的问题的解决方案。
我认为问题出在 NVIDIA 驱动程序、Cudnn 和 TensorFlow 的不兼容性上。因为我的笔记本电脑上有新的NVIDIA显卡(RTX 3060),它有NVIDIA Ampere Architecture GPU,可能与其他人不兼容。
相反,我参考了这些链接来下载 21.02 docker 容器,然后安装这个 docker。在 NVIDIA 提供的这个容器中,所有内容都经过测试,应该会提供良好的性能。
https://docs.nvidia.com/deeplearning/frameworks/tensorflow-wheel-release-notes/tf-wheel-rel.html
https://docs.nvidia.com/deeplearning/frameworks/tensorflow-release-notes/rel_21-02.html#rel_21-02
此外,要在 Linux 中安装 docker,您可以按照此处说明的过程进行操作:
我在 Linux Ubuntu 中有 TensorFlow、NVIDIA GPU (CUDA)/CPU、Keras 和 Python 3.7。 我按照本教程执行了所有步骤: https://www.youtube.com/watch?v=dj-Jntz-74g
当我运行以下代码时:
# What version of Python do you have?
import sys
import tensorflow.keras
import pandas as pd
import sklearn as sk
import tensorflow as tf
print(f"Tensor Flow Version: {tf.__version__}")
print(f"Keras Version: {tensorflow.keras.__version__}")
print()
print(f"Python {sys.version}")
print(f"Pandas {pd.__version__}")
print(f"Scikit-Learn {sk.__version__}")
gpu = len(tf.config.list_physical_devices('GPU'))>0
print("GPU is", "available" if gpu else "NOT AVAILABLE")
我得到了这些结果:
Tensor Flow Version: 2.4.1
Keras Version: 2.4.0
Python 3.7.10 (default, Feb 26 2021, 18:47:35)
[GCC 7.3.0]
Pandas 1.2.3
Scikit-Learn 0.24.1
GPU is available
但是;我不知道如何在 GPU 上 运行 我的 Keras 模型。当我 运行 我的模型时,我得到 $ nvidia-smi -l 1
,GPU 使用率在 运行 期间几乎是 %0。
from keras import layers
from keras.models import Sequential
from keras.layers import Dense, Conv1D, Flatten
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
from sklearn.metrics import r2_score
from keras.callbacks import EarlyStopping
model = Sequential()
model.add(Conv1D(100, 3, activation="relu", input_shape=(32, 1)))
model.add(Flatten())
model.add(Dense(64, activation="relu"))
model.add(Dense(1, activation="linear"))
model.compile(loss="mse", optimizer="adam", metrics=['mean_squared_error'])
model.summary()
es = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=70)
history = model.fit(partial_xtrain_CNN, partial_ytrain_CNN, batch_size=100, epochs=1000,\
verbose=0, validation_data=(xval_CNN, yval_CNN), callbacks = [es])
我是否需要更改代码的任何部分或添加部分以在 GPU 上强制执行 运行?
要在 GPU 上运行 tensorflow,有几个步骤需要完成,而且比较困难。
首先,这些框架与 NVIDIA 的兼容性比其他框架要好得多,因此如果 GPU 是 NVIDIA 并且应该在此 list。
第二件事是您需要安装所有要求:
1- GPU 驱动程序的最新版本 2- 显示 CUDA 安装 here 3- 然后安装 Anaconda 在安装时将 anaconda 添加到环境中。
所有安装完成后运行在命令提示符下执行以下命令。
conda install numba & conda install cudatoolkit
现在使用此代码评估结果:
from numba import jit, cuda
import numpy as np
# to measure exec time
from timeit import default_timer as timer
# normal function to run on cpu
def func(a):
for i in range(10000000):
a[i]+= 1
# function optimized to run on gpu
@jit(target ="cuda")
def func2(a):
for i in range(10000000):
a[i]+= 1
if __name__=="__main__":
n = 10000000
a = np.ones(n, dtype = np.float64)
b = np.ones(n, dtype = np.float32)
start = timer()
func(a)
print("without GPU:", timer()-start)
start = timer()
func2(a)
print("with GPU:", timer()-start)
此答案的部分内容来自 here,您可以阅读更多内容。
我找到了我的问题的解决方案。 我认为问题出在 NVIDIA 驱动程序、Cudnn 和 TensorFlow 的不兼容性上。因为我的笔记本电脑上有新的NVIDIA显卡(RTX 3060),它有NVIDIA Ampere Architecture GPU,可能与其他人不兼容。
相反,我参考了这些链接来下载 21.02 docker 容器,然后安装这个 docker。在 NVIDIA 提供的这个容器中,所有内容都经过测试,应该会提供良好的性能。
https://docs.nvidia.com/deeplearning/frameworks/tensorflow-wheel-release-notes/tf-wheel-rel.html
https://docs.nvidia.com/deeplearning/frameworks/tensorflow-release-notes/rel_21-02.html#rel_21-02
此外,要在 Linux 中安装 docker,您可以按照此处说明的过程进行操作: