测试TensorFlow/PyTorch的GPU版本是否启用

文章目录

  • [1. Pytorch测试代码](#1. Pytorch测试代码)
  • [2. TensorFlow测试代码](#2. TensorFlow测试代码)

后续遇到好的会不断更新。。。


1. Pytorch测试代码

python 复制代码
import torch
def gpu_is_available():
    print('\nGPU details:')
    print(f'    gpu_is_available      : ', torch.cuda.is_available())
    print(f'    cuda_device_count     : ', torch.cuda.device_count())
    print(f'    cuda_device_name      : ', torch.cuda.get_device_name())
    print(f'    cuda_device_capability: ', torch.cuda.get_device_capability(0))
gpu_is_available()

来源:"PyTorch快速安装并验证GPU是否可用"

python 复制代码
#测试pytorch-gpu是否能用
import torch
flag = torch.cuda.is_available()
print(flag)
ngpu= 1
# Decide which device we want to run on
device = torch.device("cuda:0" if (torch.cuda.is_available() and ngpu > 0) else "cpu")
print('cuda设备名:',device)
print('gpu名称:',torch.cuda.get_device_name(0))
print('pytorch版本:',torch.__version__)
print('cuda版本:',torch.version.cuda)
print('cudnn版本号:',torch.backends.cudnn.version())
print('定义一个torch格式的3*3的矩阵:',torch.rand(3,3).cuda())

来源:"如何测试pytorch-gpu版本和tensorflow-gpu版本是否安装成功"

python 复制代码
import torch
# 使用GPU训练
if not torch.cuda.is_available():
    print('CUDA is not available.  Training on CPU ...')
else:
    print('CUDA is available.  Training on GPU ...')
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

来源:"深入学习之anaconda、pytorch、cuda安装"

python 复制代码
#coding=gbk
import torch

# 定义张量的形状和大小
shape = (100, 1000)
num_tensors = 50000

device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
data = [torch.rand(shape, device=device) for _ in range(num_tensors)]

total_sum = torch.tensor([0.0])
for tensor in data:
    total_sum += tensor.sum().cpu()

print('Total sum:', total_sum.item())

来源:"测试pytorch-gpu"

2. TensorFlow测试代码

python 复制代码
#测试tensorflow-gpu是否能用
import tensorflow as tf
print('\n\nGPU',tf.config.list_physical_devices('GPU'))
a = tf.constant(2.)
b = tf.constant(4.)
print('打印a*b:',a * b)
print("tensorflow版本:", tf.__version__)

来源:"如何测试pytorch-gpu版本和tensorflow-gpu版本是否安装成功"

python 复制代码
import tensorflow as tf
print(tf.test.is_gpu_available())

来源:"检测安装Tensorflow后是否成功调用GPU"

相关推荐
只是有点小怂13 分钟前
【PYG】处理Cora数据集分类任务使用的几个函数log_softmax,nll_loss和argmax
人工智能·分类·数据挖掘
TechLead KrisChang22 分钟前
合合信息大模型“加速器”重磅上线
人工智能·深度学习·机器学习
SEU-WYL23 分钟前
基于深度学习的电力分配
人工智能·深度学习·dnn
Wincyfu24 分钟前
FuTalk设计周刊-Vol.064
人工智能·ui·aigc
空青72625 分钟前
ChatGPT在Java后端开发中的应用与影响
java·开发语言·人工智能·后端·神经网络·机器学习·chatgpt
只是有点小怂35 分钟前
【PYG】 PyTorch中size方法和属性
人工智能·pytorch·python
黑白企鹅鹅35 分钟前
云计算与AI技术融合:AWS、代理、RPA和面部识别机器人的协同创新
人工智能·机器人·云计算·aws·rpa
小魔王降临1 小时前
图像练习-识别中圆形锡点 (04)
人工智能·计算机视觉
光电的一只菜鸡1 小时前
相机光学(二十五)——数字相机和模拟相机
人工智能·数码相机
Czi.2 小时前
Build a Large Language Model (From Scratch)附录E(gpt-4o翻译版)
人工智能·语言模型·自然语言处理