测试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"

相关推荐
Coovally AI模型快速验证2 分钟前
开放词汇3D实例分割新思路:框引导+超点融合,精准检索罕见物体
人工智能·计算机视觉·3d·语言模型·机器人·无人机
拓端研究室4 分钟前
2025机器人行业白皮书:人形机器人、工业机器人、具身智能、核心零部件|附200+份报告PDF、数据、可视化模板汇总下载
人工智能
破烂pan4 分钟前
大语言模型在翻译领域的演进与游戏本地化应用分析
人工智能·游戏·语言模型
汤汤upup5 分钟前
Nature 2025 TabPFN的使用与报错解决
人工智能·机器学习
zandy10115 分钟前
从ChatBI到Agentic BI:HENGSHI SENSE 6.0如何用AI Agent重构企业决策智能
人工智能·重构·ai agent·chatbi·agentic bi
Codebee6 分钟前
告别 “糙” 体验!Ooder 企业级 AI:重构国产企业软件的 4 大核心解决方案
人工智能
OpenCSG11 分钟前
XNet :面向大模型与数据集的块级存储与传输能力
人工智能·开源·opencsg·agentichub
文档伴侣12 分钟前
体验访答:我的私有知识库新选择
人工智能·aigc·ocr
海边夕阳200612 分钟前
【每天一个AI小知识】:什么是自注意力?
人工智能·经验分享·机器学习·强化学习·自注意力
DX_水位流量监测18 分钟前
城市易涝点水位雨量监测设备技术体系与实践应用
大数据·运维·服务器·网络·人工智能