标签: huggingface-transformers

Huggingface - 在本地保存微调模型 - 以及标记器?

我只是想知道如果微调 BERT 模型并保存它,分词器是否会受到某种影响或改变。我是否也需要在本地保存分词器,以便稍后使用保存的 BERT 模型时重新加载它?

我只是做:

bert_model.save_pretrained('./Fine_tune_BERT/')
Run Code Online (Sandbox Code Playgroud)

然后稍后

bert_model = TFBertModel.from_pretrained('./Fine_tune_BERT/')
Run Code Online (Sandbox Code Playgroud)

但我也需要保存标记器吗?或者我可以以正常方式使用它,例如:

tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
Run Code Online (Sandbox Code Playgroud)

bert-language-model huggingface-transformers

4
推荐指数
2
解决办法
3828
查看次数

Huggingface TFBertForSequenceClassification 始终预测相同的标签

TL;DR:\n我的模型总是预测相同的标签,但我不知道为什么。下面是我的微调代码,希望有人能指出我哪里出错了。

\n

我使用 Huggingface 的 TFBertForSequenceClassification 进行序列分类任务来预测德语文本中句子的 4 个标签。

\n

我使用 bert-base-german-cased 模型,因为我不只使用小写文本(因为德语比英语更区分大小写)。

\n

我从一个 csv 文件中获取输入,该文件是根据收到的带注释的语料库构建的。这是其中的一个示例:

\n
0       Hier kommen wir ins Spiel Die App Cognitive At...\n1       Doch wenn Athlet Lebron James jede einzelne Mu...\n2       Wie kann ein Gehirn auf Hochleistung getrimmt ...\n3       Wie schafft es Warren Buffett knapp 1000 W\xc3\xb6rte...\n4       Entfalte dein mentales Potenzial und werde ein...\nName: sentence_clean, Length: 3094, dtype: object\n
Run Code Online (Sandbox Code Playgroud)\n

这些是我的标签,来自同一个 csv 文件:

\n
0       e_1\n1       e_4\n2       e_4\n3       e_4\n4       e_4\n
Run Code Online (Sandbox Code Playgroud)\n

不同的标签是:e_1、e_2、e_3 和 e_4

\n …

python tensorflow bert-language-model huggingface-transformers

4
推荐指数
1
解决办法
3615
查看次数

BertModel 或 BertForPreTraining

我只想使用 Bert 进行嵌入,并使用 Bert 输出作为我将从头开始构建的分类网络的输入。

我不确定是否要对模型进行微调。

我认为相关的类是 BertModel 或 BertForPreTraining。

BertForPreTraining head 包含两个“动作”:self.predictions 是 MLM(Masked Language Modeling)head,赋予 BERT 修复语法错误的能力,self.seq_relationship 是 NSP(Next Sentence Prediction);通常称为分类头。

class BertPreTrainingHeads(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.predictions = BertLMPredictionHead(config)
        self.seq_relationship = nn.Linear(config.hidden_size, 2)
Run Code Online (Sandbox Code Playgroud)

我认为 NSP 与我的任务无关,所以我可以“覆盖”它。MLM 是做什么的?它与我的目标相关吗?还是我应该使用 BertModel?

nlp transformer-model deep-learning bert-language-model huggingface-transformers

4
推荐指数
1
解决办法
4709
查看次数

BertTokenizer.from_pretrained 错误并显示“连接错误”

我正在尝试从 Huggingface 下载 BERT 的分词器。

我正在执行:

tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
Run Code Online (Sandbox Code Playgroud)

错误:

<Path>\tokenization_utils_base.py in from_pretrained(cls, pretrained_model_name_or_path, *init_inputs, **kwargs)
   1663                         resume_download=resume_download,
   1664                         local_files_only=local_files_only,
-> 1665                         use_auth_token=use_auth_token,
   1666                     )
   1667 

<Path>\file_utils.py in cached_path(url_or_filename, cache_dir, force_download, proxies, resume_download, user_agent, extract_compressed_file, force_extract, use_auth_token, local_files_only)
   1140             user_agent=user_agent,
   1141             use_auth_token=use_auth_token,
