如何使用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 (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...