我正在训练一个使用 Bert (huggingface) 的二元分类器。该模型如下所示:
def get_model(lr=0.00001):
inp_bert = Input(shape=(512), dtype="int32")
bert = TFBertModel.from_pretrained('bert-base-multilingual-cased')(inp_bert)[0]
doc_encodings = tf.squeeze(bert[:, 0:1, :], axis=1)
out = Dense(1, activation="sigmoid")(doc_encodings)
model = Model(inp_bert, out)
adam = optimizers.Adam(lr=lr)
model.compile(optimizer=adam, loss="binary_crossentropy", metrics=["accuracy"])
return model
Run Code Online (Sandbox Code Playgroud)
对分类任务进行微调后,我想保存模型。
model.save("best_model.h5")
Run Code Online (Sandbox Code Playgroud)
然而,这会引发 NotImplementedError:
---------------------------------------------------------------------------
NotImplementedError Traceback (most recent call last)
<ipython-input-55-8c5545f0cd9b> in <module>()
----> 1 model.save("best_spam.h5")
2 # import transformers
~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/network.py in save(self, filepath, overwrite, include_optimizer, save_format, signatures, options)
973 """
974 saving.save_model(self, filepath, overwrite, include_optimizer, save_format,
--> 975 signatures, options)
976
977 def …Run Code Online (Sandbox Code Playgroud) 通常,变压器分词器将输入编码为字典。
{"input_ids": tf.int32, "attention_mask": tf.int32, "token_type_ids": tf.int32}
Run Code Online (Sandbox Code Playgroud)
为了对大型数据集进行更好的性能处理,最好实现一个管道,其中包括将Dataset.map分词器函数应用于输入数据集的每个元素。与 Tensorflow 教程中所做的完全相同:加载文本。
但是,tf.py_function(用于包装 map python 函数)不支持返回张量字典,如上所示。
例如,如果加载文本中的分词器(编码器)返回以下字典:
{
"input_ids": [ 101, 13366, 2131, 1035, 6819, 2094, 1035, 102 ],
"attention_mask": [ 1, 1, 1, 1, 1, 1, 1, 1 ]
}
Run Code Online (Sandbox Code Playgroud)
如何设置 的Tout参数tf.py_function来获取所需的张量字典:
{
'input_ids': <tf.Tensor: shape=(16,), dtype=int32, numpy = array(
[ 101, 13366, 2131, 1035, 6819, 2094, 1035, 102 ], dtype=int32)>
'attention_mask': <tf.Tensor: shape=(16,), dtype=int32, numpy=array(
[ 1, 1, …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 NLP 计算句子中单词的概率或任何类型的分数。我已经使用 Huggingface Transformers 库对 GPT2 模型尝试了这种方法,但是,由于模型的单向性质,我无法在上下文中进行预测,因此无法获得令人满意的结果。所以我想知道是否有办法使用 BERT 计算上述内容,因为它是双向的。
我发现这篇文章相关,我前几天随机看到的,但没有看到任何对我有用的答案。
希望我能够收到想法或解决方案。任何帮助表示赞赏。谢谢你。
我想在 Flask 应用程序中执行文本生成任务并将其托管在 Web 服务器上,但是在下载 GPT 模型时,弹性 beantalk 管理的 EC2 实例崩溃,因为下载需要太多时间和内存
from transformers.tokenization_openai import OpenAIGPTTokenizer
from transformers.modeling_tf_openai import TFOpenAIGPTLMHeadModel
model = TFOpenAIGPTLMHeadModel.from_pretrained("openai-gpt")
tokenizer = OpenAIGPTTokenizer.from_pretrained("openai-gpt")
Run Code Online (Sandbox Code Playgroud)
这些是导致问题的相关线路。GPT 大约为 445 MB。我正在使用变压器库。我没有在这一行下载模型,而是想知道是否可以对模型进行腌制,然后将其捆绑为存储库的一部分。这个图书馆可以吗?否则我如何预加载这个模型以避免我遇到的问题?
machine-learning transformer-model flask amazon-elastic-beanstalk huggingface-transformers
在 Huggingface 中使用 Roberta 标记器时,我感到很困惑。
>>> tokenizer = RobertaTokenizer.from_pretrained('roberta-base')
>>> x = tokenizer.tokenize("The tiger is ___ (big) than the dog.")
['The', '?tiger', '?is', '?___', '?(', 'big', ')', '?than', '?the', '?dog', '.']
>>> x = tokenizer.tokenize("The tiger is ___ ( big ) than the dog.")
['The', '?tiger', '?is', '?___', '?(', '?big', '?)', '?than', '?the', '?dog', '.']
>>> x = tokenizer.encode("The tiger is ___ (big) than the dog.")
[0, 20, 23921, 16, 2165, 36, 8527, 43, 87, 5, 2335, 4, 2]
>>> …Run Code Online (Sandbox Code Playgroud) 我很好奇transformers.BertModel 的内存使用情况。我想使用预训练模型来转换文本并保存标记 [CLS] 的输出。没有训练,只有推理。
我对 bert 的输入是 511 个令牌。由于批量大小为 16,我的代码内存不足。GPU 有 32GB 内存。我的问题是如何估计Bert的内存使用量。
奇怪的是,批处理大小为 32 的另一个作业成功完成,设置相同。我的代码如下。
# Create dataloader
bs = 16
train_comb = ConcatDataset([train_data, valid_data])
train_dl = DataLoader(train_comb, sampler=RandomSampler(train_data), batch_size=bs)
model = BertModel.from_pretrained('/my_dir/bert_base_uncased/',
output_attentions=False,
output_hidden_states=False)
model.cuda()
out_list = []
model.eval()
with torch.no_grad():
for d in train_dl:
d = [i.cuda() for i in d]. # d = [input_ids, attention_mask, token_type_ids, labels]
inputs, labels = d[:3], d[3] # input_ids has shape 16 x 511
output = model(*inputs)[0][:, 0, :]
out_list.append(output)
outputs …Run Code Online (Sandbox Code Playgroud) 我想从 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)
Run Code Online (Sandbox Code Playgroud)
我可以很好地提取 logits,
inputs = nlp._parse_and_tokenize(responses, candidate_labels, hypothesis_template)
predictions = nlp.model(**inputs, return_dict=True, output_hidden_states=True)
predictions['logits']
Run Code Online (Sandbox Code Playgroud)
并且模型返回一个我感兴趣的层。我试图保留关于我感兴趣的单个 logit 的梯度和反向传播:
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)
Run Code Online (Sandbox Code Playgroud)
然而,layer.grad == None不管我怎么努力。模型的其他命名参数计算了它们的梯度,所以我不确定我做错了什么。我如何获得encoder_hidden_states …
我只是尝试了拥抱脸网站的示例代码:https : //huggingface.co/albert-base-v2
`from transformers import AlbertTokenizer, AlbertModel`
`tokenizer = AlbertTokenizer.from_pretrained('albert-base-v2')`
`text = "Replace me by any text you'd like."`
`encoded_input = tokenizer(text, return_tensors='pt')`
Run Code Online (Sandbox Code Playgroud)
然后在标记器步骤中出现以下错误:----> 5 encoding_input = tokenizer(text, return_tensors='pt')
TypeError: 'NoneType' 对象不可调用
我在本地机器上尝试了相同的代码,没有问题。问题似乎在 Colab 中。但是,我确实需要帮助才能在 colab GPU 上运行此模型。
我在 colab 上的 Python 版本是 Python 3.6.9
google-colaboratory huggingface-transformers huggingface-tokenizers
我正在 Google Colab 上进行机器学习项目,最近似乎在尝试从转换器导入包时出现问题。错误消息说:
导入错误:无法从“torch.optim.lr_scheduler”(/usr/local/lib/python3.7/dist-packages/torch/optim/lr_scheduler.py)导入名称“SAVE_STATE_WARNING”
代码很简单,如下所示:
!pip install transformers==3.5.1
from transformers import BertTokenizer
Run Code Online (Sandbox Code Playgroud)
到目前为止,我已经尝试安装不同版本的转换器,并导入一些其他包,但似乎导入任何包:
from transformers import *Package
Run Code Online (Sandbox Code Playgroud)
python nlp google-colaboratory bert-language-model huggingface-transformers
我正在关注本教程:https : //huggingface.co/transformers/torchscript.html
来创建我的自定义 BERT 模型的跟踪,但是在运行完全相同的模型时,dummy_input我收到一个错误:
TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect.
We cant record the data flow of Python values, so this value will be treated as a constant in the future.
Run Code Online (Sandbox Code Playgroud)
在我的模型和标记器中加载后,创建跟踪的代码如下:
text = "[CLS] Who was Jim Henson ? [SEP] Jim Henson was a puppeteer [SEP]"
tokenized_text = tokenizer.tokenize(text)
# Masking one of the input tokens
masked_index = 8
tokenized_text[masked_index] = '[MASK]'
indexed_tokens = tokenizer.convert_tokens_to_ids(tokenized_text) …Run Code Online (Sandbox Code Playgroud)