我想从 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 的毕业生?