Skip to content

RuntimeError: Unsloth: Saving LoRA finetune failed since # of LoRAs = 196 does not match # of saved modules = 392. Please file a bug report! #2238

Closed

Description

@embedded-robotics

Hi,

I have fine-tuned a LLaMA-3.2-3B-Instruct model using LoRA setting load_in_8bit = True. The fine-tuning goes on well. However, when I go on to save the merged model "16-bit", I am getting the error as:

RuntimeError: Unsloth: Saving LoRA finetune failed since # of LoRAs = 196 does not match # of saved modules = 392. Please file a bug report!

Please find my code below for any references:

model, tokenizer = FastLanguageModel.from_pretrained(
    model_name = "unsloth/Llama-3.2-3B-Instruct",
    max_seq_length = 2048,
    load_in_4bit = False, # 4 bit quantization to reduce memory
    load_in_8bit = True, # [NEW!] A bit more accurate, uses 2x memory
    full_finetuning = False, # [NEW!] We have full finetuning now!
    dtype=None, #None for auto-detection. Can be torch.bfloat16 or torch.float16 (will be automatically detected)
    device_map="auto"
)

model = FastLanguageModel.get_peft_model(
    model,
    r = 64, #max_full_rank=64 by default in FastLanguageModel
    target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
                      "gate_proj", "up_proj", "down_proj",],
    lora_alpha = 64, #scaling_factor = lora_alpha/r. If we select lora_alpha = 2 * r then it will multiply the adapter weights by 2 which can be un-ncessary
    lora_dropout = 0.1,
    bias = "none",
    use_gradient_checkpointing = "unsloth",
    use_rslora = True,
    loftq_config = None,
)

training_args = TrainingArguments(
        output_dir=peft_model_path,
        per_device_train_batch_size=4,
        per_device_eval_batch_size=2,
        # gradient_accumulation_steps=4,
        eval_strategy="steps",
        eval_steps=0.1,
        logging_strategy="steps",
        logging_steps=50,
        save_strategy="steps",
        save_steps=0.1,
        warmup_steps = 5,
        num_train_epochs = 3,
        learning_rate = 2e-4,
        fp16 = not is_bfloat16_supported(),
        bf16 = is_bfloat16_supported(),
        optim = "adamw_8bit",
        weight_decay = 0.01,
        lr_scheduler_type = "linear",
        load_best_model_at_end=True,
        metric_for_best_model="eval_loss",
        greater_is_better=False,
        seed = 42,
        report_to = "none",
    )

trainer = SFTTrainer(
    model = model,
    tokenizer = tokenizer,
    train_dataset=dataset_formatted["train"],
    eval_dataset=dataset_formatted["test"],
    dataset_text_field = "text",
    max_seq_length = 2048,
    data_collator = DataCollatorForSeq2Seq(tokenizer = tokenizer), #only use when using train_on_responses_only()
    dataset_num_proc = 2,
    packing = False, # Can make training 5x faster for short sequences.
    args = training_args)

trainer = train_on_responses_only(
    trainer,
    instruction_part = "<|start_header_id|>user<|end_header_id|>\n\n",
    response_part = "<|start_header_id|>assistant<|end_header_id|>\n\n",
)

trainer_stats = trainer.train()

peft_merged_model_path = "./llama32-sft-peft-merged-counselchat"
model.save_pretrained_merged(peft_merged_model_path, tokenizer, save_method = "merged_16bit")

Following is the complete Error Stack:

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[28], line 2
      1 peft_merged_model_path = "./llama32-sft-peft-merged-counselchat"
----> 2 model.save_pretrained_merged(peft_merged_model_path, tokenizer, save_method = "merged_16bit")

File /data/mn27889/miniconda3/envs/mental-health-agents/lib/python3.12/site-packages/unsloth/save.py:2357, in unsloth_generic_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)
   2355 arguments["model"] = self
   2356 del arguments["self"]
-> 2357 unsloth_generic_save(**arguments)
   2358 for _ in range(3):
   2359     gc.collect()

File /data/mn27889/miniconda3/envs/mental-health-agents/lib/python3.12/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 /data/mn27889/miniconda3/envs/mental-health-agents/lib/python3.12/site-packages/unsloth/save.py:2304, in unsloth_generic_save(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)
   2274 @torch.inference_mode
   2275 def unsloth_generic_save(
   2276     model,
   (...)   2301     maximum_memory_usage : float = 0.9,
   2302 ):
   2303     if token is None and push_to_hub: token = get_token()
-> 2304     merge_and_overwrite_lora(
   2305         get_model_name,
   2306         model                = model,
   2307         tokenizer            = tokenizer,
   2308         save_directory       = save_directory,
   2309         push_to_hub          = push_to_hub,
   2310         private              = private,
   2311         token                = token,
   2312         output_dtype         = None,
   2313         low_disk_space_usage = True,
   2314         use_temp_file        = False,
   2315     )
   2316     return

File /data/mn27889/miniconda3/envs/mental-health-agents/lib/python3.12/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 /data/mn27889/miniconda3/envs/mental-health-agents/lib/python3.12/site-packages/unsloth_zoo/saving_utils.py:650, in merge_and_overwrite_lora(get_model_name, model, tokenizer, save_directory, push_to_hub, private, token, output_dtype, low_disk_space_usage, use_temp_file, cleanup_temp_file)
    648 # Check for errors
    649 if len(lora_weights) != n_saved_modules:
