5

我想从 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)

我可以很好地提取logits,

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

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

layer = predictions['encoder_hidden_states'][0]
layer.retain_grad()
predictions['logits'][0][2].backward(retain_graph=True)

但是,layer.grad == None无论我尝试什么。模型的其他命名参数计算了它们的梯度,所以我不确定我做错了什么。如何获得encoder_hidden_​​states 的毕业生?

4

1 回答 1

5

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

encoder_states = tuple(hidden_state.transpose(0, 1) for hidden_state in encoder_states)

如果您将其注释掉,您将获得仅带有一些尺寸转置的渐变。此问题与 Pytorch Autograd 在此处提到的就地操作上表现不佳有关。

因此,概括一下解决方案是在modeling_bart.py.

您将获得具有此形状 T x B x C 而不是 B x T x C 的渐变,但您可以稍后根据需要重新调整它的形状。

于 2020-11-16T23:03:07.173 回答