Skip to content

GRPO merging Adapters+ re-training not working #1877

Closed

Description

@Cgrandjean

Hello,
I got those version for libraries:

bitsandbytes==0.45.3
deepspeed==0.16.4
transformers==4.49.0
unsloth @ git+https://github.com/unslothai/unsloth.git@5d0ee525c1b6a3522f64ad9722249ae34b584555
unsloth_zoo @ git+https://github.com/unslothai/unsloth-zoo.git@f1f367b871f687dfd8d1c2a1c483f3b6b8142ccb
vllm==0.7.2

I recently trained a model with GRPO using Lora adapter:

model = FastLanguageModel.get_peft_model(
    model,
    r = lora_rank, # 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 = lora_rank,
    use_gradient_checkpointing = "unsloth", # Enable long context finetuning
    random_state = 3407,
)

Training went well but i noticed two problems after it.

However when i reload my model :

max_seq_length = 3684 # Can increase for longer reasoning traces
lora_rank = 16 # Larger rank = smarter, but slower
model, tokenizer = FastLanguageModel.from_pretrained(
    model_name = './outputs/Model_GRPO_14B_Qwen_Coder_GR_2025_02_25_08_47/checkpoint-700',
    max_seq_length = max_seq_length,
    load_in_4bit = True, # False for LoRA 16bit
    fast_inference = True, # Enable vLLM fast inference
    max_lora_rank = lora_rank,
    gpu_memory_utilization = 0.67, # Reduce if out of memory
)

(exact same parameter as during training)

  1. Model merging does not work for 4 bits but works for 16 bits:
model.save_pretrained_merged(save_directory='./outputs/Model_GRPO_14B_Qwen_Coder_GR_2025_02_25_08_47/merged_700_steps',tokenizer=tokenizer,save_method='merged_16bit')
Unsloth: Merging 4bit and LoRA weights to 16bit...
Unsloth: Will use up to 32.82 out of 60.46 RAM for saving.
Unsloth: Saving model... This might take 5 minutes ...
  6%|▋         | 3/48 [00:00<00:07,  5.74it/s]
We will save to Disk and not RAM now.
100%|██████████| 48/48 [01:01<00:00,  1.27s/it]
Unsloth: Saving tokenizer... Done.




model.save_pretrained_merged(save_directory='./outputs/Model_GRPO_14B_Qwen_Coder_GR_2025_02_25_08_47/merged_700_steps_4bits',tokenizer=tokenizer,save_method='merged_4bit_forced')
Unsloth: Merging 4bit and LoRA weights to 4bit...
This might take 5 minutes...
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[11], line 1
----> 1 model.save_pretrained_merged(save_directory='./outputs/Model_GRPO_14B_Qwen_Coder_GR_2025_02_25_08_47/merged_700_steps_4bits',tokenizer=tokenizer,save_method='merged_4bit_forced',maximum_memory_usage=0.95)

File ~/anaconda3/envs/python3/lib/python3.10/site-packages/unsloth/save.py:1311, in unsloth_save_pretrained_merged(self, save_directory, tokenizer, save_method, push_to_hub, token, is_main_process, state_dict, save_function, max_shard_size, safe_serialization, variant, save_peft_format, tags, temporary_location, maximum_memory_usage)
   1309 arguments["model"] = self
   1310 del arguments["self"]
-> 1311 unsloth_save_model(**arguments)
   1312 for _ in range(3):
   1313     gc.collect()

File ~/anaconda3/envs/python3/lib/python3.10/site-packages/torch/utils/_contextlib.py:116, in context_decorator.<locals>.decorate_context(*args, **kwargs)
    113 @functools.wraps(func)
    114 def decorate_context(*args, **kwargs):
    115     with ctx_factory():
--> 116         return func(*args, **kwargs)

File ~/anaconda3/envs/python3/lib/python3.10/site-packages/unsloth/save.py:296, in unsloth_save_model(model, tokenizer, save_directory, save_method, push_to_hub, token, is_main_process, state_dict, save_function, max_shard_size, safe_serialization, variant, save_peft_format, use_temp_dir, commit_message, private, create_pr, revision, commit_description, tags, temporary_location, maximum_memory_usage)
    294 # Counteract no LoRA adapters!
    295 if hasattr(model, "merge_and_unload"):
