测试tensorflow-gpu的GPU代码,观察显卡占用情况判断

# import tensorflow as tf
#
# sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(log_device_placement=True))
# 如果为False, 检查tensorflow-gpu、cudatoolkit和cudnn版本是否对应一致
# print(tf.test.is_gpu_available())


from __future__ import print_function
'''
Basic Multi GPU computation example using TensorFlow library.
Author: Aymeric Damien
Project: https://github.com/aymericdamien/TensorFlow-Examples/
'''

'''
This tutorial requires your machine to have 1 GPU
"/cpu:0": The CPU of your machine.
"/gpu:0": The first GPU of your machine
'''

import numpy as np
import tensorflow as tf
import datetime

tf.compat.v1.disable_eager_execution()

# Processing Units logs
log_device_placement = True

# Num of multiplications to perform
n = 10

'''
Example: compute A^n + B^n on 2 GPUs
Results on 8 cores with 2 GTX-980:
 * Single GPU computation time: 0:00:11.277449
 * Multi GPU computation time: 0:00:07.131701
'''
# Create random large matrix
A = np.random.rand(10000, 10000).astype('float32')
B = np.random.rand(10000, 10000).astype('float32')

# Create a graph to store results
c1 = []
c2 = []

def matpow(M, n):
    if n < 1: #Abstract cases where n < 1
        return M
    else:
        return tf.compat.v1.matmul(M, matpow(M, n-1))

'''
Single GPU computing
'''
with tf.device('/gpu:0'):
    a = tf.compat.v1.placeholder(tf.float32, [10000, 10000])
    b = tf.compat.v1.placeholder(tf.float32, [10000, 10000])
    # Compute A^n and B^n and store results in c1
    c1.append(matpow(a, n))
    c1.append(matpow(b, n))

with tf.compat.v1.device('/cpu:0'):
  sum = tf.compat.v1.add_n(c1) #Addition of all elements in c1, i.e. A^n + B^n

t1_1 = datetime.datetime.now()
with tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(log_device_placement=log_device_placement)) as sess:
    # Run the op.
    sess.run(sum, {a:A, b:B})
t2_1 = datetime.datetime.now()

print("Single GPU computation time: " + str(t2_1-t1_1))

 

### TensorFlow-GPU 安装配置及性能优化 for NVIDIA GeForce RTX 4080 #### 确认硬件支持 为了确保 TensorFlow 能够充分利用 GPU 的计算能力,确认所使用的 NVIDIA GeForce RTX 4080 显卡已安装最新的驱动程序并启用了 CUDA 支持。通常情况下,RTX 4080 是完全兼容最新版本的 CUDA 和 cuDNN。 #### 创建 Python 虚拟环境 建议创建一个新的 Python 虚拟环境来隔离依赖项,防止与其他项目发生冲突: ```bash python -m venv tensorflow_env source tensorflow_env/bin/activate # Linux/MacOS .\tensorflow_env\Scripts\activate # Windows ``` #### 更新 pip 工具 更新 `pip` 到最新版本可以提高包管理效率,并减少潜在的安装问题: ```bash pip install --upgrade pip ``` #### 安装特定版本的 TensorFlow-GPU 对于指定版本的 TensorFlow (2.6.0),使用清华大学镜像源加速下载过程是一个不错的选择: ```bash pip install tensorflow-gpu==2.6.0 -i https://pypi.tuna.tsinghua.edu.cn/simple ``` #### 验证安装 验证 TensorFlow 是否能够识别到 GPU 设备非常重要,在 Python 解释器中执行如下代码片段测试: ```python import tensorflow as tf print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU'))) ``` 如果一切正常,则会显示可用的 GPU 数量;如果有任何警告或错误消息,请按照提示解决问题后再继续下一步操作[^1]。 #### Keras 版本匹配 考虑到不同版本之间的兼容性问题,推荐安装与 TensorFlow 2.6.0 兼容的具体版本号的 Keras: ```bash pip install keras==2.3.1 ``` #### 性能调优技巧 - **启用 XLA 编译**:通过设置环境变量 `TF_XLA_FLAGS=--tf_xla_auto_jit=2` 来开启自动 JIT 编译功能; - **调整内存增长策略**:允许 TensorFlow 动态分配显存而不是一次性占用全部资源; ```python for gpu in tf.config.experimental.list_physical_devices('GPU'): tf.config.experimental.set_memory_growth(gpu, True) ``` - **利用混合精度训练**:采用 FP16 数据类型代替传统的 FP32 可显著提升模型推理速度而不明显影响准确性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值