Below is a practical, end-to-end recipe that has worked well for teams that want to “RFT” (Reinforcement Fine-Tune) an open-source model without paying for proprietary RLHF stacks.
The same pipeline works for both instruction-tuning (e.g., Llama-2-chat → better chat) and task-specific tuning (e.g., code generation, SQL, summarisation).
-
Freeze the vocabulary & tokenizer
• Keep the original tokenizer unless you have a very strong reason not to.
• If you do extend it, run transformers.AutoTokenizer.add_tokens(...) and resize the embedding matrix (model.resize_token_embeddings(...)).
-
Create three datasets
A. Prompts (P) – what the model will see at inference.
B. Demonstrations (D) – high-quality completions for SFT.
C. Preferences (R) – ranked pairs/triplets for reward modelling.
Format examples
• Prompt: {"prompt": "Write a Python function that …"}
• Demonstration: {"prompt": "...", "completion": "def foo(...): ..."}
• Preference: {"prompt": "...", "chosen": "...", "rejected": "..."}
Tools to build them quickly
• Distilabel, Argilla, or Label-Studio for human annotation.
• openai/llm-blender or trlx/ultrafeedback for synthetic preference data.
-
Supervised Fine-Tune (SFT) first
Library: transformers.Trainer or trl.SFTTrainer
from trl import SFTTrainer
trainer = SFTTrainer(
model,
train_dataset=demonstrations,
dataset_text_field="completion",
max_seq_length=2048,
args=TrainingArguments(..., num_train_epochs=2, lr=5e-6)
)
trainer.train()
trainer.save_model("sft_model")
-
Train a reward model (RM)
Library: transformers + torch or trl.RewardTrainer
from trl import RewardTrainer
reward_model = AutoModelForSequenceClassification.from_pretrained(
"sft_model", num_labels=1)
trainer = RewardTrainer(
model=reward_model,
train_dataset=preferences,
args=TrainingArguments(..., num_train_epochs=1, lr=1e-5)
)
trainer.train()
trainer.save_model("reward_model")
-
Reinforcement Fine-Tuning (RFT)
Two mainstream open-source stacks:
a) TRL + PPO (works on a single 24 GB GPU with LoRA)
from trl import PPOTrainer, PPOConfig
from peft import LoraConfig, get_peft_model
lora_config = LoraConfig(task_type="CAUSAL_LM", r=64, lora_alpha=16)
model = get_peft_model(model, lora_config)
ppo_config = PPOConfig(
model_name="sft_model",
learning_rate=1e-5,
batch_size=256,
mini_batch_size=64,
gradient_accumulation_steps=1,
ppo_epochs=4,
)
ppo_trainer = PPOTrainer(ppo_config, model, None, reward_model, tokenizer)
for epoch, batch in enumerate(ppo_trainer.dataloader(prompts)):
query_tensors = tokenizer(batch["prompt"], return_tensors="pt").input_ids
response_tensors = ppo_trainer.generate(query_tensors, max_new_tokens=256)
rewards = reward_model(response_tensors).logits
stats = ppo_trainer.step(query_tensors, response_tensors, rewards)
b) TRLX (multi-GPU, DPO, ILQL, PPO)
pip install trlx
trlx train --config configs/ppo_config.yml
c) DPO (Direct Preference Optimisation) – simpler, no reward model needed
from trl import DPOTrainer
dpo_trainer = DPOTrainer(
model,
ref_model=None, # use same model as reference
beta=0.1,
train_dataset=preferences,
tokenizer=tokenizer,
args=TrainingArguments(..., num_train_epochs=1, lr=5e-6)
)
dpo_trainer.train()
-
Evaluation loop
• Automatic: MT-Bench, Alpaca-Eval, OpenAI Evals, Eleuther LM-Eval-Harness.
• Human: pairwise A/B on 100–200 edge cases.
• KL-divergence vs. SFT model to detect reward hacking.
-
Guardrails & reproducibility checklist
□ LoRA or QLoRA to fit 7–13 B models on 1×A100.
□ Gradient checkpointing + bf16 or fp16.
□ Track reward mean/variance per rollout to spot collapse.
□ Save checkpoints every 50–100 PPO steps; rollback if reward spikes.
□ Push final adapter + base model to Hugging Face Hub with a model card.