【问题标题】:Longformer get last_hidden_stateLongformer 获取 last_hidden_​​state
【发布时间】:2021-06-13 17:23:45
【问题描述】:

我正在尝试在此处 https://huggingface.co/transformers/model_doc/longformer.html 的拥抱脸文档中遵循此示例:

import torch
from transformers import LongformerModel, LongformerTokenizer
model = LongformerModel.from_pretrained('allenai/longformer-base-4096')
tokenizer = LongformerTokenizer.from_pretrained('allenai/longformer-base-4096')
SAMPLE_TEXT = ' '.join(['Hello world! '] * 1000)  # long input document
input_ids = torch.tensor(tokenizer.encode(SAMPLE_TEXT)).unsqueeze(0)  # batch of size 1
# Attention mask values -- 0: no attention, 1: local attention, 2: global attention
attention_mask = torch.ones(input_ids.shape, dtype=torch.long, device=input_ids.device) # initialize to local attention
global_attention_mask = torch.zeros(input_ids.shape, dtype=torch.long, device=input_ids.device) # initialize to global attention to be deactivated for all tokens
global_attention_mask[:, [1, 4, 21,]] = 1  # Set global attention to random tokens for the sake of this example
                                    # Usually, set global attention based on the task. For example,
                                    # classification: the <s> token
                                    # QA: question tokens
                                    # LM: potentially on the beginning of sentences and paragraphs
outputs = model(input_ids, attention_mask=attention_mask, global_attention_mask=global_attention_mask, output_hidden_states= True)
sequence_output = outputs[0].last_hidden_state
pooled_output = outputs.pooler_output

我想这会返回一个嵌入示例文本的文档。 但是,我遇到了以下错误:

AttributeError: 'Tensor' object has no attribute 'last_hidden_state'

为什么不能调用last_hidden_​​state?

【问题讨论】:

    标签: python nlp pytorch huggingface-transformers


    【解决方案1】:

    不要通过索引选择:

    sequence_output = outputs.last_hidden_state
    

    outputs 是具有以下属性的 LongformerBaseModelOutputWithPooling 对象:

    print(outputs.keys())
    

    输出:

    odict_keys(['last_hidden_state', 'pooler_output', 'hidden_states'])
    

    调用outputs[0]outputs.last_hidden_state 都会给你相同的张量,但是这个张量没有一个名为last_hidden_state 的属性。

    【讨论】:

      猜你喜欢
      • 2021-12-30
      • 2022-01-09
      • 2020-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-17
      • 2016-05-27
      相关资源
      最近更新 更多