-> 1142             local_files_only=local_files_only,
   1143         )
   1144     elif os.path.exists(url_or_filename):

<Path>\file_utils.py in get_from_cache(url, cache_dir, force_download, proxies, etag_timeout, resume_download, user_agent, use_auth_token, local_files_only)
   1347                 else:
   1348                     raise ValueError(
-> 1349                         "Connection error, and we cannot find the requested files in the cached …
Run Code Online (Sandbox Code Playgroud)

python ssl ssl-certificate huggingface-transformers

4
推荐指数
1
解决办法
1万
查看次数

T5模型如何使用forward()方法代替model.generate()

对于我的用例,我需要使用 model.forward() 而不是 model.generate() 方法,即代替下面的代码

outs = model.model.generate(input_ids=batch['source_ids'],
                                 attention_mask=batch['source_mask'],
                                 output_scores=True,
                                 max_length=model.model_arguments.max_output_seq_length)

preds_cleaned = [model.tokenizer.decode(ids, skip_special_tokens=True, clean_up_tokenization_spaces=True) for ids in outs]
Run Code Online (Sandbox Code Playgroud)

我需要使用

model_outputs = model.model(
            input_ids=batch["source_ids"],
            attention_mask=batch["source_mask"],
            labels=lm_labels.to(device),
            decoder_attention_mask=batch['target_mask']
        )
logits = model_outputs.logits
softmax_logits = m(logits)
max_logits = torch.max(softmax_logits, dim=2)

    
Run Code Online (Sandbox Code Playgroud)

解码这些 logits 会给出未处理的文本,该文本存在许多问题,例如末尾重复单词等。我需要做什么才能获得与 model.generate() 相同的结果?

nlp huggingface-transformers

4
推荐指数
1
解决办法
3176
查看次数

如何使用停用词列表提前停止自回归模型?

我正在使用 GPT-Neo 模型来transformers生成文本。因为我使用的提示以 开头'{',所以我想在'}'生成配对后停止该句子。我发现源代码中有一个StoppingCriteria方法,但没有进一步说明如何使用它。有人找到了提前停止模型生成的方法吗?谢谢!

这是我尝试过的:

from transformers import StoppingCriteria, AutoModelForCausalLM, AutoTokenizer
model_name = 'gpt2'
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, pad_token_id=tokenizer.eos_token_id, torch_dtype=dtype).eval()

class KeywordsStoppingCriteria(StoppingCriteria):
    def __init__(self, keywords_ids:list):
        self.keywords = keywords_ids

    def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
        if input_ids in self.keywords:
            return True
        return False

stop_words = ['}', ' }', '\n']
stop_ids = [tokenizer.encode(w) for w in stop_words]
stop_ids.append(tokenizer.eos_token_id)
stop_criteria = KeywordsStoppingCriteria(stop_ids)

model.generate(
    text_inputs='some text:{', 
    StoppingCriteria=stop_criteria
)

Run Code Online (Sandbox Code Playgroud)

python autoregressive-models huggingface-transformers gpt-2

4
推荐指数
1
解决办法
2938
查看次数

Huggingface 长文档摘要

我预计摘要任务通常会假设长文档。但是,根据此处的文档,我所做的任何简单摘要调用都表示我的文档太长:

>>> summarizer = pipeline("summarization")
>>> summarizer(fulltext)
Token indices sequence length is longer than the specified maximum sequence length for this model (5620 > 1024). Running this sequence through the model will result in indexing errors

>>> summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
>>> summary = summarizer(fulltext)
Token indices sequence length is longer than the specified maximum sequence length for this model (8084 > 1024). Running this sequence through the model will result in indexing errors

