import json
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
# From transformers, we can use the tokenizer and model for simplicity
from transformers import GPT2Tokenizer, GPT2LMHeadModel
# 1. Load data from JSON file
with open('dataset.json', 'r', encoding='utf-8') as f:
data = json.load(f)
texts = data['texts'] # Assuming the JSON has a key 'texts' with a list of text data
# 2. Tokenize the data
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
# Add special tokens if needed
special_tokens_dict = {'pad_token': '[PAD]'}
num_added_toks = tokenizer.add_special_tokens(special_tokens_dict)
# Update the model with new tokens
model = GPT2LMHeadModel.from_pretrained('gpt2')
model.resize_token_embeddings(len(tokenizer))
# Convert texts to token ids
inputs = []
for text in texts:
input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors='pt')
inputs.append(input_ids)
# 3. Create a custom dataset
class TextDataset(Dataset):
def __init__(self, inputs):
self.inputs = inputs
def __len__(self):
return len(self.inputs)
def __getitem__(self, idx):
return self.inputs[idx]
dataset = TextDataset(inputs)
dataloader = DataLoader(dataset, batch_size=1, shuffle=True)
# 4. Define the training loop with human corrections
optimizer = optim.AdamW(model.parameters(), lr=5e-5)
model.train()
for epoch in range(1): # For demonstration, we'll run only one epoch
for batch in dataloader:
optimizer.zero_grad()
input_ids = batch[0]
# Model generates text based on input
outputs = model.generate(input_ids, max_length=50, num_return_sequences=1)
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(f"Generated Text: {generated_text}")
# Human checks and provides correction
correction = input("Please provide correction (or press Enter to accept): ")
if correction.strip() == '':
# No correction provided; use generated text as is
corrected_text = generated_text
else:
corrected_text = correction
# Tokenize corrected text
corrected_input_ids = tokenizer.encode(corrected_text + tokenizer.eos_token, return_tensors='pt')
# 5. Compute loss based on distance between generated and corrected text
# Here we can use CrossEntropyLoss between generated tokens and corrected tokens
# Make sure both sequences are the same length by padding
max_len = max(input_ids.size(-1), corrected_input_ids.size(-1))
input_ids_padded = nn.functional.pad(input_ids, (0, max_len - input_ids.size(-1)), value=tokenizer.pad_token_id)
corrected_input_ids_padded = nn.functional.pad(corrected_input_ids, (0, max_len - corrected_input_ids.size(-1)), value=tokenizer.pad_token_id)
# Shift logits and labels for CrossEntropyLoss
outputs = model(input_ids_padded)
logits = outputs.logits[:, :-1, :].contiguous()
labels = corrected_input_ids_padded[:, 1:].contiguous()
loss_fn = nn.CrossEntropyLoss(ignore_index=tokenizer.pad_token_id)
loss = loss_fn(logits.view(-1, logits.size(-1)), labels.view(-1))
print(f"Loss: {loss.item()}")
# 6. Backpropagation and optimization step
loss.backward()
optimizer.step()
print("Training complete.")
Explanation:
-
Loading Data:
- We load the JSON file
dataset.json, which should contain a key called 'texts' that holds a list of text data.
- Example content of
dataset.json:
{
"texts": [
"Hello, how are you?",
"I am fine, thank you!",
"This is a sample text for the language model."
]
}
-
Tokenization:
- We use
GPT2Tokenizer for tokenizing the text data.
- We add a special padding token
[PAD] to handle padding of sequences.
- Each text is encoded into tokens and stored in a list.
-
Preparing the Dataset:
- We create a custom
TextDataset class that extends Dataset from torch.utils.data.
- The dataset holds the tokenized input sequences.
- We use a
DataLoader to load data in batches.
-
Model Initialization:
- We load
GPT2LMHeadModel and resize its token embeddings to accommodate any new tokens we've added to the tokenizer.
-
Training Loop with Human Corrections:
- For each batch, the model generates text.
- The generated text is displayed, and the user is prompted to provide a correction. If no correction is provided, the generated text is used as the corrected text.
- Both the generated text and the corrected text are tokenized.
- We pad the sequences so they are the same length.
- We calculate the loss using
CrossEntropyLoss, comparing the model's outputs to the corrected text tokens.
- The loss is printed, and we perform backpropagation and an optimization step to update the model weights.
-
Loss Calculation:
- The loss is lower when the generated text is closer to the corrected text, as per the user's requirement.
- This method ensures that the model learns from the corrections and adapts to reduce future errors.
-
Iteration and Optimization:
- We run the training loop for one epoch for demonstration purposes.
- In practice, you would run for more epochs and possibly save the model checkpoints.
Note:
- Ensure that the
dataset.json file is properly formatted and located in the same directory as the script.
- This script requires the
transformers library. Install it using pip install transformers.
- The script uses a simple approach for the loss calculation for demonstration. Depending on your specific needs, you might want to customize the loss function further.
Example Interaction:
Generated Text: Hello, how are you? I'm doing well, thank you for asking. How about you?
Please provide correction (or press Enter to accept): Hello, how are you? I'm fine, thanks for asking. What about you?
Loss: 1.23456789
This interaction shows the model generating text, the user providing a correction, and the model calculating the loss based on the difference between the generated text and the correction.
Conclusion:
This code sets up a basic framework for interactive training of a language model with human corrections using PyTorch. By adapting the loss function to minimize the distance between the generated text and the human-provided corrections, the model learns to produce more accurate and acceptable text over time.
Feel free to expand upon this code to suit your specific application, such as handling larger datasets, implementing a more sophisticated user interface, or integrating with other systems.