Can you give me code to run a finetuned version of GPT-2 on Math questions, it received…
- User
Can you give me code to run a finetuned version of GPT-2 on Math questions, it received a validation loss of 1.4 which is good considering the validation loss without any finetuning was way higher (~100), here is the code we used to finetune GPT-2: import torch from transformers import GPT2Tokenizer, GPT2LMHeadModel, Trainer, TrainingArguments from datasets import load_dataset
Load and preprocess the dataset
dataset = load_dataset('json', data_files={'train': 'GSM2K.jsonl', 'validation': 'GSM2K.jsonl'})
Define a function to concatenate the question and answer
def concatenate_qa(example): example['input_text'] = example['question'] + " " + example['answer'] return example
Apply the function to concatenate the question and answer
dataset = dataset.map(concatenate_qa)
Create GPT-2 tokenizer and add special tokens
tokenizer = GPT2Tokenizer.from_pretrained("gpt2") special_tokens_dict = {"sep_token": ""} tokenizer.add_special_tokens(special_tokens_dict) tokenizer.pad_token = tokenizer.eos_token
Update the model to account for new tokens
model = GPT2LMHeadModel.from_pretrained("gpt2") model.resize_token_embeddings(len(tokenizer))
Tokenization function with reduced max_length and including labels
def tokenize_function(examples): # Tokenize inputs for language modeling tokenized_inputs = tokenizer( examples["input_text"], max_length=320, # Adjust as needed based on GPU capacity padding="max_length", truncation=True, return_tensors="pt" ) # In language modeling, the labels are the same as the input IDs tokenized_inputs["labels"] = tokenized_inputs["input_ids"].clone() return tokenized_inputs
Tokenize dataset
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') model.to(device)
Clear any residual GPU memory
torch.cuda.empty_cache()
Define training arguments with reduced batch sizes and enabled mixed precision
training_args = TrainingArguments( learning_rate=3e-5, per_device_train_batch_size=12, # Reduced train batch size per_device_eval_batch_size=16, # Reduced eval batch size (can be larger than train batch if eval is less memory-intensive) gradient_accumulation_steps=4, # Set this higher if reducing batch sizes is not enough fp16=True, # Enable mixed precision logging_dir="./logs", logging_steps=50, output_dir='./results', num_train_epochs=4, warmup_steps=500, weight_decay=0.05, evaluation_strategy="epoch", save_strategy="epoch", load_best_model_at_end=True, )
Initialize Trainer
trainer = Trainer( model=model, args=training_args, train_dataset=tokenized_datasets["train"], eval_dataset=tokenized_datasets["validation"], tokenizer=tokenizer )
- Assistant
- User
- Assistant
The error you are encountering seems to be related to the
google.protobufpackage. The issue might be because of an outdated version of theprotobufpackage or a corrupted installation.Here are the steps to address this issue:
- First, update the
protobufpackage to the latest version:
bashpip install --upgrade protobuf- If updating
protobufdoes not solve the problem, try reinstallingprotobufand thetransformerslibrary:
bash - First, update the