Setting Up the Development Environment
Working with LLMs requires a robust environment capable of handling intensive numerical computation (tensors). We will use Python and PyTorch, the industry-standard framework for deep learning research.
2.1 Prerequisites
- Operating system: Linux (Ubuntu 20.04+ recommended) or Windows with WSL2.
- Hardware: An NVIDIA GPU is recommended (with CUDA drivers installed) for efficient training or inference.
- Python: Version 3.8 to 3.11.
2.2 Managing Virtual Environments
Never install libraries into the global Python environment. Use venv or Conda.
# Creating the virtual environment (Linux/Mac)
# python3 -m venv .venv
# Activating the environment
# source .venv/bin/activate
# On Windows (PowerShell):
python -m venv .venv
.\venv\Scripts\Activate.ps1
A simple Python example
print("Hello World")
2.3 Installing PyTorch
The PyTorch installation depends on your CUDA version. Visit pytorch.org for the exact command. Below is a standard example for CUDA 11.8:
# Installation with GPU support (NVIDIA)
pip install torch torchvision torchaudio
--index-url https://download.pytorch.org/whl/cu118
# If you do not have a GPU (CPU only - very slow for LLMs):
# pip install torch torchvision torchaudio
2.4 The Hugging Face Ecosystem
Hugging Face’s transformers library is the standard interface for accessing pre-trained models.
pip install transformers accelerate datasets torch
- transformers: Loads models and tokenizers.
- accelerate: Optimizes training and inference on varied hardware (multi-GPU, mixed precision).
- datasets: Makes it easy to download and process large text corpora.
2.5 Verification Script (Sanity Check)
Create a file called check_env.py to validate that PyTorch can access the GPU and that the Transformers library works.
import torch
from transformers import pipeline
def check_environment():
print("=== Environment Check ===")
# 1. Check Python and PyTorch
print(f"PyTorch Version: {torch.__version__}")
# 2. Check CUDA (GPU) availability
cuda_available = torch.cuda.is_available()
print(f"CUDA Available: {cuda_available}")
if cuda_available:
print(f"GPU Device: {torch.cuda.get_device_name(0)}")
print(f"VRAM: {torch.cuda.get_device_properties(0).total_memory
/ 1e9:.2f} GB")
else:
print("WARNING: Running on CPU. Performance will be limited.")
# 3. Quick inference test with a small model (GPT-2)
print("\n=== Inference Test (Hugging Face) ===")
try:
# The pipeline abstracts away tokenization and model complexity
generator = pipeline('text-generation', model='gpt2', device=0
if cuda_available else -1)
prompt = "The future of AI is"
result = generator(prompt, max_length=30, max_new_tokens=30, num_return_sequences=1,
truncation=True)
print(f"Prompt: {prompt}")
print(f"Output: {result[0]['generated_text']}")
print("\nSUCCESS: Environment configured correctly.")
except Exception as e:
print(f"""\nERROR: Failed to load the model or run inference.
\nDetails: {e}""")
if __name__ == "__main__":
check_environment()
Here are a few simple examples that illustrate basic Transformer concepts using Hugging Face’s transformers library:
from transformers import AutoTokenizer, AutoModel
import torch
# Load a pre-trained tokenizer and model
model_name = "bert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModel.from_pretrained(model_name)
# Example text
text = "Transformers are amazing for NLP!"
# Tokenization
inputs = tokenizer(text, return_tensors="pt")
# Get the model's embeddings
outputs = model(**inputs)
last_hidden_states = outputs.last_hidden_state
print(last_hidden_states.shape) # (batch_size, sequence_length, hidden_size)
last_hidden_states
This code shows how to load a pre-trained Transformer model (BERT), tokenize a text, and obtain the model’s internal representations (embeddings).
Another simple example uses a Transformer model for text classification:
from transformers import pipeline
# Create a sentiment classification pipeline
classifier = pipeline("sentiment-analysis")
# Classify text
result = classifier("I love learning about Transformers!")
print(result)
This example uses a ready-made sentiment analysis pipeline, which internally relies on a Transformer model to classify the text.
Summary
We set up an isolated Python environment, installed PyTorch with CUDA support, and validated the installation by running a basic GPT-2 model.
2.6 Making the Experiment Reproducible
An environment that works today is not guaranteed to work after an update. Record the versions of Python, PyTorch, the driver, and the installed libraries. In academic projects, save the dependencies in requirements.txt or pyproject.toml and note the random seed used in the experiments. The seed does not eliminate every source of nondeterminism on GPU, but it reduces variations that are hard to investigate.
Before training, estimate memory. Parameters are only part of the consumption: activations, gradients, and optimizer states also take up space. A float32 model uses four bytes per parameter for the weights alone; during training with AdamW, the total can be several times larger. Starting with a small batch and sequence length avoids confusing a lack of memory with a bug in the code.
Diagnostic checklist
First run a small operation on the CPU, then on the GPU, confirm
tensor.device, and inspect the shapes withtensor.shape. If an out of memory error occurs, reducebatch_sizeorseq_lenbefore changing the architecture.
2.7 Understanding the Path to the GPU
A GPU speeds up training because it executes many similar numerical operations in parallel. However, the gain only appears when there is enough work to occupy its cores and when data movement does not dominate the total time. A program may have a GPU available and still be slow because of very small batches, blocking data loading, or frequent copies between CPU and device.
Three resources compete for memory: weights, the states needed for backpropagation, and the batch data. Reduced precision, gradient accumulation, and gradient checkpointing attack different parts of this consumption. Reduced precision lowers the bytes per number; accumulation simulates a larger batch with several micro-batches; checkpointing saves activations and recomputes them during the backward pass.
import torch
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
x = torch.randn(32, 128, 512, device=device)
print("device:", x.device)
print("tensor memory (MiB):", x.nelement() * x.element_size() / 2**20)
When measuring performance, synchronize the GPU before and after the timed section, since CUDA operations are asynchronous. Run a few warm-up iterations and compare the same computation; measuring only the first run includes initialization and kernel compilation.
Evidence-driven diagnosis
If the GPU is underutilized, investigate data feeding and the size of the operations. If it is out of memory, investigate shapes, activations, and batch size. If it is fully utilized, kernel and precision optimizations may be more relevant.