I get this :
Epoch Training Loss Validation Loss
0 1.443500 1.128806
1 1.014600 0.959285
There were missing keys in the checkpoint model loaded: ['lm_head.weight']. when i run this code: import torch
from transformers import GPT2Tokenizer, GPT2LMHeadModel, Trainer, TrainingArguments
from datasets import load_dataset
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=288, # 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
There were missing keys in the checkpoint model loaded: ['lm_head.weight'].
is indicating that the lm_head.weight parameter was expected but not found in the model checkpoint you loaded. This can happen when you load a pre-trained model and then alter its architecture by, for example, adding new tokens as you did with . Here's what's likely occurring:
User
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, Trainer, TrainingArguments
from datasets import load_dataset
Your code appears to be a fine-tuning script for a model based on the LLaMA (likely the GPT-style language model) provided by . The structure of the code follows a standard fine-tuning process using Hugging Face's Transformers library and . Here's what your script does:
User
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, Trainer, TrainingArguments
from datasets import load_dataset
When you load the original GPT-2 model and then resize its token embeddings to accommodate the new special tokens, it may not carry over the weights for the language model head (lm_head). The language model head is responsible for generating the predictions using the last layer of the network. If this head was not part of the original pre-trained model downloaded or there are changes in the architecture, this warning can appear.
This warning is often not critical because when you perform fine-tuning as in your case, the language model head (if not loaded) will be randomly initialized and then updated during training based on your dataset.
One way to check if the weights for the lm_head are really missing or causing issues is to verify the model's parameters using:
If the weights for lm_head.weight were indeed missing, you would see it in missing_keys. Since you don't have this explicitly in your code and you are already fine-tuning the model, the weights would be learned for your task during the training process.
Everything else in your code seems to be in order for fine-tuning GPT-2 on your custom dataset. Make sure that train.jsonl and test.jsonl are formatted correctly for your dataset to be handled properly by the load_dataset function, and keep an eye on both the training loss and the validation loss to ensure your model is learning effectively and not overfitting.
If you wanted to explicitly initialize the lm_head weights, you could do so before training, especially if you want to use the pre-trained head weights (assuming lm_head is a part of the original checkpoint), but that might not be necessary unless you are seeing poor performance after fine-tuning.
Define a function to concatenate the question and answer
model = AutoModelForCausalLM.from_pretrained("allenai/llama")
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,
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
Loads a dataset from JSON Line .jsonl files: GSM2K.jsonl for training and test.jsonl for validation.
It defines and applies a function concatenate_qa to concatenate questions and answers into a single input sequence.
It prepares an AutoTokenizer and an AutoModelForCausalLM for LLaMA.
It extends the tokenizer and model embeddings to accommodate a new special token <sep>.
It tokenizes the preprocessed data with a maximum input length of 320 tokens and pads or truncates the rest.
Prepares the model and ensures that it's on the correct device (GPU if available).
Sets training arguments, including learning rate, batch size, number of epochs, logging, etc.
Initializes the Trainer object with the model, training arguments, and tokenized datasets.
Trains the model on the dataset.
Saves the fine-tuned model under the specified directory "LLaMA-Finetuned-SS".
Important points to check to ensure smooth training:
Confirm that GSM2K.jsonl and test.jsonl are well-formatted and compatible with the load_dataset function. They should contain the fields question and answer according to your processing function concatenate_qa.
Before executing the script, ensure that both train and validation sets are large enough to allow for adequate generalization and evaluation of the model.
Ensure you have adequate computational resources (a capable GPU with enough memory) for fine-tuning, due to the memory requirements of deep language models.
Check if the model is designed to be fine-tuned in this manner. Some models, like decoder-only models (GPT-style), are suited for causal language modeling and fine-tuning given the combined questions and answers.
As for the code itself, the training procedure looks standard. If there were any specific issues occurring when you run this code, it would help to share the error or warning messages for more directed assistance. If you encountered the "missing keys" warning as in the previous attempt, the explanation would be similar. It may indicate that the model's head parameters were not found in the provided checkpoint, and they will usually be initialized to random weights before fine-tuning.
Define a function to concatenate the question and answer
model = AutoModelForCausalLM.from_pretrained("microsoft/phi-1_5")
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,
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
The script you've provided is almost the same as the previous one, with some minor adjustments. The model being fine-tuned is from a different source, microsoft/phi-1_5, which is part of the GPT-3.5 series by OpenAI, as indicated by the AutoModelForCausalLM.from_pretrained("microsoft/phi-1_5") line.
Everything else looks appropriate for fine-tuning a causal language model (LLM) on a custom dataset, where each example combines a question and answer separated by a special token (<sep>). Here's what the script is set up to do:
Load the training and validation datasets from .jsonl files.
Concatenate questions and answers using a custom function.
Load a tokenizer and a causal language model appropriate for the dataset.
Add a special token to the tokenizer.
Resize the model's token embeddings to incorporate the special token.
Tokenize the dataset while performing necessary padding and truncation.
Train the loaded model on the dataset using a GPU if available.
Save the fine-tuned model.
Here are a few best practices and things to look out for:
Dataset: Ensure your train.jsonl and test.jsonl are formatted correctly. They must contain at least two fields: question and answer, which you are using in the concatenate_qa function.
Computational Resources: Make sure your runtime environment has a suitable GPU for training these kinds of models. Fine-tuning GPT-3.5 or any significant LLM requires substantial amounts of memory and computational power.
Tokenizer and Model Consistency: Check that the tokenizer and model are compatible regarding the architecture and the types of tokens they handle. You have already adjusted the tokenizer and model to include the new <sep> token, which is good.
Mixed Precision Training: You have enabled this with fp16=True, which can provide significant speed gains. Be aware that it can also lead to numerical instability in certain cases, although that's relatively rare with modern frameworks.
Tokenization: The tokenization step seems correct, and you have properly created labels for the language modeling task by cloning the input_ids.
Trainer: The Trainer class from Hugging Face is a versatile way to handle training without much boilerplate code. You've set it up with appropriate arguments for your task and computational resources.
Given the adjustments that you've made and presuming that your dataset is in the correct format, the script should fine-tune the microsoft/phi-1_5 model on your data.
If you encounter the warning about missing keys in the checkpoint as before, it's likely due to the change in the model's architecture when resizing token embeddings. Since you are fine-tuning the model, you can typically ignore this warning, as the missing weights will be learned during training.
Remember, each adjustment to the training script can change the training dynamics, so ensure you monitor the training progress and validate the model to make sure that it's learning as expected.