标签: huggingface-transformers

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

从 Huggingface 模型中提取中性情绪

我正在使用 Hugging-face 管道进行情绪分析任务,它为我提供积极/消极情绪以及置信度得分。就我而言,我需要三个输出(正/中性/负)。问题是,即使是中性句子(例如:“他有她有”),拥抱脸也会给我很高的置信度分数?有什么建议么?

from transformers import pipeline
model = pipeline(task = 'sentiment-analysis')
sentence = 'some text to evaluate'
predicted = model(sentence)
print(predicted)
Run Code Online (Sandbox Code Playgroud)

以下是一些输出示例:

----------------------------------------------
sentence = 'I love you'
predicted = model(sentence)
predicted
[{'label': 'POSITIVE', 'score': 0.9998656511306763}]
----------------------------------------------
sentence = 'I hate you'
predicted = model(sentence)
predicted
[{'label': 'NEGATIVE', 'score': 0.9991129040718079}]
----------------------------------------------
sentence = 'I have she had'
predicted = model(sentence)
predicted
[{'label': 'POSITIVE', 'score': 0.9821817874908447}]
----------------------------------------------
sentence = 'I go to work'
predicted = model(sentence)
predicted
[{'label': 'POSITIVE', 'score': …
Run Code Online (Sandbox Code Playgroud)

python nlp sentiment-analysis huggingface-transformers

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

Huggingface GPT2 损失理解

(也发布在这里https://discuss.huggingface.co/t/newbie-understanding-gpt2-loss/33590

我对 GPT2 损失的理解陷入困境。我想为模型提供具有它将生成的目标的标签,以便我可以看到损失为零。

我有一个输入文本 input_text = "Welcome to New York" 当前模型预测下一个单词为City 如果我将标签指定为 input_text,则损失永远不会为零。我如何模拟给出“欢迎来到纽约市”标签,以便内部神经网络(无论模型如何)给出零或接近零的损失?

为了更多地解释我的意思,这是片段。

注意 - 我已阅读论坛和文档,标签可以与输入文本相同,模型将向左移动标签,并且不会计算最后一个标记的损失。但损失仍然应该为零,但事实并非如此。

语言建模的标签。请注意,标签在模型内部移动,即您可以设置 labels = input_ids...。

from transformers import GPT2LMHeadModel, GPT2Tokenizer

model_name = 'gpt2'
tokenizer = GPT2Tokenizer.from_pretrained(model_name,model_max_length=1024,padding_side='left')
tokenizer.pad_token = tokenizer.eos_token # == <|endoftext|> = 50256
model = GPT2LMHeadModel.from_pretrained(model_name)

batch_size=5
input_text  = "<|endoftext|> Welcome to New York"
target_text = "Welcome to New York City"

# encode the inputs
encoding = tokenizer(input_text,padding=True,max_length=batch_size,truncation=True,return_tensors="pt",)
input_ids, attention_mask = encoding.input_ids, encoding.attention_mask
# encode the targets
target_encoding = …
Run Code Online (Sandbox Code Playgroud)

pytorch huggingface-transformers gpt-2

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

AutoModelForCausalLM 用于提取文本嵌入

我有一个使用 AutoModelForCausalLM 来回答问题的应用程序。我需要使用相同的模型从文本中提取嵌入。我知道我可以使用 SentenceTransformer,但这意味着我加载模型权重的两倍。如何使用 AutoModelForCausalLM 从文本中提取嵌入?

huggingface-transformers

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

使用 Huggingface Trainer 时如何指定使用哪个 GPU

HuggingFace 提供如下的training_args。当我使用 HF trainer 训练模型时,我发现默认使用 cuda:0。

我浏览了 HuggingFace 文档,但仍然不知道在使用 HF 训练器时如何指定在哪个 GPU 上运行。

training_args = TrainingArguments(
    output_dir='./results',          # output directory
    num_train_epochs=3,              # total # of training epochs
    per_device_train_batch_size=16,  # batch size per device during training
    per_device_eval_batch_size=64,   # batch size for evaluation
    warmup_steps=500,                # number of warmup steps for learning rate scheduler
    weight_decay=0.01,               # strength of weight decay
    logging_dir='./logs',            # directory for storing logs
)
Run Code Online (Sandbox Code Playgroud)

huggingface-transformers

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

如何将 Llama 模型与 langchain 结合使用?它给出了一个错误:管道无法从以下位置推断出合适的模型类:&lt;model_name&gt; - HuggingFace

使用 peft 和 lora微调模型 ( https://huggingface.co/decapoda-research/llama-7b-hf ) 并保存为https://huggingface.co/lucas0/empath-llama-7bPipeline cannot infer suitable model classes from现在,当我尝试将它与 langchain 和 chroma vectordb 一起使用时,我得到:

from langchain.embeddings import HuggingFaceHubEmbeddings
from langchain import PromptTemplate, HuggingFaceHub, LLMChain
from langchain.chains import RetrievalQA
from langchain.prompts import PromptTemplate
from langchain.vectorstores import Chroma

repo_id = "sentence-transformers/all-mpnet-base-v2"
embedder = HuggingFaceHubEmbeddings(
    repo_id=repo_id,
    task="feature-extraction",
    huggingfacehub_api_token="XXXXX",
)
comments = ["foo", "bar"]
embeddings = embedder.embed_documents(texts=comments)
docsearch = Chroma.from_texts(comments, embedder).as_retriever()
#docsearch = Chroma.from_documents(texts, embeddings)

llm = HuggingFaceHub(repo_id='lucas0/empath-llama-7b', huggingfacehub_api_token='XXXXX')
qa = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=docsearch, return_source_documents=False) …
Run Code Online (Sandbox Code Playgroud)

python huggingface-transformers langchain large-language-model chromadb

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

flan-t5-xxl:ValueError:需要包含卸载权重的“state_dict”或“save_folder”

我尝试在我的 Mac M1 和 Google Colab 中运行 Hugging Face 中的 flan-t5-xxx 模型,两者都有相同的错误:

ValueError: Need either a state_dict or a save_folder containing offloaded weights.

模型卡中的代码:

from transformers import T5Tokenizer, T5ForConditionalGeneration
tokenizer = T5Tokenizer.from_pretrained("google/flan-t5-xxl")
model = T5ForConditionalGeneration.from_pretrained("google/flan-t5-xxl", device_map="auto")
input_text = "translate English to German: How old are you?"
input_ids = tokenizer(input_text, return_tensors="pt").input_ids.to("cuda")
outputs = model.generate(input_ids)
print(tokenizer.decode(outputs[0]))
Run Code Online (Sandbox Code Playgroud)

huggingface-transformers

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

ERR_REQUIRE_ESM 用于使用 @xenova/transformers 导入

在我的 NodeJS 应用程序中,我像这样导入:

import { AutoModel, AutoTokenizer } from '@xenova/transformers';
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

const tokenizer = await AutoTokenizer.from_pretrained('bert-base-uncased');
Run Code Online (Sandbox Code Playgroud)

但是,当我运行脚本时,我得到以下信息:

> node --experimental-modules lib/index.js

No storage option exists to persist the session, which may result in unexpected behavior when using auth.
        If you want to set persistSession to true, please provide a storage option or you may set persistSession to false to disable this warning.
Starting script...
Error [ERR_REQUIRE_ESM]: require() of ES Module /home/me/Projects/node_modules/@xenova/transformers/src/transformers.js from /home/me/Projects/lib/pinecone/utils.js not supported.
Instead change the require of …
Run Code Online (Sandbox Code Playgroud)

node.js typescript huggingface-transformers

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

使用 HuggingFace 库在 Pytorch 中训练 BERT 的最后 n% 层(训练 Last 5 BERTLAYER out of 12 。)

Bert 有一个类似于encoder -> 12 BertLayer -> Pooling. 我想训练 Bert 模型的最后 40% 层。我可以将所有图层冻结为:

# freeze parameters
bert = AutoModel.from_pretrained('bert-base-uncased')
for param in bert.parameters():
    param.requires_grad = False

Run Code Online (Sandbox Code Playgroud)

但我想训练最后 40% 的层。当我这样做时len(list(bert.parameters())),它给了我 199。所以让我们假设 79 是参数的 40%。我可以做这样的事情:

for param in list(bert.parameters())[-79:]: # total  trainable 199 Params: 79 is 40%
    param.requires_grad = False
Run Code Online (Sandbox Code Playgroud)

我认为它会冻结前 60% 的层。

另外,有人可以告诉我它会根据架构冻结哪些层吗?

nlp deep-learning torch pytorch huggingface-transformers

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

将 seq2seq NLP 模型转换为 ONNX 格式会对其性能产生负面影响吗?

我正在考虑将 ml NLP 模型转换为 ONNX 格式,以利用其速度提升(ONNX 运行时)。但是,我真的不明白新模型与旧模型相比有什么根本性的变化。另外,不知道有没有什么缺点。对此的任何想法将不胜感激。

python nlp machine-learning onnx huggingface-transformers

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