为什么 GPU 在 google colab 中比 cpu 慢很多?

Why GPU is much slower than cpu in google colab?

我正在 google colab 上训练 RNN,这是我第一次使用 gpu 训练神经网络。从我的角度来看,GPU应该比cpu快得多,将设备从cpu更改为gpu只需要在model/loss/variable的定义中添加.to('cuda')并设置google colab 'running on gpu'.

当我在cpu上训练它时,平均速度是650iteration/s

Training on cpu in google colab

但是我在gpu上训练的时候,平均速度只有340iterations/s,只有cpu

的一半

Training on gpu in google colab

这发生在每个时代

这是我的代码。

def train(num_epoch = 30,len_vocab = 1, num_hidden=256,embedding_dim = 8,batch_size = 100):
    data = get_data()

    model = MyRNN(len_vocab,num_hidden,embedding_dim).to('cuda') #here 
    if os.path.exists('QingBinLi'):
        model.load_state_dict(torch.load('QingBinLi'))

    criterion = nn.MSELoss().to('cuda')   #here 
    optimizer = torch.optim.Adam(model.parameters(), lr=0.1, weight_decay=1e-5)
    loss_for_draw = []
    model.train()
    data = data.detach().to('cuda') #here 

    for epoch in range(num_epoch+1):

        h = torch.randn(1,batch_size,num_hidden).to('cuda')  #here 
        loss_average = 0
        for i in tqdm(range(data.shape[-2] -batch_size)):
            optimizer.zero_grad()
            pre,h = model(data[:,:,i:i+batch_size,:].squeeze(0) ,h)
            h = h.detach()
            pre = pre.unsqueeze(0).unsqueeze(0)
            loss = criterion(pre, data[:,:,i+1:i+1+batch_size,:].squeeze(0))
            loss_average += loss.item()
            loss.backward()
            nn.utils.clip_grad_norm_(model.parameters(), max_norm=10)
            optimizer.step()

        loss_for_draw.append(loss_average/(data.shape[-2] -batch_size))
        torch.save(model.state_dict(), 'QingBinLi')
        print(f'now epoch:{epoch}, loss = {loss_for_draw[-1]}')


    return loss_for_draw

当我尝试在 gpu 上 运行 时,我只是在其中添加 '.to('cuda')'。

那么,为什么当我 运行在 gpu 上运行我的代码时它会慢得多?也许我应该修改更多代码?

大哥说张量很大的时候,比如100万维,gpu可以比cpu快,不然我们连并行计算都不需要,因为计算主要不是张量乘法,但是在复制张量和其他类似的东西上。

我的RNN大约有256x256+256x8个参数,batch_size是100个,维数远低于100万。所以gpu要慢得多。

而且,当我将 batch_size 更改为 10000 时,gpu 为 145 iteration/s 而 cpu 仅为 15iterations/s。这次gpu快多了。

一个CNN,stride 1,在gpu中我们可以计算filter_size *image_size * batch_size,同时相乘大约2,415,919,104次。所以在这种计算中,gpu要快得多。