在 Huggingface 模块中梯度返回 None

Hoo*_*ked 4 python nlp pytorch huggingface-transformers

我想从 pytorch/huggingface 模型中获取嵌入层的梯度。这是一个最小的工作示例:

from transformers import pipeline

nlp = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")

responses = ["I'm having a great day!!"]
hypothesis_template = 'This person feels {}'
candidate_labels = ['happy', 'sad']
nlp(responses, candidate_labels, hypothesis_template=hypothesis_template)
Run Code Online (Sandbox Code Playgroud)

我可以很好地提取 logits,

inputs = nlp._parse_and_tokenize(responses, candidate_labels, hypothesis_template)
predictions = nlp.model(**inputs, return_dict=True, output_hidden_states=True)
predictions['logits']   
Run Code Online (Sandbox Code Playgroud)

并且模型返回一个我感兴趣的层。我试图保留关于我感兴趣的单个 logit 的梯度和反向传播:

from transformers import pipeline

nlp = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")

responses = ["I'm having a great day!!"]
hypothesis_template = 'This person feels {}'
candidate_labels = ['happy', 'sad']
nlp(responses, candidate_labels, hypothesis_template=hypothesis_template)
Run Code Online (Sandbox Code Playgroud)

然而,layer.grad == None不管我怎么努力。模型的其他命名参数计算了它们的梯度,所以我不确定我做错了什么。我如何获得encoder_hidden_​​states 的等级?

Rog*_*llo 5

我也对这个问题感到非常惊讶。尽管我从未使用过该库,但我进行了一些调试并发现问题出在库转换器上。问题来自这一

encoder_states = tuple(hidden_state.transpose(0, 1) for hidden_state in encoder_states)
Run Code Online (Sandbox Code Playgroud)

如果你把它注释掉,你会得到一些尺寸转置的渐变。此问题与 Pytorch Autograd 在此处提到的就地操作上做得不太好这一事实有关。

因此,总结一下解决方案是在modeling_bart.py.

您将获得此形状 T x B x C 而不是 B x T x C 的渐变,但您可以稍后根据需要对其进行整形。