I have finetuned a DistilBert model using this code : import torch from transformers…
- User
I have finetuned a DistilBert model using this code : import torch from transformers import DistilBertTokenizerFast, DistilBertForSequenceClassification, Trainer, TrainingArguments from datasets import load_dataset
Load and preprocess the dataset
dataset = load_dataset('json', data_files={'train': 'GSM2K.jsonl', 'validation': 'test.jsonl'})
Extract all unique answers and create a mapping to integers
unique_answers = set() for split in dataset: unique_answers.update(dataset[split]['answer']) answer_to_id = {answer: idx for idx, answer in enumerate(unique_answers)}
Define a function to encode the labels
def encode_labels(example): example['labels'] = answer_to_id[example['answer']] # Map the answer to an integer label return example
Apply the function to encode labels
dataset = dataset.map(encode_labels, remove_columns=['answer']) # Also remove the original 'answer' column
Load DistilBert tokenizer
tokenizer = DistilBertTokenizerFast.from_pretrained('distilbert-base-uncased')
Tokenize the input (this may take a while)
def tokenize_function(examples): return tokenizer(examples['question'], padding='max_length', truncation=True)
tokenized_datasets = dataset.map(tokenize_function, batched=True)
Ensure you have a GPU available for training (if you're using one)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
Load DistilBert model with the correct number of labels
model = DistilBertForSequenceClassification.from_pretrained( 'distilbert-base-uncased', num_labels=len(unique_answers) ).to(device)
Define training arguments
training_args = TrainingArguments( output_dir='./results', # output directory for checkpoints num_train_epochs=2, # number of training epochs per_device_train_batch_size=32, # batch size for 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 evaluation_strategy="epoch", # evaluate after each epoch save_strategy="epoch", # save model after each epoch load_best_model_at_end=True, # whether to load the best model (according to validation) at the end of training )
Initialize Trainer
trainer = Trainer( model=model, args=training_args, train_dataset=tokenized_datasets["train"], eval_dataset=tokenized_datasets["validation"], tokenizer=tokenizer )
Fine-tune the model
trainer.train()
Save the model
trainer.save_model("DistilBert-Math")
- Assistant
It appears you've successfully fine-tuned the DistilBert model for sequence classification with your own dataset loaded from JSON files using the Hugging Face's transformers and datasets library. Your model is trained to classify sequences based on questions contained in your dataset, using answers as labels.
Let's breakdown the steps:
-
Dataset Loading and Preprocessing: You load the dataset from JSON files (one for training and one for validation), create a unique set of labels from the answers in your dataset, and create a label encoder to map these answers to integer labels.
-
- User
I have made this gradio web app for running a finetuned GPT-2 model, but i need you to modify it to run this distilbert instead, gradio code has been changed since your knowledge cutoff: import gradio as gr import torch from transformers import GPT2Tokenizer, GPT2LMHeadModel
Load the finetuned model and the tokenizer
model_dir = "GPT-2-Mathematician-SS" tokenizer = GPT2Tokenizer.from_pretrained(model_dir) model = GPT2LMHeadModel.from_pretrained(model_dir) model.eval() # Set the model to inference mode
Make sure to have a GPU or CPU device ready for inference
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model.to(device)
Function to generate an answer given a math question
- Assistant
To modify the existing Gradio web app to use the fine-tuned DistilBert model that you have trained instead of the GPT-2 model, you need to replace the GPT-2 specific code with DistilBert equivalents. Here is a modified version of the code that should work with your DistilBert model for sequence classification:
- User
answer_to_id is not defined in the code
- Assistant
- User
- Assistant
The error message suggests there is a problem with the version of the
protobufpackage that is incompatible with the TensorFlow code you're trying to run. This issue arises because TensorFlow, which is often installed alongside thetransformerslibrary, requires a particular version ofprotobuf. The error is not directly related to Gradio or the DistilBert model code.The error message itself offers a couple of potential solutions:
- Upgrade the
protobufpackage to version 3.19.0 or higher. - Downgrade the
protobufpackage to 3.20.x or lower if you are using a newer version that is causing issues. - Set the environment variable
PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=pythonto fall back to Python implementation, though this may significantly reduce performance.
To resolve the issue, you should try adjusting the
protobufversion:Upgrade to a compatible version:
bash - Upgrade the