Okay, let's create a very small, functional Language Model (LLM) using Python, PyTorch, and the Hugging Face transformers library. This will demonstrate the core concepts of setup, training, and inference.
Goal: Train a tiny GPT-2-like model on a very small custom dataset to generate text in a similar style.
Disclaimer: This model will be extremely basic and limited due to the small dataset size, model size, and training time. It's for educational purposes to illustrate the pipeline.
1. Setup Environment
First, ensure you have Python installed. Then, install the necessary libraries:
bash
pip install torch transformers datasets accelerate bitsandbytes # bitsandbytes is optional but helps with memory
torch: The deep learning framework.
transformers: Provides models, tokenizers, and training utilities from Hugging Face.
datasets: Helps load and process data efficiently.
accelerate: Simplifies running PyTorch code on different hardware (CPU, GPU, multi-GPU).
bitsandbytes: (Optional) Can help reduce memory usage during training/inference, especially on GPUs.
2. Prepare Data
We need some text data. Let's create a tiny dataset directly in the script for simplicity. In a real scenario, you'd load data from files or Hugging Face Datasets.
python
# Sample dataset (a few sentences about programming)
dataset_text = """
Programming is fun.
Python is a popular programming language.
Learning to code can open up many opportunities.
Large language models are transforming technology.
Transformers are a key architecture in modern NLP.
Training requires data and compute power.
Let's train a small model.
This model will learn patterns from this text.
We use PyTorch and Hugging Face libraries.
Inference is the process of using the trained model.
"""
3. Tokenization
We need to convert text into numbers (tokens) that the model can understand. We'll use a pre-trained tokenizer (like GPT-2's) for simplicity.
python
from transformers import AutoTokenizer, DataCollatorForLanguageModeling
import torch
# Load a pre-trained tokenizer (GPT-2's tokenizer is suitable)
tokenizer_name = "gpt2" # Using GPT-2's tokenizer config
tokenizer = AutoTokenizer.from_pretrained(tokenizer_name)
# Add a padding token if it doesn't exist (GPT-2 usually doesn't have one by default)
if tokenizer.pad_token is None:
tokenizer.add_special_tokens({'pad_token': '[PAD]'})
# Tokenize the dataset
def tokenize_function(examples):
# Using return_special_tokens_mask=True is often helpful but not strictly needed here
return tokenizer(examples["text"], truncation=True, max_length=128, padding="max_length")
from datasets import Dataset, DatasetDict
# Create a Hugging Face Dataset object
data = Dataset.from_dict({"text": dataset_text.strip().split('\n')})
tokenized_datasets = data.map(tokenize_function, batched=True, remove_columns=["text"])
# Rename 'input_ids' to 'labels' for causal language modeling
# The model will predict the next token based on previous ones.
# Labels are typically the input_ids shifted. The data collator handles this.
tokenized_datasets = tokenized_datasets.rename_column("input_ids", "labels")
# Create a Data Collator
# This prepares batches, handles padding, and creates labels for Causal LM
data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False) # mlm=False for Causal LM (like GPT)
4. Model Definition & Configuration
We'll define a very small version of the GPT-2 architecture.
python
from transformers import AutoConfig, AutoModelForCausalLM, TrainingArguments, Trainer
# Configure a small GPT-2 model
# Reduce layers, heads, embedding size drastically
config = AutoConfig.from_pretrained(
tokenizer_name,
# --- Making it SMALL ---
n_layer=2, # Number of transformer layers (e.g., 2 instead of 12)
n_head=4, # Number of attention heads (e.g., 4 instead of 12)
n_embd=128, # Embedding dimension (e.g., 128 instead of 768)
# --- --- --- --- ---
# Use the pad token id we potentially added
pad_token_id=tokenizer.pad_token_id,
# For causal LM, ensure this is set correctly
is_decoder=True,
# Add other necessary config parameters based on the base model if needed
)
# Load the model using the small configuration
model = AutoModelForCausalLM.from_config(config)
# Resize token embeddings if we added a new token
model.resize_token_embeddings(len(tokenizer))
print(f"Model Parameter Count: {model.num_parameters():,}")
5. Training
We use the Hugging Face Trainer API for a simplified training loop.
python
# Define training arguments
output_dir = "./small-llm-finetuned"
training_args = TrainingArguments(
output_dir=output_dir,
overwrite_output_dir=True,
num_train_epochs=3, # VERY FEW epochs for demonstration
per_device_train_batch_size=2, # SMALL batch size
save_steps=10_000, # Save checkpoint less frequently for this small run
save_total_limit=2, # Limit the number of saved checkpoints
logging_dir='./logs',
logging_steps=50,
learning_rate=5e-5, # Standard learning rate
weight_decay=0.01,
fp16=torch.cuda.is_available(), # Use mixed precision if GPU is available
report_to="none", # Disable reporting to external services for simplicity
# Add other arguments as needed
)
# Initialize the Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_datasets,
data_collator=data_collator,
tokenizer=tokenizer,
)
# Start training
print("Starting training...")
trainer.train()
print("Training finished.")
# Save the final model and tokenizer
print("Saving model...")
trainer.save_model(output_dir)
tokenizer.save_pretrained(output_dir)
print(f"Model saved to {output_dir}")
6. Inference (Using the Trained Model)
Now, let's load the model we just fine-tuned and generate some text.
python
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
import torch
# Load the fine-tuned model and tokenizer
model_path = "./small-llm-finetuned" # Directory where the model was saved
try:
model = AutoModelForCausalLM.from_pretrained(model_path)
tokenizer = AutoTokenizer.from_pretrained(model_path)
# Set pad_token_id if it was added during setup/training
if tokenizer.pad_token_id is None:
tokenizer.pad_token_id = tokenizer.eos_token_id # Use EOS as PAD if needed
# Move model to GPU if available
device = 0 if torch.cuda.is_available() else -1 # 0 for cuda:0, -1 for CPU
# Create a text generation pipeline
generator = pipeline(
'text-generation',
model=model,
tokenizer=tokenizer,
device=device # Specify device (GPU or CPU)
)
# Define a prompt
prompt = "Learning to code"
# Generate text
print("\n--- Generating Text ---")
generated_text = generator(
prompt,
max_length=50, # How long the output should be
num_return_sequences=3, # Generate multiple options
temperature=0.7, # Controls randomness (lower = more predictable)
top_p=0.9, # Nucleus sampling
do_sample=True, # Enable sampling
pad_token_id=tokenizer.eos_token_id # Important for generation
)
# Print the generated text
for i, output in enumerate(generated_text):
print(f"Sample {i+1}: {output['generated_text']}")
except Exception as e:
print(f"\nError during inference: {e}")
print("Make sure training completed successfully and the output directory exists.")
How it Works:
Setup: Installs essential Python libraries for ML and NLP tasks.
Data Prep: Takes raw text, converts it into numerical IDs (tokens) using a tokenizer. The DataCollatorForLanguageModeling prepares batches suitable for training a model that predicts the next token.
Model Config: We define the architecture of our model. We use AutoConfig to specify parameters like the number of layers (n_layer), attention heads (n_head), and embedding size (n_embd), making them much smaller than standard models like GPT-2. AutoModelForCausalLM then builds the model structure based on this config.
Training: The Trainer handles the complexities of the training loop (forward pass, loss calculation, backward pass, optimizer step). We feed it our tokenized data, the small model, and configuration parameters like the number of epochs and batch size. The goal is to minimize the difference between the model's predictions and the actual next tokens in the data.
Inference: After training, we load the saved model weights. The pipeline function provides an easy interface to feed a prompt (starting text) to the model and get generated text completions based on the patterns it learned.
This provides a basic, end-to-end example of the LLM lifecycle on a minimal scale.