Skip to content

100+ AI Agents, Agent Skills and RAG Apps - Free and Open Source.

feat: Add Gemma 3 fine-tuning tutorial

Shubhamsaboo1672412de025
diff --git a/README.md b/README.md
index bfa8581a..191ffed3 100644
--- a/README.md
+++ b/README.md
@@ -178,6 +178,7 @@ A curated collection of **Awesome LLM apps built with RAG, AI Agents, Multi-agen
### 🔧 LLM Fine-tuning Tutorials
+* [🔧 Gemma 3 Fine-tuning](advanced_llm_apps/llm_finetuning_tutorials/gemma3_finetuning/)
* [🔧 Llama 3.2 Fine-tuning](advanced_llm_apps/llm_finetuning_tutorials/llama3.2_finetuning/)
diff --git a/advanced_llm_apps/llm_finetuning_tutorials/gemma3_finetuning/README.md b/advanced_llm_apps/llm_finetuning_tutorials/gemma3_finetuning/README.md
new file mode 100644
index 00000000..f8c3ce33
--- /dev/null
+++ b/advanced_llm_apps/llm_finetuning_tutorials/gemma3_finetuning/README.md
@@ -0,0 +1,45 @@
+## 🦥 Finetune Gemma 3 with Unsloth (simple 4-bit LoRA)
+
+Minimal example to finetune Google's Gemma 3 Instruct models with Unsloth using 4-bit loading + LoRA. Small, readable, and runnable on a CUDA GPU.
+
+- **Models**: 270M, 1B, 4B, 12B, 27B
+- **Dataset**: FineTome-100k (ShareGPT-style multi-turn chats)
+- **Method**: Parameter-efficient LoRA (not full FT)
+
+Reference: Unsloth’s Gemma 3 notes: [unsloth.ai/blog/gemma3](https://unsloth.ai/blog/gemma3)
+
+### Install
+
+```bash
+pip install -r requirements.txt
+# or latest Unsloth per their guidance
+pip install --upgrade --force-reinstall --no-cache-dir unsloth unsloth_zoo
+```
+
+### Run
+
+```bash
+python finetune_gemma3.py
+```
+
+Outputs are saved to `finetuned_model/`.
+
+### What the script does
+
+1. Loads Gemma 3 with 4-bit quantization via Unsloth’s `FastModel`.
+2. Attaches LoRA adapters to attention/MLP projections.
+3. Prepares FineTome-100k by applying the Gemma 3 chat template.
+4. Trains with TRL’s `SFTTrainer` for a few demo steps.
+5. Saves the finetuned weights.
+
+### Change model or settings
+
+Edit the top of `finetune_gemma3.py`:
+
+- `MODEL_NAME` (e.g., `unsloth/gemma-3-270m-it`, `unsloth/gemma-3-1b-it`)
+- `MAX_SEQ_LEN`, `LOAD_IN_4BIT`, `FULL_FINETUNING`
+
+Note: 4-bit/8-bit loading requires a CUDA GPU. On Mac (M1/M2), run on CPU/MPS without quantization or use a GPU machine.
+
+
+
diff --git a/advanced_llm_apps/llm_finetuning_tutorials/gemma3_finetuning/finetune_gemma3.py b/advanced_llm_apps/llm_finetuning_tutorials/gemma3_finetuning/finetune_gemma3.py
new file mode 100644
index 00000000..8634dfdc
--- /dev/null
+++ b/advanced_llm_apps/llm_finetuning_tutorials/gemma3_finetuning/finetune_gemma3.py
@@ -0,0 +1,90 @@
+import torch
+from unsloth import FastModel # Unsloth fast loader + training utils
+from unsloth.chat_templates import get_chat_template, standardize_sharegpt
+from datasets import load_dataset # Hugging Face datasets
+from trl import SFTTrainer # Supervised fine-tuning trainer
+from transformers import TrainingArguments # Training hyperparameters
+
+# Minimal config (GPU expected). Adjust sizes: 270m, 1b, 4b, 12b, 27b
+MODEL_NAME = "unsloth/gemma-3-270m-it"
+MAX_SEQ_LEN = 2048
+LOAD_IN_4BIT = True # 4-bit quantized loading for low VRAM
+LOAD_IN_8BIT = False # 8-bit quantized loading for low VRAM
+FULL_FINETUNING = False # LoRA adapters (efficient) instead of full FT
+
+
+def load_model_and_tokenizer():
+ # Load Gemma 3 + tokenizer with desired context/quantization
+ model, tokenizer = FastModel.from_pretrained(
+ model_name=MODEL_NAME,
+ max_seq_length=MAX_SEQ_LEN,
+ load_in_4bit=LOAD_IN_4BIT,
+ load_in_8bit=LOAD_IN_8BIT,
+ full_finetuning=FULL_FINETUNING,
+ )
+
+ if not FULL_FINETUNING:
+ # Add LoRA adapters on attention/MLP projections (PEFT)
+ model = FastModel.get_peft_model(
+ model,
+ r=16,
+ target_modules=[
+ "q_proj", "k_proj", "v_proj", "o_proj",
+ "gate_proj", "up_proj", "down_proj",
+ ],
+ )
+
+ # Apply Gemma 3 chat template for correct conversation formatting
+ tokenizer = get_chat_template(tokenizer, chat_template="gemma-3")
+ return model, tokenizer
+
+
+def prepare_dataset(tokenizer):
+ # Load ShareGPT-style conversations and standardize schema
+ dataset = load_dataset("mlabonne/FineTome-100k", split="train")
+ dataset = standardize_sharegpt(dataset)
+ # Render each conversation into a single training string
+ dataset = dataset.map(
+ lambda ex: {"text": [tokenizer.apply_chat_template(c, tokenize=False) for c in ex["conversations"]]},
+ batched=True,
+ )
+ return dataset
+
+
+def train(model, dataset):
+ # Choose precision based on CUDA capabilities
+ use_bf16 = torch.cuda.is_available() and torch.cuda.is_bf16_supported()
+ use_fp16 = torch.cuda.is_available() and not use_bf16
+
+ trainer = SFTTrainer(
+ model=model,
+ train_dataset=dataset,
+ dataset_text_field="text",
+ max_seq_length=MAX_SEQ_LEN,
+ args=TrainingArguments(
+ per_device_train_batch_size=2,
+ gradient_accumulation_steps=4,
+ warmup_steps=5,
+ max_steps=60,
+ learning_rate=2e-4,
+ bf16=use_bf16,
+ fp16=use_fp16,
+ logging_steps=1,
+ output_dir="outputs",
+ ),
+ )
+ trainer.train()
+
+
+def main():
+ # 1) Load model/tokenizer, 2) Prep data, 3) Train, 4) Save weights
+ model, tokenizer = load_model_and_tokenizer()
+ dataset = prepare_dataset(tokenizer)
+ train(model, dataset)
+ model.save_pretrained("finetuned_model")
+
+
+if __name__ == "__main__":
+ main()
+
+
diff --git a/advanced_llm_apps/llm_finetuning_tutorials/gemma3_finetuning/requirements.txt b/advanced_llm_apps/llm_finetuning_tutorials/gemma3_finetuning/requirements.txt
new file mode 100644
index 00000000..6672c236
--- /dev/null
+++ b/advanced_llm_apps/llm_finetuning_tutorials/gemma3_finetuning/requirements.txt
@@ -0,0 +1,6 @@
+torch
+transformers
+datasets
+trl
+unsloth
+unsloth_zoo