Repository navigation
Closed
Description
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!
Reacted by Aravind S
Metadata
Metadata
Assignees
Labels
No labels
Activity
aravind-selvam commentedon Apr 2, 2025
Same issue here
TheTsar8756 commentedon May 12, 2025
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.
sam-paech commentedon May 16, 2025
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"]
-->
target_modules=["lm_head"]
-->
srikanthsrnvs commentedon May 20, 2025
You must set the
modules_to_saveparameterandreasspap commentedon May 29, 2025
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?
BUAADreamer commentedon Jun 2, 2025
@andreasspap have you solved it??
rolandtannous commentedon Jun 30, 2025
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
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
training: switch from lm_head LoRA to modules_to_save + fix PEFT reload