【发布时间】:2020-12-26 07:58:55
【问题描述】:
我正在关注 PyTorch tutorial,它使用 Huggingface Transformers 库中的 BERT NLP 模型(特征提取器)。有两段相互关联的梯度更新代码我看不懂。
(1)torch.no_grad()
本教程有一个类,其中 forward() 函数围绕对 BERT 特征提取器的调用创建一个 torch.no_grad() 块,如下所示:
bert = BertModel.from_pretrained('bert-base-uncased')
class BERTGRUSentiment(nn.Module):
def __init__(self, bert):
super().__init__()
self.bert = bert
def forward(self, text):
with torch.no_grad():
embedded = self.bert(text)[0]
(2)param.requires_grad = False
在同一教程中的另一部分,BERT 参数被冻结。
for name, param in model.named_parameters():
if name.startswith('bert'):
param.requires_grad = False
我什么时候需要 (1) 和/或 (2)?
- 如果我想使用冻结的 BERT 进行训练,是否需要同时启用两者?
- 如果我想训练以更新 BERT,是否需要同时禁用两者?
另外,我跑了所有四个组合,发现:
with torch.no_grad requires_grad = False Parameters Ran
------------------ --------------------- ---------- ---
a. Yes Yes 3M Successfully
b. Yes No 112M Successfully
c. No Yes 3M Successfully
d. No No 112M CUDA out of memory
有人能解释一下发生了什么吗? 为什么我收到 CUDA out of memory 表示 (d) 而不是 (b)?两者都有 112M 的可学习参数。
【问题讨论】:
标签: python machine-learning pytorch bert-language-model huggingface-transformers