Repository navigation
Closed
Description
I am trying to run GRPOTrainer with unsloth but it crashes. How to fix this?
unsloth 2025.2.4
unsloth 2025.2.3
transformers 4.47.1
torch 2.5.1
trl 0.14.0
This is the relevant code:
model, tokenizer = FastLanguageModel.from_pretrained(
model_name = base_model,
max_seq_length = 2048,
attn_implementation="flash_attention_2",
dtype = torch.bfloat16,
load_in_4bit = True,
)
training_args = GRPOConfig(
output_dir=output_dir,
learning_rate=5e-6,
adam_beta1 = 0.9,
adam_beta2 = 0.99,
weight_decay = 0.05,
bf16=True,
warmup_ratio = 0.1,
lr_scheduler_type='cosine',
logging_steps=1,
per_device_train_batch_size=1,
gradient_accumulation_steps=2,
num_generations=8,
max_prompt_length=256,
max_completion_length=786,
num_train_epochs=1,
save_steps=steps_num,
save_total_limit=2,
max_grad_norm=0.1,
report_to="none",
log_on_each_node=False,
)
model = FastLanguageModel.get_peft_model(
model,
r = 32, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj",],
lora_alpha = 32,
lora_dropout = 0, # Currently only supports dropout = 0
bias = "none", # Currently only supports bias = "none"
use_gradient_checkpointing = "unsloth",
random_state = 3407,
use_rslora = False, # We support rank stabilized LoRA
loftq_config = None, # And LoftQ
)
trainer = GRPOTrainer(
model=model,
processing_class=tokenizer,
reward_funcs=reward_func,
args=training_args,
train_dataset=dataset,
)
trainer.train()
This is the message when it crashes:
Traceback (most recent call last):
File "/home/user/ft/grpo.py", line 184, in <module>
trainer.train()
File "/home/user/anaconda3/lib/python3.12/site-packages/transformers/trainer.py", line 2164, in train
return inner_training_loop(
^^^^^^^^^^^^^^^^^^^^
File "<string>", line 382, in _fast_inner_training_loop
File "<string>", line 31, in _unsloth_training_step
File "/home/user/anaconda3/lib/python3.12/site-packages/trl/trainer/grpo_trainer.py", line 422, in compute_loss
prompt_completion_ids = unwrapped_model.generate(
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/anaconda3/lib/python3.12/site-packages/peft/peft_model.py", line 1838, in generate
outputs = self.base_model.generate(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/anaconda3/lib/python3.12/site-packages/torch/utils/_contextlib.py", line 116, in decorate_context
return func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "/home/user/anaconda3/lib/python3.12/site-packages/transformers/generation/utils.py", line 2252, in generate
result = self._sample(
^^^^^^^^^^^^^
File "/home/user/anaconda3/lib/python3.12/site-packages/transformers/generation/utils.py", line 3251, in _sample
outputs = self(**model_inputs, return_dict=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/anaconda3/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1736, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/anaconda3/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1747, in _call_impl
return forward_call(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/anaconda3/lib/python3.12/site-packages/unsloth/models/llama.py", line 1025, in _CausalLM_fast_forward
outputs = fast_forward_inference(
^^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/anaconda3/lib/python3.12/site-packages/unsloth/models/gemma2.py", line 397, in Gemma2Model_fast_forward_inference
seq_len = past_key_values[0][0].shape[-2]
~~~~~~~~~~~~~~~^^^
File "<string>", line 10, in __cache_utils_getitem__
RuntimeError: Unsloth: You must call `FastLanguageModel.for_inference(model)` before doing inference for Unsloth models.
Reacted by Batorskq
Metadata
Metadata
Assignees
Labels
No labels
Activity
danielhanchen commentedon Feb 6, 2025
It should work now! Please update Unsloth via
pip install --upgrade --force-reinstall --no-cache-dir unsloth_zoo unsloththen before your script, do:Eliorkalfon commentedon Feb 6, 2025
Im getting this error:
RuntimeError: Failed to import trl.trainer.alignprop_trainer because of the following error (look up to see its traceback): cannot import name 'DDPOStableDiffusionPipeline' from 'trl.models' ([/home/elior/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/trl/models/__init__.py](http://localhost:8888/home/elior/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/trl/models/__init__.py))Already tried to reinstall trl but still can't run it.
UmarIgan commentedon Feb 6, 2025
I got this error as well
amrrs commentedon Feb 6, 2025
I guess because of the same reason, even if we start the training, it shows strange generation?
amrrs commentedon Feb 6, 2025
Guys I got it
This works, not sure you guys installed
diffusersas wellymcki commentedon Feb 6, 2025
Thanks for the reply. I am trying to fine tune gemma-2-2b but it got this vllm error:
But after I get rid of "use_vllm=True", it seems to be running.
ymcki commentedon Feb 6, 2025
I find that if you manually change ~/anaconda3/lib/python3.12/site-packages/trl/trainer/alignprop_trainer.py from
from ..models import DDPOStableDiffusionPipeline
to
from ..models.modeling_sd_base import DDPOStableDiffusionPipeline
Then it can run.
ymcki commentedon Feb 7, 2025
Fixed myself. Forgot to add fast_inference=True to FastLanguageModel.from_pretained
However, it core dumped on me. Is this an OOM error?
danielhanchen commentedon Feb 7, 2025
@ymcki Could you try decreasing
gpu_memory_utilizationmaybe to 0.4danielhanchen commentedon Feb 7, 2025
Oh also Gemma doesn't work yet - I'll make it work later today! Currently only Llama, Mistral, Qwen, Phi type architectures work
ymcki commentedon Feb 7, 2025
What do you mean by "gemma doesn't work?" I get it running when I turn vllm off.
ymcki commentedon Feb 7, 2025
I can confirm that vllm works for llama-3.2-3b. It is expected to finish one epoch in 50hrs.
In contrast, gemma-2-2b without vllm is expected to finish in 175hrs.
kallewoof commentedon Feb 7, 2025
The correct fix is to
pip install diffusers.gmonair commentedon Feb 7, 2025
@danielhanchen I'm getting OOMs after training for ~120+ steps, any ideas on what might cause that?
My current workflow is to try and lower both
max_completion_lengthandgpu_memory_utilization, but I have to run it multiple times and it only OOMs after a while. I'm currently at 0.32 gpu_memory_utilization with 4096 max_completion_length on a 7b model and an A6000 (48gb).kallewoof commentedon Feb 7, 2025
@gmonair You have a varied size dataset, I assume? I bet your 120th sample is simply long enough to cause an OOM.
You can check the size by e.g. putting
at grpo_trainer.py in
_get_per_token_logps. (the 2nd entry is the token count, I believe)(It would be nice if the code did what e.g. qlora-pipe does, i.e. after shuffling the dataset, move the largest sample to the top so it OOM's immediately.)
9 remaining items
ymcki commentedon Feb 12, 2025
Does anyone getting positive rewards/soft_format_reward_func using the example code?
Mine always stuck at zero despite rewards/strict_format_reward_func getting positive values.
Isn't rewards/soft_format_reward_func less strict than rewards/strict_format_reward_func such that it should be positive when the latter is also positive?
I changed it to
It seems to work as I expect.
kallewoof commentedon Feb 12, 2025
Yep,
re.searchis correct.ymcki commentedon Feb 12, 2025
Anyone observed self-correction behavior while training? I found one case near the end of the second epoch while training Llama-3.1-8B. However, it self corrected the correct answer into a wrong answer. >.<
omercelik commentedon Feb 15, 2025
Hello, is there an update on Gemma? Does it work now? Is there a sample notebook for Gemma?
kallewoof commentedon Feb 17, 2025
BTW, I thought I was doing this, but it turns out the trainer will use
def _get_train_sampler(self)which ends up returning aRandomSampler(self.train_dataset), which will scramble your dataset, so my "place biggest sample first" approach was a NOP, until I sub-classed the GRPOTrainer withObvious caveat that you need to actually shuffle the dataset yourself if you use it.
x4080 commentedon Apr 3, 2025
Hi, is gemma 2 9b supported yet ? I got RuntimeError('Triton Error [CUDA]: an illegal memory access was encountered'), already tried using L40S (48gb) and load_in_4bit, still got that error is it OOM or problem with gemma 2 ?
ymcki commentedon Apr 3, 2025
I too upgraded to 2025.3.18 but it still doesn't support gemma 2 with vllm. :(
ymcki commentedon Apr 3, 2025
I can confirm that unsloth 2025.3.19 works with gemma 2 and 3 by turning off vllm. However, it crashes on both when vllm is on. Since unsloth is too slow to be useful without vllm, so I suppose I will keep this issue open.
x4080 commentedon Apr 3, 2025
@ymcki Thanks for your info, I was thinking that I was doing something wrong, is it because vllm cannot run inference for gemma ?
kaitorecca commentedon Apr 6, 2025
@x4080 @ymcki : same problem with Qwen 2.5 3B
RuntimeError: Can't pickle local object 'patch_vllm_compute_dtype..BitsAndBytesConfig'
vishnuthegeek commentedon Apr 30, 2025
I'm getting this error in nvidiaA100 gpu when trying to save lora weights:
below error comes in at step : model.save_lora("grpo_saved_lora")
AttributeError: 'PeftModelForCausalLM' object has no attribute 'save_lora'
Any clue guys?
rolandtannous commentedon Jun 30, 2025
@vishnuthegeek model.save_pretrained and tokenizer.save_pretrained
danielhanchen commentedon Jun 18, 2026
This should be fixed now - sorry on the delay - please update with
uv pip install --upgrade unsloth unsloth_zoo --force-reinstall --no-cache-dir- if it's not fixed yet, it'll be in the next pip / PyPI release - if it's still not working after that, please open another issue - appreciate it again!