python - 为什么Google Colab中GPU比CPU慢很多?

标签 python deep-learning pytorch google-colaboratory

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

当我在cpu上训练时,平均速度为650迭代/秒

Training on cpu in google colab

但是当我在gpu上训练它时,平均速度只有340迭代/秒,只有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次迭代/秒,而CPU仅为15次迭代/秒。这次 GPU 快得多。

一个CNN,步长为1,在GPU中我们可以计算filter_size * image_size * batch_size,大约同时乘法2,415,919,104次。所以在这种计算中,GPU 的速度要快得多。

关于python - 为什么Google Colab中GPU比CPU慢很多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71003586/

相关文章:

python - 使用 VS Code Python 扩展 - 如何将 python 模块安装到虚拟环境之外的永久位置?

python - 将结果限制为 django 和 mezzanine 的最新结果

tensorflow - 自定义 Tensorflow Hub 模块的输入

python - 为 PyTorch reshape 图像

python - 获取 PyInstaller 导入 Basemap

python - 如何使 Pyglet 的 ScrollableTextLayout 中的文本向上滚动,而不是向下滚动? .view_y 似乎没有文档中列出的效果

python - TensorFlow - Tflearning 错误 feed_dict

python - TensorFlow:如何处理图像分割中的无效标记数据?

python - PyTorch 模型未进行训练

neural-network - 二进制分类PyTorch的损失函数及其输入