--> 296     model = model.merge_and_unload()
    297 pass
    298 print("Done.")

File ~/anaconda3/envs/python3/lib/python3.10/site-packages/peft/tuners/lora/model.py:892, in LoraModel.merge_and_unload(self, progressbar, safe_merge, adapter_names)
    864 def merge_and_unload(
    865     self, progressbar: bool = False, safe_merge: bool = False, adapter_names: Optional[list[str]] = None
    866 ) -> torch.nn.Module:
    867     r"""
    868     This method merges the LoRa layers into the base model. This is needed if someone wants to use the base model
    869     as a standalone model.
   (...)
    890     ```
    891     """
--> 892     return self._unload_and_optionally_merge(
    893         progressbar=progressbar, safe_merge=safe_merge, adapter_names=adapter_names
    894     )

File ~/anaconda3/envs/python3/lib/python3.10/site-packages/peft/tuners/lora/model.py:514, in LoraModel._unload_and_optionally_merge(self, merge, progressbar, safe_merge, adapter_names)
    512 if hasattr(target, "base_layer"):
    513     if merge:
--> 514         target.merge(safe_merge=safe_merge, adapter_names=adapter_names)
    515     self._replace_module(parent, target_name, target.get_base_layer(), target)
    516 elif isinstance(target, ModulesToSaveWrapper):
    517     # save any additional trainable modules part of `modules_to_save`

File ~/anaconda3/envs/python3/lib/python3.10/site-packages/peft/tuners/lora/layer.py:514, in Linear.merge(self, safe_merge, adapter_names)
    512 delta_weight = self.get_delta_weight(active_adapter)
    513 if not self.use_dora[active_adapter]:
