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

相关推荐
ACP广源盛139246256731 分钟前
M6/M5 Pro Mac mini 端侧 AI 爆发@ACP#YLB3118 存储扩展芯片在本地 AI 服务中的机会与落地场景
大数据·网络·数据库·人工智能·嵌入式硬件·macos
Rain5096 分钟前
谁动了我的 URL?——记一次微前端“灵异 Bug“的排查实录
前端·vue.js·人工智能·前端框架·bug·ai编程
外域速览10 分钟前
OpenAI Astra 跨过「高危红线」、李飞飞世界模型 Atlas 落地:AI 行业进入「安全与落地」双拐点
人工智能·安全
Mr数据杨11 分钟前
莫斯科公寓价格预测实战 从 Kaggle 房价回归到可落地估值流程
人工智能·数据分析·kaggle竞赛
故七月13 分钟前
产业观察|从 9 月行业数据看西南市场 GEO 落地现状与发展路径
大数据·人工智能
丶浅行DE时光16 分钟前
管道式电磁流量计选型指南 介质腐蚀与工况适配方案推荐
大数据·网络·人工智能·科技·推荐算法
电子科技圈16 分钟前
芯科科技在IOTE 2026上以全栈无线连接与边缘AI展现其在智能网联领域的卓越领导力
人工智能·科技
Ro Jace17 分钟前
基于深度学习的图像处理方法
图像处理·人工智能·深度学习
Y_Mathison19 分钟前
Agent安全护栏设计:权限控制、对抗鲁棒性与人工确认环
人工智能·ai
KKKlucifer19 分钟前
多模态数据精准识别:智能分类分级引擎在运营商场景的技术突破
人工智能·分类·数据挖掘