Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 正确使用Pytork';s non_blocking=对于数据预取为真_Python_Python 3.x_Deep Learning_Pytorch - Fatal编程技术网

Python 正确使用Pytork';s non_blocking=对于数据预取为真

Python 正确使用Pytork';s non_blocking=对于数据预取为真,python,python-3.x,deep-learning,pytorch,Python,Python 3.x,Deep Learning,Pytorch,当模型在GPU上训练时,我正在研究从CPU将数据预取到GPU中。重叠的CPU到GPU的数据传输与GPU模型训练似乎需要两者 使用data=data.cuda(非阻塞=True)将数据传输到GPU 使用train\u loader=DataLoader(…,Pin\u memory=True)将数据固定到CPU内存中 但是,我无法理解如何在此代码块中执行非阻塞传输,特别是此代码块: for i, (images, target) in enumerate(train_loader):

当模型在GPU上训练时,我正在研究从CPU将数据预取到GPU中。重叠的CPU到GPU的数据传输与GPU模型训练似乎需要两者

  • 使用
    data=data.cuda(非阻塞=True)将数据传输到GPU
  • 使用
    train\u loader=DataLoader(…,Pin\u memory=True)将数据固定到CPU内存中
  • 但是,我无法理解如何在此代码块中执行非阻塞传输,特别是此代码块:

    for i, (images, target) in enumerate(train_loader):
            # measure data loading time
            data_time.update(time.time() - end)
    
            if args.gpu is not None:
                images = images.cuda(args.gpu, non_blocking=True)
            if torch.cuda.is_available():
                target = target.cuda(args.gpu, non_blocking=True)
    
            # compute output
            output = model(images)
            loss = criterion(output, target)
    
    在执行
    output=model(images)
    之前,不需要
    images.cuda(non_blocking=True)
    target.cuda(non_blocking=True)
    完成。由于这是一个同步点,
    图像必须首先完全传输到CUDA设备,因此数据传输步骤实际上不再是无阻塞的

    由于
    output=model(images)
    是阻塞的,
    images.cuda()
    target.cuda()
    for
    循环的下一次
    i
    迭代中将不会发生,直到计算出模型输出,这意味着在下一次循环迭代中不会进行预取


    如果这是正确的,那么对GPU执行数据预取的正确方法是什么?

    要在PyTorch上正确实现GPU预取,必须将for循环转换为while循环

    应使用
    iter
    函数将数据加载器更改为迭代器,例如
    iterator=iter(加载器)

    在while循环中的每个步骤中使用
    next(迭代器)
    ,以获得下一个小批量

    可以通过从迭代器捕获
    StopIteration
    来检测数据加载器的结束

    当引发
    StopIteration
    时,使用标志结束while循环