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

相关推荐
大模型真好玩22 分钟前
LangChain DeepAgents 速通指南(三)—— 让Agent告别混乱:Tool Selector与Todo List中间件解析
人工智能·langchain·trae
孟祥_成都1 小时前
【全网最通俗!新手到AI全栈开发必读】 AI 是如何进化到大模型的
前端·人工智能·全栈
牛奶1 小时前
AI辅助开发的基础概念
前端·人工智能·ai编程
东坡肘子1 小时前
OpenClaw 不错,但我好像没有那么需要 -- 肘子的 Swift 周报 #125
人工智能·swiftui·swift
风象南9 小时前
普通人用AI加持赚到的第一个100块
人工智能·后端
牛奶9 小时前
2026年大模型怎么选?前端人实用对比
前端·人工智能·ai编程
牛奶9 小时前
前端人为什么要学AI?
前端·人工智能·ai编程
罗西的思考12 小时前
AI Agent框架探秘:拆解 OpenHands(10)--- Runtime
人工智能·算法·机器学习
冬奇Lab13 小时前
OpenClaw 源码精读(2):Channel & Routing——一条消息如何找到它的 Agent?
人工智能·开源·源码阅读
冬奇Lab13 小时前
一天一个开源项目(第38篇):Claude Code Telegram - 用 Telegram 远程用 Claude Code,随时随地聊项目
人工智能·开源·资讯