huggingface 模块中的梯度返回 None
Gradients returning None in huggingface module
我想从 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']
和模型 returns 是我感兴趣的层。我试图保留梯度和反向传播关于我感兴趣的单个 logit:
layer = predictions['encoder_hidden_states'][0]
layer.retain_grad()
predictions['logits'][0][2].backward(retain_graph=True)
但是,layer.grad == None
无论我怎样尝试。模型的其他命名参数计算了它们的梯度,所以我不确定我做错了什么。我如何获得 encoder_hidden_states 的毕业证书?
这个问题我也很意外。尽管我从未使用过该库,但我还是进行了一些调试,发现问题出在库转换器上。问题来自这个 line :
encoder_states = tuple(hidden_state.transpose(0, 1) for hidden_state in encoder_states)
如果你把它注释掉,你会得到只是一些尺寸转置的渐变。
这个问题与 Pytorch Autograd 在原地操作上表现不佳有关 here.
所以总结一下解决方案是在 modeling_bart.py
.
中注释第 382 行
您将获得形状为 T x B x C 而不是 B x T x C 的渐变,但您可以稍后根据需要重新调整形状。
我想从 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']
和模型 returns 是我感兴趣的层。我试图保留梯度和反向传播关于我感兴趣的单个 logit:
layer = predictions['encoder_hidden_states'][0]
layer.retain_grad()
predictions['logits'][0][2].backward(retain_graph=True)
但是,layer.grad == None
无论我怎样尝试。模型的其他命名参数计算了它们的梯度,所以我不确定我做错了什么。我如何获得 encoder_hidden_states 的毕业证书?
这个问题我也很意外。尽管我从未使用过该库,但我还是进行了一些调试,发现问题出在库转换器上。问题来自这个 line :
encoder_states = tuple(hidden_state.transpose(0, 1) for hidden_state in encoder_states)
如果你把它注释掉,你会得到只是一些尺寸转置的渐变。 这个问题与 Pytorch Autograd 在原地操作上表现不佳有关 here.
所以总结一下解决方案是在 modeling_bart.py
.
您将获得形状为 T x B x C 而不是 B x T x C 的渐变,但您可以稍后根据需要重新调整形状。