>>> summarizer = pipeline("summarization", …
Run Code Online (Sandbox Code Playgroud)

python huggingface-transformers

4
推荐指数
1
解决办法
3782
查看次数

Transformers:如何使用 CUDA 进行推理?

我已经使用 GPU 微调了我的模型,但推理过程非常慢,我认为这是因为推理默认使用 CPU。这是我的推理代码:

txt = "This was nice place"
model = transformers.BertForSequenceClassification.from_pretrained(model_path, num_labels=24)
tokenizer = transformers.BertTokenizer.from_pretrained('TurkuNLP/bert-base-finnish-cased-v1')
encoding = tokenizer.encode_plus(txt, add_special_tokens = True, truncation = True, padding = "max_length", return_attention_mask = True, return_tensors = "pt")
output = model(**encoding)
output = output.logits.softmax(dim=-1).detach().cpu().flatten().numpy().tolist()
Run Code Online (Sandbox Code Playgroud)

这是我的第二个推理代码,它使用管道(针对不同的模型):

classifier = transformers.pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
result = classifier(txt)
Run Code Online (Sandbox Code Playgroud)

如何强制 Transformer 库在 GPU 上进行更快的推理?我尝试添加model.to(torch.device("cuda"))但会引发错误:

Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu
Run Code Online (Sandbox Code Playgroud)

我认为问题与未发送到 GPU 的数据有关。这里有一个类似的问题:pytorch summarise Failures …

python inference pytorch huggingface-transformers

4
推荐指数
1
解决办法
1万
查看次数

在代理后面拥抱人脸管道 - Windows Server OS

我正在尝试在代理后面使用拥抱面部管道。考虑以下代码行

from transformers import pipeline
sentimentAnalysis_pipeline = pipeline("sentiment-analysis")
Run Code Online (Sandbox Code Playgroud)

上面的代码给出了以下错误。

HTTPSConnectionPool(host='huggingface.co', port=443): url 超出最大重试次数:/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/config.json (由 ProxyError('Your代理似乎只使用 HTTP 而不是 HTTPS,请尝试将代理 URL 更改为 HTTP。请参阅:https: //urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#https-proxy-error-http -proxy' , SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] 版本号错误 (_ssl.c:1091)'))))

我尝试使用以下代码检查具有操作系统“windows server 2016 Datacenter”的计算机上的代理。

import urllib.request
print(urllib.request.getproxies())
Run Code Online (Sandbox Code Playgroud)

输出如下:

{'http': 'http://12.10.10.12:8080', 'https': 'https://12.10.10.12:8080', 'ftp': 'ftp://12.10.10.12:8080'}
Run Code Online (Sandbox Code Playgroud)

但是,根据urlib3页面的文档,上述设置不兼容,问题在于 https 设置:

{  
"http": "http://127.0.0.1:8888", 
"https": "https://127.0.0.1:8888"  # <--- This setting is the problem! 
} 
Run Code Online (Sandbox Code Playgroud)

正确的设置是

{  # Everything is good here! :)
  "http": "http://127.0.0.1:8888",
  "https": "http://127.0.0.1:8888"
}
Run Code Online (Sandbox Code Playgroud)

我们如何在 Windows 操作系统中将"https": "https://127.0.0.1:8888"代理设置更改为 …

windows proxy machine-learning deep-learning huggingface-transformers

4
推荐指数
1
解决办法
6315
查看次数

Huggingface 模型的 OSError

我正在尝试使用拥抱模型(CamelBERT),但在加载分词器时出现错误:代码:

from transformers import AutoTokenizer, AutoModelForMaskedLM
tokenizer = AutoTokenizer.from_pretrained("CAMeL-Lab/bert-base-arabic-camelbert-ca")
model = AutoModelForMaskedLM.from_pretrained("CAMeL-Lab/bert-base-arabic-camelbert-ca")
Run Code Online (Sandbox Code Playgroud)

错误:

OSError: Can't load config for 'CAMeL-Lab/bert-base-arabic-camelbert-ca'. Make sure that:

- 'CAMeL-Lab/bert-base-arabic-camelbert-ca' is a correct model identifier listed on 'https://huggingface.co/models'

- or 'CAMeL-Lab/bert-base-arabic-camelbert-ca' is the correct path to a directory containing a config.json file
Run Code Online (Sandbox Code Playgroud)

由于此错误,我无法运行该模型。

python nlp deep-learning bert-language-model huggingface-transformers

4
推荐指数
1
解决办法
2万
查看次数