Skip to content

Inconsistent Inference Results After Saving and Loading LoRA Model #1670

Closed

Description

@Xiaohan-Tian

I was following the official Google Colab notebook to train my reasoning LoRA model on Paperspace. I was able to run the notebook without any issues.

However, when trying to save the trained model, I encountered some unexpected behavior. I have attempted multiple methods to save the trained model/LoRA, but none of them produce the same chat response after loading (I'm using temperature = 0.0).

Additionally, if I save the LoRA using model.save_lora("grpo_saved_lora"), After restarting and kernel and reload the model, I get the exact same inference response whether I use lora_request = None or load it with model.load_lora("grpo_saved_lora").

Issue Details

I consistently use SYSTEM_PROMPT to construct the prompt, and my test question is:
"How many r's are in strawberry?"

Responses Right After Training

  • Without LoRA: <reasoning> To determine how many times the letter 'r' appears in the word "strawberry", I will go through the word character by character and count each occurrence of 'r'. </reasoning> <answer> The letter 'r' appears 3 times in the word "strawberry". </answer>
  • With LoRA: <reasoning>\nTo determine the number of \'r\'s in the word "strawberry," we need to count each occurrence of the letter \'r\' in the word. Let\'s examine the word character by character:\n\n1. s\n2. t\n3. r\n4. a\n5. w\n6. b\n7. y\n8. r\n9. r\n\nWe can see that the letter \'r\' appears twice in the word "strawberry."\n</reasoning>\n<answer>\n2\n</answer>

Responses After Saving and Reloading

Method 1: model.save_lora("grpo_saved_lora"), Restart Kernel, Load with model.load_lora("grpo_saved_lora")

  • With or Without LoRA: '<reasoning>\nTo determine how many times the letter \'r\' appears in the word "strawberry", we can go through the word character by character and count each occurrence of \'r\'. \n\n- The first character is \'s\', not \'r\'.\n- The second character is \'t\', not \'r\'.\n- The third character is \'r\', this is the first occurrence of \'r\'.\n- The fourth character is \'w\', not \'r\'.\n- The fifth character is \'a\', not \'r\'.\n- The sixth character is \'r\', this is the second occurrence of \'r\'.\n- The seventh character is \'r\', this is the third occurrence of \'r\'.\n- The eighth character is \'b\', not \'r\'.\n- The ninth character is \'b\', not \'r\'.\n- The tenth character is \'e\', not \'r\'.\n\nBy going through the word, we find that the letter \'r\' appears 3 times.\n</reasoning>\n<answer>\n3\n</answer>'

Method 2: model.save_pretrained_merged("qwen-2.5-3b-lora-251", tokenizer, save_method="lora"), Load with FastLanguageModel.from_pretrained(...)

  • Without LoRA: Same result as Method 1.
  • With LoRA: Error - 'Qwen2ForCausalLM' object has no attribute 'load_lora'.

Workaround

The only way I found to get consistent responses is to use the "Finetuning from Last Checkpoint" method:

  1. Load the model.
  2. Execute the same training code, but use trainer.train(resume_from_checkpoint=True). Ensure max_steps <= save_steps to stop training immediately.

By doing this, the inference response matches what I got during the initial training.


I'm unsure if this is a bug or if I'm missing something in the saving/loading process. Could you please advise?

Thanks!

Activity

  1. danielhanchen commented on Feb 12, 2025

    @danielhanchen
    Member

    Have you tried directly loading the LoRA ie FastLanguageModel.from_pretrained("qwen-2.5-3b-lora-251")

  2. Xiaohan-Tian commented on Feb 12, 2025

    @Xiaohan-Tian
    Author

    Yes, I tried that, and it produces the same result as in Method 1 when I pass lora_request = None to model.fast_generate():

    <reasoning>\nTo determine how many times the letter \'r\' appears in the word "strawberry", we can go through the word character by character and count each occurrence of \'r\'. \n\n- The first character is \'s\', not \'r\'.\n- The second character is \'t\', not \'r\'.\n- The third character is \'r\', this is the first occurrence of \'r\'.\n- The fourth character is \'w\', not \'r\'.\n- The fifth character is \'a\', not \'r\'.\n- The sixth character is \'r\', this is the second occurrence of \'r\'.\n- The seventh character is \'r\', this is the third occurrence of \'r\'.\n- The eighth character is \'b\', not \'r\'.\n- The ninth character is \'b\', not \'r\'.\n- The tenth character is \'e\', not \'r\'.\n\nBy going through the word, we find that the letter \'r\' appears 3 times.\n</reasoning>\n<answer>\n3\n</answer>
    

    However, if I try to load the LoRA with model.load_lora("grpo_saved_lora"), I get the following error:
    AttributeError: 'Qwen2ForCausalLM' object has no attribute 'load_lora'.

    Here is the code I'm using to load the model:

    model, tokenizer = FastLanguageModel.from_pretrained(
        model_name = "qwen-2.5-3b-lora-251",
        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.5, # Reduce if out of memory
    )

    And here is the code I'm using to perform the inference:

    output = model.fast_generate(
        [text],
        sampling_params = sampling_params,
        lora_request = None,   # `model.load_lora("grpo_saved_lora")` will throw error
    )[0].outputs[0].text

    I'm not sure if I'm missing something or if there's an issue with the loading process. Any guidance would be appreciated.

  3. BY571 commented on Feb 13, 2025

    @BY571

    @Xiaohan-Tian Hey, did you figure out how to load the lora adapter?

  4. Xiaohan-Tian commented on Feb 14, 2025

    @Xiaohan-Tian
    Author

    I'm able to load the model, but the inference results I'm getting now aren't consistent with what I saw immediately after training (w/LoRA). I'll investigate further tomorrow.

  5. Erland366 commented on Feb 15, 2025

    @Erland366
    Collaborator

    I think load_lora has already been fixed. I did a fresh install and now it's working.

  6. saadi297 commented on Feb 17, 2025

    @saadi297

    @Xiaohan-Tian I am facing the same issue. Did you find the solution?

  7. fullstackwebdev commented on Feb 18, 2025

    @fullstackwebdev

    I am getting this error when I try to load a LoRA

    Error generating response: 'Qwen2ForCausalLM' object has no attribute 'load_lora'
    

    with this script and my LoRA
    https://gist.github.com/fullstackwebdev/c5af23b036cc30a71f8c7331a30bbf1c

  8. janpf commented on Feb 20, 2025

    @janpf

    Hey all,
    I managed to make it reproducible. The only way I managed to load the adapter is via the trained hack described by @Xiaohan-Tian.

    I trained using GRPO and a random reward with an absurd LR, in order to break the model and make the effect of loading the adapter more clearly visible.
    Please see attached notebook for more details :) (i had to rename it to .txt, as github doesn't allow ipynb, sorry.)

    try_to_load_model.ipynb

  9. lucky-bai commented on Feb 21, 2025

    @lucky-bai

    Hi @Xiaohan-Tian, I'm attempting to follow your suggestion to load the LoRA adapter from a trained checkpoint using your workaround of doing trainer.train(resume_from_checkpoint=True) with 0 steps:

    model, tokenizer = FastLanguageModel.from_pretrained(
        model_name="./my-trained-model/checkpoint-6000",
        max_seq_length=512,
        load_in_4bit=True,
        fast_inference=True,
        max_lora_rank=32,
        gpu_memory_utilization=0.6,
    )
    FastLanguageModel.for_inference(model)
    
    class DummyDataset:
        def __len__(self):
            return 0
        def __getitem__(self, idx):
            return {}
    
    dummy_dataset = DummyDataset()
    trainer = GRPOTrainer(
        model=model,
        output_dir="./asdfadsf",
        train_dataset=dummy_dataset,
        processing_class=tokenizer,
        reward_funcs=[],
        args=GRPOConfig(max_steps=0),
    )
    trainer.train(resume_from_checkpoint=True)
    

    When I do this, the model produces output that's different from the base model but is not the trained model either (using version unsloth==2025.2.15). Not sure what's happening - perhaps it is randomly initializing instead. Can you share how you're loading from checkpoint with this method if it's working correctly for you?

  10. janpf commented on Feb 21, 2025

    @janpf

    not sure if it helps, but i also tried this in above notebook and it reproduces the adapter outputs exactly :)

  11. wooozihui commented on Feb 22, 2025

    @wooozihui

    Same issue, and when I want to solve the problem

    Error generating response: 'Qwen2ForCausalLM' object has no attribute 'load_lora'
    

    by using:

    from unsloth_zoo.vllm_utils import  load_lora 
    ....
    output = model.generate(
            text,
            sampling_params=sampling_params,
            lora_request = load_lora(model,"my_lora_path")
        )[0].outputs[0].text
    

    report a new error:

    AttributeError: 'Qwen2ForCausalLM' object has no attribute 'peft_config'
    
  12. wooozihui commented on Feb 22, 2025

    @wooozihui

    not sure if it helps, but i also tried this in above notebook and it reproduces the adapter outputs exactly :)

    Hi, can you share your versions of transformers and vllm?

  13. janpf commented on Feb 22, 2025

    @janpf

    not sure if it helps, but i also tried this in above notebook and it reproduces the adapter outputs exactly :)

    Hi, can you share your versions of transformers and vllm?

    sure, it's all in the notebook in the first cell:

    vllm==0.7.2
    transformers==4.48.3
    
  14. wooozihui commented on Feb 22, 2025

    @wooozihui

    This code works for me:

    from transformers import AutoModelForCausalLM, AutoTokenizer
    from peft import PeftModel
    import torch
    import argparse
    
    device = "cuda" if torch.cuda.is_available() else "cpu"
    
    # Load model and tokenizer
    base_model = AutoModelForCausalLM.from_pretrained(
        "Qwen/Qwen2.5-7B-Instruct",
        device_map=device,
        trust_remote_code=True,
        torch_dtype=torch.bfloat16
    )
    
    model = PeftModel.from_pretrained(
        base_model,
        "my_lora",
        device_map=device,
        trust_remote_code=True,
        torch_dtype=torch.bfloat16
    )
    
    tokenizer = AutoTokenizer.from_pretrained(
        "Qwen/Qwen2.5-7B-Instruct",
        trust_remote_code=True,
    )
    
    def generate_response(prompt: str, temperature: float = 0.1) -> str:
        """Function to generate response"""
        # Prepare input
        text = tokenizer.apply_chat_template([
            {"role": "user", "content": prompt},
        ], tokenize=False, add_generation_prompt=True)
        inputs = tokenizer(text, return_tensors="pt").to(model.device)
        
        # Generate response
        outputs = model.generate(
            **inputs,
            max_new_tokens=1024,
            temperature=temperature,
            top_p=0.95,
            pad_token_id=tokenizer.pad_token_id,
        )
        response = tokenizer.decode(outputs[0], skip_special_tokens=True)
        
        return response 
    
    def merge_and_save_lora(output_dir: str):
        """Merge LoRA weights and save model"""
        print("Starting to merge LoRA weights...")
        # Merge LoRA weights into base model
        merged_model = model.merge_and_unload()
        
        print(f"Saving merged model to: {output_dir}")
        # Save merged model
        merged_model.save_pretrained(
            output_dir,
            safe_serialization=True
        )
        # Save tokenizer
        tokenizer.save_pretrained(output_dir)
        print("Model saving completed!")
    
    if __name__ == "__main__":
        # Add model export functionality
        parser = argparse.ArgumentParser()
        parser.add_argument("--export_model", action="store_true", help="Whether to export the merged model")
        parser.add_argument("--output_dir", type=str, default="merged_model", help="Path to save the exported model")
        args = parser.parse_args()
    
        if args.export_model:
            merge_and_save_lora(args.output_dir)
        else:
            test_prompt = '''Hi, how are you?'''
            response = generate_response(test_prompt)
            print(f"Question: {test_prompt}")
            print(f"Answer: {response}")
            #Usage for merge lora: python infer_with_lora.py --export_model --output_dir ./merged_model_path
    
  15. SpaceHunterInf commented on Mar 14, 2025

    @SpaceHunterInf

    I have the same issue, I think this should be an urgent bug to fix.

  16. danielhanchen commented on Mar 18, 2025

    @danielhanchen
    Member

    Apologies on the issue - 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

  17. 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

  18. added
    fixed - pending confirmation
    on Mar 18, 2025
  19. canrertugrul commented on Mar 18, 2025

    @canrertugrul

    This fix has not addressed the issue.

  20. shimmyshimmer commented on Mar 19, 2025

    @shimmyshimmer
    Member

    This fix has not addressed the issue.

    do you know if this issue is for grpo specifically or also normal SFT?

  21. canrertugrul commented on Mar 19, 2025

    @canrertugrul

    This fix has not addressed the issue.

    do you know if this issue is for grpo specifically or also normal SFT?

    I am having this issue with normal SFT. Haven't tried GRPO.

  22. canrertugrul commented on Mar 19, 2025

    @canrertugrul

    For reference, I am expanding the model's vocabulary with a few new tokens. Perhaps that might be related?

  23. whiskyboy commented on Mar 22, 2025

    @whiskyboy

    Facing the same issue.

    @shimmyshimmer Upgrading unsloth to 2025.3.18 and passing load_tensors = False to model.load_lora(...) did not work in my code. It still reported the following error:
    AttributeError: 'Qwen2ForCausalLM' object has no attribute 'load_lora

    My current workaround is to get a PEFT model as in training script, then execute model.load_lora(...) explicitly, finally call generate:

    model = FastLanguageModel.get_peft_model(...)
    model.load_lora(...)
    
    model.fast_generate(
        prompts,
        sampling_params = sampling_params,
        lora_request = model.load_lora(...),
    )
    

    No idea why the above code works.

  24. canrertugrul commented on Mar 22, 2025

    @canrertugrul

    The only workaround I’ve found so far is to upload the adapters to Hugging Face and load them before running inference.

  25. yuimo commented on Mar 24, 2025

    @yuimo

    Facing the same issue.

    @shimmyshimmer Upgrading unsloth to 2025.3.18 and passing load_tensors = False to model.load_lora(...) did not work in my code. It still reported the following error: AttributeError: 'Qwen2ForCausalLM' object has no attribute 'load_lora

    My current workaround is to get a PEFT model as in training script, then execute model.load_lora(...) explicitly, finally call generate:

    model = FastLanguageModel.get_peft_model(...)
    model.load_lora(...)
    
    model.fast_generate(
        prompts,
        sampling_params = sampling_params,
        lora_request = model.load_lora(...),
    )
    

    No idea why the above code works.

    after installing the latest version of unsloth,and it works for me.

  26. rolandtannous commented on Jun 6, 2025

    @rolandtannous
    Contributor

    @BY571 @FloLey @Joinn99 @K1nght @Mtrya @SpaceHunterInf @Xiaohan-Tian @Yangt524 @canrertugrul @fullstackwebdev @janpf @juli2807 @kjm981995 @liuchengyuan123 @lucky-bai @maopian2333 @matthewchung74 @mingqing431 @mominabbass @saadi297 @vasqu @whiskyboy @wofeishenling @wooozihui @yuimo @yuiseki

    Please use FastVisionModel.from_pretrained or FastLanguageModel.from_pretrained to load your lora model directly.
    If you want to use load_adapter, follow my comment here: #2411 (comment)

    As for saving and merging:

    A fix has now been merged into pypi for both vision and language models and extensively tested.
    reference:
    unslothai/unsloth-zoo#135
    unslothai/unsloth-zoo#158
    #2673
    Merging and saving should work now.

    Best Practice is save to 16bits (which is the default operation if you do not specify anything), and load in 4 bits if you have to.
    For production systems, you might wanna consider post training quantization methods with calibration. These take longer but can also be more reliable.
    Saving and merging to 4bits might degrade performance of the model.

    To access this recent fix, and if you're running this in a local python environment, please make sure to upgrade your python environment using

    pip install --upgrade unsloth_zoo
    pip install --upgrade unsloth
    

    If you're in colab, the notebooks install cell will also be updated shortly but should be something like

    %%capture
    import os
    if "COLAB_" not in "".join(os.environ.keys()):
        !pip install unsloth
    else:
        # Do this only in Colab notebooks! Otherwise use pip install unsloth
        !pip install --no-deps bitsandbytes accelerate xformers==0.0.29.post3 peft trl triton transformers cut_cross_entropy unsloth_zoo
        !pip install sentencepiece protobuf "datasets>=3.4.1" huggingface_hub hf_transfer
        !pip install --no-deps unsloth
    

    as we're no longer pinning transformers or trl.

    Also note that whenever you need to merge while saving or while pushing to hub, make sure to use

    save_pretrained_merged()
    

    and

    push_to_hub_merged()
    

    If you are not merging at all, use

    save_pretrained
    

    and

    push_to_hub
    

    instead.

    I'll close this for now. Feel free to comment if you face any problems.
    Happy finetuning.

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