How to perform LoRA-based GRPO after LoRA SFT? (gsm8k_peft.py seems removed)
Hi, thanks for your great work!
I have a question regarding applying LoRA for GRPO after LoRA SFT.
I noticed that you mentioned gsm8k_peft.py in some earlier discussions, but it seems that this file has been removed from the repo.
- Could you kindly share how you recommend performing LoRA-based GRPO after completing LoRA SFT with your current codebase?
- I modified
verifiers/verifiers/utils/model_utils.pyto load a LoRA adapter on top of the base model, but I’m not sure if this is the correct approach and whether this actually constitutes LoRA-based GRPO.
The following is my script
import verifiers as vf
from verifiers.envs.multiturn_env_jailbreak import JailBreakEnv
from typing import Optional, Union, Dict, Any
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from importlib.util import find_spec
from peft import PeftModel, PeftConfig
import pdb
"""
inference:
CUDA_VISIBLE_DEVICES=3 vf-vllm --model /NAS/xiongxq/LLaMA-Factory/output/Qwen2.5-7B-Instruct-sft-lora
training:
CUDA_VISIBLE_DEVICES=0 accelerate launch --num-processes 1 verifiers/examples/jailbreak.py
"""
exp_name = 'test_Qwen2.5-7B-Instruct-sft-lora'
model_name = '/NAS/xiongxq/LLaMA-Factory/output/Qwen2.5-7B-Instruct-sft-lora'
peft_model_path = '/NAS/xiongxq/LLaMA-Factory/saves/qwen_sft/converted_sft'
def is_liger_available() -> bool:
return find_spec("liger_kernel") is not None
def get_model(
model_name: str,
use_liger: bool = True,
model_kwargs: Optional[Dict[str, Any]] = None,
peft_model_path: Optional[str] = None,
merge_and_unload: bool = False
) -> Union[AutoModelForCausalLM, PeftModel]:
"""
Load the base model or LoRA fine-tuned model.
Args:
model_name: Name or path of the base model.
use_liger: Whether to use the Liger kernel (if available).
model_kwargs: Additional arguments for model loading.
peft_model_path: Path to the LoRA adapter (if loading fine-tuned model).
merge_and_unload: Whether to merge LoRA weights into the base model.
Returns:
The loaded model (base model or PeftModel).
"""
# Set default model parameters
if model_kwargs is None:
model_kwargs = dict(
torch_dtype=torch.bfloat16,
attn_implementation="flash_attention_2",
use_cache=False,
)
# Check if Liger is available
if is_liger_available() and use_liger:
print("Using Liger kernel")
from liger_kernel.transformers import AutoLigerKernelForCausalLM
model = AutoLigerKernelForCausalLM.from_pretrained(model_name, **model_kwargs)
else:
model = AutoModelForCausalLM.from_pretrained(model_name, **model_kwargs)
# Load LoRA adapter if provided
if peft_model_path is not None:
try:
# Check adapter configuration
peft_config = PeftConfig.from_pretrained(peft_model_path)
if peft_config.base_model_name_or_path != model_name:
print(f"Warning: LoRA adapter was trained on {peft_config.base_model_name_or_path}, "
f"but loading onto {model_name}")
# Load LoRA adapter
model = PeftModel.from_pretrained(model, peft_model_path)
# Merge LoRA weights if required
if merge_and_unload:
model = model.merge_and_unload()
print("LoRA weights have been merged into the base model")
except Exception as e:
print(f"Error loading LoRA adapter: {str(e)}")
raise
return model
def get_tokenizer(
model_name: str,
peft_model_path: Optional[str] = None
) -> Any:
"""
Load tokenizer, prioritizing the tokenizer in the LoRA adapter directory if available.
Args:
model_name: Name of the base model.
peft_model_path: Path to the LoRA adapter (optional).
Returns:
The loaded tokenizer.
"""
# Try to load tokenizer from LoRA directory first
if peft_model_path is not None:
try:
return AutoTokenizer.from_pretrained(peft_model_path)
except:
print("Using base model tokenizer instead of LoRA directory tokenizer")
# Fallback to base model tokenizer
tokenizer = AutoTokenizer.from_pretrained(model_name)
if not hasattr(tokenizer, "chat_template"):
raise ValueError(
f"Tokenizer for model {model_name} does not have chat_template attribute, "
"and could not find a tokenizer with the same name as the model with suffix "
"'-Instruct'. Please provide a tokenizer with the chat_template attribute."
)
return tokenizer
model = get_model(model_name=model_name, peft_model_path=peft_model_path)
tokenizer = get_tokenizer(model_name=model_name, peft_model_path=peft_model_path)
vf_env = JailBreakEnv(
# num_samples=200,
# num_eval_samples=20,
# max_concurrent=32,
seed = 42,
max_turns = 10,
max_concurrent=1,
)
run_name = f"jailbreak-grpo-{exp_name}"
training_args=vf.grpo_defaults(run_name=run_name)
training_args.max_steps=10
training_args.per_device_train_batch_size=2
training_args.gradient_accumulation_steps=2
training_args.num_iterations=1
training_args.num_train_epochs=1
training_args.save_steps=5
training_args.eval_steps=5
training_args.num_generations=4
training_args.async_generation_timeout=120000 # 200 minutes
training_args.max_prompt_length=4096
training_args.max_completion_length=32768
training_args.mask_env_responses=True
trainer = vf.GRPOTrainer(
model=model,
processing_class=tokenizer,
env=vf_env,
args=training_args,
)
trainer.train()
Any guidance or example scripts would be greatly appreciated!
Thanks in advance for your time and help.
LoRA still works! you can just pass a LoraConfig to the GRPOTrainer and it'll use it with your model for the GRPO run.
trainer = vf.GRPOTrainer(
model=model,
processing_class=tokenizer,
env=vf_env,
args=training_args,
peft_config=LoraConfig(...)
)
Made a note to add a proper example soon, apologies.
LoRA still works! you can just pass a LoraConfig to the GRPOTrainer and it'll use it with your model for the GRPO run.
trainer = vf.GRPOTrainer( model=model, processing_class=tokenizer, env=vf_env, args=training_args, peft_config=LoraConfig(...) ) Made a note to add a proper example soon, apologies.
Thanks a lot for the quick reply and clarification!
Just to confirm — if I already have a base model after LoRA SFT, but I didn’t merge the LoRA adapter into the base model (i.e., I have both the base model and the separate LoRA adapter), how should I correctly pass the model and peft_config to GRPOTrainer for LoRA-based GRPO?
Should I: 1. First load the LoRA adapter into the model myself (as I currently do in model_utils.py), and still provide a peft_config for the GRPO LoRA? 2. Or do you recommend another clean setup for this situation?
Sorry if this is a naive question — I’m quite new to this area and trying to get my setup correct. I really appreciate your patience and your work on this repo!
Loading the first LoRA into the base model like you're doing is good! After that, it's no longer a PeftModel, just a normal model (with the weight diff applied). Alternatively, you can save the flattened model to disk, and then load it as pre-flattened. Either way, the trainer doesn't and shouldn't know about the old LoRA, it just sees a normal model.
See gsm8k.py for passing the LoRA config (same as snippet I shared) -- it's still being used there, I just changed the name.