【发布时间】:2022-01-24 09:22:51
【问题描述】:
我正在尝试更好地了解梯度累积的工作原理以及它为何有用。为此,我想问一下这两种可能的具有梯度累积的自定义训练循环的类似 PyTorch 的实现之间有什么区别(如果有的话):
gradient_accumulation_steps = 5
for batch_idx, batch in enumerate(dataset):
x_batch, y_true_batch = batch
y_pred_batch = model(x_batch)
loss = loss_fn(y_true_batch, y_pred_batch)
loss.backward()
if (batch_idx + 1) % gradient_accumulation_steps == 0: # (assumption: the number of batches is a multiple of gradient_accumulation_steps)
optimizer.step()
optimizer.zero_grad()
y_true_batches, y_pred_batches = [], []
gradient_accumulation_steps = 5
for batch_idx, batch in enumerate(dataset):
x_batch, y_true_batch = batch
y_pred_batch = model(x_batch)
y_true_batches.append(y_true_batch)
y_pred_batches.append(y_pred_batch)
if (batch_idx + 1) % gradient_accumulation_steps == 0: # (assumption: the number of batches is a multiple of gradient_accumulation_steps)
y_true = stack_vertically(y_true_batches)
y_pred = stack_vertically(y_pred_batches)
loss = loss_fn(y_true, y_pred)
loss.backward()
optimizer.step()
optimizer.zero_grad()
y_true_batches.clear()
y_pred_batches.clear()
另外,作为一个不相关的问题:由于梯度累积的目的是在内存限制的情况下模拟更大的批量大小,这是否意味着我也应该按比例提高学习率?
【问题讨论】:
标签: python pytorch gradient-descent