Downloads ยท 30 days
0
ahczhg/llama-3.2-safe-finetuning
llama-3.2-safe-finetuning is a machine learning model from ahczhg. Use it for the machine learning task on the model card, and read the license before you ship it in a product.
[](https://huggingface.co/meta-llama/Llama-3.2-1B) [](https://www.python.org/downloads/) [](https://colab.research.google.com/)
Downloads ยท 30 days
0
Access
Public
Updated Nov 15, 2025
Repo size
โ
Likes
0
Public
Click a slice to open those files.
.ipynb283 KB ยท 94%
From the Hugging Face model README
A production-ready notebook for fine-tuning Meta's Llama 3.2 1B model using Supervised Fine-Tuning (SFT) and Direct Preference Optimization (DPO) with extensive memory management and crash prevention.
This project implements a two-stage fine-tuning pipeline for Llama 3.2 focused on content safety:
Runtime โ Change runtime type โ T4 GPUEdit โ Notebook settings โ High-RAM# Clone the repository
git clone https://github.com/YOUR_USERNAME/llama-3.2-safe-finetuning.git
cd llama-3.2-safe-finetuning
# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install torch transformers datasets accelerate peft trl bitsandbytes scipy
# Launch Jupyter
jupyter notebook llama_3_2_minimal_safe.ipynb
| Parameter | SFT | DPO |
|---|---|---|
| Epochs | 2 | 1 |
| Batch Size | 1 | 1 |
| Gradient Accumulation | 8 | 8 |
| Learning Rate | 1e-5 | 5e-7 |
| Max Sequence Length | 1024 | 1024 |
| LoRA r | 8 | 8 |
| LoRA alpha | 16 | 16 |
| Training Time | ~20-30 min | ~10-20 min |
LoRA_R = 8 # Rank
LoRA_ALPHA = 16 # Alpha scaling
LoRA_DROPOUT = 0.05 # Dropout rate
TARGET_MODULES = ["q_proj", "k_proj", "v_proj", "o_proj"]
llama-3.2-safe-finetuning/
โโโ llama_3_2_minimal_safe.ipynb # Main training notebook
โโโ README.md # This file
โโโ LICENSE # Llama 3.2 Community License
โโโ requirements.txt # Python dependencies (if local)
โโโ sft_output/ # SFT training checkpoints
โโโ dpo_output/ # DPO training checkpoints
โโโ llama-3.2-1b-sft/ # Final SFT model
โโโ llama-3.2-1b-sft-dpo/ # Final merged model
โโโ model_card.md # Generated model card for HF Hub
Update these variables in Step 5 before training:
# Model Configuration
MODEL_NAME = "meta-llama/Llama-3.2-1B"
DATASET_NAME = "nvidia/Aegis-AI-Content-Safety-Dataset-2.0"
NEW_MODEL_NAME = "Llama-3.2-1B-Aegis-SFT-DPO"
# โ ๏ธ UPDATE THIS!
HF_USERNAME = "ahczhg" # Your Hugging Face username
# Memory-optimized settings
MAX_SEQ_LENGTH = 1024 # Reduce to 512 if memory issues
NUM_SAMPLES = 500 # Reduce to 200-300 if needed
| Step | Description | Time | Can Skip |
|---|---|---|---|
| 1 | Environment setup | <1 min | โ |
| 2 | GPU verification | <1 min | โ |
| 3 | Package installation | 3-5 min | โ |
| 4 | Import libraries | <1 min | โ |
| 5 | Configuration | <1 min | โ |
| 6 | HuggingFace login | <1 min | โ |
| 7 | Utility functions | <1 min | โ |
| 8 | Load dataset | 1-2 min | โ |
| 9 | Load tokenizer | 1-2 min | โ |
| 10 | Load model | 2-5 min | โ |
| 11 | SFT setup | <1 min | โ |
| 12 | SFT training | 15-30 min | โ |
| 13 | Save SFT model | 1-2 min | โ |
| 14 | DPO preparation | 2-5 min | โ Optional |
| 15 | DPO training | 10-20 min | โ Optional |
| 16 | Save DPO model | 1-2 min | โ Optional |
| 17 | Upload to HF Hub | 5-15 min | โ Optional |
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
# Load model
model_name = "ahczhg/Llama-3.2-1B-Aegis-SFT-DPO"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype=torch.bfloat16,
device_map="auto"
)
# Prepare prompt
messages = [{"role": "user", "content": "What is artificial intelligence?"}]
inputs = tokenizer.apply_chat_template(
messages,
add_generation_prompt=True,
return_tensors="pt"
).to(model.device)
# Generate
outputs = model.generate(
inputs,
max_new_tokens=256,
temperature=0.7,
top_p=0.9,
do_sample=True
)
# Decode
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(response)
messages = [
{"role": "user", "content": "What is machine learning?"},
{"role": "assistant", "content": "Machine learning is..."},
{"role": "user", "content": "Can you give an example?"}
]
inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to(model.device)
outputs = model.generate(inputs, max_new_tokens=256, temperature=0.7)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
Symptoms: RuntimeError: CUDA out of memory
Solutions:
BATCH_SIZE to 1 (in Step 5)MAX_SEQ_LENGTH to 512 or 768NUM_SAMPLES to 200-300Symptoms: Colab session disconnects at Step 10
Solutions:
Runtime โ Restart runtimeSymptoms: ImportError: cannot import name...
Solutions:
Runtime โ Restart runtimeSymptoms: 401 Unauthorized during login
Solutions:
Symptoms: Stuck downloading dataset in Step 8
Solutions:
NUM_SAMPLES to 200Symptoms: Loss stays constant or increases
Solutions:
# In Step 5, adjust:
BATCH_SIZE = 2 # If you have >16GB VRAM
GRAD_ACCUM = 4 # Reduce if batch size increased
MAX_SEQ_LENGTH = 768 # Shorter sequences = faster
NUM_SAMPLES = 300 # Fewer samples = faster
# In Step 5, adjust:
SFT_EPOCHS = 3 # More epochs
DPO_EPOCHS = 2 # More DPO training
NUM_SAMPLES = 1000 # More training data
LORA_R = 16 # Larger LoRA rank
LORA_ALPHA = 32 # Match 2x rank
Contributions are welcome! Please:
git checkout -b feature/improvement)git commit -am 'Add new feature')git push origin feature/improvement)This project is licensed under the Llama 3.2 Community License Agreement.
Key points:
Full license text: See LICENSE file or https://huggingface.co/meta-llama/Llama-3.2-1B
If you use this project in your research or work, please cite:
@misc{llama32_safe_finetuning,
author = {Community Contributor},
title = {Llama 3.2 Fine-tuning - Memory-Safe Version},
year = {2024},
publisher = {GitHub},
url = {https://github.com/YOUR_USERNAME/llama-3.2-safe-finetuning}
}