Here's a Python script that trains a Mixture of Experts (MoE) model with two experts on the "roneneldan/TinyStories" dataset. One expert is trained for 3 epochs, and the other for 1 epoch. During inference, a random expert is selected for each prompt, and the script prints out which expert is used. The weights of both experts are kept in RAM, and only the selected expert's weights are loaded into VRAM to reduce VRAM usage. The inference script records and prints VRAM usage accordingly.
Training Script (train.py)
import torch
from torch.utils.data import DataLoader
from transformers import AutoTokenizer, AutoModelForCausalLM, Trainer, TrainingArguments
from datasets import load_dataset
import os
def train_expert(expert_name, num_epochs):
# Load the dataset
dataset = load_dataset('roneneldan/TinyStories', split='train')
# Load the tokenizer and model
tokenizer = AutoTokenizer.from_pretrained('gpt2') # Using GPT-2 tokenizer
model = AutoModelForCausalLM.from_pretrained('gpt2') # Using GPT-2 model
# Tokenize the dataset
def tokenize_function(examples):
return tokenizer(examples['text'], return_tensors='pt', padding='max_length', truncation=True, max_length=128)
tokenized_dataset = dataset.map(tokenize_function, batched=True, remove_columns=['text'])
# Set format for PyTorch tensors
tokenized_dataset.set_format(type='torch', columns=['input_ids', 'attention_mask'])
# Define training arguments
training_args = TrainingArguments(
output_dir=f'./{expert_name}', # Output directory
num_train_epochs=num_epochs, # Number of epochs
per_device_train_batch_size=8, # Batch size per device
save_steps=5000, # Save checkpoint every 5000 steps
save_total_limit=2, # Only keep the last 2 checkpoints
logging_steps=100, # Log every 100 steps
weight_decay=0.01, # Weight decay
evaluation_strategy='no', # No evaluation
learning_rate=5e-5, # Learning rate
push_to_hub=False, # Do not push to hub
fp16=torch.cuda.is_available(), # Mixed precision training if GPU is available
)
# Initialize the Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_dataset,
tokenizer=tokenizer,
)
# Train the model
trainer.train()
# Save the model
model.save_pretrained(f'./{expert_name}')
tokenizer.save_pretrained(f'./{expert_name}')
if __name__ == '__main__':
# Train Expert A for 3 epochs
train_expert('ExpertA', num_epochs=3)
# Train Expert B for 1 epoch
train_expert('ExpertB', num_epochs=1)
Explanation:
- Dataset: Loads the "roneneldan/TinyStories" dataset.
- Experts: Trains two experts (
ExpertA and ExpertB) for different numbers of epochs.
- Tokenizer and Model: Uses the GPT-2 tokenizer and model from Hugging Face Transformers.
- Tokenization: Tokenizes the dataset with padding and truncation to a maximum length of 128 tokens.
- Training Arguments: Sets up training parameters, including mixed precision training if a GPU is available.
- Training: Uses the
Trainer class to handle the training loop.
- Saving Models: Saves the trained models and tokenizers for later use.
Inference Script (inference.py)
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
import random
import gc
def print_vram_usage():
allocated = torch.cuda.memory_allocated() / (1024 ** 3) # Convert bytes to GB
reserved = torch.cuda.memory_reserved() / (1024 ** 3)
print(f"VRAM Usage: Allocated: {allocated:.2f} GB, Reserved: {reserved:.2f} GB")
def free_gpu_memory():
torch.cuda.empty_cache()
gc.collect()
def main():
device = 'cuda' if torch.cuda.is_available() else 'cpu'
# Load tokenizers and models into RAM (on CPU)
tokenizerA = AutoTokenizer.from_pretrained('./ExpertA')
modelA = AutoModelForCausalLM.from_pretrained('./ExpertA').to('cpu')
tokenizerB = AutoTokenizer.from_pretrained('./ExpertB')
modelB = AutoModelForCausalLM.from_pretrained('./ExpertB').to('cpu')
prompt = "Once upon a time"
# Randomly choose an expert
expert_choice = random.choice(['A', 'B'])
print(f"Selected Expert {expert_choice}")
# Move the selected expert to VRAM, and move the other back to RAM
if expert_choice == 'A':
modelA.to('cuda')
modelB.to('cpu')
selected_model = modelA
selected_tokenizer = tokenizerA
else:
modelB.to('cuda')
modelA.to('cpu')
selected_model = modelB
selected_tokenizer = tokenizerB
free_gpu_memory() # Clean up VRAM
print_vram_usage()
# Encode the prompt
input_ids = selected_tokenizer.encode(prompt, return_tensors='pt').to('cuda')
# Generate text
output = selected_model.generate(input_ids, max_length=50)
# Decode the output
generated_text = selected_tokenizer.decode(output[0], skip_special_tokens=True)
print("\nGenerated Text:")
print(generated_text)
# Print VRAM usage after inference
print_vram_usage()
if __name__ == '__main__':
main()
Explanation:
- Loading Models: Loads both experts into RAM (CPU memory).
- Expert Selection: Randomly selects one of the experts for inference.
- Memory Management:
- Moves the selected expert's weights to VRAM.
- Ensures the unused expert's weights are kept in RAM with only references in VRAM.
- Frees up any unused VRAM to reduce memory usage.
- Inference:
- Encodes the input prompt and runs inference using the selected expert.
- Generates and decodes the output text.
- VRAM Usage: Prints VRAM usage before and after inference.
Note: To monitor VRAM usage accurately, make sure you're running on a machine with a CUDA-compatible GPU and have the necessary NVIDIA drivers installed.
Running the Scripts
-
Install Dependencies:
pip install torch transformers datasets
-
Train the Experts:
python train.py
The models will be saved in the directories ./ExpertA and ./ExpertB.
-
Run Inference:
python inference.py
Each time you run the inference script, it will randomly select an expert, print which expert is used, display VRAM usage, and generate text based on the prompt.
Sample Output
Selected Expert B
VRAM Usage: Allocated: 0.59 GB, Reserved: 0.59 GB
Generated Text:
Once upon a time, in a small village nestled among the rolling hills, there lived a young girl named Lily. She was known for her bright smile and kind heart.
VRAM Usage: Allocated: 0.61 GB, Reserved: 0.61 GB
VRAM Usage Explanation:
- Allocated Memory: The actual memory used by tensors.
- Reserved Memory: The reserved memory by the caching allocator that may not necessarily be used.
By loading only the selected expert into VRAM and keeping the other in RAM, the script minimizes VRAM usage, which is crucial when working with limited GPU resources.
Important Notes
- Hardware Requirements: A CUDA-compatible GPU is recommended for training and inference.
- Performance Considerations: Loading models to and from VRAM can introduce latency. This script demonstrates the mechanism for reducing VRAM usage but may not be suitable for real-time applications without optimization.
- Memory Management: The
free_gpu_memory function helps in freeing up unused VRAM, which can be critical in memory-constrained environments.
- Model Complexity: Using larger models or increasing the number of experts will require more RAM and VRAM. Adjust the batch size and model architecture according to your hardware capabilities.
Feel free to modify the scripts to suit your specific needs or to experiment with different configurations.