机器学习使用GPU

使用GPU

使用下面的命令来查看GPU的状态

shell 复制代码
!nvidia-smi
代码 含义
Memory-Usage 内存使用量/总量
GPU-Util (运行时)GPU使用量
CUDA Version CUDA的版本, 需要对应版本的框架

使用GPU运算

张量
python 复制代码
import torch

torch.device('cpu')
torch.device('cuda') # 使用GPU
torch.device('cuda:1')  # 访问第一个GPU

查看有多少GPU

python 复制代码
torch.cuda.device_count()

测试GPU环境

python 复制代码
def try_gpu(i=0):
	if torch.cuda.device_count() >= i + 1:
		return torch.device(f'cuda:{i}')
	return torch.device('cpu')

def try_all_gpu():
	devices = [torch.device(f'cuda:{i}') for i in range(torch.cuda.device_count())]
	return devices if devices else [torch.device('cpu')]

查询张量所在的设备

python 复制代码
x = torch.tensor([1, 2, 3])
x.device # device(type='cpu')

存储在gpu

python 复制代码
X = torch.ones(2, 3, device=try_gpu())
X # tensor(..., device='cuda:0')

第二个GPU创建张量

python 复制代码
X = torch.ones(2, 3, device=try_gpu(1))
X # tensor(..., device='cuda:1')

计算X, Y, 需要确定在同一个GPU执行计算操作

python 复制代码
Z = X.cuda(1)
Z # tensor(..., device='cuda:1')

Z.cuda(1) is Z  # True, 如果已经在对应的GPU, 不会做任何改变和开销

如果将不同的层分散放在CPU和GPU, 计算时会造成很大开销和性能问题, 并且不易排查, 所以最开始初始化就建议使用一个环境, 不要来回COPY切换

神经网络

神经网络在GPU

python 复制代码
net = nn.Sequential(nn.Linear(3, 1))
net = net.to(device=try_gpu())

net(X)

确认模型参数存储在同一个GPU

python 复制代码
net[0].weight.data.device # device(type='cuda',index=0)
相关推荐
开源技术19 分钟前
深入了解Turso,这个“用Rust重写的SQLite”
人工智能·python
初恋叫萱萱21 分钟前
构建高性能生成式AI应用:基于Rust Axum与蓝耘DeepSeek-V3.2大模型服务的全栈开发实战
开发语言·人工智能·rust
水如烟7 小时前
孤能子视角:“组织行为学–组织文化“
人工智能
大山同学8 小时前
图片补全-Context Encoder
人工智能·机器学习·计算机视觉
薛定谔的猫19828 小时前
十七、用 GPT2 中文对联模型实现经典上联自动对下联:
人工智能·深度学习·gpt2·大模型 训练 调优
壮Sir不壮8 小时前
2026年奇点:Clawdbot引爆个人AI代理
人工智能·ai·大模型·claude·clawdbot·moltbot·openclaw
PaperRed ai写作降重助手8 小时前
高性价比 AI 论文写作软件推荐:2026 年预算友好型
人工智能·aigc·论文·写作·ai写作·智能降重
玉梅小洋8 小时前
Claude Code 从入门到精通(七):Sub Agent 与 Skill 终极PK
人工智能·ai·大模型·ai编程·claude·ai工具
-嘟囔着拯救世界-8 小时前
【保姆级教程】Win11 下从零部署 Claude Code:本地环境配置 + VSCode 可视化界面全流程指南
人工智能·vscode·ai·编辑器·html5·ai编程·claude code
正见TrueView8 小时前
程一笑的价值选择:AI金玉其外,“收割”老人败絮其中
人工智能