解决pytorch训练的过程中内存一直增加的问题

来自:解决pytorch训练的过程中内存一直增加的问题 - 知乎

pytorch训练中内存一直增加的原因(部分)

  • 代码中存在累加loss,但每步的loss没加item()

    import torch
    import torch.nn as nn
    from collections import defaultdict

    if torch.cuda.is_available():
    device = 'cuda'
    else:
    device = 'cpu'

    model = nn.Linear(100, 400).to(device)
    criterion = nn.L1Loss(reduction='mean').to(device)
    optimizer = torch.optim.Adam(model.parameters(), lr=0.001)

    train_loss = defaultdict(float)
    eval_loss = defaultdict(float)

    for i in range(10000):
    model.train()
    x = torch.rand(50, 100, device=device)
    y_pred = model(x) # 50 * 400
    y_tgt = torch.rand(50, 400, device=device)

    复制代码
      loss = criterion(y_pred, y_tgt)
      optimizer.zero_grad()
      loss.backward()
      optimizer.step()
      
      # 会导致内存一直增加,需改为train_loss['loss'] += loss.item()
      train_loss['loss'] += loss
    
      if i % 100 == 0:
          train_loss = defaultdict(float)
          model.eval()
          x = torch.rand(50, 100, device=device)
          y_pred = model(x) # 50 * 400
    
          y_tgt = torch.rand(50, 400, device=device)
          loss = criterion(y_pred, y_tgt)
    
          # 会导致内存一直增加,需改为eval_loss['loss'] += loss.item()
          eval_loss['loss'] += loss

以上代码会导致内存占用越来越大,解决的方法是:train_l oss['loss'] += loss.item() 以及 eval_loss['loss'] += loss.item()。值得注意的是,要复现内存越来越大的问题,模型中需要切换model.train() 和 model.eval(),train_loss以及eval_loss的作用是保存模型的平均误差(这里是累积误差),保存到tensorboard中。

相关推荐
薛定猫AI17 分钟前
【深度解析】Gemini Omni 多模态生成与 Agent 化创作工作流:从视频编辑到 UI 生成的技术演进
人工智能·ui·音视频
羊羊小栈17 分钟前
AI赋能电力巡检:智能故障预警系统
人工智能·yolo·目标检测·毕业设计·大作业
Python私教23 分钟前
视觉 Agent 爬取 vs Playwright 脚本:Browser Use 2026 选型表
人工智能
Python私教26 分钟前
Crawlee StagehandCrawler:自然语言点 Load More 的工程化爬虫
人工智能
南屹川27 分钟前
【容器化】Docker实战:从入门到生产环境部署
人工智能
海蓝可知天湛1 小时前
Agent&IELTS雅思口语专属语料库
人工智能·github·rag·ielts·skills
随身数智备忘录1 小时前
什么是设备管理体系?设备管理体系包含哪些核心模块?
网络·数据库·人工智能
OpenBayes贝式计算1 小时前
涵盖 OCR 与多轮对话:1.3B 端侧多模态模型 MiniCPM-V-4.6 正式发布;百万级智能体数据集 AgentTrove 开源!包含代码修复及数学求解
人工智能
189228048611 小时前
NY352固态MT29F32T08GWLBHD6-24QJ:B
大数据·服务器·人工智能·科技·缓存
南屹川1 小时前
【数据库】PostgreSQL实战:从基础到高级特性
人工智能