繁体   English   中英

如何调整来自 huggingface bert 的嵌入向量的大小

[英]how to resize the embedding vectors from huggingface bert

我尝试使用 tokenizer 方法对句子进行标记化,然后将注意力掩码集中起来以获取每个句子的向量。 但是,当前的默认大小嵌入是 768,我想将它减少到 200,但失败了。 下面是我的代码。

from transformers import AutoTokenizer, AutoModel
import torch


#Mean Pooling - Take attention mask into account for correct averaging
def mean_pooling(model_output, attention_mask):
    token_embeddings = model_output[0] #First element of model_output contains all token embeddings
    input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
    return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)


# Sentences we want sentence embeddings for
sentences = ['This is an example sentence', 'Each sentence is converted']

# Load model from HuggingFace Hub
tokenizer = AutoTokenizer.from_pretrained('sentence-transformers/bert-base-nli-mean-tokens')
model = AutoModel.from_pretrained('sentence-transformers/bert-base-nli-mean-tokens')
model.resize_token_embeddings(200)
# Tokenize sentences
encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')

# Compute token embeddings
with torch.no_grad():
    model_output = model(**encoded_input)

# Perform pooling. In this case, max pooling.
sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])

print("Sentence embeddings:")
print(sentence_embeddings)

错误:

   2193     # Note [embedding_renorm set_grad_enabled]
   2194     # XXX: equivalent to
   2195     # with torch.no_grad():
   2196     #   torch.embedding_renorm_
   2197     # remove once script supports set_grad_enabled
   2198     _no_grad_embedding_renorm_(weight, input, max_norm, norm_type)
-> 2199 return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse)

IndexError: index out of range in self

我预期的 output 是:

使用时:

print(len(sentence_embeddings[0]))
-> 200

我认为您误解了resize_token_embeddings 根据文档

如果 new_num_tokens.= >config.vocab_size,则调整 model 的输入标记嵌入矩阵的大小。

如果 model class 具有 >tie_weights() 方法,则负责绑定权重嵌入。

这意味着当您从词汇表中添加/删除标记时会使用它。 这里resizing指的是调整token->embedding字典的大小。

我猜你想做的是更改 bert hidden_size的 hidden_size。为此,你必须更改hidden_size中的config.json ,这将重新初始化所有权重,你必须重新训练所有内容,即计算成本非常高。

我认为您最好的选择是在尺寸为(768x200)BertModel之上添加一个线性层,然后微调您的下游任务。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM