나는 BERT 기반 어휘 대체에 관한 논문 을 따르고있었습니다 (특히 방정식 (2)를 구현하려고 시도했습니다-누군가가 이미 전체 논문을 구현했다면 좋을 것입니다). 따라서 마지막 은닉 레이어 (출력에서 레이어의 순서가 확실하지 않은 것은 마지막 첫 번째 또는 첫 번째 먼저?)와 기본 BERT 모델 (bert-base-uncased)의 관심을 모두 얻고 싶었습니다.
그러나 bert-base-uncased에 대한 허깅 페이스 / 트랜스포머 라이브러리가 실제로주의를 출력 하는지 (나는 횃불을 사용하고 있었지만 대신 TF를 사용하는 데 열려 있는지) 확실하지 않습니다.
에서 내가 읽은 것을 , 나는 (logits, hidden_states, 관심)의 튜플을 얻을 것으로 예상했지만, (실행 구글 Colab에서 예) 아래의 예와, 내가 대신 길이 2의 수.
내가 얻는 것을 오해하거나 잘못된 방식으로 진행하고 있습니까? 나는 명백한 테스트를 수행하고 output_attention=False
대신 사용 output_attention=True
했으며 ( output_hidden_states=True
실제로 예상대로 숨겨진 상태를 추가하는 것처럼 보임) 얻은 출력에 아무것도 변경되지 않았습니다. 그것은 분명히 도서관에 대한 나의 이해에 대한 나쁜 신호이거나 문제를 나타냅니다.
import numpy as np
import torch
!pip install transformers
from transformers import (AutoModelWithLMHead,
AutoTokenizer,
BertConfig)
bert_tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
config = BertConfig.from_pretrained('bert-base-uncased', output_hidden_states=True, output_attention=True) # Nothign changes, when I switch to output_attention=False
bert_model = AutoModelWithLMHead.from_config(config)
sequence = "We went to an ice cream cafe and had a chocolate ice cream."
bert_tokenized_sequence = bert_tokenizer.tokenize(sequence)
indexed_tokens = bert_tokenizer.encode(bert_tokenized_sequence, return_tensors='pt')
predictions = bert_model(indexed_tokens)
########## Now let's have a look at what the predictions look like #############
print(len(predictions)) # Length is 2, I expected 3: logits, hidden_layers, attention
print(predictions[0].shape) # torch.Size([1, 16, 30522]) - seems to be logits (shape is 1 x sequence length x vocabulary
print(len(predictions[1])) # Length is 13 - the hidden layers?! There are meant to be 12, right? Is one somehow the attention?
for k in range(len(predictions[1])):
print(predictions[1][k].shape) # These all seem to be torch.Size([1, 16, 768]), so presumably the hidden layers?
import numpy as np
import torch
!pip install transformers
from transformers import BertModel, BertConfig, BertTokenizer
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
config = BertConfig.from_pretrained('bert-base-uncased', output_hidden_states=True, output_attentions=True)
model = BertModel.from_pretrained('bert-base-uncased', config=config)
sequence = "We went to an ice cream cafe and had a chocolate ice cream."
tokenized_sequence = tokenizer.tokenize(sequence)
indexed_tokens = tokenizer.encode(tokenized_sequence, return_tensors='pt'
enter code here`outputs = model(indexed_tokens)
print( len(outputs) ) # 4
print( outputs[0].shape ) #1, 16, 768
print( outputs[1].shape ) # 1, 768
print( len(outputs[2]) ) # 13 = input embedding (index 0) + 12 hidden layers (indices 1 to 12)
print( outputs[2][0].shape ) # for each of these 13: 1,16,768 = input sequence, index of each input id in sequence, size of hidden layer
print( len(outputs[3]) ) # 12 (=attenion for each layer)
print( outputs[3][0].shape ) # 0 index = first layer, 1,12,16,16 = , layer, index of each input id in sequence, index of each input id in sequence
그 이유는 AutoModelWithLMHead
실제 모델의 래퍼를 사용하고 있기 때문입니다 . BERT 모델 (즉,의 인스턴스 BERTModel
)을 호출 한 다음 임베딩 행렬을 단어 예측을위한 가중치 행렬로 사용합니다. 기본 모델 사이에서 실제로주의를 반환하지만 래퍼는 신경 쓰지 않고 로짓 만 반환합니다.
을 호출하여 BERT 모델을 직접 가져올 수 있습니다 AutoModel
. 이 모델은 로짓이 아니라 은닉 상태를 반환합니다.
bert_model = AutoModel.from_config(config)
또는 다음 BertWithLMHead
을 호출 하여 객체 에서 가져올 수 있습니다 .
wrapped_model = bert_model.base_model
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다