Skip to content

Does unsloth support loading existing lora weights when finetuning? #59

Closed

Description

@IvoryTower800

This is really an amazing project. I really speed up my model finetuning with 2x faster.

I'm wondering whether can I add an existing lora adapter to the model, so as to continue training the lora on another dataset.
currently, it seems that I have to merge my base model and lora weights in advance if using unsloth.
Therefore, I have to update and save my newly merged model each time before further training.

so, will this project support loading existing lora weights in the near futher?

Thank you!

Activity

  1. danielhanchen commented on Dec 30, 2023

    @danielhanchen
    Member

    Thanks @IvoryTower800 for the encouragement! Appreciate it! I'll see what I can do :) Do you have an approx script oh what you would normally do?

  2. IvoryTower800 commented on Dec 30, 2023

    @IvoryTower800
    Author

    @danielhanchen Thanks for your reply. I actually use LLaMA-Factory's script to do finetune. the full script is as below.

    The problem is that if I remove --use_unsloth. the lora adapter can be loaded correctly. if I add --use_unsloth argument. during the preparing process, the log shows that "unsloth does not support loading adapters", thus ignorning loading my specified adapter weights.

    So I have to first merge the model before further training and passing the merged model to --model_name_or_path. This is pretty inconvenient for me to save every newer version of merged model on a cloud drive.

    CUDA_VISIBLE_DEVICES=0 deepspeed --num_gpus=1 /root/LLaMA-Factory/src/train_bash.py
    --model_name_or_path /root/model/base_model \ # an tinyllama model
    --adapter_name_or_path /root/model/lora_model \ # an lora model trained previously through SFT stage
    --dataset_dir /root/dataset/
    --output_dir /root/output/story_lora \ # checkpoints of lora adapters
    --use_unsloth \ # specify this to activate unsloth
    --dataset dpo_data
    --stage dpo
    --do_train True
    --finetuning_type lora
    --quantization_bit 4
    --template llama2_zh
    --cutoff_len 16384
    --learning_rate 1e-4
    --preprocessing_num_workers 8
    --num_train_epochs 1.0
    --max_samples 1000000
    --per_device_train_batch_size 1
    --gradient_accumulation_steps 32
    --lr_scheduler_type cosine
    --max_grad_norm 1.0
    --logging_steps 1
    --save_steps 100
    --warmup_steps 0
    --neftune_noise_alpha 5
    --lora_rank 128
    --lora_alpha 256
    --lora_dropout 0
    --lora_target all
    --fp16 True
    --plot_loss True
    --overwrite_output_dir True
    --deepspeed ds_config_zero2.json

    Again, I'm totally impressed by the speed acceleration and vram saving of unsloth especially on my V100 machine which does not support flash-attn2 these days. But I'm really confused by above mentioned issue.
    Thank you.

  3. danielhanchen commented on Dec 30, 2023

    @danielhanchen
    Member

    Ok cool hmm I'll see what I can do for loading pretrained PEFT models. Oh ye V100s, Tesla T4s and RTX 20xx :)

  4. neph1 commented on Jan 22, 2024

    @neph1
    Contributor

    You can load a lora as an adapter like this:

    from peft import LoraConfig

    lora_config = LoraConfig(
    target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
    "gate_proj", "up_proj", "down_proj",],
    init_lora_weights=False
    )

    model.add_adapter(lora_config, adapter_name="lora_path")

    You then also skip the model = FastLanguageModel.get_peft_model( call

    I wasn't able to merge them to save VRAM, though.

  5. danielhanchen commented on Jan 22, 2024

    @danielhanchen
    Member

    @neph1 @IvoryTower800 I actually forgot to mention now FastLanguageModel.from_pretrained supports loading adapters directly, allowing you to continue finetuning. I also auto patch the model to enable 2x faster finetuning.

    lora_model = FastLanguageModel.from_pretrained("my_lora_model", ...)
    # DO NOT call FastLanguageModel.get_peft_model - we already do it for you!
    trainer.train()
  6. added
    fixed - pending confirmation
    on Jan 27, 2024
  7. Huan80805 commented on Aug 12, 2024

    @Huan80805

    Hi, @danielhanchen I have a similar question but with different objective.
    I would like to use a different peft config for training the new adapter.
    How can I first load previous trained adapter, merge it to base model, and initialize/train a new adapter?

  8. danielhanchen commented on Aug 13, 2024

    @danielhanchen
    Member

    You can use model.save_pretrained_merged(...) then load it, then add LoRA adapters

  9. nofreewill42 commented on Oct 5, 2024

    @nofreewill42

    @neph1 @IvoryTower800 I actually forgot to mention now FastLanguageModel.from_pretrained supports loading adapters directly, allowing you to continue finetuning. I also auto patch the model to enable 2x faster finetuning.

    lora_model = FastLanguageModel.from_pretrained("my_lora_model", ...)
    # DO NOT call FastLanguageModel.get_peft_model - we already do it for you!
    trainer.train()

    Hey there!
    What do you mean you autopatch to 2x fine-tuning speed?

  10. James4Ever0 commented on Sep 28, 2025

    @James4Ever0

    Not fully resolved. When I check it with the following code, some parameters like "lm_head" and "embed_tokens" are not marked as trainable. Only those params with "lora" in their names are trainable. Also some parameters are mysteriously missing when loading the LoRA model.

    #2902

    # docker image pull unsloth/unsloth:2025.8.10-main-repo-pt2.7.0-cu12.6_xformers033-flex_attention-gptoss
    
    import unsloth
    
    print(unsloth.__version__)
    # '2025.8.10'
    
    max_seq_length = 2048
    
    model, tokenizer = unsloth.FastLanguageModel.from_pretrained(
        model_name="unsloth/Qwen3-4B-Thinking-2507",
        dtype=None,  # None for auto detection
        max_seq_length=max_seq_length,  # Choose any for long context!
        load_in_4bit=True,  # 4 bit quantization to reduce memory
        full_finetuning=False,  # [NEW!] We have full finetuning now!
    )
    
    model = unsloth.FastLanguageModel.get_peft_model(
        model,
        r=16,  # 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",    
            "embed_tokens", 
            "lm_head",
        ], # Add for continual pretraining: embed_tokens, lm_head
        lora_alpha=16,
        lora_dropout=0,  # Supports any, but = 0 is optimized
        bias="none",  # Supports any, but = "none" is optimized
        # [NEW] "unsloth" uses 30% less VRAM, fits 2x larger batch sizes!
        use_gradient_checkpointing="unsloth",  # True or "unsloth" for very long context
        random_state=3407,
        use_rslora=False,  # We support rank stabilized LoRA
        loftq_config=None,  # And LoftQ
    )
    
    model.print_trainable_parameters()
    # trainable params: 810,942,464 || all params: 5,222,366,720 || trainable%: 15.5283
    
    model.save_pretrained("lora_model")  # Local saving
    tokenizer.save_pretrained("lora_model")
    
    
    model, tokenizer = unsloth.FastLanguageModel.from_pretrained(
        model_name="lora_model",
        max_seq_length=max_seq_length,  # Choose any for long context!
        load_in_4bit=True,  # 4 bit quantization to reduce memory
    )
    
    print(len([name for name, params in model.named_parameters()])) # 504
    
    model.print_trainable_parameters()
    # trainable params: 33,030,144 || all params: 4,833,410,560 || trainable%: 0.6834
    
    # will cause "ValueError: Attempting to unscale FP16 gradients"
    if False:
        for name, param in model.named_parameters():
            if "embed_tokens" in name:
                param.requires_grad = True
            if "lm_head" in name:
                param.requires_grad = True
    
    # in contrary, if we do "unsloth.FastLanguageModel.get_peft_model" again over the loaded Lora model, we will not get error.
    model = unsloth.FastLanguageModel.get_peft_model(
        model,
        r=16,  # 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",    
            "embed_tokens", 
            "lm_head",
        ], # Add for continual pretraining: embed_tokens, lm_head
        lora_alpha=16,
        lora_dropout=0,  # Supports any, but = 0 is optimized
        bias="none",  # Supports any, but = "none" is optimized
        # [NEW] "unsloth" uses 30% less VRAM, fits 2x larger batch sizes!
        use_gradient_checkpointing="unsloth",  # True or "unsloth" for very long context
        random_state=3407,
        use_rslora=False,  # We support rank stabilized LoRA
        loftq_config=None,  # And LoftQ
    )
    
    print(len([name for name, params in model.named_parameters()])) # 506
    
    model.print_trainable_parameters()
    # trainable params: 810,942,464 || all params: 4,833,410,560 || trainable%: 16.7779
  11. James4Ever0 commented on Sep 28, 2025

    @James4Ever0

    @danielhanchen Please reopen.

    @neph1 Would you like to direct me to the pull request or the code block responsible for loading lora models using "FastLanguageModel.from_pretrained"? I will see what I can do there.

  12. neph1 commented on Sep 28, 2025

    @neph1
    Contributor

    @James4Ever0 Sorry, I ran out of context length and don't remember where I quoted that piece of code from. Do a search for LoraConfig.

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