Repository navigation
Description
When I merged the models, I encountered the following error. How can I fix it?
RuntimeError Traceback (most recent call last)
Cell In[16], line 1
----> 1 model.save_pretrained_merged("/home/ubuntu/work_space/models/Qwen3-8B-catgirl", tokenizer, save_method = "merged_16bit",)
File ~/miniconda3/envs/SFT/lib/python3.12/site-packages/unsloth/save.py:2378, 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)
2376 arguments["model"] = self
2377 del arguments["self"]
-> 2378 unsloth_generic_save(**arguments)
2379 for _ in range(3):
2380 gc.collect()
File ~/miniconda3/envs/SFT/lib/python3.12/site-packages/torch/utils/_contextlib.py:116, in context_decorator..decorate_context(*args, **kwargs)
113 @functools.wraps(func)
114 def decorate_context(*args, **kwargs):
115 with ctx_factory():
--> 116 return func(*args, **kwargs)
File ~/miniconda3/envs/SFT/lib/python3.12/site-packages/unsloth/save.py:2324, 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)
2321 elif save_method == "merged_4bit_forced":
2322 save_method = "merged_4bit"
-> 2324 merge_and_overwrite_lora(
2325 get_model_name,
2326 model = model,
2327 tokenizer = tokenizer,
2328 save_directory = save_directory,
2329 push_to_hub = push_to_hub,
2330 private = private,
2331 token = token,
2332 save_method = save_method,
2333 output_dtype = None,
2334 low_disk_space_usage = True,
2335 use_temp_file = False,
2336 )
2337 return
File ~/miniconda3/envs/SFT/lib/python3.12/site-packages/torch/utils/_contextlib.py:116, in context_decorator..decorate_context(*args, **kwargs)
113 @functools.wraps(func)
114 def decorate_context(*args, **kwargs):
115 with ctx_factory():
--> 116 return func(*args, **kwargs)
File ~/miniconda3/envs/SFT/lib/python3.12/site-packages/unsloth_zoo/saving_utils.py:817, in merge_and_overwrite_lora(get_model_name, model, tokenizer, save_directory, push_to_hub, private, token, save_method, output_dtype, low_disk_space_usage, use_temp_file, cleanup_temp_file)
810 hf_hub_download(
811 repo_id = model_name,
812 filename = filename,
813 repo_type = "model",
814 local_dir = save_directory,
815 )
816 pass
--> 817 n_saved_modules += _merge_and_overwrite_lora(
818 save_directory = save_directory,
819 filename = filename,
820 lora_weights = lora_weights,
821 output_dtype = output_dtype,
822 model_class_name = find_lora_base_model(model).class.name,
823 )
824 torch.cuda.empty_cache()
825 if low_disk_space_usage and push_to_hub:
File ~/miniconda3/envs/SFT/lib/python3.12/site-packages/torch/utils/_contextlib.py:116, in context_decorator..decorate_context(*args, **kwargs)
113 @functools.wraps(func)
114 def decorate_context(*args, **kwargs):
115 with ctx_factory():
--> 116 return func(*args, **kwargs)
File ~/miniconda3/envs/SFT/lib/python3.12/site-packages/unsloth_zoo/saving_utils.py:375, in _merge_and_overwrite_lora(save_directory, filename, lora_weights, output_dtype, model_class_name)
373 if lora_stats is not None and hasattr(lora_stats, 'lora_A') and lora_stats.lora_A is not None:
374 count += 1
--> 375 W = _merge_lora(W, lora_stats, key)
376 if psutil.virtual_memory().available <= limit:
377 temp_file = tempfile.NamedTemporaryFile(suffix = ".pt")
File ~/miniconda3/envs/SFT/lib/python3.12/site-packages/unsloth_zoo/saving_utils.py:149, in merge_lora(W, lora_stats, name)
147 if lora_stats.lora_A is None or lora_stats.lora_B is None: return W
148 W = W.to("cuda", dtype = torch.float32, non_blocking = True)
--> 149 W = W.addmm(
150 lora_stats.lora_B.to("cuda", dtype = torch.float32, non_blocking = True),
151 lora_stats.lora_A.to("cuda", dtype = torch.float32, non_blocking = True),
152 alpha = lora_stats.alpha,
153 )
154 if not torch.isfinite(torch.amax(W)).item():
155 raise ValueError('Unsloth: Merge failed as there are infinite elements in ' + name)
RuntimeError: Bad in-place call: input tensor size [2097152, 1] and output tensor size [1024, 4096] should match
Activity
[-][Bug][/-][+][Bug] RuntimeError: Bad in-place call: input tensor size [2097152, 1] and output tensor size [1024, 4096] should match[/+]ma7awork commentedon Jun 17, 2025
same error how to fix
risqaliyevds commentedon Jun 18, 2025
same problem is it bugor i am doing wrong?
ttt-noora commentedon Jun 23, 2025
same error
rolandtannous commentedon Jun 23, 2025
hello @ttt-noora @risqaliyevds @ma7awork @xiaopang927423
will investigate. However I need you to share
sujianwei1 commentedon Jun 24, 2025
Detected local model directory: /workdir/model/qwen3-8b
Found HuggingFace hub cache directory: /root/.cache/huggingface/hub
Copying safetensors from local directory: /workdir/model/qwen3-8b
Copied safetensors index file from local model
Unsloth: Merging weights into 16bit: 0%| | 0/2 [00:10<?, ?it/s]
Copied model-00002-of-00002.safetensors from local model directory
RuntimeError Traceback (most recent call last)
Cell In[8], line 1
----> 1 model.save_pretrained_merged("model", tokenizer, save_method = "merged_16bit",)
File /usr/local/lib/python3.10/site-packages/unsloth/save.py:2378, 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)
2376 arguments["model"] = self
2377 del arguments["self"]
-> 2378 unsloth_generic_save(**arguments)
2379 for _ in range(3):
2380 gc.collect()
File /usr/local/lib/python3.10/site-packages/torch/utils/_contextlib.py:116, in context_decorator..decorate_context(*args, **kwargs)
113 @functools.wraps(func)
114 def decorate_context(*args, **kwargs):
115 with ctx_factory():
--> 116 return func(*args, **kwargs)
File /usr/local/lib/python3.10/site-packages/unsloth/save.py:2324, 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)
2321 elif save_method == "merged_4bit_forced":
2322 save_method = "merged_4bit"
-> 2324 merge_and_overwrite_lora(
2325 get_model_name,
2326 model = model,
2327 tokenizer = tokenizer,
2328 save_directory = save_directory,
2329 push_to_hub = push_to_hub,
2330 private = private,
2331 token = token,
2332 save_method = save_method,
2333 output_dtype = None,
2334 low_disk_space_usage = True,
2335 use_temp_file = False,
2336 )
2337 return
File /usr/local/lib/python3.10/site-packages/torch/utils/_contextlib.py:116, in context_decorator..decorate_context(*args, **kwargs)
113 @functools.wraps(func)
114 def decorate_context(*args, **kwargs):
115 with ctx_factory():
--> 116 return func(*args, **kwargs)
File /usr/local/lib/python3.10/site-packages/unsloth_zoo/saving_utils.py:817, in merge_and_overwrite_lora(get_model_name, model, tokenizer, save_directory, push_to_hub, private, token, save_method, output_dtype, low_disk_space_usage, use_temp_file, cleanup_temp_file)
810 hf_hub_download(
811 repo_id = model_name,
812 filename = filename,
813 repo_type = "model",
814 local_dir = save_directory,
815 )
816 pass
--> 817 n_saved_modules += _merge_and_overwrite_lora(
818 save_directory = save_directory,
819 filename = filename,
820 lora_weights = lora_weights,
821 output_dtype = output_dtype,
822 model_class_name = find_lora_base_model(model).class.name,
823 )
824 torch.cuda.empty_cache()
825 if low_disk_space_usage and push_to_hub:
File /usr/local/lib/python3.10/site-packages/torch/utils/_contextlib.py:116, in context_decorator..decorate_context(*args, **kwargs)
113 @functools.wraps(func)
114 def decorate_context(*args, **kwargs):
115 with ctx_factory():
--> 116 return func(*args, **kwargs)
File /usr/local/lib/python3.10/site-packages/unsloth_zoo/saving_utils.py:375, in _merge_and_overwrite_lora(save_directory, filename, lora_weights, output_dtype, model_class_name)
373 if lora_stats is not None and hasattr(lora_stats, 'lora_A') and lora_stats.lora_A is not None:
374 count += 1
--> 375 W = _merge_lora(W, lora_stats, key)
376 if psutil.virtual_memory().available <= limit:
377 temp_file = tempfile.NamedTemporaryFile(suffix = ".pt")
File /usr/local/lib/python3.10/site-packages/unsloth_zoo/saving_utils.py:149, in merge_lora(W, lora_stats, name)
147 if lora_stats.lora_A is None or lora_stats.lora_B is None: return W
148 W = W.to("cuda", dtype = torch.float32, non_blocking = True)
--> 149 W = W.addmm(
150 lora_stats.lora_B.to("cuda", dtype = torch.float32, non_blocking = True),
151 lora_stats.lora_A.to("cuda", dtype = torch.float32, non_blocking = True),
152 alpha = lora_stats.alpha,
153 )
154 if not torch.isfinite(torch.amax(W)).item():
155 raise ValueError('Unsloth: Merge failed as there are infinite elements in ' + name)
RuntimeError: Bad in-place call: input tensor size [25165824, 1] and output tensor size [4096, 12288] should match
sujianwei1 commentedon Jun 24, 2025
==((====))== Unsloth 2025.6.3: Fast Qwen3 patching. Transformers: 4.51.3.
\ /| Tesla T4. Num GPUs = 1. Max memory: 14.578 GB. Platform: Linux.
O^O/ _/ \ Torch: 2.6.0+cu124. CUDA: 7.5. CUDA Toolkit: 12.4. Triton: 3.2.0
\ / Bfloat16 = FALSE. FA [Xformers = 0.0.29.post3. FA2 = False]
"-____-" Free license: http://github.com/unslothai/unsloth
Unsloth: Fast downloading is enabled - ignore downloading bars which are red colored!
xiaopang927423 commentedon Jun 24, 2025
``> hello @ttt-noora @risqaliyevds @ma7awork @xiaopang927423 will investigate. However I need you to share
`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 cut_cross_entropy unsloth_zoo
!pip install sentencepiece protobuf "datasets>=3.4.1" huggingface_hub hf_transfer
!pip install --no-deps unsloth
from unsloth import FastLanguageModel
import torch
model, tokenizer = FastLanguageModel.from_pretrained(
model_name = "/home/ubuntu/work_space/models/Qwen3-8B-bnb-4int",
max_seq_length = 2048,
load_in_4bit = False,
load_in_8bit = True,
full_finetuning = False, # LoRA
)
model = FastLanguageModel.get_peft_model(
model,
r = 32, # 选择任意大于 0的数字! 建议 8, 16, 32, 64, 128
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj",],
lora_alpha = 32,
lora_dropout = 0,
bias = "none",
use_gradient_checkpointing = "unsloth",
random_state = 3407,
use_rslora = False,
loftq_config = None,
)`
xiaopang927423 commentedon Jun 24, 2025
the code was coding by the link code
https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Gemma3_(4B).ipynb
KaiDF commentedon Jun 25, 2025
same issue with the latest version of unsloth
rolandtannous commentedon Jun 25, 2025
@KaiDF @xiaopang927423 @sujianwei1 @ttt-noora @ma7awork
You are running out of system RAM on the colab T4 while trying to save and merge . The Colab T4 has maximum of 12.7GB system RAM, while save and merge peaks system RAM at 18GB system RAM. You will need a larger machine. Try Colab T4+High RAM or a Colab Pro A100. We might try to see if optimizing the merging code even more can maybe allow it to fit on a colab T4, but that's not guarranteed.
xiaopang927423 commentedon Jun 25, 2025
I didn't use the machine on Colab; instead, I used my local GPU, an RTX 4090 with 48GB of VRAM. Under normal circumstances, this should be sufficient for the cache requirements. I observed that my GPU utilization wasn't at full capacity—it was only using about one quarter of its resources.
rolandtannous commentedon Jun 25, 2025
@xiaopang927423 The save and merge process currently uses System RAM , not VRAM (GPU RAM).
xiaopang927423 commentedon Jun 25, 2025
@rolandtannous thanks,i will choose other size
2 remaining items
rolandtannous commentedon Jun 25, 2025
@risqaliyevds what is the model you are using?
and is there any chance you can hop unto the discord server so we can troubleshoot this in person?
sunyilgdx commentedon Jun 30, 2025
Same error
Dao007forever commentedon Jul 1, 2025
Printed out the layers where it happens with Qwen3-32B-unsloth-bnb-4bit.
This happens without any SFT, just calling
FastLanguageModel.get_peft_modelthen save.layer 49 -> 54.
rolandtannous commentedon Jul 1, 2025
@Dao007forever I just ran the exact same process.
Loaded Qwen3-32B-unsloth-bnb-4bit. with the Peft model then save_pretrained_merged
I used an H100 with 80GB VRAM and 230GB System RAM. the process ran successfully. Check the screenshots below :)
The process works fine and you shouldn't get fixated on the runtime errors simply because we don't yet have proper exception handling integrated into unsloth, so when the machine crashes because it doesn't have enough system RAM or disk or sometimes VRAM , the runtime exception isn't exactly pinpointing the root event that caused the exception.
Note that for Qwen3-32B-unsloth-bnb-4bit, you need the following:
Note that you're probably running out of 1 of the above resources and that's why it's not working out.
If you don't currently have access to a larger machine, I suggest you try the 4bit mode when you save and merge but your model will lose some accuracy
Dao007forever commentedon Jul 1, 2025
I'm running on p24de with 2 GPU, 80GB VRAM each, 96GB RAM, EBS volume. I saw only 9 shards? https://huggingface.co/unsloth/Qwen3-32B-unsloth-bnb-4bit/tree/main
When I print out layer 49 (in shard 7), I do see the difference in dimension:
vs
rolandtannous commentedon Jul 1, 2025
@Dao007forever the save and merge process doesn't use VRAM but system RAM.
And yes this is the same model. Here is a screenshot. You can also see 9 shards when it's initially loading the model . That's because it's loading a 4bit quantized model
The reason why it uses 14 shards during save and merge, is because by default you're saving and merging with full precision (unless you specify save_method as 4bit). So it has to download the base model in full precision, it can't use a quantized base model to merge. It therefore downloads the shards from here https://huggingface.co/unsloth/Qwen3-32B/tree/main
If you check that repo, you'll see that there are 14 shards.
On your machine, you might also wanna Do the following checks:
Dao007forever commentedon Jul 1, 2025
@rolandtannous Thanks, my problem was I downloaded the
unsloth-bnb-4bitand pointed to the directory. When trying to merge, it uses the 9 shards for the 4bit model instead and somehow that's broken.When specifying the model name and let HF download it, it works.
I'd expect using a downloaded model should work...
hufeide commentedon Jul 12, 2025
when lora fineture gemma3-27b-4bit save model :RuntimeError: Bad in-place call: input tensor size [57802752, 1] and output tensor size [5376, 21504] should match
javajuice1337 commentedon Jul 12, 2025
Same problem here... after fine-tuning
unsloth/Qwen2.5-VL-32B-Instruct-bnb-4bit, this error occurs during saving to 16-bit:Calling
model.save_pretrained_merged(os.path.join(OUTPUT_DATA_PATH, "model-16bit"), tokenizer, save_method = "merged_16bit")Traceback (most recent call last):
File "/home/user/train/./unsloth_trainer.py", line 186, in
model.save_pretrained_merged(os.path.join(OUTPUT_DATA_PATH, "model-16bit"), tokenizer, save_method = "merged_16bit")
File "/home/user/.venv/lib/python3.12/site-packages/unsloth/save.py", line 2378, in unsloth_generic_save_pretrained_merged
unsloth_generic_save(**arguments)
File "/home/user/.venv/lib/python3.12/site-packages/torch/utils/_contextlib.py", line 116, in decorate_context
return func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "/home/user/.venv/lib/python3.12/site-packages/unsloth/save.py", line 2324, in unsloth_generic_save
merge_and_overwrite_lora(
File "/home/user/.venv/lib/python3.12/site-packages/torch/utils/_contextlib.py", line 116, in decorate_context
return func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "/home/user/.venv/lib/python3.12/site-packages/unsloth_zoo/saving_utils.py", line 873, in merge_and_overwrite_lora
n_saved_modules += _merge_and_overwrite_lora(
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/.venv/lib/python3.12/site-packages/torch/utils/_contextlib.py", line 116, in decorate_context
return func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "/home/user/.venv/lib/python3.12/site-packages/unsloth_zoo/saving_utils.py", line 384, in _merge_and_overwrite_lora
W = _merge_lora(W, lora_stats, key) # Assume _merge_lora is defined elsewhere
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/.venv/lib/python3.12/site-packages/unsloth_zoo/saving_utils.py", line 150, in merge_lora
W = W.addmm(
^^^^^^^^^
RuntimeError: Bad in-place call: input tensor size [70778880, 1] and output tensor size [5120, 27648] should match
rolandtannous commentedon Jul 12, 2025
@hufeide @javajuice1337
we're aware of the problem. i'll be releasing a fix in the next two days.
for now, in order to solve the problem temporarily, make sure to delete the 4bit quantized base model from your local huggingface cache and the current folder, this will make unsloth download the correct unquantized base model for the merge operation
javajuice1337 commentedon Jul 16, 2025
I tried your suggestion and couldn't get it to work... it keeps redownloading the 4bit quantized files. Patiently waiting for the official fix!
rolandtannous commentedon Jul 17, 2025
@javajuice1337 noted
do you happen to be on our discord server. If yes, could you please ping me there?
hiki1002 commentedon Jul 22, 2025
model.save_pretrained_merged(save_directory = "Qwen3-4B-finetuned-fp16",
tokenizer = tokenizer,
save_method = "merged_16bit")
RuntimeError: Bad in-place call: input tensor size [12451840, 1] and output tensor size [2560, 9728] should match
Hello, could please let me know if there have been any recent updates or progress regarding this issue? I'm currently encountering the same problem when saving LoRA fine-tuned Qwen3-4B-unsloth-bnb-4bit and Qwen3-8B-unsloth-bnb-4bit models.
szyulian commentedon Jul 31, 2025
Same error encountered.
rolandtannous commentedon Aug 28, 2025
Dao007forever @KaiDF @hiki1002 @hufeide @javajuice1337 @ma7awork @risqaliyevds @sujianwei1 @sunyilgdx @szyulian @ttt-noora @xiaopang927423
I've just merged a pull request that should fix this issue. Our LoRA merging process now supports both 16-bit base models and mxfp4 native models (such as gpt-oss).
The exception you encountered typically occurs in two scenarios:
1. Local 4-bit model conflict
A 4-bit version of the model exists in your current folder. Previously, our merge process would automatically use this local version without checking its bit precision. We've now updated the logic to select between local folders and Hugging Face repositories based on the model's quantization state, with a preference for unquantized local versions when available.
2. Sequential fine-tuning on 4-bit models
You're attempting to fine-tune a 4-bit merged model that was previously fine-tuned. We strongly advise against this approach as it significantly degrades performance. Instead, we recommend:
To apply the fix:
Update your installations using these commands:
Please try again after updating and let me know if this resolves the issue.