--> 514     base_layer.weight.data += delta_weight
    515 else:
    516     # handle dora
    517     # since delta_weight already includes scaling, set it to 1 here
    518     weight_norm = (
    519         self.lora_magnitude_vector[active_adapter]
    520         .get_weight_norm(
   (...)
    523         .detach()
    524     )

RuntimeError: The size of tensor a (13107200) must match the size of tensor b (5120) at non-singleton dimension 0
  1. I cant retrain my model by loading the adapter i created in first place:
trainer.train()
==((====))==  Unsloth - 2x faster free finetuning | Num GPUs = 1
   \\   /|    Num examples = 1,128 | Num Epochs = 2
O^O/ \_/ \    Batch size per device = 6 | Gradient Accumulation steps = 4
\        /    Total batch size = 24 | Total steps = 500
 "-____-"     Number of trainable parameters = 68,812,800
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
File ~/anaconda3/envs/python3/lib/python3.10/site-packages/peft/peft_model.py:824, in PeftModel.__getattr__(self, name)
    823 try:
--> 824     return super().__getattr__(name)  # defer to nn.Module's logic
    825 except AttributeError:

File ~/anaconda3/envs/python3/lib/python3.10/site-packages/torch/nn/modules/module.py:1931, in Module.__getattr__(self, name)
   1930         return modules[name]
-> 1931 raise AttributeError(
   1932     f"'{type(self).__name__}' object has no attribute '{name}'"
   1933 )

AttributeError: 'PeftModelForCausalLM' object has no attribute 'load_lora'

During handling of the above exception, another exception occurred:

AttributeError                            Traceback (most recent call last)
File ~/anaconda3/envs/python3/lib/python3.10/site-packages/peft/tuners/lora/model.py:371, in LoraModel.__getattr__(self, name)
    370 try:
--> 371     return super().__getattr__(name)  # defer to nn.Module's logic
    372 except AttributeError:

File ~/anaconda3/envs/python3/lib/python3.10/site-packages/torch/nn/modules/module.py:1931, in Module.__getattr__(self, name)
   1930         return modules[name]
-> 1931 raise AttributeError(
   1932     f"'{type(self).__name__}' object has no attribute '{name}'"
   1933 )

AttributeError: 'LoraModel' object has no attribute 'load_lora'

During handling of the above exception, another exception occurred:

AttributeError                            Traceback (most recent call last)
Cell In[19], line 1
----> 1 trainer.train()

File ~/anaconda3/envs/python3/lib/python3.10/site-packages/transformers/trainer.py:2241, in Trainer.train(self, resume_from_checkpoint, trial, ignore_keys_for_eval, **kwargs)
   2239         hf_hub_utils.enable_progress_bars()
   2240 else:
-> 2241     return inner_training_loop(
   2242         args=args,
   2243         resume_from_checkpoint=resume_from_checkpoint,
   2244         trial=trial,
   2245         ignore_keys_for_eval=ignore_keys_for_eval,
   2246     )

File <string>:329, in _fast_inner_training_loop(self, batch_size, args, resume_from_checkpoint, trial, ignore_keys_for_eval)

File <string>:25, in _unsloth_training_step(self, model, inputs, num_items_in_batch)

File ~/SageMaker/GR_GRPO/unsloth_compiled_cache/UnslothGRPOTrainer.py:902, in _UnslothGRPOTrainer._prepare_inputs(self, inputs)
    900 all_prompts_text = gather_object(prompts_text)
    901 if self.accelerator.is_main_process:
--> 902     outputs = self.llm.generate(all_prompts_text, sampling_params=self.sampling_params, use_tqdm=False, lora_request = self.model.load_lora('grpo_trainer_lora_model', load_tensors = True))
    903     completion_ids = [out.token_ids for completions in outputs for out in completions.outputs]
    904 else:

File ~/anaconda3/envs/python3/lib/python3.10/site-packages/peft/peft_model.py:828, in PeftModel.__getattr__(self, name)
    826 if name == "base_model":  # see #1892: prevent infinite recursion if class is not initialized
    827     raise
--> 828 return getattr(self.base_model, name)

File ~/anaconda3/envs/python3/lib/python3.10/site-packages/peft/tuners/lora/model.py:375, in LoraModel.__getattr__(self, name)
    373 if name == "model":  # see #1892: prevent infinite recursion if class is not initialized
    374     raise
--> 375 return getattr(self.model, name)

File ~/anaconda3/envs/python3/lib/python3.10/site-packages/torch/nn/modules/module.py:1931, in Module.__getattr__(self, name)
   1929     if name in modules:
   1930         return modules[name]
-> 1931 raise AttributeError(
   1932     f"'{type(self).__name__}' object has no attribute '{name}'"
   1933 )

AttributeError: 'Qwen2ForCausalLM' object has no attribute 'load_lora'

Did someone experience this?

Activity

  1. changed the title [-]GRPO merging Adapters[/-] [+]GRPO merging Adapters+ re-training not working[/+] on Mar 3, 2025
  2. mariiapronesti01 commented on Mar 3, 2025

    @mariiapronesti01

    I am facing the same problem. I have a finetuned Llama 3.2 3B model, which was finetuned using supervised finetuning with LoRA (no GRPO).
    Now I'm trying to enanche the performance of this model by applying GRPO and I got the same error (AttributeError: 'LlamaForCausalLM' object has no attribute 'load_lora')

  3. ashishp166 commented on Mar 4, 2025

    @ashishp166

    Facing same problems as above 2.

  4. Cgrandjean commented on Mar 5, 2025

    @Cgrandjean
    Author

    Did anyone got problem with merging adapters ? Because i got that on different machine, additionally the 16 Bit merged model does not work as expected neither... So must be something on my libs but cant find what

  5. w601sxs commented on Mar 5, 2025

    @w601sxs

    Same as above:

    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    File [/opt/conda/lib/python3.11/site-packages/peft/peft_model.py:824](https://ja4mp3pvyldhlsj.studio.us-east-1.sagemaker.aws/opt/conda/lib/python3.11/site-packages/peft/peft_model.py#line=823), in PeftModel.__getattr__(self, name)
        823 try:
    --> 824     return super().__getattr__(name)  # defer to nn.Module's logic
        825 except AttributeError:
    
    File [/opt/conda/lib/python3.11/site-packages/torch/nn/modules/module.py:1931](https://ja4mp3pvyldhlsj.studio.us-east-1.sagemaker.aws/opt/conda/lib/python3.11/site-packages/torch/nn/modules/module.py#line=1930), in Module.__getattr__(self, name)
       1930         return modules[name]
    -> 1931 raise AttributeError(
       1932     f"'{type(self).__name__}' object has no attribute '{name}'"
       1933 )
    
    AttributeError: 'PeftModelForCausalLM' object has no attribute 'load_lora'
    
    During handling of the above exception, another exception occurred:
    
    AttributeError                            Traceback (most recent call last)
    File [/opt/conda/lib/python3.11/site-packages/peft/tuners/lora/model.py:371](https://ja4mp3pvyldhlsj.studio.us-east-1.sagemaker.aws/opt/conda/lib/python3.11/site-packages/peft/tuners/lora/model.py#line=370), in LoraModel.__getattr__(self, name)
        370 try:
    --> 371     return super().__getattr__(name)  # defer to nn.Module's logic
        372 except AttributeError:
    
    File [/opt/conda/lib/python3.11/site-packages/torch/nn/modules/module.py:1931](https://ja4mp3pvyldhlsj.studio.us-east-1.sagemaker.aws/opt/conda/lib/python3.11/site-packages/torch/nn/modules/module.py#line=1930), in Module.__getattr__(self, name)
       1930         return modules[name]
    -> 1931 raise AttributeError(
       1932     f"'{type(self).__name__}' object has no attribute '{name}'"
       1933 )
    
    AttributeError: 'LoraModel' object has no attribute 'load_lora'
    
    During handling of the above exception, another exception occurred:
    
    AttributeError                            Traceback (most recent call last)
    Cell In[8], line 14
          1 trainer = GRPOTrainer(
          2     model = model,
          3     processing_class = tokenizer,
       (...)
         12     train_dataset = dataset,
         13 )
    ---> 14 trainer.train(resume_from_checkpoint = True)
    
    File [/opt/conda/lib/python3.11/site-packages/transformers/trainer.py:2171](https://ja4mp3pvyldhlsj.studio.us-east-1.sagemaker.aws/opt/conda/lib/python3.11/site-packages/transformers/trainer.py#line=2170), in Trainer.train(self, resume_from_checkpoint, trial, ignore_keys_for_eval, **kwargs)
       2169         hf_hub_utils.enable_progress_bars()
       2170 else:
    -> 2171     return inner_training_loop(
       2172         args=args,
       2173         resume_from_checkpoint=resume_from_checkpoint,
       2174         trial=trial,
       2175         ignore_keys_for_eval=ignore_keys_for_eval,
       2176     )
    
    File <string>:382, in _fast_inner_training_loop(self, batch_size, args, resume_from_checkpoint, trial, ignore_keys_for_eval)
    
    File <string>:25, in _unsloth_training_step(self, model, inputs, num_items_in_batch)
    
    File [/mnt/custom-file-systems/efs/fs-08496486d420aa592_fsap-03196f50ed69e16b6/unsloth_compiled_cache/UnslothGRPOTrainer.py:902](https://ja4mp3pvyldhlsj.studio.us-east-1.sagemaker.aws/mnt/custom-file-systems/efs/fs-08496486d420aa592_fsap-03196f50ed69e16b6/unsloth_compiled_cache/UnslothGRPOTrainer.py#line=901), in _UnslothGRPOTrainer._prepare_inputs(self, inputs)
        900 all_prompts_text = gather_object(prompts_text)
        901 if self.accelerator.is_main_process:
    --> 902     outputs = self.llm.generate(all_prompts_text, sampling_params=self.sampling_params, use_tqdm=False, lora_request = self.model.load_lora('grpo_trainer_lora_model', load_tensors = True))
        903     completion_ids = [out.token_ids for completions in outputs for out in completions.outputs]
        904 else:
    
    File [/opt/conda/lib/python3.11/site-packages/peft/peft_model.py:828](https://ja4mp3pvyldhlsj.studio.us-east-1.sagemaker.aws/opt/conda/lib/python3.11/site-packages/peft/peft_model.py#line=827), in PeftModel.__getattr__(self, name)
        826 if name == "base_model":  # see #1892: prevent infinite recursion if class is not initialized
        827     raise
    --> 828 return getattr(self.base_model, name)
    
    File [/opt/conda/lib/python3.11/site-packages/peft/tuners/lora/model.py:375](https://ja4mp3pvyldhlsj.studio.us-east-1.sagemaker.aws/opt/conda/lib/python3.11/site-packages/peft/tuners/lora/model.py#line=374), in LoraModel.__getattr__(self, name)
        373 if name == "model":  # see #1892: prevent infinite recursion if class is not initialized
        374     raise
    --> 375 return getattr(self.model, name)
    
    File [/opt/conda/lib/python3.11/site-packages/torch/nn/modules/module.py:1931](https://ja4mp3pvyldhlsj.studio.us-east-1.sagemaker.aws/opt/conda/lib/python3.11/site-packages/torch/nn/modules/module.py#line=1930), in Module.__getattr__(self, name)
       1929     if name in modules:
       1930         return modules[name]
    -> 1931 raise AttributeError(
       1932     f"'{type(self).__name__}' object has no attribute '{name}'"
       1933 )
    
    AttributeError: 'LlamaForCausalLM' object has no attribute 'load_lora'
    
    

    I have the Lora saved, but I need to continue training with slightly different settings. What is the best way to do this?

    I tried:

    1. merge and unload - does not work
    2. load the lora model directly and use for training (see above does not work)
    3. patch peft method - does not work either
    4. wrapped in get_peft_model gives TypeError: Unsloth: Your model already has LoRA adapters. Your new parameters are different.
  6. Cgrandjean commented on Mar 6, 2025

    @Cgrandjean
    Author

    @w601sxs what you can try is merge and saving with save_pretrained_merged in 16 bits , reload the model and create a new adapter . To be honest i'm not sure the merge works properly but could work.

    On another hand i checked the notebook example for grpo i trained it a bit and tried to merge and unload , does not work there neither. I got same error, so i m not sure if its due to my configuration or something else .

  7. daleseepersadapps commented on Mar 7, 2025

    @daleseepersadapps

    I am trying to do the same thing. It would be great of someone solved this issue.

  8. DiTo97 commented on Mar 14, 2025

    @DiTo97

    @danielhanchen u have any official guidelines or proven experiments running multi-stage-training? I have had similar issues to the OP multiple times, and have had to revert back not to be using the library when SFT and reinforcement learning were both needed.

    This is especially interesting now that you are opening up to everything-tuning and planning to support distributed training in the near future.

  9. shimmyshimmer commented on Mar 18, 2025

    @shimmyshimmer
    Member

    So we investigated the issue and were able to reproduce the issue (results after merging in 16-bit are same as before training).

    However, we checked that _merge_lora is working as expected and that the base_layer weights before / after merging are indeed different by roughly the magnitude of B @ A (since the scale factor is 1 per the default Qwen-GRPO notebook).

    We will need to conduct a deeper investigation into this, thank you.

    Do you guys know when this issue started firstly occuring? Seems to be 2 weeks ago?

  10. danielhanchen commented on Mar 18, 2025

    @danielhanchen
    Member

    Apologies on the issue everyone again - I might, but not 100% sure might have fixed the issue - if you guys still have the trained LoRA on your disk, could you try model.load_lora( "directory", load_tensors = False) ie use load_tensors = False as the extra argument

  11. shimmyshimmer commented on Mar 18, 2025

    @shimmyshimmer
    Member

    Hi guys we have likely resolved the issue. Please update unsloth and let us know if it works! Thank you

  12. added
    fixed - pending confirmation
    on Mar 18, 2025
  13. jiemocoder commented on Mar 23, 2025

    @jiemocoder

    Hi guys we have likely resolved the issue. Please update unsloth and let us know if it works! Thank you

    Thank you, could you explain the GRPO from Last Checkpoint method again? I need to use different datasets for training.

  14. daegonYu commented on Apr 14, 2025

    @daegonYu

    Is this issue resolved?

    I am also training LoRA using the unsloth/gemma2-9b-it model, and when I resume training, I find that the log is not continuing the checkpoint reward.

    Image

  15. Cgrandjean commented on May 5, 2025

    @Cgrandjean
    Author

    Sorry guys for disappearing,
    I solved it reloading the adapter without vllm and then merging worked just fine . I think with last versions must be fixed anyways.
    Thanks for the support!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    fixed - pending confirmation

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions