梯度累积

2021-03-30  本文已影响0人  三方斜阳

1. gradient_accumulation_steps

for step, batch in enumerate(tqdm(train_dataloader, desc="Iteration")):
     batch = tuple(t.to(device) for t in batch)
     input_ids, input_mask, segment_ids, label_ids = batch
     outputs = model(input_ids, label_ids, segment_ids, input_mask)
     loss = outputs#r如果没有调用任何函数,那么返回的是forward函数中的返回值
     if n_gpu > 1:
        loss = loss.mean() # mean() to average on multi-gpu.
        if args.gradient_accumulation_steps > 1:##所以loss应该是间隔指定梯度累积步的均值
            loss = loss / args.gradient_accumulation_steps
       loss.backward()
       tr_loss += loss.item()##设置经过多少个 梯度累积步 之后才更新网络的参数
       if (step + 1) % args.gradient_accumulation_steps == 0:#设定多少batch时更新神经网络的参数
           optimizer.step()
           scheduler.step()  # Update learning rate schedule
           model.zero_grad()
           global_step += 1      

gradient_accumulation_steps通过累计梯度来解决本地显存不足问题。
假设原来的batch_size=6,样本总量为24,gradient_accumulation_steps=2
那么参数更新次数=24/6=4
现在,减小batch_size=6/2=3,参数更新次数不变=24/3/2=4

num_train_optimization_steps = int(total_train_examples / args.train_batch_size / args.gradient_accumulation_steps)

一般说batch_size越大越好,现在降低为batch_size=3 的话,一共24个样本,需要每两个batch 更新一次参数,因为引入了梯度累积,
3+3——>1
3+3——>1
3+3——>1
3+3——>1
总共更新4次数
如果batch_size=6,没有梯度累计引入,那么每个batch 更新一次梯度:
6——>1
6——>1
6——>1
6——>1

参考:
gradient_accumulation_steps
gradient_accumulation_steps-CSDN博客

上一篇 下一篇

猜你喜欢

热点阅读