机器学习使用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)
相关推荐
武天旭几秒前
AI安全--AI大模型的漏洞攻防与数据投毒风险
人工智能·安全
智恒百亿2 分钟前
RTX 5090 多卡集群工程实践:消费旗舰卡搭建 8 卡算力平台的坑与边界
服务器·人工智能·ai算力·rtx5090
JavaEdge.3 分钟前
Qodo v.s AI IDE Code Review
ide·人工智能·代码复审
for_ever_love__4 分钟前
LangChain 多工具协作:一个 Agent 不够用时怎么办
人工智能·langchain·langgraph·协作·多agent·多工具·工具编排
野生码农AI实战4 分钟前
我把P1迭代丢给免费模型MIMO:4.4小时干完,全口径token账7233万
人工智能
小飞象—木兮5 分钟前
经营分析核心思路:经营分析的六层执行框架、底层原则、 全行业通用经营分析方法论
大数据·人工智能·矩阵·数据分析·用户运营
luiyarch6 分钟前
TBOX信息安全系列6设计篇-系统数据安全方案
人工智能·安全·车载系统·汽车
for_ever_love__7 分钟前
LangChain 效果评测:没有评测,优化就是在瞎调
人工智能·学习·langchain·rag·评估·langsmith·评测指标
得物技术8 分钟前
动态规则的 Agent 实践:用确定性工程驾驭 LLM 的资产智能验收
人工智能·后端·llm
投资者内参9 分钟前
高通CEO安蒙重磅发声:有AI厂商要求2028年在手机上跑千亿参数大模型,AI竞争从模型向终端延伸,手机换机潮将至,最看好智能眼镜
人工智能