--> 650     raise RuntimeError(
    651         f"Unsloth: Saving LoRA finetune failed since # of LoRAs = {len(lora_weights)} "\
    652         f"does not match # of saved modules = {n_saved_modules}. Please file a bug report!"
    653     )
    654 pass
    655 if temp_file is not None:

RuntimeError: Unsloth: Saving LoRA finetune failed since # of LoRAs = 196 does not match # of saved modules = 392. Please file a bug report!

Activity

  1. aravind-selvam commented on Apr 2, 2025

    @aravind-selvam
    RuntimeError: Unsloth: Saving LoRA finetune failed since # of LoRAs = 238 does not match # of saved modules = 0. Please file a bug report!
    

    Same issue here

  2. TheTsar8756 commented on May 12, 2025

    @TheTsar8756

    RuntimeError: Unsloth: Saving LoRA finetune failed since # of LoRAs = 336 does not match # of saved modules = 0. Please file a bug report!
    I also have the same issue.

  3. sam-paech commented on May 16, 2025

    @sam-paech

    I'm getting this issue also. Notably, only when I include lm_head in the target modules.

    This is training gemma-3-4b-it w/ dpo.

    target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]

    --> ok

    target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj", "lm_head"]

    -->

    Unsloth: Merging weights into 16bit: 100%|██████████████████████████████████████████████████| 2/2 [00:17<00:00,  8.92s/it]
    2025-05-16 01:45:02,938 - core.finetuning - ERROR - Error saving model: Unsloth: Saving LoRA finetune failed since # of LoRAs = 320 does not match # of saved modules = 319. Please file a bug report!
    Traceback (most recent call last):
      File "/root/auto-antislop/core/finetuning.py", line 853, in run_dpo_finetune
        model.save_pretrained_merged(str(merged_path), tokenizer, save_method="merged_16bit", safe_serialization=True)
      File "/usr/local/lib/python3.10/dist-packages/unsloth/save.py", line 2370, in unsloth_generic_save_pretrained_merged
        unsloth_generic_save(**arguments)
      File "/usr/local/lib/python3.10/dist-packages/torch/utils/_contextlib.py", line 116, in decorate_context
        return func(*args, **kwargs)
      File "/usr/local/lib/python3.10/dist-packages/unsloth/save.py", line 2316, in unsloth_generic_save
        merge_and_overwrite_lora(
      File "/usr/local/lib/python3.10/dist-packages/torch/utils/_contextlib.py", line 116, in decorate_context
        return func(*args, **kwargs)
      File "/usr/local/lib/python3.10/dist-packages/unsloth_zoo/saving_utils.py", line 680, in merge_and_overwrite_lora
        raise RuntimeError(
    RuntimeError: Unsloth: Saving LoRA finetune failed since # of LoRAs = 320 does not match # of saved modules = 319. Please file a bug report!
    

    target_modules=["lm_head"]

    -->

    2025-05-16 00:50:01,663 - core.finetuning - ERROR - Error saving model: Unsloth: Saving LoRA finetune failed since # of Lo
    RAs = 1 does not match # of saved modules = 0. Please file a bug report!
    Traceback (most recent call last):
      File "/root/auto-antislop/core/finetuning.py", line 831, in run_dpo_finetune
        model.save_pretrained_merged(str(merged_path), tokenizer, save_method="merged_16bit", safe_serialization=True)
      File "/usr/local/lib/python3.10/dist-packages/unsloth/save.py", line 2370, in unsloth_generic_save_pretrained_merged
        unsloth_generic_save(**arguments)
      File "/usr/local/lib/python3.10/dist-packages/torch/utils/_contextlib.py", line 116, in decorate_context
        return func(*args, **kwargs)
      File "/usr/local/lib/python3.10/dist-packages/unsloth/save.py", line 2316, in unsloth_generic_save
        merge_and_overwrite_lora(
      File "/usr/local/lib/python3.10/dist-packages/torch/utils/_contextlib.py", line 116, in decorate_context
        return func(*args, **kwargs)
      File "/usr/local/lib/python3.10/dist-packages/unsloth_zoo/saving_utils.py", line 680, in merge_and_overwrite_lora
        raise RuntimeError(
    RuntimeError: Unsloth: Saving LoRA finetune failed since # of LoRAs = 1 does not match # of saved modules = 0. Please file a bug report!
    
  4. srikanthsrnvs commented on May 20, 2025

    @srikanthsrnvs

    You must set the modules_to_save parameter

  5. andreasspap commented on May 29, 2025

    @andreasspap

    RuntimeError: Unsloth: Saving LoRA finetune failed since # of LoRAs = 196 does not match # of saved modules = 0. Please file a bug report! I have this issue. anyone can help me please?

  6. BUAADreamer commented on Jun 2, 2025

    @BUAADreamer

    @andreasspap have you solved it??

  7. rolandtannous commented on Jun 30, 2025

    @rolandtannous
    Contributor

    Hello ,

    This should now work with the latest version of Unsloth as we have recently introduced improvements to the saving and merging logic for both language and vision models.
    Please make sure to upgrade your installation to the latest version using

    pip install --upgrade unsloth-zoo
    pip install --upgrade unsloth
    

    Will close this for now.
    Please feel free to comment back if you are still facing the same issue after trying the above.
    Thank you for using Unsloth

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions