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

相关推荐
User_芊芊君子17 小时前
AI Ping 深度评测:大模型 API 选型的 “理性决策中枢”,终结经验主义选型时代
人工智能
明天再做行么17 小时前
一些我用人工智能 翻译文章的心得
人工智能
晚霞的不甘1 天前
小智AI音箱:智能语音交互的未来之选
人工智能·交互·neo4j
飞Link1 天前
【网络与 AI 工程的交叉】多模态模型的数据传输特点:视频、音频、文本混合通道
网络·人工智能·音视频
老蒋新思维1 天前
创客匠人峰会实录:知识变现的场景化革命 —— 创始人 IP 如何在垂直领域建立变现壁垒
网络·人工智能·tcp/ip·重构·知识付费·创始人ip·创客匠人
老蒋新思维1 天前
创客匠人峰会深度解析:智能体驱动知识变现的数字资产化路径 —— 创始人 IP 的长期增长密码
人工智能·网络协议·tcp/ip·重构·知识付费·创始人ip·创客匠人
为爱停留1 天前
Spring AI实现RAG(检索增强生成)详解与实践
人工智能·深度学习·spring
像风没有归宿a1 天前
2025年人工智能十大技术突破:从AGI到多模态大模型
人工智能
深鱼~1 天前
十分钟在 openEuler 上搭建本地 AI 服务:LocalAI 快速部署教程
人工智能