I want you to fine-tune GPT-2 from Transformers using Python to generate JSON code only, create a function called "generate_content(system, prompt)". The system should give the AI instructions to follow, and the prompt is where I shall enter my questions
Assistant
Certainly! Below is a Python function generate_content(system, prompt) that uses the Hugging Face Transformers library to fine-tune GPT-2 for generating JSON code only. This function assumes you have access to a dataset suitable for fine-tuning the model to generate JSON outputs.
Please note that fine-tuning a language model like GPT-2 requires a significant amount of computational resources and time. The code provided demonstrates the overall process but may need adjustments based on your specific environment and dataset.
python
# Import necessary libraries
import torch
from transformers import GPT2LMHeadModel, GPT2Tokenizer, TextDataset, DataCollatorForLanguageModeling, Trainer, TrainingArguments
def generate_content(system, prompt):
"""
Fine-tunes GPT-2 to generate JSON code based on the system instructions and user prompt.
Parameters:
- system (str): Instructions for the AI to follow.
- prompt (str): The user's prompt or question.
Returns:
- str: Generated JSON code as a string.
"""
# Initialize the tokenizer and model
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
model = GPT2LMHeadModel.from_pretrained('gpt2')
# Add special tokens if needed
special_tokens_dict = {'additional_special_tokens': ['<JSON>', '</JSON>']}
tokenizer.add_special_tokens(special_tokens_dict)
model.resize_token_embeddings(len(tokenizer))
# Prepare the dataset for fine-tuning
# Assume you have a text file 'json_dataset.txt' with JSON examples
def load_dataset(tokenizer, file_path, block_size=128):
return TextDataset(
tokenizer=tokenizer,
file_path=file_path,
block_size=block_size)
def create_data_collator(tokenizer):
return DataCollatorForLanguageModeling(
tokenizer=tokenizer, mlm=False)
# Load and preprocess the dataset
dataset = load_dataset(tokenizer, 'json_dataset.txt')
data_collator = create_data_collator(tokenizer)
# Set up training arguments
training_args = TrainingArguments(
output_dir='./results',
overwrite_output_dir=True,
num_train_epochs=1,
per_device_train_batch_size=1,
save_steps=10_000,
save_total_limit=2,
)
# Initialize the Trainer
trainer = Trainer(
model=model,
args=training_args,
data_collator=data_collator,
train_dataset=dataset,
)
# Fine-tune the model
trainer.train()
# Combine system instructions and user prompt
input_text = f"{system}\nUser Prompt: {prompt}\nJSON Output:"
# Tokenize the input
input_ids = tokenizer.encode(input_text, return_tensors='pt')
# Generate text with the fine-tuned model
output = model.generate(
input_ids,
max_length=512,
num_return_sequences=1,
no_repeat_ngram_size=2,
repetition_penalty=1.5,
top_p=0.95,
temperature=0.8,
eos_token_id=tokenizer.eos_token_id,
pad_token_id=tokenizer.eos_token_id
)
# Decode the generated text
generated_text = tokenizer.decode(output[0], skip_special_tokens=True)
# Extract the JSON code from the generated text
json_output = generated_text.split('JSON Output:')[-1].strip()
return json_output
# Example usage:
# system_instructions = "Generate a JSON representation of the user's request."
# user_prompt = "Create a JSON object for a book with title '1984' and author 'George Orwell'."
# json_result = generate_content(system_instructions, user_prompt)
# print(json_result)
Explanation:
Imports:
torch: PyTorch library for tensor computations.
transformers: Hugging Face Transformers library for model and tokenizer.
Function generate_content:
Accepts system and prompt as inputs.
Initializes the GPT-2 tokenizer and model.
Adds special tokens if necessary (e.g., <JSON> tags) to help the model focus on JSON structures.
Prepares the dataset for fine-tuning. You need a text file (json_dataset.txt) containing examples of JSON code to fine-tune the model effectively.
Sets up training arguments and initializes the Trainer for fine-tuning.
Fine-tunes the model using trainer.train().
Combines the system instructions and prompt to form the input text.
Tokenizes the input and generates text using the fine-tuned model.
Decodes and extracts the JSON code from the generated text.
Example Usage:
Provided at the bottom as a comment to show how to use the function.
Important Notes:
Dataset Preparation:
You must provide a dataset (json_dataset.txt) containing valid JSON examples for fine-tuning. The quality and size of this dataset will significantly impact the model's ability to generate accurate JSON code.
Computational Resources:
Fine-tuning GPT-2 can be resource-intensive. Ensure you have access to a machine with a GPU to accelerate training.
Adjustments:
Depending on your specific use case and the complexity of the JSON structures, you might need to adjust parameters like max_length, num_train_epochs, and others.
Error Handling:
In a production environment, include try-except blocks and input validation to handle potential errors gracefully.
Dependencies:
Make sure you have the required libraries installed:
bash
pip install torch transformers
Alternative Approach:
If fine-tuning is not feasible due to resource constraints, consider using prompt engineering with GPT-2 or a more recent model like GPT-3 (via OpenAI API) to guide the model to generate JSON outputs without fine-tuning.
Let me know if you need further assistance or adjustments to the code!