docs
stringclasses
4 values
category
stringlengths
3
31
thread
stringlengths
7
255
href
stringlengths
42
278
question
stringlengths
0
30.3k
context
stringlengths
0
24.9k
marked
int64
0
1
huggingface
Beginners
Custom Distilbert does not use CUDA for predition
https://discuss.huggingface.co/t/custom-distilbert-does-not-use-cuda-for-predition/8699
Hi, I am using the model classifier = pipeline(“text-classification”,model=‘bhadresh-savani/distilbert-base-uncased-emotion’, return_all_scores=True) for emotion classification of my datatset of 1.2m client feedbacks. I am not training the model, I am just doing a prediction. I noticed that the model uses CPU and does ...
I found a solution, add parameter device=0. But I have to classify in small batches as the GPU RAM is a serious limit, even my GPU has 16 GB
0
huggingface
Beginners
Trying to Build Datasets, Random Items Get Added
https://discuss.huggingface.co/t/trying-to-build-datasets-random-items-get-added/8724
Hi all, I’m currently trying to load in fastai’s version of the IMDB dataset, to learn how to build a Dataset from a folder of .txt's. I’m preparing my data with the following: # Downloading the dataset from fastai.data.external import untar_data, URLs from fastai.data.transforms import get_files path = untar_data(URL...
I think it’s because the “text” loader creates a new sample for each “\n” it sees, so the texts you have that contain some of those are then split into several samples. @lhoestq or @albertvillanova if you could conifrm? PS: it would be easier to just do dsets = load_dataset('imdb') :-p
0
huggingface
Beginners
Evaluation became slower and slower during Trainer.train()
https://discuss.huggingface.co/t/evaluation-became-slower-and-slower-during-trainer-train/8682
When I used Trainer.train() to fine-tune BartBase, I found something weird that the speed shown in progress bar became slower and slower (from 6 item/s to 0.29 item/s. Please help me, I’m new to transformers. Here are my codes. training_args = TrainingArguments( output_dir="Model/BartBase", overwrite_output_dir...
After debugging step by step, I found that If I remove the compute_metrics=compute_metrics in Trainer, the evaluation went well. Even if I use a quite simple compute_metrics, the evaluation became slow and stopped eventually (without finishing progress) .def compute_metrics(eval_pred): return {'f1': 1} Pleas...
0
huggingface
Beginners
Passing additional tensors into metric evaluation function
https://discuss.huggingface.co/t/passing-additional-tensors-into-metric-evaluation-function/8618
Hi, I was wondering if it is possible to pass additional labels into metric evaluation function. In more details, I want to calculate metrics using not all predicted tokens but only a small subset, and to do this I need to pass a tensor of indices of that tokens into the metric evaluation function. But I don’t need th...
If you leave it in your dataset, you will have an error since your model can’t consume it. You will need to write a manual evaluation loop for this use case.
0
huggingface
Beginners
Error while training a custom pretrained model
https://discuss.huggingface.co/t/error-while-training-a-custom-pretrained-model/8588
Hi, I trained a model as follows: checkpoint = “bert-base-uncased” tokenizer = AutoTokenizer.from_pretrained(checkpoint) model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=5) After 3 epochs I wanted to finetune this model again with the following code (I tried all three versions): #1 mode...
It’s logical you got that error for the last two lines since BertModel does not accept a labels argument. I don’t think you had that exact error for the first one as it does accept a labels argument.
0
huggingface
Beginners
How can I do word classification?
https://discuss.huggingface.co/t/how-can-i-do-word-classification/8639
I am very new to nlp so sorry for the question. I am wondering if there a name for this task and if I can do it in deep learning or even in huggingdace Let say I have some sentences, for example: s1: I have a dog s2: I am new to this, I convert my sentences to embedded features and now I have an inputs with shape of...
I’m not sure that I understood your question entirely. But classifying words like you said, would be close to a Named Entity Recognition task I think. BERT like models can produce word embeddings for input sentences, which means separate embedding vector for each word. Maybe you could use such model for your task.
0
huggingface
Beginners
How to specify different batch sizes for different GPUs when training with rum_mlm.py?
https://discuss.huggingface.co/t/how-to-specify-different-batch-sizes-for-different-gpus-when-training-with-rum-mlm-py/8573
Hi, I’m using run_mlm.py to train a custom BERT model. I have two GPUs available. One has 24GB of memory and the other has 11 GB of memory. I want to use the batch size of 64 for the larger GPU and the batch size of 16 for the smaller GPU. How can I do so? The --per_device_train_batch_size parameter only takes one numb...
This use case is not supported by the Trainer API, it would require custom scripts (one per GPU) to work, and even then, I’m not sure you will see any speed gain by training on two different GPUs that are not of the same type.
0
huggingface
Beginners
“compute_loss” function
https://discuss.huggingface.co/t/compute-loss-function/8649
Could someone give some insight to the “model.compute_loss” function which is used when fine-tuning the models without the trainer API (e.g- Keras native training). How does it work (i.e.- for different tasks how it’s adapted.)? It says that it takes the first element of the output, how is the loss calculated then?
as shown in here in Huggingface documentation, Fine-tuning with custom datasets — transformers 4.7.0 documentation 1
0
huggingface
Beginners
BERT: AttributeError: ‘RobertaForMaskedLM’ object has no attribute ‘bert’
https://discuss.huggingface.co/t/bert-attributeerror-robertaformaskedlm-object-has-no-attribute-bert/8362
I am trying to freeze some layers of my masked language model using the following code: for param in model.bert.parameters(): param.requires_grad = False However, when I execute the code above, I get this error: AttributeError: 'RobertaForMaskedLM' object has no attribute 'bert' In my code, I have the following i...
The name of the body of the model roberta for Roberta models, not bert. So you should loop on for param in model.roberta.parameters(). In general, the attribute that is model agnostic is base_model, so for param in model.base_model.parameters() should work anywhere.
0
huggingface
Beginners
Accessing uncontextualized BERT word embeddings
https://discuss.huggingface.co/t/accessing-uncontextualized-bert-word-embeddings/1812
Hi there! Once I’ve imported a BERT model from HuggingFace, is there a way to convert a sequence of encoded tokens into BERT’s raw embeddings without contextualizing them using self-attention, or otherwise extract the raw embedding for a given token?
Try this. I think the apis change a bit between models so take a look before you copy paste model = DistilBertForTokenClassification.from_pretrained( "distilbert-base-cased", num_labels=self.num_labels ) word_embeddings = model.distilbert.embeddings.word_embeddings([...
0
huggingface
Beginners
Converting TF-Bert to Torch using conversion script works, but
https://discuss.huggingface.co/t/converting-tf-bert-to-torch-using-conversion-script-works-but/574
Hi there - we are using this BERT architecture from Google: * attention_probs_dropout_prob:0.1 * hidden_act:"gelu" * hidden_dropout_prob:0.1 * hidden_size:768 * initializer_range:0.02 * intermediate_size:3072 * max_position_embeddings:512 * num_attention_heads:12 * num_hidden_layers:12 * type_vocab_size:2 * vocab_size:...
Just in case someone runs into the same issue: It was a problem with the naming of the layers our naming came from an Nvidia TF package and it is differed from standard naming - we did the mapping ourselves and now the model is working and producing the same output for identical input. the script was still useful to s...
0
huggingface
Beginners
Training a reformer from scratch
https://discuss.huggingface.co/t/training-a-reformer-from-scratch/8287
Hello, I want to train a reformer for a sequence classification task. The sequences are of protein so I thought of making a new tokenizer and then loaded as a reformer tokenizer which is defined as below. spm.SentencePieceTrainer.train(input='./sequences_scope.txt', model_prefix='REFORM', max_sentence_length=2000, voca...
hey @choke what does an example in your tokenized inputs look like? from the error, i think you could try renaming the target column to labels which is what the Trainer expects by default
0
huggingface
Beginners
How does BERT know which contextualised embedding to choose for a word?
https://discuss.huggingface.co/t/how-does-bert-know-which-contextualised-embedding-to-choose-for-a-word/8516
Hi! I am trying to explain BERT. I understand the concept of contextualised embedding, where one word has different embeddings depending on the context. I also understand that when by using bidirectionality, BERT can learn these contextualised embedding during pretraining. My question is when finetuning BERT for a task...
I am new to the topic of Transformers, but my understanding (limited as it is) of BERT is that whilst the pre-trained embedding is created through semi-supervised learning (just large unannoted text corpora), when it comes to fine-tuning BERT for a specific task then this is usually a supervised learning process. So ef...
0
huggingface
Beginners
Is Transformers using GPU by default?
https://discuss.huggingface.co/t/is-transformers-using-gpu-by-default/8500
I’m instantiating a model with this tokenizer = AutoTokenizer.from_pretrained("nlptown/bert-base-multilingual-uncased-sentiment") model = AutoModelForSequenceClassification.from_pretrained("nlptown/bert-base-multilingual-uncased-sentiment") Then running a for loop to get prediction over 10k sentences on a G4 instance ...
This like with every PyTorch model, you need to put it on the GPU, as well as your batches of inputs.
0
huggingface
Beginners
Small Doubt :- Is there any mistake while finding results from DeBERTa model for SNLI Dataset
https://discuss.huggingface.co/t/small-doubt-is-there-any-mistake-while-finding-results-from-deberta-model-for-snli-dataset/8311
Hi everyone. from transformers import DebertaTokenizer, DebertaForSequenceClassification import torch max_length = 512 premise = "I do not love you" hypothesis = "I love you" hg_model_hub_name = "microsoft/deberta-base-mnli" tokenizer = DebertaTokenizer.from_pretrained(hg_model_hub_name) model = DebertaForSequence...
hey @akshat-suwalka i think the reason why you’re getting a much lower score on the snli dataset is due to a misalignment between the label → label_id mappings in the model and dataset. to explain what i mean, note that the config.json of the deberta model has the following mappings: "id2label": { "0": "CONTRADIC...
0
huggingface
Beginners
Some functions when customizing trainer
https://discuss.huggingface.co/t/some-functions-when-customizing-trainer/8413
Hi, it is glad to find the behavior of “Trainer” can be customized by overriding its methods. However, I am facing a problem with the originally existed functions. For example: def training_step(self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]) -> torch.Tensor: ... if is_sagemaker_mp_enabled(...
There is no reason you shouldn’t be able to import is_sagemaker_mp_enabled from its location (transformers.file_utils).
0
huggingface
Beginners
Compare the likelihood of various sentences in a LM?
https://discuss.huggingface.co/t/compare-the-likelihood-of-various-sentences-in-a-lm/7234
Hi! I have the beginning of a sentence (2-3 words) and couple candidate full sentences starting or ending with those words. Is there an easy way to use Transformers to know which of the full sentences was more likely to be output by a language model?
Hi Olivier, What about comparing the average log-likelihoods 4 of yours candidates?
0
huggingface
Beginners
Make predictions with the Dropout on
https://discuss.huggingface.co/t/make-predictions-with-the-dropout-on/5138
The default behavior of Trainer(...) when evaluating model is disabling Dropout. Concretely, y_pred for M runs will be exactly the same for i in range(M): logits, labels, metrics = trainer.predict(tokenized_datasets["eval"]) y_pred = np.argmax(logits, axis=2) ... Now I am trying to apply Monte Carlo Dropou...
I don’t think this is possible with the Trainer class as it is, but you can derive this class and then change the relevant methods. In your case, I think you need to change the evaluation_loop method and delete the model.eval() line. I think it would be better to keep the model.eval() line and set only the Dropout laye...
0
huggingface
Beginners
AdamW implementation
https://discuss.huggingface.co/t/adamw-implementation/8426
Hi, I was looking at the implementation of the AdamW optimizer 5 and I didn’t understand why you put the weight decay at the end. Shouldn’t you swap between this line: p.data.addcdiv_(exp_avg, denom, value=-step_size) and the weight decay part? Thanks. The AdamW algorithm from the “DECOUPLED WEIGHT DECAY REGULARIZATIO...
The two lines substract an independent thing to the model parameters, so executing them in any order will give the same results.
0
huggingface
Beginners
Fine-tune a model on translation:
https://discuss.huggingface.co/t/fine-tune-a-model-on-translation/8443
when passing all along with datasets to the Seq2SeqTrainercall I got : HTTPError: 400 Client Error: Bad Request for url: https://huggingface.co/api/repos/create - Only regular characters and ‘-’, ‘_’, ‘.’ accepted
You should post relevant code when asking for help, otherwise no one can really understand what’s going on. In this instance, the problem is very likely when your define your Seq2SeqTrainingArguments, so please share how you defined those, or if you used your code as a script, what arguments you passed to it,
0
huggingface
Beginners
Memory issues with model deployment
https://discuss.huggingface.co/t/memory-issues-with-model-deployment/748
With the help of awesome transformers library I have trained a multilabel classificator, which predicts topics for comments. I’m using TFDistilBertModel as a layer, wrapped in Keras functional API. So the architecture of a model is following: 2 input layers, then a layer, respawned as such: distilbert_layer = TFDistilB...
I am currently facing the same issue. I deployed a question and answering model on digital ocean server droplet. After sending it a few texts the server stopped running and went down. My take is ONNX runtime 2 would help; have you tried it? I am converting the model to onnx and redeploying it to see how it would perfor...
0
huggingface
Beginners
Deploy multilingual sentence tansformer into cloud
https://discuss.huggingface.co/t/deploy-multilingual-sentence-tansformer-into-cloud/4354
Hi community, I am new to transformer models and particularly interested by a multilingual sentence transformer (stsb-xlm-r-multilingual, 1.1 Go). I have passed multiple times to search on how to deploy this model on cloud with the highest throughput (up to 1000 requests/sec) and lowest latency (<1 sec), while trying t...
Hi, Would anyone have advice? Thanks !
0
huggingface
Beginners
Truncating sequence – within a pipeline
https://discuss.huggingface.co/t/truncating-sequence-within-a-pipeline/336
Hi all, Thanks for making this forum! I have a list of tests, one of which apparently happens to be 516 tokens long. I have been using the feature-extraction pipeline to process the texts, just using the simple function: nlp = pipeline('feature-extraction') When it gets up to the long text, I get an error: Token indi...
One quick follow-up – I just realized that the message earlier is just a warning, and not an error, which comes from the tokenizer portion. I then get an error on the model portion: IndexError: index out of range in self So I have two questions: Is there a way to just add an argument somewhere that does the truncati...
0
huggingface
Beginners
Do we need to fine-tune Wav2Vec2FeatureExtractor?
https://discuss.huggingface.co/t/do-we-need-to-fine-tune-wav2vec2featureextractor/8260
Hi, I’m thinking about training wav2vec2 model for Japanese. And I have a question. Do we need Wav2Vec2FeatureExtractor as well? Or can we use Wav2Vec2FeatureExtractor for any languages? Thanks in advacne.
[Found answer]It seems there are 2 kinds of feature extractors. 1st one is just normalize raw audio and 2nd one is part of architecture. Since 1st one is just normalizing raw audio, I don’t think we need to train it.
0
huggingface
Beginners
Batch input for wav2vec2 pretraining
https://discuss.huggingface.co/t/batch-input-for-wav2vec2-pretraining/8133
Hi I have a question about how to pad audio when training wav2vec2 model. The tutorial explains how to handle batch size of one. input_values = processor(ds["speech"][0], return_tensors="pt").input_values # Batch size 1 logits = model(input_values).logits predicted_ids = torch.argmax(logits, dim=-1) But I think I nee...
[Found Answer] It’s going to pad with 0.0. I found it…
0
huggingface
Beginners
Is it possible to create a Résumé parser using a Huggingface model?
https://discuss.huggingface.co/t/is-it-possible-to-create-a-resume-parser-using-a-huggingface-model/2840
In other words, is it possible to train a supervised transformer model to pull out specific from unstructured or semi-structured text and if so, which pretrained model would be best for this? In the resume example, I’d want to input the text version of a person’s resume and get a json like the following as output: {‘Ed...
Is there any reason you’re looking to do this with a transformer? This is a common vision problem, and transformers aren’t usually the first port of call for a problem like this.
0
huggingface
Beginners
How to freeze layers using trainer?
https://discuss.huggingface.co/t/how-to-freeze-layers-using-trainer/4702
Hey, I am trying to figure out how to freeze layers of a model and read that I had to use for param in model.base_model.parameters(): param.requires_grad = False if I wanted to freeze the encoder of a pretrained MLM for example. But how do I use this with the Trainer? I tried the following: from transformers impor...
Looking at the source code of BertForMaskedLM 33, the base model is the “bert” attribute, not the “base_model” attribute. So if you want to freeze the parameters of the base model before training, you should type for param in model.bert.parameters(): param.requires_grad = False instead.
0
huggingface
Beginners
Get Optuna study from hyperparameter-search in Trainer?
https://discuss.huggingface.co/t/get-optuna-study-from-hyperparameter-search-in-trainer/4784
Hi there, I use hyperparameter-search in Trainer with Optuna and wanted to know if there is an easy option to access the study itself. From what I’ve read in the implementation, only the BestRun is returned by run_hp_search_optuna() and not the study itself. (I’m asking because I wanted to try out the plot functions of...
Hello, I have this confusion too. Have you solved this problem? After some trying, I find this page is helpful——Saving/Resuming Study with RDB Backend 23.
0
huggingface
Beginners
Predicting only ” ” after training (S2T) Wav2Vec2CTC
https://discuss.huggingface.co/t/predicting-only-after-training-s2t-wav2vec2ctc/5702
My work so far: colab.research.google.com Google Colaboratory 2 So I have copied the code from Fine-Tune XLSR-Wav2Vec2 for low-resource ASR with 🤗 Transformers 2 and tried to implement things separately. But, after I run trainer.train and try to get the prediction...
I have the same issue, the loss is nan and after 1 epoch the model predicts empty strings please, have you found the root of the issue? thanks.
0
huggingface
Beginners
“AttributeError: ‘Seq2SeqTrainer’ object has no attribute ‘repo’” after running trainer.push_to_hub()
https://discuss.huggingface.co/t/attributeerror-seq2seqtrainer-object-has-no-attribute-repo-after-running-trainer-push-to-hub/8274
Just fine-tuned pegasus-large on Google Colab Pro. I create a Seq2SeqTrainer like so: trainer = Seq2SeqTrainer( model=model, args=args, train_dataset=tokenized_datasets["train"], eval_dataset=tokenized_datasets["test"], data_collator=data_collator, tokenizer=tokenizer, compute_metrics=comput...
hey @JakeMSc this error is a bit odd because it suggests the Trainer.init_git_repo function is not being called which can only happen if TrainingArguments.push_to_hub is not set to True. in particular, i could not reproduce your error by pushing a seq2seq model to the hub with the official translation tutorial here: Go...
0
huggingface
Beginners
Convert bert tokenizer to onnx
https://discuss.huggingface.co/t/convert-bert-tokenizer-to-onnx/8299
I was referring to the following blog to convert bert model to onnx. Medium – 17 Jun 20 Accelerate your NLP pipelines using Hugging Face Transformers and ONNX Runtime 2 This post was written by Morgan Funtowicz from Hugging Face and Tianlei Wu from Microsoft Reading time: 6 min ...
hi @hasak, hasak: Is there a way, where I’ll be able to pass sentence as input to the onnx tokenizer and get encodings as output, so that I’ll be able to use the model platform-independent the tokenizer is independent of onnx / onnxruntime, so you could create a simple function that converts your string inputs i...
0
huggingface
Beginners
Set the format of the datasets to return pytorch tensors return list of tensors but why?
https://discuss.huggingface.co/t/set-the-format-of-the-datasets-to-return-pytorch-tensors-return-list-of-tensors-but-why/8084
Hello, I am folllowing this tutorial to use Fine-tuning a pretrained model — transformers 4.7.0 documentation 4 in order to use the flauBert to produce embeddings to train my classifier. In one of the lines , I have to set my dataset to pytorch tensors but when applying that line I get a list format which I do not unde...
The reason could be that during tokenization, padding and/or truncation is not enabled which results in encoded inputs with different lengths. This would prevent the type conversion to convert input_ids to a tensor since its elements are of different size and the result would be a list of tensors.
0
huggingface
Beginners
How downstream tasks work
https://discuss.huggingface.co/t/how-downstream-tasks-work/8249
Hello. I was surprised that I only need to add a few lines of code to solve various tasks with the help of Bert. For exampe below is downstream task code for ML one: (cls): BertOnlyMLMHead( (predictions): BertLMPredictionHead( (transform): BertPredictionHeadTransform( (dense): Linear(in_features=768...
During the pretraining procedure of BERT, there are two tasks: Masked Language Modeling and Next Sequence Prediction. Masked Language Prediction requires the model to make predictions for every token in the model, including the [MASK] token which is modeled by a layer that generates outputs over the entire vocabulary, ...
0
huggingface
Beginners
“Dump_all() got an unexpected keyword argument ‘sort_keys’” after running trainer.push_to_hub()
https://discuss.huggingface.co/t/dump-all-got-an-unexpected-keyword-argument-sort-keys-after-running-trainer-push-to-hub/8269
Just fine-tuned pegasus-large on Google Colab Pro with trainer.train(), then executed the following commands: !huggingface-cli login !pip install hf-lfs !git config --global user.email "jakemsc@example.com" !git config --global user.name "JakeMSc" trainer.push_to_hub("test_model") Which leads to the following error: T...
What is your version of pyaml? I think you need a more recent version (pip install --upgrade pyyaml). Will adjust the setup.
0
huggingface
Beginners
Metric computation code
https://discuss.huggingface.co/t/metric-computation-code/8266
Hi, can somebody points out where I can find the metric computation code in the HF? e.g. CIDEr, METEOR, ROUGE, BLEU Thanks.
hey @zuujhyt you can find all the scripts to compute metrics in the datasets library here: datasets/metrics at master · huggingface/datasets · GitHub 5
0
huggingface
Beginners
Defining a custom dataset for fine-tuning translation
https://discuss.huggingface.co/t/defining-a-custom-dataset-for-fine-tuning-translation/6913
I’m a first time user of the huggingface library. I am struggling to convert my custom dataset into one that can be used by the hugginface trainer for translation task with MBART-50 2. The languages I am trying to train on are a part of the pre-trained model, I am simply trying to improve the model’s translation capabi...
This is exactly what I am trying to do too with no luck yet. Please let me know if you have found a way to do this.
0
huggingface
Beginners
Add a classification head to a fine-tuned language model
https://discuss.huggingface.co/t/add-a-classification-head-to-a-fine-tuned-language-model/8176
We I have fine-tuned a GPT-2 model with a language model head on medical triage text, and would like to use this model as a classifier. However, as far as I can tell, the Automodel Huggingface library allows me to have either a LM or a classifier etc. head, but I don’t see a way to add a classifier on top of a fine-tun...
You need to use the AutoModelForSequenceClassification class to add a classification head on top of your pretrained model.
0
huggingface
Beginners
What should be shifted for decoder input for Bart
https://discuss.huggingface.co/t/what-should-be-shifted-for-decoder-input-for-bart/8175
Hi, In HF’s doc 1, regarding decoder_input_ids it says ... create this tensor by shifting the `input_ids` to the right..... Shouldn’t it be shifting the labels? because the input is noisy? Thank you.
I think this is copy pasted from the causal language modeling doc (for which your labels are your inputs shifted to the right).
0
huggingface
Beginners
Getting the MLM accuracy for the BERT model I am training from scratch
https://discuss.huggingface.co/t/getting-the-mlm-accuracy-for-the-bert-model-i-am-training-from-scratch/6795
Hi I am training a BERTforMaskedLM model from scratch. This is my tokenizer (previously trained) tokenizer = BertTokenizer('vocab.txt') This is my config: config = BertConfig( vocab_size=20000, max_position_embeddings=258 ) This is how I load the model from the last checkpoint: model = BertForMaskedLM.from_pr...
How many total steps are there in your training? Since you chose the "steps" strategy, I wonder if it’s just because evaluation is never run?
0
huggingface
Beginners
Summarization : Conversation
https://discuss.huggingface.co/t/summarization-conversation/8117
I am new in this area. Please advise some good models to generate a summary on conversation between two persons. Thank you!
hey @MattJan a good place to start would be by looking at models fine-tuned on the samsum dataset (dialogues between two people + their summary): Hugging Face – The AI community building the future. 12 if you want to fine-tune your own model, a good start would be to use a pegasus model that has already be trained for ...
0
huggingface
Beginners
Training a Tokenizer on a Streamed Dataset
https://discuss.huggingface.co/t/training-a-tokenizer-on-a-streamed-dataset/8026
Hi, I’m trying to train a tokenizer on a dataset that uses streaming. I followed the instructions provided here 4, with the addition of streaming=True during the dataset loading step. However, it quickly failed as the IterableDataset class does not have a length property (unlike the normal Dataset class). How can I wor...
Hi ! You can follow the instructions here 4 and use this batch iterator instead: def batch_iterator(batch_size=1000): batch = [] for example in dataset: batch.append(example["text"]) if len(batch) == batch_size: yield batch batch = [] if batch: # yield last batch ...
0
huggingface
Beginners
Loading dataset with streaming model
https://discuss.huggingface.co/t/loading-dataset-with-streaming-model/7826
I am trying to load dataset in streaming model. The current datasets version I am using is 1.8. But it is producing the following error. --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-3-518060a18801>...
@valhalla Can you take a look?
0
huggingface
Beginners
ValueError: not enough values to unpack (expected 2, got 1)
https://discuss.huggingface.co/t/valueerror-not-enough-values-to-unpack-expected-2-got-1/3516
i am trying to create xlnet classification def __init__(self,n_classes): super(SentimentClassifier, self).__init__() self.xlnet = XLNetModel.from_pretrained(PRE_TRAINED_MODEL_NAME) self.drop = nn.Dropout(p=0.3) self.out = nn.Linear(self.xlnet.config.hidden_size, n_classes) def forward(self, input_i...
Hi @sru, Can you please include the stack trace so we can help out more?
0
huggingface
Beginners
Download model without the trained weights
https://discuss.huggingface.co/t/download-model-without-the-trained-weights/7613
Hey community, i hope you’re doing fine. I’m new to the huggingface framework, so my question is if there any way to download hugging face models(like bert…) without it’s pretrained weights? the architecture only? i’m using pytorch Thank you so much.
you can construct one using your own defined configuration. from transformers import BertForMaskedLM model = BertForMaskedLM(config=config) where in the config variable, you provide the parameters of the model - the no. of heads for attention, FCN size etc. So you can train from scratch, but you won’t need to downloa...
0
huggingface
Beginners
Use Pretrained T5 for Summarization
https://discuss.huggingface.co/t/use-pretrained-t5-for-summarization/1992
Hello, Is there any code snippet of how to use T5 pretrained model in order to do summarization?
I used the following code to do my task: from transformers import T5ForConditionalGeneration tokenizer = T5Tokenizer.from_pretrained('t5-small') model = T5ForConditionalGeneration.from_pretrained('t5-small', return_dict=True) input = "This is a summarization example. This is a large sentence." input_ids = tokenize...
0
huggingface
Beginners
Separate LM fine tuning and classification head training
https://discuss.huggingface.co/t/separate-lm-fine-tuning-and-classification-head-training/1404
I have a large text corpus, and a small subset of it that is labelled for a mutli-label text classification task. I’ve seen many (excellent!) examples of fine-tuning different models for sequence classification, but I couldn’t find one in which the training is separated to two distinct stages: Fine-tune a specific lan...
Hi @adamh You can use the run_language_modeling script here 16 to finetune the pre-trained model for ex BertForMaksedLM. Then you should be able to load the model using BertForSequenceClassification model which will take the base model and add a classification head on top, which you can then fine-tune for classificati...
0
huggingface
Beginners
UnicodeDecodeError with xprophetnet-large-wiki100-cased-xglue-qg model
https://discuss.huggingface.co/t/unicodedecodeerror-with-xprophetnet-large-wiki100-cased-xglue-qg-model/7539
Hi I’m new to the transformer model and when I run this code from transformers import ProphetNetTokenizer, ProphetNetForConditionalGeneration, ProphetNetConfig model = ProphetNetForConditionalGeneration.from_pretrained('microsoft/xprophetnet-large-wiki100-cased-xglue-qg') tokenizer = ProphetNetTokenizer.from_pretraine...
Slight hack to fix the decoder error - I tried editing ProphetNetTokenizer itself, specifically the load_vocab method and changed the encoding to ‘latin-1’. image998×420 40 KB The edit is made here 2, I did it locally so I’m not sure whether this could be done for Colab notebooks. This stackoverflow page 3 gave some ...
0
huggingface
Beginners
Running custom modifications in modeling_bart.py
https://discuss.huggingface.co/t/running-custom-modifications-in-modeling-bart-py/7448
Hi, I am planning to modify the output attention weights from the decoder in modeling_bart.py for conditional abstractive summarization. To achieve this I changed the transformers module to mytransformers and made the changes I wanted in the modeling_bart.py script. Now, when I run the run_summarization.py, I cannot im...
You can’t add files to the library like that, but you can have your updated model in the same folder as your example script with the name mytransformers.py which will then allow you to import from it.
0
huggingface
Beginners
Understanding data of dataset_infos.json
https://discuss.huggingface.co/t/understanding-data-of-dataset-infos-json/7549
Hi everyone, I was exploring dataset_infos.json , and I couldn’t figure out what some of the keys represent in the file. Could someone please point me to a reference, which I could use as column descriptions. eg of some confusing columns: “download_size”, “dataset_size”, “size_in_bytes”, “post_processing_size” and “num...
hey @dk-crazydiv you can find a description of all the DatasetInfo fields in the docs: Main classes — datasets 1.8.0 documentation 2 if something is unclear / could be improved, feel free to open a pr!
0
huggingface
Beginners
MLM: IndexError: index out of bounds
https://discuss.huggingface.co/t/mlm-indexerror-index-out-of-bounds/6722
Hi, I am following this tutorial on masked language modelling using my own dataset: notebooks/language_modeling.ipynb at master · huggingface/notebooks · GitHub 2, and I am coming across this error: Input: lm_datasets = tokenized_datasets.map( group_texts, batched=True, batch_size=1000, num_proc=4, ) O...
You should deactivate multiprocessing to have a clearer error message (remove num_proc=4). It looks like an indexing error in your dataset.
0
huggingface
Beginners
Does task specific prefix matters for T5 fine-tuning?
https://discuss.huggingface.co/t/does-task-specific-prefix-matters-for-t5-fine-tuning/501
If I understand correctly pre-trained T5 models were pre-trained with an unsupervised objective without any task specific prefix like “translate”, “summarize”, etc. Is it important then to create my summarization dataset for fine-tuning in a way that every input starts with "summarize: "?
I think it is important, but am not totally certain why. You could test it pretty easily I bet.
0
huggingface
Beginners
Why do I get ‘Ġ’ when adding emojis to the tokenizer?
https://discuss.huggingface.co/t/why-do-i-get-g-when-adding-emojis-to-the-tokenizer/7056
Hello, I have added custom tokens to my tokenizer, which are emojis. This is the code I have used, which adds the new tokens: model = AutoModelForMaskedLM.from_pretrained(model_checkpoint) num_added_toks = tokenizer.add_tokens(['👏']) print('We have added', num_added_toks, 'tokens') model.resize_token_embeddings(len(t...
github.com/pytorch/fairseq In the vocab of bart.bpe.bpe.decoder, what does Ġ mean for those words prefixed with 'Ġ'? 15 opened Feb 17, 2020 closed ...
0
huggingface
Beginners
XLM-R classifier predictions produce errors
https://discuss.huggingface.co/t/xlm-r-classifier-predictions-produce-errors/7292
Hi, I am using tf-xlm-r-base model for a sentiment classification (multi-class) task with 4 classes. I used both trainer() api and keras native method. Initially, I got some acceptable result but later it predicts only one class for the same data set. I am following this guide. Below are my outputs and code. My inputs ...
also found that for binary classification, (two from above four classes), it behaves similarly. And tried changing labels to float type and different loss function too.
0
huggingface
Beginners
Fine Tune BERT Models
https://discuss.huggingface.co/t/fine-tune-bert-models/1554
Hey, curious question to illuminate my understanding. Fine Tuning a BERT model for you downstream task can be important. So I like to tune the BERT weights. Thus, I can extract them from the BertForSequenceClassification which I can fine tune. if you fine tune eg. BertForSequenceClassification you tune the weights of t...
Any suggestions? Also what came in my mind. That TFBertForSequence is using the pooled_output. So the model is finetuned viad this pooled_output. But instead I could use the cls embedding or the globalaveragepooling of the hiddensequence for finetuning (pass to the classifier layer), right?
0
huggingface
Beginners
How to merge two dataset objects?
https://discuss.huggingface.co/t/how-to-merge-two-dataset-objects/844
Hi everyone! I have two datasets, loaded as CSV files, which have the same features/columns. I would like to know if there is a way to merge both datasets into a larger one (like I would do with pd.concat((df_1, df_2))using pandas. In case that such method does not exist, would it be interesting to implement such funct...
I would rather combine the csv’s
0
huggingface
Beginners
Distilbert-base-multilingual-cased’
https://discuss.huggingface.co/t/distilbert-base-multilingual-cased/7054
Hello I am running distilbert-base-multilingual-cased’ on Pytorch. My model has 4 classes in the target. In the code in models/distilbert/modeling_distilbert.py. I am reaching this state elif self.config.problem_type == “multi_label_classification”: ** loss_fct = BCEWithLogitsLoss()** ** l...
Note that multi_label_classification is only for problems where you can have multiple labels for one example, so you should use the default if your samples can only have one label. If you are in a true multiple label problem, then it’s very likely your labels are already in a one-hot format. For your second question, y...
0
huggingface
Beginners
How to test masked language model after training it?
https://discuss.huggingface.co/t/how-to-test-masked-language-model-after-training-it/7029
Hi, I have followed and trained my masked language model using this tutorial: notebooks/language_modeling.ipynb at master · huggingface/notebooks · GitHub 10 Now, once the model as been saved using this code below: trainer.save_model("my_model") But, the notebook does not seem to include any code to allow me to test m...
You can load it in a pipeline by using the folder where you saved it: mask_filler = pipeline("fill-mask", model="my_model")
0
huggingface
Beginners
Is it normal of more memory use of DistributedDataParallel than single
https://discuss.huggingface.co/t/is-it-normal-of-more-memory-use-of-distributeddataparallel-than-single/6987
Hello , I am new here. I try to Fine-turn MBart model ( mbart-large-cc25 ), My device : one pc(ubuntu), gpu(10GB) memory * 2 When i fine-turn on single gpu, first load model to gpu , only cost 3(GB) memory and start train it, increase to 8(GB), so i can fine-turn with small batch. I use DistributedDataParallel to have ...
There is a slight overhead when using DistributedDataParallel so it’s normal to see a bit more GPU usage yes.
0
huggingface
Beginners
How can I renew my API Key?
https://discuss.huggingface.co/t/how-can-i-renew-my-api-key/6975
Hello, is there a way I can renew my API Key? I’ve seen a few forum posts about it but I’d like to reset it.
cc @julien-c or @pierric
0
huggingface
Beginners
Non shuffle training
https://discuss.huggingface.co/t/non-shuffle-training/6986
Hi there, In order to debug something I need to make data non-shuffle. Can you please tell me how to turn off the shuffle? I am using from transformers import Trainer for training and from datasets import load_dataset for data loading with default arguments.
There is no option to do this natively in the Trainer, you can either make a source install and change the line that creates the training dataloader, or subclass Trainer and override the get_train_dataloader method.
0
huggingface
Beginners
Multiple Categories (labels)
https://discuss.huggingface.co/t/multiple-categories-labels/6961
Hi @joeddav and @bhadresh-savani I am using your text-classification models, but I am encountering a problem, nothing I try allows me to retrieve all the values: always just the first value is returned, would you be able to advise me, thanks so much. image1040×157 7.12 KB huggingface.co joedda...
Hi @snowdere, I am really glad you use this model, you can use it like either of the below ways from transformers import pipeline classifier = pipeline("text-classification",model='bhadresh-savani/distilbert-base-uncased-emotion', return_all_scores=True) prediction = classifier("I love using transformers. The best part...
0
huggingface
Beginners
Showing individual token and corresponding score during beam search
https://discuss.huggingface.co/t/showing-individual-token-and-corresponding-score-during-beam-search/3735
Hello, I am using beam search with a pre-trained T5 model for summarization. I would like to visualize the beam search process by showing the tokens with the highest scores, and eventually the chosen beam like this diagram: image894×669 56.8 KB (Taken from How to generate text: using different decoding methods for lang...
Tagging @patrickvonplaten reposted my question from Github, thanks for directing me to the forum
0
huggingface
Beginners
Token Classification (ValueError: NumPy boolean array indexing assignment)
https://discuss.huggingface.co/t/token-classification-valueerror-numpy-boolean-array-indexing-assignment/5564
I was reading and working through “Token Classification with W-NUT Emerging Entities” tutorial on Fine-tuning with custom datasets — transformers 4.5.0.dev0 documentation 6 using a different data. To replicate the data structure of the tutorial, I used the code below to insert a blank space between sentences/tags # ins...
I have the same problem, maybe because of the training data problem, you can try to UTF-8 encoding to UTF-8-SIG raw_text = file_path.read_text(encoding='UTF-8-sig').strip() Because UTF-8 may cause an extra \ufeff character in the encoded data
0
huggingface
Beginners
Trouble with the built in inference API example
https://discuss.huggingface.co/t/trouble-with-the-built-in-inference-api-example/6983
Hi I’m just starting out with the inference API examples. While I can get other examples to work using the same formatting , I get this error {“error”:“d argument needs to be of type (SquadExample, dict)”} When using the example for deepset/roberta-base-squad2 · Hugging Face import json import requests API_URL = "http...
Hi @LowellR I just tried your exact pasted code and it worked fine. {'answer': 'Clara', 'end': 16, 'score': 0.9326569437980652, 'start': 11} Could you confirm if you are running this same code? Thanks!
0
huggingface
Beginners
Question about supported framework
https://discuss.huggingface.co/t/question-about-supported-framework/6942
Dear All, I have some experience with BERT and text analysis, but I’m a beginner at . And so, please bear my question which might be a little silly. Here is the situation, I would like to solve a text comprehension task with a proper model. However, some model seems not supported in TensorFlow according to the followin...
The documentation should be interpreted as “any model saved as before can be loaded back either in PyTorch or TensorFlow as long as there is an implementation for both frameworks”, so no, you wouldn’t be able to use Bert Generation in TensorFlow at all.
0
huggingface
Beginners
Cannot download translation models in Colab
https://discuss.huggingface.co/t/cannot-download-translation-models-in-colab/6952
I am trying to translate English text to German. And so I run this- translator = pipeline("translation", model="Helsinki-NLP/opus-mt-en-de") But I get thrown an error- ValueError: This tokenizer cannot be instantiated. Please make sure you have sentencepiece installed in order to use this tokenizer. Full error mes...
okay, I tried to run this locally (not in Colab): from transformers import pipeline translator = pipeline("translation", model="Helsinki-NLP/opus-mt-en-de") translation = translator("hello, my name is Bob") print(translation) and it printed out: [{'translation_text': 'Hallo, mein Name ist Bob.'}] I don’t know wher...
0
huggingface
Beginners
Model Parallelism, how to parallelize transformer?
https://discuss.huggingface.co/t/model-parallelism-how-to-parallelize-transformer/6260
Hi there, I am pretty new, I hope to do it right:) I have two gpus nvidia, which work fine. I can train model on each of them, I can use data parallelism. I wonder if I can parallelize the model itself. Surfing the internet I found it is possible but no one tells how. Some frameworks do it as torchgpipe, deepspeed Pipe...
hey @valgi0 my suggestion would be to try out the new accelerate library: GitHub - huggingface/accelerate: 🚀 A simple way to train and use PyTorch models with multi-GPU, TPU, mixed-precision 151 in particular, there is an nlp example that shows you how to configure accelerate for the multi-GPU case here: accelerate/ex...
0
huggingface
Beginners
How to do sentiment analysis on my own dataset?
https://discuss.huggingface.co/t/how-to-do-sentiment-analysis-on-my-own-dataset/6792
Hi, I have seen this 3 example, which does sentiment analysis on product reviews. Therefore, is there a way to do this with my own dataset? I want to classify the sentiment of text as “happy”, “sad” or “neutral” using my own dataset. Thanks.
You have to define your own torch.utils.data.Dataset and torch.utils.data.DataLoader to load your own labeled text. Then choose an LM like BERT from the huggingface library to finetune.
0
huggingface
Beginners
Get word embeddings from transformer model
https://discuss.huggingface.co/t/get-word-embeddings-from-transformer-model/6929
Hi I would like to plot semantic space for specific words. Usually, we use word embeddings for this. But model I use (xlm-roberta) deala with language on the level of part of words (BPE tokens). It means that if I give to the model a word ‘hello’ I will get 2-3 vectors for each part of this word, right? model(**tokeniz...
I’m not sure what’s the best approach since I’m not an expert in this , but you can always do mean pooling to the output. Here is a working example from transformers import AutoTokenizer, AutoModelForMaskedLM def mean_pooling(model_output, attention_mask): token_embeddings = model_output[0] #First element of mod...
0
huggingface
Beginners
Adding New Tokens - IndexError: index out of range in self
https://discuss.huggingface.co/t/adding-new-tokens-indexerror-index-out-of-range-in-self/6731
Hi, I have added custom tokens using this code: # Let's see how to increase the vocabulary of Bert model and tokenizer tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') model = AutoModelForMaskedLM.from_pretrained('bert-base-uncased') num_added_toks = tokenizer.add_tokens(['😎', '🤬']) print('We have adde...
hey @anon58275033 without seeing the full code it’s a bit hard to debug, but my first question would be whether you tokenized the corpus after adding the new tokens? if yes, did you observe whether the tokenization is working as expected?
0
huggingface
Beginners
Reducing output size when performing hyperparameter search
https://discuss.huggingface.co/t/reducing-output-size-when-performing-hyperparameter-search/6701
Hello everyone! I’ve been trying to perform a simple hyperparameter research on ‘distilroberta-base’. When using Kaggle notebooks there is a 20 GB limit on outputs. Even when i am doing only 5 trials the output directory fills up. I am used to using GridSearchCV for HP-search which only keeps track of the best paramete...
Set load_best_model_at_end=False, and add save_strategy = 'no', # The checkpoint save strategy to adopt during training. On the training arguments
0
huggingface
Beginners
Extracting token embeddings from pretrained language models
https://discuss.huggingface.co/t/extracting-token-embeddings-from-pretrained-language-models/6834
I am interested in extracting feature embedding from famous and recent language models such as GPT-2, XLNeT or Transformer-XL. Is there any sample code to learn how to do that? Thanks in advance
Hello! You can use the feature-extraction pipeline for this. from transformers import pipeline pipeline = pipeline('feature-extraction', model='xlnet-base-cased') data = pipeline("this is a test") print(data) You can also do this through the Inference API.
0
huggingface
Beginners
Saving-Loading Model in Colab and Making Predictions
https://discuss.huggingface.co/t/saving-loading-model-in-colab-and-making-predictions/6723
I’m fairly new to Python and HuggingFace and have what is probably a simple question about saving and loading a model. I can’t figure out how to save a trained classifier model and then reload so to make target variable predictions on new data. As an example, I trained a model to predict imbd ratings with an example fr...
Any insights on this? I can’t find any examples start to finish, which seems like it should be straightforward
0
huggingface
Beginners
Does it make sense to train DistilBERT from scratch in a new corpus
https://discuss.huggingface.co/t/does-it-make-sense-to-train-distilbert-from-scratch-in-a-new-corpus/3503
Hi! First post in the forums, excited to start getting deep into this great library! I have a rookie, theoretical question. I have been reading the DistilBERT paper (fantastic!) and was wondering if it makes sense to pretrain a DistilBERT model from scratch. In the paper 2, the authors specify that “The student is trai...
Hi @lesscomfortable welcome to the forum! In the DistilBERT paper they use bert-base-uncased as the teacher for pretraining (i.e. masked language modelling). In particular, the DistilBERT student is pretrained on the same corpus as BERT (Toronto Books + Wikipedia) which is probably quite important for being able to eff...
0
huggingface
Beginners
Certain words don’t work with bert?
https://discuss.huggingface.co/t/certain-words-dont-work-with-bert/6562
hi, I was trying to run bert but was getting the error “IndexError: index out of range in self”. after troubleshooting for a couple of days I figured out it was the word “screwing” that was breaking my code. is this a bug or is there certain words you cant use with bert? or am I just doing something wrong? thanks. her...
I hope you’ve figured out the solution already but it seems that the tokenizer you use bert-base-uncased and the model initialized in the SentimentClassifier class bert-base-cased do not match. There may be overlaps in the vocabulary of the cased and uncased tokenizers which may seem working fine in some cases but the ...
0
huggingface
Beginners
Accuracy less than 100, but no mistakes
https://discuss.huggingface.co/t/accuracy-less-than-100-but-no-mistakes/6691
Hello all, I am training a model using Huggingface and when evaluating it I get approx 80% accuracy. I then try to plot the confusion matrix (using pycm) but I see no error. Any ideas what this might be?
Could you be providing the same labels to the confusion matrix plotting function, like plotting predictions versus predictions or ground truth versus ground truth? That kind of mistake is one that I make all the time.
0
huggingface
Beginners
How to stop Optuna saving checkpoints during Hyperparameter Search
https://discuss.huggingface.co/t/how-to-stop-optuna-saving-checkpoints-during-hyperparameter-search/6785
Hello I am running a Hyperparameter search using Optuna. As I am using Colab, I have limited diskspace, so I was wondering how to stop saving checkpoints, I only care about the final result and don’t need all the intermediate steps saved. I tried the following argument sin my TrainingArguments parameter, but its not wo...
Ok after reading the documentation carefully, it turns out setting load_best_model_at_end=True, overrides the strategy. Took it off and now it works.
0
huggingface
Beginners
NameError: name ‘BertTokenizer’ is not defined
https://discuss.huggingface.co/t/nameerror-name-berttokenizer-is-not-defined/6727
Hi, I am trying to add custom tokens using this code below: # Let's see how to increase the vocabulary of Bert model and tokenizer tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') model = AutoModelForMaskedLM.from_pretrained('bert-base-uncased') num_added_toks = tokenizer.add_tokens(['token_1']) print('W...
hey @anon58275033 what version of transformers are you using? i was not able to reproduce the error in v4.6.1
0
huggingface
Beginners
How to add new tokens for existing masked language modelling?
https://discuss.huggingface.co/t/how-to-add-new-tokens-for-existing-masked-language-modelling/6720
Hi, I have followed this tutorial from GitHub on masked language modelling: notebooks/language_modeling.ipynb at master · huggingface/notebooks · GitHub 3 But, I am wondering, how do I modfiy this code below for the masked language modelling task, and where in my code do I place it? In the tutorial, this line of code i...
First of all, I guess you want to use BertForMaskedLM instead of BertModel. The other parts should work AFAIK.
0
huggingface
Beginners
API Rest with several models loaded using GPU but not at same time
https://discuss.huggingface.co/t/api-rest-with-several-models-loaded-using-gpu-but-not-at-same-time/6673
I am creating an API Rest (using Flask) that does inference with several models given a list. For example summarization, sequence-to-sequence classification, etc … The problem is that all the models don’t fit at GPU at the same time. Is there a way of loading a model into GPU make inference with that model and move it ...
UPDATE The Summarization task works on GPU if I run the script on the Virtual Machine without calling it on flask. However, once I start it on Flask I get: RuntimeError: CUDA error: CUBLAS_STATUS_INTERNAL_ERROR when calling `cublasCreate(handle)`
0
huggingface
Beginners
How to test my text classification model after training it?
https://discuss.huggingface.co/t/how-to-test-my-text-classification-model-after-training-it/6689
Hello, I have followed this tutorial on text classification: notebooks/text_classification.ipynb at master · huggingface/notebooks · GitHub 5 Now, I have trained it using my own data, but I am unsure how to actually deploy it to carry out a classification task. For example, I want to input the following sentence: “You ...
That’s a good question. cc @sgugger, would be great if the several notebooks also include an inference part. I had to look into several notebooks before finding out you can access the trained model using trainer.model. Here’s how to do inference on a new, unseen sentence: sentence = “You look good today.” # encode sen...
0
huggingface
Beginners
Which loss function in bertforsequenceclassification regression
https://discuss.huggingface.co/t/which-loss-function-in-bertforsequenceclassification-regression/1432
BertForSequenceClassification can be used for regression when number of classes is set to 1. The documentation says that BertForSequenceClassification calculates cross-entropy loss for classification. What kind of loss does it return for regression? (I’ve been assuming it is root mean square error, but I read recentl...
This is the GitHub 135 link At line 1354, you have the condition to check the labels (if it is one or more) if self.num_labels == 1: # We are doing regression loss_fct = MSELoss() loss = loss_fct(logits.view(-1), labels.view(-1)) else: loss_fct = CrossEntropyLoss() loss = loss_fct(logits.view(-1, self.num_labels), lab...
0
huggingface
Beginners
Change length of GPT-neo output
https://discuss.huggingface.co/t/change-length-of-gpt-neo-output/5307
Any way to modify the length of the output text generated by the GPT-neo inference API?
Does anyone know a solution for this?
0
huggingface
Beginners
Evaluate Model on Test dataset (PPL)
https://discuss.huggingface.co/t/evaluate-model-on-test-dataset-ppl/6528
Hi guys, i am kinda new to hugginface and have a question regarding the PPL. So what i have is, i fine-tuned a model and at the end of the traning i get the PPL for the dev dataset by doing: eval_results = trainer.evaluate() print(f"Perplexity: {math.exp(eval_results['eval_loss']):.2f}") However, in my DatasetsDict I ...
Hey Chris, i’m a begginer as well but i think you could try using EvalPrediction 4. You pass your test_set and it’s labels and then you should get your loss at the specific set.
0
huggingface
Beginners
How to load ckpt into my model base on tf2.x
https://discuss.huggingface.co/t/how-to-load-ckpt-into-my-model-base-on-tf2-x/6415
I need to load ckpt file from google-search’s bert ckpt. I have read all questions related to this and tried some methods but it seem still doesn’t work . ckpt files are like this: I have tried method like: bert_config = transformers.BertConfig.from_json_file('./bert/bert_config.json') bert = transformers.TFBertModel....
hello?Can someone help me?
0
huggingface
Beginners
What’s the difference between wordpiece and sentencepiece?
https://discuss.huggingface.co/t/whats-the-difference-between-wordpiece-and-sentencepiece/6676
I found that the wordpiece training and the sentencepiece are almost the same. So what’s the difference ?? Thanks
See for example this post: https://towardsdatascience.com/a-comprehensive-guide-to-subword-tokenisers-4bbd3bad9a7c 7
0
huggingface
Beginners
Evaluating Finetuned BERT Model for Sequence Classification
https://discuss.huggingface.co/t/evaluating-finetuned-bert-model-for-sequence-classification/5265
Python 3.7.6 Transformers 4.4.2 Pytorch 1.8.0 Hi HF Community! I would like to finetune BERT for sequence classification on some training data I have and also evaluate the resulting model. I am using the Trainer class to do the training and am a little confused on what the evaluation is doing. Below is my code: import ...
If you want other metrics, you have to indicate that to the Trainer by passing a compute_metrics function. See for instance our official GLUE example 20 or the corresponding notebook 30.
0
huggingface
Beginners
Why my simple Bert model for text classification could not learn anything?
https://discuss.huggingface.co/t/why-my-simple-bert-model-for-text-classification-could-not-learn-anything/6654
Hello, I try transformers.BertModel to deal with a simple text classification, but the result makes me puzzled. the code is simple,I implement the model with pytorch. they are… # a Dataset class for BertModel class BertDataset(Dataset): def __init__(self, train_file, tokenizer): super(BertDataset, self).__...
I think the problem might be that you call optimizer.zero_grad() after outputs are calculated, and it zeros out the gradients from the forward pass. Try putting that line before the line where outputs are calculated.
0
huggingface
Beginners
How to train from scratch with run_mlm.py, .txt file?
https://discuss.huggingface.co/t/how-to-train-from-scratch-with-run-mlm-py-txt-file/6588
Hello! Essentially what I want to do is: point the code at a .txt file, and get a trained model out. How can I use run_mlm.py to do this? I’d be satisfied if someone could help me figure out how to even just recreate the EsperBERTo tutorial. I’m getting bogged down in flags, trying to load tokenizers, errors, etc. What...
You seem to be on the correct path, could you tell us more about the index error you encountered? What did the stack trace look like? Also could you try briefly with another model than roberta (like bert for instance) and report if the error disappears?
0
huggingface
Beginners
KeyError: ‘loss’ during Fine Tuning bert-base-italian-cased for QA
https://discuss.huggingface.co/t/keyerror-loss-during-fine-tuning-bert-base-italian-cased-for-qa/6638
I was finetuning bert-base-italian-cased on SQuAD-it dateset with the following arguments args = TrainingArguments( f"test-squad_it", evaluation_strategy = "epoch", learning_rate=2e-5, per_device_train_batch_size=8, per_device_eval_batch_size=8, num_train_epochs=3, weight_decay=0.01, lab...
How is your model created? How is your data processed? It’s hard to help debug the root of the error without seeing those.
0
huggingface
Beginners
Evaluating QA model on single SQuAD file
https://discuss.huggingface.co/t/evaluating-qa-model-on-single-squad-file/6622
Hello guys I would like to evaluate a model from the HF repo (‘mrm8488/bert-italian-finedtuned-squadv1-it-alfa’) on a SQuAD file I compiled, just to have a rough estimation of what could be the metrics. This is the code i wrote: from transformers import AutoTokenizer, AutoModelForQuestionAnswering, Trainer, TrainingArg...
The Trainer requires processed data. Have a look at the run_qa examples to see how it can be done,
0
huggingface
Beginners
I got ‘ValueError: You have to specify either input_ids or inputs_embeds’ when I am training GPT2 using huggingface Trainer
https://discuss.huggingface.co/t/i-got-valueerror-you-have-to-specify-either-input-ids-or-inputs-embeds-when-i-am-training-gpt2-using-huggingface-trainer/6611
Below is the error code generated ValueError Traceback (most recent call last) <ipython-input-38-29d47e6260b2> in <module>() ----> 1 trainer.train( ) 4 frames /usr/local/lib/python3.7/dist-packages/transformers/models/gpt2/modeling_gpt2.py in forward(self, input_ids, past_key_values, att...
You haven’t processed your dataset: it only contains the raw texts and not the input IDs the model expects. Have a look at the training tutorial to see how you can tokenize it!
0
huggingface
Beginners
Request to reset API key
https://discuss.huggingface.co/t/request-to-reset-api-key/6613
Hi, may I get some help resetting my API key? I might have leaked mine. Thanks! @julien-c @pierric I followed a previous post: How can I renew my API key 6
@r3dhummingbird Your api token was successfully renewed.
0
huggingface
Beginners
Wav2Vec2-XLSR-53
https://discuss.huggingface.co/t/wav2vec2-xlsr-53/6587
I tried to run notebook facebook/wav2vec2-large-xlsr-53 · Hugging Face But when I run model = Wav2Vec2ForCTC.from_pretrained( "facebook/wav2vec2-base-960h", attention_dropout=0.1, hidden_dropout=0.1, feat_proj_dropout=0.0, mask_time_prob=0.05, layerdrop=0.1, gradient_checkpointing=True, ...
Perhaps it’s a permissions error?
0
huggingface
Beginners
How to see BERT,BART… output dimensions?
https://discuss.huggingface.co/t/how-to-see-bert-bart-output-dimensions/6517
how can i see the output dimensions for BERT Large,BART Large,RoBERTa Large, BART Large CNN, XLM RoBERTa Large?
really no one knows?!
0
huggingface
Beginners
Not able to import MBart50TokenizerFast from transformers
https://discuss.huggingface.co/t/not-able-to-import-mbart50tokenizerfast-from-transformers/3706
Hi I am not able to import MBart50TokenizerFast from transformers. Below is the error that it is giving In [6]: from transformers import MBartForConditionalGeneration, MBart50TokenizerFast --------------------------------------------------------------------------- ImportError Traceback (mo...
AFAIK this model+tokenizer is not part of a full release yet. You’ll have to install from the master branch to use it.
0
huggingface
Beginners
AutoTokenizer vs. regular Tokenizer
https://discuss.huggingface.co/t/autotokenizer-vs-regular-tokenizer/6491
I understand that there are a few different tokenizers; e.g., DistilBertTokenizerFast, etc. However, I don’t understand the concept of “Auto” in tokenizer selection. Using IMDB text as an example. What do I get if I use AutoTokenizer to tokenize the text?
The AutoTokenizer will work on any checkpoint and pick the proper architecture for you (whereas DistilBNertTokenizerFast will only work for distilbert checkpoints).
0
huggingface
Beginners
Wav2vec2 for long audiofiles
https://discuss.huggingface.co/t/wav2vec2-for-long-audiofiles/6446
Hi, I’m trying to apply wave2vec2 models on long audiofiles (~1h) for speech to text. However processing the entire audio file at once is not feasible because it requires more than 16GB. How can I import a sound file as audio stream into the wave2vec models?
Here is one way to do this with librosa.stream: github.com/huggingface/transformers can't allocate memory error with wav2vec2 106 opened Feb 24, 2021 closed ...
0
huggingface
Beginners
“run_lm_finetuning.py” was replaced?
https://discuss.huggingface.co/t/run-lm-finetuning-py-was-replaced/992
Hello to all, Looking at tutorials and examples I see that many do fine tuning with run_lm_finetuning.py. However when I install the latest version of transformers this file doesn’t exist, I haven’t found it in the github repository either. So my question is if this file was discontinued, and, if so, what is the actual...
Hi, It’s now here: https://github.com/huggingface/transformers/tree/master/examples/language-modeling 960
0
huggingface
Beginners
Bug Report: Mask token mismatch with the model on hosted inference API of Model Hub
https://discuss.huggingface.co/t/bug-report-mask-token-mismatch-with-the-model-on-hosted-inference-api-of-model-hub/6476
In my model card, I used to be able to run the hosted inference successfully, but recently it prompted an error: "<mask>" must be present in your input. My model uses RoBERTa MLM and BERT Tokenizer. So the mask token is actually “[MASK]”. I have already set it in tokenizer_confg.json but the inference API still mismatc...
Should be resolved in Mask token mismatch with the model on hosted inference API of Model Hub · Issue #11884 · huggingface/transformers · GitHub 8, but if possible do not open duplicate issues/forum posts. Thanks!
0