如何使用Resnet,FCn,DeepLab图像分割评估解决GPU OOM问题?

如何解决如何使用Resnet,FCn,DeepLab图像分割评估解决GPU OOM问题?

我正在编写有关Python中图像分割的You​​Tube教程:link

本教程基于我为细化目的而一直参考的其他教程,特别是本教程: OpenCV Pytorch Segmentation

我正在使用具有8 GB GPU内存的NVDIA 2070图形卡。

我的问题是,原始教程讲授了通过FCN使用Resnet的语义分段程序的基本CPU实现。我想以此为基础来利用GPU,因此我找到了后者。我实际上在这方面没有任何经验,但是我想出了如何在GPU上运行它并立即遇到GPU OOM问题:


RuntimeError:CUDA内存不足。尝试分配184.00 MiB (GPU 0;总容量8.00 GiB;已经分配了5.85 GiB;免费有26.97 MiB; PyTorch总共保留了5.88 GiB)


当我在小图像上运行该程序时,或者将HD图像的图像质量降低到50%分辨率时,都不会出现OOM错误。

我的拨弄和询问使我相信,我的OOM是在此任务中分配内存的结果。因此,现在我尝试实现替代的DeepLab解决方案,希望它可以更有效地分配内存,但事实并非如此。

这是我的代码:

from PIL import Image
import torch
import torchvision.transforms as T
from torchvision import models
import numpy as np
import imghdr

fcn = None
dlab = None

def getRotoModel():
    global fcn
    global dlab
    fcn = models.segmentation.fcn_resnet101(pretrained=True).eval()
    dlab = models.segmentation.deeplabv3_resnet101(pretrained=1).eval()

# Define the helper function
def decode_segmap(image,nc=21):

    label_colors = np.array([(0,0),# 0=background
                           # 1=aeroplane,2=bicycle,3=bird,4=boat,5=bottle
               (128,(0,128,(128,128),# 6=bus,7=car,8=cat,9=chair,10=cow
               (0,(64,(192,# 11=dining table,12=dog,13=horse,14=motorbike,15=person
               (192,# 16=potted plant,17=sheep,18=sofa,19=train,20=tv/monitor
               (0,64,192,128)])

    r = np.zeros_like(image).astype(np.uint8)
    g = np.zeros_like(image).astype(np.uint8)
    b = np.zeros_like(image).astype(np.uint8)

    for l in range(0,nc):
        idx = image == l
        r[idx] = label_colors[l,0]
        g[idx] = label_colors[l,1]
        b[idx] = label_colors[l,2]

    rgb = np.stack([r,g,b],axis=2)
    return rgb

valid_images = ['jpg','png','rgb','pbm','ppm','tiff','rast','xbm','bmp','exr','jpeg'] #Valid image formats
dev = torch.device('cuda')
def createMatte(filename,matteName,factor):
    if imghdr.what(filename) in valid_images:
        img = Image.open(filename).convert('RGB')
        
        size = img.size
        w,h = size
        modifiedSize = h * factor
        print('Image original size is ',size)
        print('Modified size is ',modifiedSize)
        trf = T.Compose([T.Resize(int(modifiedSize)),T.ToTensor(),T.Normalize(mean = [0.485,0.456,0.406],std = [0.229,0.224,0.225])])
        inp = trf(img).unsqueeze(0)
        #inp = trf(img).unsqueeze(0).to(dev)
        
        if (fcn == None): getRotoModel()
        
        if torch.cuda.is_available():
            torch.cuda.empty_cache()
            inp = inp.to(dev)
            fcn.to(dev)
            out = fcn.to(dev)(inp)['out'][0]
        
        with torch.no_grad():
            out = fcn(inp)['out'][0]
        
        #out = fcn(inp)['out']
        #out = fcn.to(dev)(inp)['out']
        om = torch.argmax(out.squeeze(),dim=0).detach().cpu().numpy()  
        rgb = decode_segmap(om)
        im = Image.fromarray(rgb)
        im.save(matteName)
    else:
        print('File type is not supported for file ' + filename)
        print(imghdr.what(filename))
        
def createDLMatte(filename,factor):
    if imghdr.what(filename) in valid_images:
        img = Image.open(filename).convert('RGB')
            
        size = img.size
        w,0.225])])
        inp = trf(img).unsqueeze(0)
        #inp = trf(img).unsqueeze(0).to(dev)
            
        if (dlab == None): getRotoModel()
            
        if torch.cuda.is_available():
            torch.cuda.empty_cache()
            inp = inp.to(dev)
            dlab.to(dev)
            out = dlab.to(dev)(inp)['out'][0]
            
        with torch.no_grad():
            out = dlab(inp)['out'][0]
            
        #out = fcn(inp)['out']
        #out = fcn.to(dev)(inp)['out']
        om = torch.argmax(out.squeeze(),dim=0).detach().cpu().numpy()  
        rgb = decode_segmap(om)
        im = Image.fromarray(rgb)
        im.save(matteName)        

我想知道的是,是否存在GPU问题的解决方案?我不想局限于CPU渲染,而当我拥有功能强大的GPU时,每个图像大约需要一分钟的时间。正如我说的那样,我对大多数事情还是很陌生的,但是我希望有一种方法可以更好地在此过程中分配内存。

我有一些潜在的解决方案,但是我迷失了寻找实施资源的机会。

  1. (较差的解决方案)在GPU接近内存快要用完时在GPU上进行上限计算,并将其余任务切换到CPU。我不仅觉得自己很穷,而且也没有真正看到如何在任务中实现GPU CPU切换。

  2. (更好)通过将映像分段为可管理的位,然后将这些位保存到临时文件中,然后最后进行组合来固定内存分配。

  3. 两者的组合。

现在我担心的是,对图像进行分割会降低结果的质量,因为每个部分都不会与上下文相关,我需要某种智能的拼接方式,而这超出了我的薪水范围。

所以我通常会问是否有足够的资源来解决那些可能的解决方案,或者是否有更好的解决方案。

最后,我的实现是否存在问题,导致GPU OOM错误?我无法确定是我的代码没有被优化,还是DeepLab和FCN都只是超级内存密集型设备,并且从一开始就无法优化。任何帮助将不胜感激!谢谢!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-