Below is a complete, ready‑to‑run notebook‑style script that shows how to Supervised‑Fine‑Tune (SFT) the Gemma‑3‑270B‑IT model with the 🤗 TRL library.
It covers everything you need:
Environment set‑up (packages, 4‑bit quantisation with bitsandbytes so the 270 B model can fit on a single‑GPU or a modest multi‑GPU node)
Loading the model & tokenizer (google/gemma3-270b-it – replace with the exact repo name if it differs)
Preparing a simple instruction‑following dataset (JSONL → 🤗 datasets)
Tokenisation & formatting for the ChatML style used by Gemma‑IT models
Instantiating the TRL SFTTrainer (the high‑level trainer that handles mixed‑precision, gradient‑checkpointing, LoRA, etc.)
Running the training loop and saving the fine‑tuned checkpoint
(Optional) LoRA + bitsandbytes 4‑bit – the recommended way to train a 270 B model on a single A100‑40GB/80GB.
1️⃣ Environment & Installation
bash
# -------------------------------------------------
# 1️⃣ Install the required libraries (latest versions)
# -------------------------------------------------
# torch (choose the correct CUDA build for your machine)
pip install "torch>=2.3.0" --extra-index-url https://download.pytorch.org/whl/cu121
# 🤗 Transformers, Datasets, Accelerate, PEFT, TRL, BitsAndBytes
pip install transformers datasets accelerate peft trl bitsandbytes==0.43.1
# Optional: tqdm for progress bars, safetensors for fast checkpoint saving
pip install tqdm safetensors
Tip:
If you are on a multi‑node cluster, make sure accelerate is configured (accelerate config) – the same config works for a single‑GPU run as well.
2️⃣ Imports & Helper Functions
python
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
# -------------------------------------------------
# 2️⃣ Imports
# -------------------------------------------------
import os
import json
from pathlib import Path
from typing import List, Dict
import torch
from datasets import load_dataset, Dataset, DatasetDict
from transformers import AutoTokenizer, AutoModelForCausalLM, TrainingArguments
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
from trl import SFTTrainer
from tqdm import tqdm
Prompt‑formatting helper (ChatML)
Gemma‑IT models expect the ChatML format (<bos> + <im_start>user … <im_end><im_start>assistant … <im_end>).
The helper below builds that string for each example.
python
def build_chatml(prompt: str, response: str, tokenizer) -> str:
"""
Returns a single string that follows the ChatML format expected
by Gemma‑IT models.
"""
# These tokens are model‑specific; for Gemma‑IT they are:
BOS = tokenizer.bos_token or "<s>"
EOS = tokenizer.eos_token or "</s>"
# The official tags (same as OpenAI's ChatML)
IM_START = "<im_start>"
IM_END = "<im_end>"
# Build the conversation:
# <bos><im_start>system ... <im_end>
# <im_start>user\n{prompt}<im_end>
# <im_start>assistant\n{response}<im_end>
system_prompt = "You are a helpful assistant."
chat = (
f"{BOS}{IM_START}system\n{system_prompt}{IM_END}"
f"{IM_START}user\n{prompt}{IM_END}"
f"{IM_START}assistant\n{response}{IM_END}"
)
return chat
3️⃣ Load & Prepare the Dataset
Assume you have a JSON Lines file (train.jsonl) with the following schema:
json
{
"prompt": "Explain the difference between a list and a tuple in Python.",
"response": "A list is mutable …"
}
You can also load any datasets‑compatible source (CSV, Parquet, HF hub, etc.).
python
# -------------------------------------------------
# 3️⃣ Load your instruction‑following data
# -------------------------------------------------
DATA_PATH = Path("./data") # <-- put your files here
TRAIN_FILE = DATA_PATH / "train.jsonl"
VALID_FILE = DATA_PATH / "valid.jsonl" # optional – you can skip validation
def load_jsonl(file_path: Path) -> Dataset:
# `datasets` can directly load a jsonl as a Dataset
return load_dataset("json", data_files=str(file_path), split="train")
train_ds = load_jsonl(TRAIN_FILE)
if VALID_FILE.is_file():
valid_ds = load_jsonl(VALID_FILE)
dataset = DatasetDict({"train": train_ds, "validation": valid_ds})
else:
# if you don't have a validation split, we will split 5% from train
dataset = train_ds.train_test_split(test_size=0.05, seed=42)
dataset = DatasetDict({
"train": dataset["train"],
"validation": dataset["test"]
})
Tokenisation & Formatting
python
# -------------------------------------------------
# 4️⃣ Tokeniser & Model
# -------------------------------------------------
MODEL_NAME = "google/gemma3-270b-it" # <-- adjust if needed
tokenizer = AutoTokenizer.from_pretrained(
MODEL_NAME,
use_fast=True,
trust_remote_code=True # many Google models ship custom tokeniser
)
# Ensure the tokenizer knows the special tokens that Gemma‑IT uses
if tokenizer.bos_token is None:
tokenizer.bos_token = "<s>"
if tokenizer.eos_token is None:
tokenizer.eos_token = "</s>"
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
# ------------------------------
# Helper: tokenise a single sample
# ------------------------------
def preprocess(example: Dict) -> Dict:
# Build the ChatML string
chat = build_chatml(example["prompt"], example["response"], tokenizer)
# Tokenise (add_special_tokens=False because we already inserted BOS/EOS in chat)
tokenised = tokenizer(
chat,
truncation=True,
max_length=1024, # adjust to your context length (Gemma‑3 max 8192)
padding=False,
return_attention_mask=False,
)
# The model expects `labels` identical to `input_ids` for SFT
tokenised["labels"] = tokenised["input_ids"].copy()
return tokenised
# Apply preprocessing (batched for speed)
tokenized_datasets = dataset.map(
preprocess,
batched=False,
remove_columns=dataset["train"].column_names, # keep only tokenised fields
num_proc=os.cpu_count(),
)
4️⃣ Model Loading – 4‑bit + LoRA (recommended)
Fine‑tuning a 270 B model without any compression is practically impossible on a single GPU.
The easiest recipe:
Load the model in 4‑bit (bitsandbytes + load_in_4bit=True) → ~ 45 GB VRAM.
Apply LoRA (low‑rank adapters) so only a few hundred MB are trainable.
python
# -------------------------------------------------
# 5️⃣ Load the 4‑bit model and wrap with LoRA
# -------------------------------------------------
from transformers import BitsAndBytesConfig
# 4‑bit quantisation config (you can play with `llm_int8_skip_modules` if you hit errors)
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4", # "nf4" is the default for LLMs
bnb_4bit_compute_dtype=torch.bfloat16, # keep computation in bf16
bnb_4bit_use_double_quant=True,
)
model = AutoModelForCausalLM.from_pretrained(
MODEL_NAME,
device_map="auto", # automatically split across GPUs if you have >1
quantization_config=bnb_config,
trust_remote_code=True,
)
# -------------------------------------------------
# Prepare for PEFT (LoRA) training
# -------------------------------------------------
model = prepare_model_for_kbit_training(model)
lora_cfg = LoraConfig(
r=64, # rank – 64 is a good default for 270 B
lora_alpha=16,
target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj"], # typical for Gemma
lora_dropout=0.05,
bias="none",
task_type="CAUSAL_LM",
)
model = get_peft_model(model, lora_cfg)
print(model.print_trainable_parameters())
# Expected output: ~ 2‑3 GB trainable params (depends on r)
5️⃣ Training Arguments
python
# -------------------------------------------------
# 6️⃣ Training hyper‑parameters
# -------------------------------------------------
output_dir = "./gemma3-270b-it-sft"
training_args = TrainingArguments(
output_dir=output_dir,
per_device_train_batch_size=1, # 4‑bit + LoRA lets us fit batch=1 on a 40GB A100
per_device_eval_batch_size=1,
gradient_accumulation_steps=8, # effective batch size = 8
learning_rate=2e-4, # LoRA often works well with 1e-4‑2e-4
num_train_epochs=3,
lr_scheduler_type="cosine",
warmup_steps=0.1 * (len(tokenized_datasets["train"]) // (8)), # 10% warmup
logging_steps=20,
eval_steps=200,
save_steps=500,
eval_accumulation_steps=1,
fp16=True, # use bf16 if your GPU supports it (`bf16=True` can be set)
bf16=False, # set to True on newer GPUs (A100, H100)
gradient_checkpointing=True,
report_to=["tensorboard"], # or ["wandb"] if you prefer
dataloader_num_workers=4,
remove_unused_columns=False,
# **Deepspeed** can be added for multi‑GPU large‑model training:
# deepspeed="ds_config_zero2.json"
)
Why gradient‑accumulation?
With batch‑size 1 we keep VRAM usage low, but accumulate enough gradients to make training stable.
6️⃣ Instantiate the TRL SFTTrainer
python
# -------------------------------------------------
# 7️⃣ SFTTrainer (the high‑level trainer from 🤗 TRL)
# -------------------------------------------------
trainer = SFTTrainer(
model=model,
args=training_args,
train_dataset=tokenized_datasets["train"],
eval_dataset=tokenized_datasets["validation"],
tokenizer=tokenizer,
# ---- Optional callbacks -------------------------------------------------
packing=False, # set True if you want to pack multiple examples per sequence
# If you want to monitor loss on the prompt side only:
# compute_metrics=lambda eval_pred: {"loss": eval_pred.loss},
)
# -------------------------------------------------
# 8️⃣ Run training
# -------------------------------------------------
trainer.train()
Saving the LoRA‑adapted checkpoint
python
# -------------------------------------------------
# 9️⃣ Save (both the full model and ONLY the LoRA adapters)
# -------------------------------------------------
# Full model (including LoRA adapters) – this is the easiest to reload later.
trainer.model.save_pretrained(os.path.join(output_dir, "final_full_model"))
# If you only want the adapters (tiny checkpoint):
trainer.model.save_pretrained(os.path.join(output_dir, "lora_adapters"),
safe_serialization=True)
# Also save the tokenizer (always a good idea)
tokenizer.save_pretrained(os.path.join(output_dir, "tokenizer"))
7️⃣ Inference Demo
python
# -------------------------------------------------
# 10️⃣ Load the fine‑tuned model & generate
# -------------------------------------------------
from transformers import GenerationConfig
ft_model = AutoModelForCausalLM.from_pretrained(
os.path.join(output_dir, "final_full_model"),
device_map="auto",
trust_remote_code=True,
torch_dtype=torch.bfloat16,
)
ft_tokenizer = AutoTokenizer.from_pretrained(
os.path.join(output_dir, "tokenizer"),
trust_remote_code=True,
)
def chat(prompt: str):
chat_input = build_chatml(prompt, "", ft_tokenizer) # no response yet
inputs = ft_tokenizer(chat_input, return_tensors="pt").to(ft_model.device)
gen_cfg = GenerationConfig(
max_new_tokens=256,
temperature=0.7,
top_p=0.95,
do_sample=True,
pad_token_id=ft_tokenizer.eos_token_id,
)
with torch.no_grad():
generated = ft_model.generate(**inputs, generation_config=gen_cfg)
# Decode only the newly generated part (skip the prompt)
output_text = ft_tokenizer.decode(generated[0][inputs["input_ids"].shape[-1]:],
skip_special_tokens=True)
return output_text.strip()
# Example usage
print(chat("Explain why the sky appears blue in the evening."))
8️⃣ Optional – Full‑Zero‑2 DeepSpeed for multi‑GPU (>1)
If you have more than one GPU (e.g., 8 × A100‑80GB), you can switch to DeepSpeed ZeRO‑2 to further reduce memory:
accelerate launch will handle the distributed launch automatically.
9️⃣ Checklist & Troubleshooting
Issue
Fix
CUDA out‑of‑memory
* Reduce gradient_accumulation_steps. * Use torch_dtype=torch.bfloat16 (or fp16=True). * Verify you’re loading the model in 4‑bit (load_in_4bit=True).
bitsandbytes import error
Install the exact version bitsandbytes==0.43.1 (newer versions sometimes break 4‑bit on older CUDA).
Missing special tokens (<im_start>…)
Add them manually: tokenizer.add_special_tokens({"additional_special_tokens": ["<im_start>", "<im_end>"]}) and re‑initialise the model’s embeddings (model.resize_token_embeddings(len(tokenizer))).
Increase max_length in preprocess (e.g., to 2048 or 4096).
Running on CPU
Ensure device_map="auto" and torch.cuda.is_available() is True. If you have no GPU, you must switch to load_in_8bit=False and use a much smaller model.
10️⃣ TL;DR – One‑File Script
If you just want a single script you can copy‑paste everything below into run_sft_gemma3.py (adjust paths and model name, then run python run_sft_gemma3.py).