Okay, creating a truly useful LLM from scratch is a monumental task requiring massive datasets, compute power, and expertise. However, we can create a tiny, toy example to illustrate the core concepts: setup, training on a very small custom dataset, and testing inference.
We'll use the Hugging Face transformers library to leverage a pre-trained small model (like DistilGPT-2) and fine-tune it on our custom, tiny dataset. This is much more feasible.
What this example will do:
Setup: Install necessary libraries.
Load Pre-trained Model & Tokenizer: We'll use DistilGPT-2, a smaller version of GPT-2.
Prepare a Tiny Custom Dataset: Just a few lines of text to teach it a specific, simple pattern or style.
Fine-tune: Train the model on this dataset for a few epochs.
Test Inference: Give it a prompt and see what it generates.
Caveats:
"Small" is relative: Even DistilGPT-2 has millions of parameters.
Toy Dataset: The model won't become a general-purpose chatbot. It will only learn patterns from our tiny dataset.
Performance: Results will be very limited due to the dataset size.
Computational Cost: Even this will take a few minutes to run on a CPU. A GPU would speed it up.
Step 1: Setup (Installation)
bash
pip install torch transformers datasets
(If you have a CUDA-enabled GPU and want to use it, ensure PyTorch is installed with CUDA support.)
Step 2: Python Code (Setup, Training, Inference)
python
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, Trainer, TrainingArguments
from torch.utils.data import Dataset
import os
# --- Configuration ---
MODEL_NAME = "distilgpt2" # A small, manageable model
OUTPUT_DIR = "./tiny_llm_finetuned"
NUM_TRAIN_EPOCHS = 3 # Keep low for a quick demo
PER_DEVICE_TRAIN_BATCH_SIZE = 1 # Small dataset, small batch
LEARNING_RATE = 5e-5
# --- 1. Prepare a Tiny Custom Dataset ---
# Let's teach it to complete simple sentences about animals
custom_texts = [
"The cat sat on the mat.",
"The dog chased the ball.",
"The bird sang in the tree.",
"The fish swam in the pond.",
"The fox jumped over the fence.",
"The cat likes to purr.",
"The dog enjoys a walk.",
"The bird builds a nest.",
"The fish needs clean water.",
"The fox hunts at night."
]
# --- 2. Load Pre-trained Tokenizer and Model ---
print(f"Loading tokenizer and model: {MODEL_NAME}...")
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
model = AutoModelForCausalLM.from_pretrained(MODEL_NAME)
# GPT-2 models usually don't have a pad token, set it to eos_token
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
model.config.pad_token_id = model.config.eos_token_id
print("Tokenizer and model loaded.")
# --- 3. Create a Custom Dataset Class ---
class CustomTextDataset(Dataset):
def __init__(self, texts, tokenizer, max_length=128):
self.tokenizer = tokenizer
self.texts = texts
self.max_length = max_length
self.encodings = []
for text in texts:
# Add eos_token to signal end of sentence during training
encoding = tokenizer(text + tokenizer.eos_token,
truncation=True,
max_length=self.max_length,
padding="max_length", # Pad to max_length
return_tensors="pt")
self.encodings.append(encoding)
def __len__(self):
return len(self.encodings)
def __getitem__(self, idx):
item = {key: val.squeeze() for key, val in self.encodings[idx].items()}
# For language modeling, labels are usually the input_ids themselves
item["labels"] = item["input_ids"].clone()
return item
# Create dataset instance
train_dataset = CustomTextDataset(custom_texts, tokenizer)
print(f"Custom dataset created with {len(train_dataset)} samples.")
# --- 4. Fine-tuning ---
print("Setting up training arguments...")
training_args = TrainingArguments(
output_dir=OUTPUT_DIR,
num_train_epochs=NUM_TRAIN_EPOCHS,
per_device_train_batch_size=PER_DEVICE_TRAIN_BATCH_SIZE,
learning_rate=LEARNING_RATE,
logging_dir='./logs',
logging_steps=10, # Log more frequently for small dataset
save_steps=50, # Save less frequently or adjust as needed
save_total_limit=2,
overwrite_output_dir=True,
report_to="none" # Disable wandb/tensorboard for this simple example
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
# No eval_dataset for this tiny example
)
print("Starting fine-tuning...")
trainer.train()
print("Fine-tuning complete.")
# Save the fine-tuned model and tokenizer
print(f"Saving fine-tuned model to {OUTPUT_DIR}...")
model.save_pretrained(OUTPUT_DIR)
tokenizer.save_pretrained(OUTPUT_DIR)
print("Model and tokenizer saved.")
# --- 5. Test Inference with the Fine-tuned Model ---
print("\n--- Testing Inference ---")
# Load the fine-tuned model (optional, could also use the 'model' object directly)
# For a clean test, let's load it from the saved directory
fine_tuned_model = AutoModelForCausalLM.from_pretrained(OUTPUT_DIR)
fine_tuned_tokenizer = AutoTokenizer.from_pretrained(OUTPUT_DIR)
# Ensure model is on the correct device (CPU for this example if no GPU detected)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
fine_tuned_model.to(device)
fine_tuned_model.eval() # Set to evaluation mode
prompts = [
"The cat sat on the",
"The dog chased the",
"The bird sang in the",
"The fish swam in the",
"The fox jumped over"
]
for prompt_text in prompts:
print(f"\nPrompt: {prompt_text}")
inputs = fine_tuned_tokenizer.encode(prompt_text, return_tensors="pt").to(device)
# Generate text
# max_length includes the length of the prompt
# max_new_tokens is an alternative to specify only new tokens
outputs = fine_tuned_model.generate(
inputs,
max_length=len(inputs[0]) + 10, # Generate 10 new tokens
num_return_sequences=1,
pad_token_id=fine_tuned_tokenizer.eos_token_id, # Important for open-ended generation
eos_token_id=fine_tuned_tokenizer.eos_token_id,
do_sample=True, # Use sampling for more diverse outputs
top_k=50, # Consider top 50 tokens for sampling
top_p=0.95 # Use nucleus sampling
)
generated_text = fine_tuned_tokenizer.decode(outputs[0], skip_special_tokens=True)
print(f"Generated: {generated_text}")
print("\n--- Inference Test Complete ---")
# To clean up generated files (optional)
# import shutil
# if os.path.exists(OUTPUT_DIR):
# shutil.rmtree(OUTPUT_DIR)
# if os.path.exists("./logs"):
# shutil.rmtree("./logs")
How to Run:
Save the code above as a Python file (e.g., tiny_llm.py).
Open your terminal or command prompt.
Navigate to the directory where you saved the file.
Run the script: python tiny_llm.py
Expected Behavior & Output:
It will download distilgpt2 model and tokenizer files (first run only).
You'll see training progress (loss decreasing, hopefully).
The fine-tuned model will be saved in a directory named tiny_llm_finetuned.
During inference, you'll provide prompts like "The cat sat on the", and the model will try to complete them based on what it learned.
Don't expect miracles! With such a tiny dataset, the completions might be repetitive or only loosely related to the prompt, but hopefully, it tries to complete with words like "mat", "ball", etc. It might also just repeat the prompt or generate gibberish if training wasn't very effective on such a small scale.
Tokenization: Converting text to numbers the model understands.
Custom Dataset: Preparing your specific data for the model.
Fine-tuning: Adapting the pre-trained model to your specific data/task using Trainer.
Inference: Using the fine-tuned model to generate new text.
Causal Language Modeling: The task of predicting the next token in a sequence.
This is a very basic "hello world" for LLM fine-tuning. Building something robust requires significantly more data, careful hyperparameter tuning, and evaluation.