Repository navigation
Closed
Labels
fixed - pending confirmationFixed, waiting for confirmation from poster
Description
- Did you update?
pip install --upgrade unsloth unsloth_zoo ColaborKaggleor local / cloud- Number GPUs used, use
nvidia-smi: Google T4 - Which notebook?(https://www.kaggle.com/code/shubhamkurkute/unsloth-gemma-fine-tune)
Cuda Error for gemma-fine-tune unsloth notebook.
The issue goes like out of cuda memory for the trainer.train(). Although the dataset is same used in the notebook referenced by the unsloth. The error is populated after some while and not a single step is executed. Also tried it on Google Colab gives the same error.
Error
\\ /| Num examples = 129 | Num Epochs = 2 | Total steps = 30
O^O/ \_/ \ Batch size per device = 1 | Gradient accumulation steps = 8
\ / Data Parallel GPUs = 1 | Total batch size (1 x 8 x 1) = 8
"-____-" Trainable parameters = 1,361,753,856 of 5,661,833,328 (24.05% trained)
---------------------------------------------------------------------------
OutOfMemoryError Traceback (most recent call last)
/tmp/ipykernel_36/773422404.py in <cell line: 0>()
----> 1 trainer_stats = trainer.train()
/usr/local/lib/python3.11/dist-packages/transformers/trainer.py in train(self, resume_from_checkpoint, trial, ignore_keys_for_eval, **kwargs)
2236 hf_hub_utils.enable_progress_bars()
2237 else:
-> 2238 return inner_training_loop(
2239 args=args,
2240 resume_from_checkpoint=resume_from_checkpoint,
/usr/local/lib/python3.11/dist-packages/unsloth_zoo/compiler.py in _fast_inner_training_loop(self, batch_size, args, resume_from_checkpoint, trial, ignore_keys_for_eval)
/kaggle/working/unsloth_compiled_cache/UnslothSFTTrainer.py in training_step(self, *args, **kwargs)
971 def training_step(self, *args, **kwargs):
972 with self.maybe_activation_offload_context:
--> 973 return super().training_step(*args, **kwargs)
974
975 def log(self, logs: dict[str, float], start_time: Optional[float] = None) -> None:
/usr/local/lib/python3.11/dist-packages/unsloth/models/_utils.py in _unsloth_training_step(self, model, inputs, num_items_in_batch)
/kaggle/working/unsloth_compiled_cache/UnslothSFTTrainer.py in compute_loss(self, model, inputs, return_outputs, num_items_in_batch)
960
961 def compute_loss(self, model, inputs, return_outputs = False, num_items_in_batch = None):
--> 962 outputs = super().compute_loss(
963 model,
964 inputs,
/usr/local/lib/python3.11/dist-packages/unsloth/models/_utils.py in _unsloth_pre_compute_loss(self, model, inputs, *args, **kwargs)
1312 )
1313 pass
-> 1314 outputs = self._old_compute_loss(model, inputs, *args, **kwargs)
1315 return outputs
1316 pass
/usr/local/lib/python3.11/dist-packages/transformers/trainer.py in compute_loss(self, model, inputs, return_outputs, num_items_in_batch)
3882 kwargs["num_items_in_batch"] = num_items_in_batch
3883 inputs = {**inputs, **kwargs}
-> 3884 outputs = model(**inputs)
3885 # Save past state if it exists
3886 # TODO: this needs to be fixed and made cleaner later.
/usr/local/lib/python3.11/dist-packages/torch/nn/modules/module.py in _wrapped_call_impl(self, *args, **kwargs)
1737 return self._compiled_call_impl(*args, **kwargs) # type: ignore[misc]
1738 else:
-> 1739 return self._call_impl(*args, **kwargs)
1740
1741 # torchrec tests the code consistency with the following code
/usr/local/lib/python3.11/dist-packages/torch/nn/modules/module.py in _call_impl(self, *args, **kwargs)
1748 or _global_backward_pre_hooks or _global_backward_hooks
1749 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1750 return forward_call(*args, **kwargs)
1751
1752 result = None
/usr/local/lib/python3.11/dist-packages/peft/peft_model.py in forward(self, input_ids, attention_mask, inputs_embeds, labels, output_attentions, output_hidden_states, return_dict, task_ids, **kwargs)
1755 with self._enable_peft_forward_hooks(**kwargs):
1756 kwargs = {k: v for k, v in kwargs.items() if k not in self.special_peft_forward_args}
-> 1757 return self.base_model(
1758 input_ids=input_ids,
1759 attention_mask=attention_mask,
/usr/local/lib/python3.11/dist-packages/torch/nn/modules/module.py in _wrapped_call_impl(self, *args, **kwargs)
1737 return self._compiled_call_impl(*args, **kwargs) # type: ignore[misc]
1738 else:
-> 1739 return self._call_impl(*args, **kwargs)
1740
1741 # torchrec tests the code consistency with the following code
/usr/local/lib/python3.11/dist-packages/torch/nn/modules/module.py in _call_impl(self, *args, **kwargs)
1748 or _global_backward_pre_hooks or _global_backward_hooks
1749 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1750 return forward_call(*args, **kwargs)
1751
1752 result = None
/usr/local/lib/python3.11/dist-packages/peft/tuners/tuners_utils.py in forward(self, *args, **kwargs)
191
192 def forward(self, *args: Any, **kwargs: Any):
--> 193 return self.model.forward(*args, **kwargs)
194
195 def _pre_injection_hook(self, model: nn.Module, config: PeftConfig, adapter_name: str) -> None:
/kaggle/working/unsloth_compiled_cache/unsloth_compiled_module_gemma3.py in forward(self, input_ids, pixel_values, attention_mask, position_ids, past_key_values, token_type_ids, cache_position, inputs_embeds, labels, use_cache, output_attentions, output_hidden_states, return_dict, logits_to_keep, **lm_kwargs)
889 **lm_kwargs,
890 ) -> Union[tuple, Gemma3CausalLMOutputWithPast]:
--> 891 return Gemma3ForConditionalGeneration_forward(self, input_ids, pixel_values, attention_mask, position_ids, past_key_values, token_type_ids, cache_position, inputs_embeds, labels, use_cache, output_attentions, output_hidden_states, return_dict, logits_to_keep, **lm_kwargs)
892
893 def prepare_inputs_for_generation(
/kaggle/working/unsloth_compiled_cache/unsloth_compiled_module_gemma3.py in Gemma3ForConditionalGeneration_forward(self, input_ids, pixel_values, attention_mask, position_ids, past_key_values, token_type_ids, cache_position, inputs_embeds, labels, use_cache, output_attentions, output_hidden_states, return_dict, logits_to_keep, **lm_kwargs)
796 if attention_mask is not None:
797 torch._dynamo.mark_dynamic(attention_mask, 1)
--> 798 loss = unsloth_fused_ce_loss(
799 trainer = None,
800 hidden_states = _hidden_states,
/usr/local/lib/python3.11/dist-packages/unsloth_zoo/fused_losses/cross_entropy_loss.py in unsloth_fused_ce_loss(trainer, hidden_states, lm_head_weight, lm_head_bias, labels, mask, n_items, scaling, target_gb, torch_compile, overwrite, **kwargs)
360 scaling = scaler.get_scale() if scaler is not None else scaling
361 if hasattr(scaling, "get_scale"): scaling = scaling.get_scale()
--> 362 return apply_autograd_function(UnslothFusedLoss, dict(
363 loss_function = compute_fused_ce_loss,
364 hidden_states = hidden_states,
/usr/local/lib/python3.11/dist-packages/unsloth_zoo/fused_losses/cross_entropy_loss.py in apply_autograd_function(autograd, mapping)
39 def apply_autograd_function(autograd, mapping):
40 parameters, defaults = _get_mapping(autograd)
---> 41 return getattr(autograd, "apply")(*(
42 mapping.get(old_key, default) \
43 for old_key, default in zip(parameters, defaults)
/usr/local/lib/python3.11/dist-packages/torch/autograd/function.py in apply(cls, *args, **kwargs)
573 # See NOTE: [functorch vjp and autograd interaction]
574 args = _functorch.utils.unwrap_dead_wrappers(args)
--> 575 return super().apply(*args, **kwargs) # type: ignore[misc]
576
577 if not is_setup_ctx_defined:
/usr/local/lib/python3.11/dist-packages/unsloth_zoo/fused_losses/cross_entropy_loss.py in forward(ctx, loss_function, hidden_states, lm_head_weight, lm_head_bias, labels, mask, n_items, scaling, shift_labels, target_gb, torch_compile, overwrite, extra_kwargs)
300 for (grad_inputs_j, hidden_states_j, labels_j,) in \
301 zip(__grad_inputs, __shift_states, __shift_labels,):
--> 302 accumulate_chunk(
303 n_chunks = n_chunks,
304 grad_inputs_j = grad_inputs_j,
/usr/local/lib/python3.11/dist-packages/torch/_dynamo/eval_frame.py in _fn(*args, **kwargs)
572
573 try:
--> 574 return fn(*args, **kwargs)
575 finally:
576 # Restore the dynamic layer stack depth if necessary.
/usr/local/lib/python3.11/dist-packages/unsloth_zoo/fused_losses/cross_entropy_loss.py in accumulate_chunk(n_chunks, grad_inputs_j, grad_lm_head, grad_lm_head_bias, hidden_states_j, lm_head_weight, lm_head_bias, labels_j, divisor, scaling, shift_labels, **kwargs)
203 __grad_inputs = torch.chunk(grad_inputs.view(-1, hd), n_chunks, dim = 0)
204
--> 205 def accumulate_chunk(
206 n_chunks,
207 grad_inputs_j,
/usr/local/lib/python3.11/dist-packages/torch/_dynamo/eval_frame.py in _fn(*args, **kwargs)
743 )
744 try:
--> 745 return fn(*args, **kwargs)
746 finally:
747 _maybe_set_eval_frame(prior)
/usr/local/lib/python3.11/dist-packages/torch/_functorch/aot_autograd.py in forward(*runtime_args)
1182 full_args.extend(params_flat)
1183 full_args.extend(runtime_args)
-> 1184 return compiled_fn(full_args)
1185
1186 # Just for convenience
/usr/local/lib/python3.11/dist-packages/torch/_functorch/_aot_autograd/runtime_wrappers.py in runtime_wrapper(args)
321 if grad_enabled:
322 torch._C._set_grad_enabled(False)
--> 323 all_outs = call_func_at_runtime_with_args(
324 compiled_fn, args, disable_amp=disable_amp, steal_args=True
325 )
/usr/local/lib/python3.11/dist-packages/torch/_functorch/_aot_autograd/utils.py in call_func_at_runtime_with_args(f, args, steal_args, disable_amp)
124 with context():
125 if hasattr(f, "_boxed_call"):
--> 126 out = normalize_as_list(f(args))
127 else:
128 # TODO: Please remove soon
/usr/local/lib/python3.11/dist-packages/torch/_functorch/_aot_autograd/runtime_wrappers.py in inner_fn(args)
670 old_args.clear()
671
--> 672 outs = compiled_fn(args)
673
674 # Inductor cache DummyModule can return None
/usr/local/lib/python3.11/dist-packages/torch/_functorch/_aot_autograd/runtime_wrappers.py in wrapper(runtime_args)
488 )
489 return out
--> 490 return compiled_fn(runtime_args)
491
492 return wrapper
/usr/local/lib/python3.11/dist-packages/torch/_inductor/output_code.py in __call__(self, inputs)
464 assert self.current_callable is not None
465 try:
--> 466 return self.current_callable(inputs)
467 finally:
468 AutotuneCacheBundler.end_compile()
/usr/local/lib/python3.11/dist-packages/torch/_inductor/utils.py in run(new_inputs)
2126 def run(new_inputs: List[InputType]):
2127 copy_misaligned_inputs(new_inputs, inputs_to_check)
-> 2128 return model(new_inputs)
2129
2130 return run
/tmp/torchinductor_root/bz/cbz3eaqsyp6nafx4xi5bskmogxji2n3g46ifwxvmyblvoj7p5x3t.py in call(args)
406 del arg7_1
407 del buf6
--> 408 buf7 = empty_strided_cuda((262208, 2560), (2560, 1), torch.float32)
409 # Topologically Sorted Source Nodes: [_autograd_grad], Original ATen: [aten.mm]
410 extern_kernels.mm(reinterpret_tensor(buf5, (262208, s2), (1, 262208), 0), buf0, out=buf7)
OutOfMemoryError: CUDA out of memory. Tried to allocate 2.56 GiB. GPU 0 has a total capacity of 14.74 GiB of which 1.83 GiB is free. Process 2492 has 12.91 GiB memory in use. Of the allocated memory 12.67 GiB is allocated by PyTorch, and 91.94 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)
Reacted by Aphilas
Metadata
Metadata
Assignees
Labels
fixed - pending confirmationFixed, waiting for confirmation from poster
Activity
[-][Bug] Please fill in your issue title here.[/-][+][Bug] Cuda Out of Memory[/+][-][Bug] Cuda Out of Memory[/-][+][Bug] Cuda Out of Memory for fine tuning Gemma 3 (4B) model.[/+]shimmyshimmer commentedon Sep 25, 2025
I just tried training Gemma 3 4B and it worked: https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Gemma3_(4B).ipynb
Did you modify the notebook?
shubhamkurkute commentedon Sep 26, 2025
So, you tried on text which works fine on my system too, but I have concern regarding the vision when I try to run it gives me the same error.
shubhamkurkute commentedon Sep 30, 2025
So, you tried on text which works fine on my system too, but I have concern regarding the vision when I try to run it gives me the same error.
Swapnil-Kunjir commentedon Sep 30, 2025
I am also facing same problem for fine tuning of gemma3 vision as well as llama3.2 vision
rolandtannous commentedon Oct 1, 2025
we just made a pypi release today that should solve this problem.
If you have an existing environment, make sure to update it using:
if it's a new environment, simply
should work out. let us know if it does.
Swapnil-Kunjir commentedon Oct 2, 2025
tried running gemma3(4B) model for vision from you notebook present on page https://docs.unsloth.ai/get-started/fine-tuning-llms-guide/vision-fine-tuning
still got same error
rolandtannous commentedon Oct 2, 2025
Hello did you change any trainer settings like batch size? what about the context length?
or did you just run the notebook as provided by us?
Swapnil-Kunjir commentedon Oct 3, 2025
Tried as it is no changes in code whatsoever
wangxiaodong1021 commentedon Oct 3, 2025
I suspect this is mainly caused by vLLM occupying resources.
Even when I enable
fast_inferenceand set the environment variableos.environ["UNSLOTH_VLLM_STANDBY"] = "1", there’s still no way to control vLLM’s preemptive pre-allocation of GPU memory.Moreover, it seems the
gpu_memory_utilizationparameter no longer works as expected.Datta0 commentedon Oct 22, 2025
Hey @shubhamkurkute
We made a small fix just now for grpo standby patch in the unsloth main.
You can give it a try and see if that fixes your issues
You can do
pip install git+https://github.com/unslothai/unsloth.gitif you are interested in trying it outDatta0 commentedon Nov 17, 2025
Hey @shubhamkurkute I'm closing this issue as solved. If you still happen to run into the same issue, feel free to comment here and we'll be happy to help