1.installation
windows
1.创建一个新的Anaconda环境而不是更新
2.安装支持gpu的tensorflow-gpu,pip代码
pip3 install --upgrade tensorflow-gpu
利用Anaconda安装
2.Ubuntu安装tensorflow(linux)
要求:64位、Ubuntu16.04以上版本,NVDIA显卡,
NVDIA软件包括:CUDA® 工具包 9.0、与 CUDA 工具包 9.0 相关联的 NVIDIA 驱动程序、cuDNN v7.0
、CUDA 计算能力为 3.0 或更高的 GPU 卡(用于从源代码构建),以及 CUDA 计算能力为 3.5 或更高的 GPU 卡(用于安装我们的二进制文件)、libcupti-dev 库,这是 NVIDIA CUDA 分析工具接口。
如果您已安装前述软件包的旧版本,请升级到指定版本。如果升级不可行,您仍然可以运行支持 GPU 的 TensorFlow,但前提是您需要执行制定操作见链接
4.确定如何安装Tensorflow
1.确定安装Tensorflow的方式(annconda)
2.安装
3.验证
3.using a GPU点击打开链接
点击打开链接(官网)如果 TensorFlow 指令中兼有 CPU 和 GPU 实现,当该指令分配到设备时,GPU 设备有优先权
1.记录设备分配方式:要找出您的指令和张量被分配到哪个设备,请创建会话并将 log_device_placement
配置选项设为 True
。
2.手动分配设备:如果您希望特定指令在您选择的设备(而非系统自动为您选择的设备)上运行,您可以使用 with tf.device
创建设备上下文,这个上下文中的所有指令都将被分配在同一个设备上运行。
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.4
session = tf.Session(config=config, ...)
点击打开链接(非官网)
import sys
import numpy as np
import tensorflow as tf
from datetime import datetime
device_name = sys.argv[1] # Choose device from cmd line. Options: gpu or cpu
shape = (int(sys.argv[2]), int(sys.argv[2]))
if device_name == "gpu":
device_name = "/gpu:0"
else:
device_name = "/cpu:0"
with tf.device(device_name):
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()
with tf.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)
键入命令行
利用gpu计算代码python matmul.py gpu 1500
利用cpu计算代码python matmul.py cpu 1500
4.允许增加GPU内存
最理想的是进程只分配可用内存的一个子集,或者仅根据进程需要增加内存使用量。 TensorFlow 在 Session 上提供两个 Config 选项来进行控制。
1.allow_growth它刚开始分配很少的内存,随着 Session 开始运行并需要更多 GPU 内存,我们会扩展 TensorFlow 进程所需的 GPU 内存区域
2.per_process_gpu_memory_fraction它可以决定每个可见 GPU 应分配到的内存占总内存量的比例。例如,您可以通过以下方式指定 TensorFlow 仅分配每个 GPU 总内存的 40%
5.在多GPU系统中使用的一GPU
# Creates a graph.
with tf.device('/device:GPU:2'):
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
c = tf.matmul(a, b)
# Creates a session with log_device_placement set to True.
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
# Runs the op.
print(sess.run(c))
6.使用多个GPU
如果您的系统中有多个 GPU,则默认情况下将选择 ID 最小的 GPU。如果您希望在其他 GPU 上运行,则需要显式指定偏好设置:
更详细的例子可以参考 点击打开链接