This repository contains examples and scripts for fine-tuning popular transformer-based models from Hugging Face using PyTorch. The main notebook demonstrates two different NLP tasks: sequence classification (sentiment analysis) and causal language modeling (instruction tuning).
- Dataset: Yelp Review Full
- Task: Predict review star ratings (1 to 5 stars) classification.
- Model:
bert-base-cased - Techniques:
- Custom PyTorch training loop using
DataLoader,AdamW, andLambdaLRscheduler. - Evaluation using
torchmetrics.Accuracy. - Manual model saving and loading of
.ptweights.
- Custom PyTorch training loop using
- Dataset: timdettmers/openassistant-guanaco
- Task: Instruction tuning for conversational agents.
- Model:
facebook/opt-350m - Techniques:
- Training using Hugging Face's
TrainerAPI. bfloat16precision to prevent gradient overflow/NaN and reduce memory usage.- Custom
TrainingArgumentsoptimization (gradient accumulation, weight decay, learning rate). - Inference using the Hugging Face
pipelineAPI to compare pre- and post-fine-tuning outputs.
- Training using Hugging Face's
To run the notebook, install the following dependencies:
pip install torch torchvision torchaudio
pip install transformers datasets trl accelerate torchmetrics matplotlib tqdmNote: A CUDA-enabled GPU and appropriate PyTorch installation are highly recommended for reasonable training times.
- Open the Jupyter Notebook
fine-tuning_tf.ipynb. - The notebook is divided into two distinct sections:
- Cell 1–20: BERT fine-tuning (Sequence Classification).
- Cell 21–28: OPT fine-tuning (Language Modeling).
- Run the cells sequentially.
- Note: The language modeling section uses
bfloat16, requiring an Ampere architecture GPU (e.g., RTX 30-series, A100) or newer for optimal hardware support natively.
- Note: The language modeling section uses
- Loss going to NaN during LM Fine-Tuning: If using
bf16=TrueinTrainingArguments, ensure the model is loaded withtorch_dtype=torch.bfloat16from the start to prevent fp32-to-bf16 cast overflow. - Out of Memory (OOM): Reduce
per_device_train_batch_sizeand increasegradient_accumulation_stepsproportionately to keep the effective batch size the same while lowering VRAM footprint.