Skip to content

[Bug] Gemma 3n - maximum recursion depth exceeded #3650

Closed

Description

@Tacx79
  1. Did you update? pip install --upgrade unsloth unsloth_zoo - Yes
  2. Colab or Kaggle or local / cloud - local
  3. Number GPUs used, use nvidia-smi - 1
  4. Which notebook? Please link! - Some code borrowed from Gemma 3n notebook (the training seems to work there):
    https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Gemma3_(4B)-Vision.ipynb
  5. Which Unsloth version, TRL version, transformers version, PyTorch version?
    unsloth 2025.11.4
    unsloth_zoo 2025.11.5
    trl 0.23.0
    transformers 4.56.2
    torch 2.9.0
    torchao 0.14.1
    bitsandbytes 0.48.2
  6. Which trainer? SFTTrainer, GRPOTrainer etc - UnslothTrainer
import unsloth
from unsloth import FastLanguageModel, FastModel
from unsloth import UnslothTrainer, UnslothTrainingArguments
import torch
import transformers, datasets
import os

from dataloader import Data #local module

os.environ["UNSLOTH_DISABLE_AUTO_UPDATES"] = "0"
os.environ["UNSLOTH_ENABLE_FULL_FINETUNING"] = "0"

torch.set_default_dtype(torch.bfloat16)
torch.set_default_device("cuda:0")
torch._dynamo.config.recompile_limit = 64

#generator, loads paths to txt files
data = Data(dirlist = [
        "/mnt/f/_DATASETS/_curated"
    ]
)
dataset = datasets.IterableDataset(data)

model, tokenizer = FastModel.from_pretrained(
    model_name = "/mnt/f/_MODELS/[BF16]_gemma_3n_e4b_it_32k/",
    dtype = None,
    max_seq_length = 1024,
    load_in_4bit = True,
    full_finetuning = False
)

model = FastModel.get_peft_model(
    model,
    finetune_vision_layers     = False,
    finetune_language_layers   = True,
    finetune_attention_modules = True,
    finetune_mlp_modules       = True,

    r = 8,
    lora_alpha = 8,
    lora_dropout = 0,
    bias = "none",
    random_state = 42,
    use_gradient_checkpointing = True,
    max_seq_length = 1024,
    use_rslora = False
)

trainingArgs = UnslothTrainingArguments(
    embedding_learning_rate = 0.0001,
    learning_rate = 0.0002,
    lr_scheduler_type = 'cosine',
    warmup_ratio = 0.1,
    dataloader_drop_last = True,
    dataloader_pin_memory = False,
    label_smoothing_factor = 0.05,
    gradient_checkpointing = True,
    per_device_train_batch_size = 1,
    gradient_accumulation_steps = 1,
    optim = "adamw_8bit",
    weight_decay = 0.01,
    output_dir = "outputs",
    report_to = "none",
    max_steps = len(data)
)

trainer = UnslothTrainer(
    args = trainingArgs,
    model = model,
    tokenizer = tokenizer,
    dataset_text_field = "text",
    train_dataset = dataset,
    eval_dataset = None,
    max_seq_length = 1024,
    dataset_num_proc = 0,
)
trainer_stats = trainer.train()

Output:

🦥 Unsloth: Will patch your computer to enable 2x faster free finetuning.
🦥 Unsloth Zoo will now patch everything to make training faster!
==((====))==  Unsloth 2025.11.4: Fast Gemma3N patching. Transformers: 4.56.2.
   \\   /|    NVIDIA GeForce RTX 4090. Num GPUs = 1. Max memory: 23.988 GB. Platform: Linux.
O^O/ \_/ \    Torch: 2.9.0+cu128. CUDA: 8.9. CUDA Toolkit: 12.8. Triton: 3.5.0
\        /    Bfloat16 = TRUE. FA [Xformers = 0.0.33.post1. FA2 = True]
 "-____-"     Free license: http://github.com/unslothai/unsloth
Unsloth: Fast downloading is enabled - ignore downloading bars which are red colored!
Loading checkpoint shards: 100%|██████████████████████████████████████████████████████| 4/4 [01:24<00:00, 21.03s/it]
Unsloth: Making `model.base_model.model.model.language_model` require gradients
[2025-11-28 11:47:57,817] [INFO] [real_accelerator.py:219:get_accelerator] Setting ds_accelerator to cuda (auto detect)
==((====))==  Unsloth - 2x faster free finetuning | Num GPUs used = 1
   \\   /|    Num examples = 44 | Num Epochs = 9,223,372,036,854,775,807 | Total steps = 44
O^O/ \_/ \    Batch size per device = 1 | Gradient accumulation steps = 1
\        /    Data Parallel GPUs = 1 | Total batch size (1 x 1 x 1) = 1
 "-____-"     Trainable parameters = 19,210,240 of 7,869,188,432 (0.24% trained)
  0%|                                                                                        | 0/44 [00:00<?, ?it/s]Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/bitsandbytes/nn/modules.py", line 355, in __torch_function__
    @classmethod
  File "/usr/local/lib/python3.10/dist-packages/bitsandbytes/nn/modules.py", line 355, in __torch_function__        
    @classmethod
  File "/usr/local/lib/python3.10/dist-packages/bitsandbytes/nn/modules.py", line 355, in __torch_function__        
    @classmethod
  [Previous line repeated 990 more times]
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/eval_frame.py", line 1044, in _fn
    return fn(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/torch/_functorch/aot_autograd.py", line 1130, in forward
    return compiled_fn(full_args)
  File "/usr/local/lib/python3.10/dist-packages/torch/_functorch/_aot_autograd/runtime_wrappers.py", line 353, in runtime_wrapper
    all_outs = call_func_at_runtime_with_args(
  File "/usr/local/lib/python3.10/dist-packages/torch/_functorch/_aot_autograd/utils.py", line 129, in call_func_at_runtime_with_args
    out = normalize_as_list(f(args))
  File "/usr/local/lib/python3.10/dist-packages/torch/_functorch/_aot_autograd/runtime_wrappers.py", line 724, in inner_fn
    outs = compiled_fn(args)
  File "/usr/local/lib/python3.10/dist-packages/torch/_functorch/_aot_autograd/runtime_wrappers.py", line 526, in wrapper
    return compiled_fn(runtime_args)
  File "/usr/local/lib/python3.10/dist-packages/torch/_functorch/_aot_autograd/utils.py", line 103, in g
    return f(*args)
RecursionError: maximum recursion depth exceeded

Removing torch defaults from the beginning:

Traceback (most recent call last):
  File "/mnt/f/apps/_llm2/workspace/test.py", line 76, in <module>
    trainer_stats = trainer.train()
  File "/mnt/f/apps/_llm2/workspace/unsloth_compiled_cache/UnslothSFTTrainer.py", line 55, in wrapper
    output = f(self, *args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/transformers/trainer.py", line 2328, in train
    return inner_training_loop(
  File "<string>", line 323, in _fast_inner_training_loop
  File "/mnt/f/apps/_llm2/workspace/unsloth_compiled_cache/UnslothSFTTrainer.py", line 1097, in training_step       
    return super().training_step(*args, **kwargs)
  File "<string>", line 40, in _unsloth_training_step
  File "/mnt/f/apps/_llm2/workspace/unsloth_compiled_cache/UnslothSFTTrainer.py", line 1086, in compute_loss
    outputs = super().compute_loss(
  File "/usr/local/lib/python3.10/dist-packages/unsloth/models/_utils.py", line 1626, in _unsloth_pre_compute_loss  
    outputs = self._old_compute_loss(model, inputs, *args, **kwargs)
  File "<string>", line 36, in compute_loss
  File "/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py", line 1775, in _wrapped_call_impl       
    return self._call_impl(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py", line 1786, in _call_impl
    return forward_call(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/accelerate/utils/operations.py", line 814, in forward
    return model_forward(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/accelerate/utils/operations.py", line 802, in __call__
    return convert_to_fp32(self.model_forward(*args, **kwargs))
  File "/usr/local/lib/python3.10/dist-packages/torch/amp/autocast_mode.py", line 44, in decorate_autocast
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/peft/peft_model.py", line 1845, in forward
    return self.base_model(
  File "/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py", line 1775, in _wrapped_call_impl       
    return self._call_impl(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py", line 1786, in _call_impl
    return forward_call(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/peft/tuners/tuners_utils.py", line 216, in forward
    return self.model.forward(*args, **kwargs)
  File "/mnt/f/apps/_llm2/workspace/unsloth_compiled_cache/unsloth_compiled_module_gemma3n.py", line 1928, in forward
    return Gemma3nForConditionalGeneration_forward(self, input_ids, pixel_values, input_features, attention_mask, input_features_mask, position_ids, past_key_values, token_type_ids, cache_position, inputs_embeds, labels, use_cache, 
output_attentions, output_hidden_states, logits_to_keep, **lm_kwargs)
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/external_utils.py", line 196, in nonrecursive_disable_wrapper
    return fn(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/transformers/utils/generic.py", line 940, in wrapper
    output = func(self, *args, **kwargs)
  File "/mnt/f/apps/_llm2/workspace/unsloth_compiled_cache/unsloth_compiled_module_gemma3n.py", line 1745, in Gemma3nForConditionalGeneration_forward
    outputs = self.model(
  File "/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py", line 1775, in _wrapped_call_impl       
    return self._call_impl(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py", line 1786, in _call_impl
    return forward_call(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/transformers/utils/generic.py", line 940, in wrapper
    output = func(self, *args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/transformers/models/gemma3n/modeling_gemma3n.py", line 2127, in forward
    outputs = self.language_model(
  File "/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py", line 1775, in _wrapped_call_impl       
    return self._call_impl(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py", line 1786, in _call_impl
    return forward_call(*args, **kwargs)
  File "/mnt/f/apps/_llm2/workspace/unsloth_compiled_cache/unsloth_compiled_module_gemma3n.py", line 1360, in forward
    return Gemma3nTextModel_forward(self, input_ids, per_layer_inputs, attention_mask, position_ids, past_key_values, inputs_embeds, use_cache, output_attentions, output_hidden_states, cache_position, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/external_utils.py", line 196, in nonrecursive_disable_wrapper
    return fn(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/transformers/utils/generic.py", line 940, in wrapper
    output = func(self, *args, **kwargs)
  File "/mnt/f/apps/_llm2/workspace/unsloth_compiled_cache/unsloth_compiled_module_gemma3n.py", line 1238, in Gemma3nTextModel_forward
    layer_outputs = decoder_layer(
  File "/usr/local/lib/python3.10/dist-packages/transformers/modeling_layers.py", line 93, in __call__
    return self._gradient_checkpointing_func(partial(super().__call__, **kwargs), *args)
  File "/usr/local/lib/python3.10/dist-packages/torch/_compile.py", line 53, in inner
    return disable_fn(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/eval_frame.py", line 1044, in _fn
    return fn(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/torch/utils/checkpoint.py", line 496, in checkpoint
    return CheckpointFunction.apply(function, preserve, *args)
  File "/usr/local/lib/python3.10/dist-packages/torch/autograd/function.py", line 581, in apply
    return super().apply(*args, **kwargs)  # type: ignore[misc]
  File "/usr/local/lib/python3.10/dist-packages/unsloth_zoo/gradient_checkpointing.py", line 484, in forward        
    outputs = run_function(*args)
  File "/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py", line 1775, in _wrapped_call_impl       
    return self._call_impl(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py", line 1786, in _call_impl
    return forward_call(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/transformers/utils/deprecation.py", line 172, in wrapped_func       
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/transformers/models/gemma3n/modeling_gemma3n.py", line 1426, in forward
    predictions = self.altup.predict(hidden_states)
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/eval_frame.py", line 832, in compile_wrapper
    return fn(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/convert_frame.py", line 1874, in __call__
    result = self._torchdynamo_orig_backend(
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/convert_frame.py", line 688, in __call__
    result = _compile(
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/convert_frame.py", line 1433, in _compile
    guarded_code, tracer_output = compile_inner(code, one_graph, hooks)
  File "/usr/local/lib/python3.10/dist-packages/torch/_utils_internal.py", line 92, in wrapper_function
    return function(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/convert_frame.py", line 1117, in compile_inner        
    return _compile_inner(code, one_graph, hooks)
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/convert_frame.py", line 1151, in _compile_inner       
    dynamo_output = compile_frame(
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/convert_frame.py", line 1032, in compile_frame        
    bytecode, tracer_output = transform_code_object(code, transform)
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/bytecode_transformation.py", line 1592, in transform_code_object
    tracer_output = transformations(instructions, code_options)
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/convert_frame.py", line 1004, in transform
    tracer_output = trace_frame(
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/convert_frame.py", line 312, in _fn
    return fn(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/convert_frame.py", line 815, in trace_frame
    run_tracer()
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/convert_frame.py", line 797, in run_tracer
    tracer.run()
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/symbolic_convert.py", line 1487, in run
    while self.step():
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/symbolic_convert.py", line 1348, in step
    self.dispatch_table[inst.opcode](self, inst)
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/symbolic_convert.py", line 904, in wrapper
    return inner_fn(self, inst)
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/symbolic_convert.py", line 2320, in CALL_FUNCTION     
    self.call_function(fn, args, {})
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/symbolic_convert.py", line 1266, in call_function     
    self.push(fn.call_function(self, args, kwargs))  # type: ignore[arg-type]
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/variables/misc.py", line 1115, in call_function       
    return self.obj.call_method(tx, self.name, args, kwargs)
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/variables/tensor.py", line 713, in call_method        
    return wrap_fx_proxy(
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/variables/builder.py", line 2645, in wrap_fx_proxy    
    return wrap_fx_proxy_cls(target_cls=TensorVariable, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/variables/builder.py", line 2711, in wrap_fx_proxy_cls    return _wrap_fx_proxy(
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/variables/builder.py", line 2809, in _wrap_fx_proxy   
    example_value = get_fake_value(proxy.node, tx, allow_non_graph_fake=True)
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/utils.py", line 3478, in get_fake_value
    raise TorchRuntimeError(str(e)).with_traceback(e.__traceback__) from None
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/utils.py", line 3376, in get_fake_value
    ret_val = wrap_fake_exception(
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/utils.py", line 2864, in wrap_fake_exception
    return fn()
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/utils.py", line 3377, in <lambda>
    lambda: run_node(tx.output, node, args, kwargs, nnmodule)
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/utils.py", line 3587, in run_node
    raise RuntimeError(make_error_message(e)).with_traceback(
  File "/usr/local/lib/python3.10/dist-packages/torch/_dynamo/utils.py", line 3557, in run_node
    return getattr(args[0], node.target)(*args[1:], **kwargs)  # type: ignore[arg-type]
  File "/usr/local/lib/python3.10/dist-packages/torch/utils/_stats.py", line 28, in wrapper
    return fn(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/torch/_subclasses/fake_tensor.py", line 1376, in __torch_dispatch__ 
    return self.dispatch(func, types, args, kwargs)
  File "/usr/local/lib/python3.10/dist-packages/torch/_subclasses/fake_tensor.py", line 2096, in dispatch
    return self._cached_dispatch_impl(func, types, args, kwargs)
  File "/usr/local/lib/python3.10/dist-packages/torch/_subclasses/fake_tensor.py", line 1481, in _cached_dispatch_impl
    return self._dispatch_impl(func, types, args, kwargs)
  File "/usr/local/lib/python3.10/dist-packages/torch/_subclasses/fake_tensor.py", line 2755, in _dispatch_impl     
    r = func(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/torch/_ops.py", line 841, in __call__
    return self._op(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/torch/_refs/__init__.py", line 576, in _fn
    return fn(a, *args, out=a, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/torch/_prims_common/wrappers.py", line 348, in _fn
    _safe_copy_out(
  File "/usr/local/lib/python3.10/dist-packages/torch/_prims_common/wrappers.py", line 224, in _safe_copy_out       
    torch._check(
  File "/usr/local/lib/python3.10/dist-packages/torch/__init__.py", line 1695, in _check
    _check_with(RuntimeError, cond, message)
  File "/usr/local/lib/python3.10/dist-packages/torch/__init__.py", line 1677, in _check_with
    raise error_type(message_evaluated)
torch._dynamo.exc.TorchRuntimeError: Dynamo failed to run FX node with fake tensors: call_method clamp_(*(FakeTensor(..., device='cuda:0', size=(32, 1), dtype=torch.uint8), -zf37, zf37), **{}): got RuntimeError("Attempting to cast from torch.float32 to out tensor with dtype torch.uint8, but this can't be cast because it is not safe!")

from user code:
   File "/mnt/f/apps/_llm2/workspace/unsloth_compiled_cache/unsloth_compiled_module_gemma3n.py", line 819, in predict
    self.prediction_coefs.weight.data.clamp_(-self.config.altup_coef_clip, self.config.altup_coef_clip)

Set TORCHDYNAMO_VERBOSE=1 for the internal stack trace (please do this especially if you're reporting a bug to PyTorch). For even more developer context, set TORCH_LOGS="+dynamo"

Similar behavior with
unsloth-zoo 2025.9.14
unsloth 2025.9.11
pytorch 2.9.1+cu12.8
bitsandbytes 0.47.0

In addition, full finetunning seems to work with:

os.environ["UNSLOTH_ENABLE_FULL_FINETUNING"] = "1"

tokenizer = transformers.AutoTokenizer.from_pretrained("../models/test/tokenizer/")
config = transformers.Gemma3nTextConfig(dtype=torch.bfloat16, use_cache=False, attn_implementation='sdpa', vocab_size=512, vocab_size_per_layer_input=512)
model = transformers.Gemma3nForCausalLM(config)
model._saved_temp_tokenizer = tokenizer

{'loss': 6.6753, 'grad_norm': 36700160.0, 'learning_rate': 0.0, 'epoch': 0.02}

But lora training results in

os.environ["UNSLOTH_ENABLE_FULL_FINETUNING"] = "0"
model = FastLanguageModel.get_peft_model(
    model=model,
    r=8,
    lora_alpha=8,
    use_gradient_checkpointing=True,
    random_state=42,
    max_seq_length=1024,
    use_rslora=False,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
                      "gate_proj", "up_proj", "down_proj",
                      "embed_tokens", "lm_head",
                      "correction_coefs", "prediction_coefs", "modality_router",
                      "linear_left", "linear_right", "per_layer_input_gate", "per_layer_projection",
                      "embed_tokens_per_layer", "per_layer_model_projection"],
)

NotImplementedError: Unsloth: gemma3n_text is not yet implemented!

Activity

  1. mmathew23 commented on Dec 5, 2025

    @mmathew23
    Contributor

    @Tacx79 Could you try using SFTtrainer for this?

    But then the other thing I would try is using trl==0.22.2

  2. Tacx79 commented on Dec 6, 2025

    @Tacx79
    Author

    @mmathew23 both downgrading trl or/and using SFTtrainer result in the same recursion error

  3. mmathew23 commented on Dec 6, 2025

    @mmathew23
    Contributor

    @Tacx79 Does the issue reproduce if you use a the gemma3n model from huggingface.co? unsloth/gemma-3n-E2B-it

    And if you use a dataset from https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Gemma3N_(4B)-Conversational.ipynb ?

    The notebooks running fine which does both, so now I'm trying to figure out if it's an environment issue, a dataset issue, or a loading model issue.

  4. Tacx79 commented on Dec 6, 2025

    @Tacx79
    Author

    @mmathew23 yes, loading unsloth/gemma-3n-E2B-it from hub and from local dir gives the same result, same as using dataset from the notebook.

    I found that changing load_in_4bit to False fixes it and the lora training works

  5. mmathew23 commented on Dec 6, 2025

    @mmathew23
    Contributor

    https://colab.research.google.com/drive/1ESiYli-nalHvVP0dBfikrP6siRtOVc8k?usp=sharing

    @Tacx79

    This colab uses the notebooks dataset, and the model from the hub. It seems to work. So if you're more or less following this exactly then there is some sort of issue with one of the package deps in your local environment.

    Alternatively if you can edit the notebook and show how to reproduce the error there, please share.

  6. Tacx79 commented on Dec 6, 2025

    @Tacx79
    Author

    @mmathew23 in my setup forcing datatype (float16 / bfloat16 / float32) and device results in RecursionError when I load the model in 4 bits, the same as in the notebook. But when I comment out this chunk

    torch.set_default_dtype(torch.bloat16)
    torch.set_default_device("cuda:0")

    The code runs in the notebook, but fails on my local setup with the output below. I also noticed that unsloth quietly switches to float32 and converts model to float16 in the notebook but it stays on bfloat16 on my end, even when I try to force other datatypes, or don't specify them

    Notebook:
    ==((====))==  Unsloth 2025.11.6: Fast Gemma3N patching. Transformers: 4.56.2.
       \\   /|    Tesla T4. Num GPUs = 1. Max memory: 14.741 GB. Platform: Linux.
    O^O/ \_/ \    Torch: 2.9.0+cu126. CUDA: 7.5. CUDA Toolkit: 12.6. Triton: 3.5.0
    \        /    Bfloat16 = FALSE. FA [Xformers = 0.0.33.post1. FA2 = False]
     "-____-"     Free license: http://github.com/unslothai/unsloth
    Unsloth: Fast downloading is enabled - ignore downloading bars which are red colored!
    Unsloth: Using float16 precision for gemma3n won't work! Using float32.
    Loading checkpoint shards: 100%
     3/3 [00:41<00:00, 12.26s/it]
    Unsloth: Making `model.base_model.model.model.language_model` require gradients
    Unsloth: Switching to float32 training since model cannot work with float16
    
    Local setup:
    🦥 Unsloth: Will patch your computer to enable 2x faster free finetuning.
    🦥 Unsloth Zoo will now patch everything to make training faster!
    ==((====))==  Unsloth 2025.11.4: Fast Gemma3N patching. Transformers: 4.56.2.
       \\   /|    NVIDIA GeForce RTX 4090. Num GPUs = 1. Max memory: 23.988 GB. Platform: Linux.
    O^O/ \_/ \    Torch: 2.9.0+cu128. CUDA: 8.9. CUDA Toolkit: 12.8. Triton: 3.5.0
    \        /    Bfloat16 = TRUE. FA [Xformers = 0.0.33.post1. FA2 = True]
     "-____-"     Free license: http://github.com/unslothai/unsloth
    Unsloth: Fast downloading is enabled - ignore downloading bars which are red colored!
    Loading checkpoint shards: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 3/3 [00:53<00:00, 17.81s/it]
    Unsloth: Making `model.base_model.model.model.language_model` require gradients
    
    
    Unsloth: Standardizing formats (num_proc=32): 100%|████████████████████████████████████████████████████████████████████████████████████████████████| 3000/3000 [00:01<00:00, 2573.10 examples/s]
    Map: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 3000/3000 [00:00<00:00, 11302.15 examples/s]
    Unsloth: Tokenizing ["text"] (num_proc=36): 100%|███████████████████████████████████████████████████████████████████████████████████████████████████| 3000/3000 [00:16<00:00, 183.54 examples/s]
    [2025-12-06 21:00:52,854] [INFO] [real_accelerator.py:219:get_accelerator] Setting ds_accelerator to cuda (auto detect)
    ==((====))==  Unsloth - 2x faster free finetuning | Num GPUs used = 1
       \\   /|    Num examples = 3,000 | Num Epochs = 1 | Total steps = 10
    O^O/ \_/ \    Batch size per device = 1 | Gradient accumulation steps = 1
    \        /    Data Parallel GPUs = 1 | Total batch size (1 x 1 x 1) = 1
     "-____-"     Trainable parameters = 10,567,680 of 5,450,005,952 (0.19% trained)
      0%|                                                                                                                                                                    | 0/10 [00:00<?, ?it/s]
    Unsloth: Will smartly offload gradients to save VRAM!
    Traceback (most recent call last):
    (...)
    torch._dynamo.exc.TorchRuntimeError: Dynamo failed to run FX node with fake tensors: call_method clamp_(*(FakeTensor(..., device='cuda:0', size=(32, 1), dtype=torch.uint8), -zf37, zf37), **{}): got RuntimeError("Attempting to cast from torch.float32 to out tensor with dtype torch.uint8, but this can't be cast because it is not safe!")
    
    from user code:
       File "/mnt/f/apps/_llm2/workspace/unsloth_compiled_cache/unsloth_compiled_module_gemma3n.py", line 819, in predict
        self.prediction_coefs.weight.data.clamp_(-self.config.altup_coef_clip, self.config.altup_coef_clip)
    

    I'm happy with using full precision as workaround since it doesn't overflow my memory, but I can help with diagnosing it further if necessary. (Any way to disable bfloat and fa2 in unsloth?)

  7. mmathew23 commented on Dec 7, 2025

    @mmathew23
    Contributor

    @Tacx79 Could you try setting up a new venv so flash attention is disabled? It should work without setting default dtypes and devices.

    If linux based

    python -m venv .freshvenv
    source .freshvenv/bin/activate
    

    Then pip install unsloth and rerun the script.

  8. Tacx79 commented on Dec 8, 2025

    @Tacx79
    Author

    @mmathew23 same behavior

    (.freshvenv) # python3 test2.py 
    🦥 Unsloth: Will patch your computer to enable 2x faster free finetuning.
    🦥 Unsloth Zoo will now patch everything to make training faster!
    ==((====))==  Unsloth 2025.12.1: Fast Gemma3N patching. Transformers: 4.57.3.
       \\   /|    NVIDIA GeForce RTX 4090. Num GPUs = 1. Max memory: 23.988 GB. Platform: Linux.
    O^O/ \_/ \    Torch: 2.9.1+cu128. CUDA: 8.9. CUDA Toolkit: 12.8. Triton: 3.5.1
    \        /    Bfloat16 = TRUE. FA [Xformers = 0.0.33.post2. FA2 = False]
     "-____-"     Free license: http://github.com/unslothai/unsloth
    Unsloth: Fast downloading is enabled - ignore downloading bars which are red colored!
    Loading checkpoint shards: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 3/3 [01:10<00:00, 23.62s/it]
    The module name  (originally ) is not a valid Python identifier. Please rename the original module to avoid import issues.
    Unsloth: Making `model.base_model.model.model.language_model` require gradients
    The model is already on multiple devices. Skipping the move to device specified in `args`.
    ==((====))==  Unsloth - 2x faster free finetuning | Num GPUs used = 1
       \\   /|    Num examples = 44 | Num Epochs = 9,223,372,036,854,775,807 | Total steps = 44
    O^O/ \_/ \    Batch size per device = 1 | Gradient accumulation steps = 1
    \        /    Data Parallel GPUs = 1 | Total batch size (1 x 1 x 1) = 1
     "-____-"     Trainable parameters = 10,567,680 of 5,450,005,952 (0.19% trained)
      0%|                                                                                                                                                                                        | 0/44 [00:00<?, ?it/s]Unsloth: Will smartly offload gradients to save VRAM!
    Traceback (most recent call last):
      File "/mnt/f/apps/_llm2/workspace/test2.py", line 77, in <module>
        trainer_stats = trainer.train()
      File "/mnt/f/apps/_llm2/workspace/unsloth_compiled_cache/UnslothSFTTrainer.py", line 55, in wrapper
        output = f(self, *args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/transformers/trainer.py", line 2325, in train
        return inner_training_loop(
      File "<string>", line 328, in _fast_inner_training_loop
      File "/mnt/f/apps/_llm2/workspace/unsloth_compiled_cache/UnslothSFTTrainer.py", line 1082, in training_step
        return super().training_step(*args, **kwargs)
      File "<string>", line 40, in _unsloth_training_step
      File "/mnt/f/apps/_llm2/workspace/unsloth_compiled_cache/UnslothSFTTrainer.py", line 1071, in compute_loss
        outputs = super().compute_loss(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/unsloth/models/_utils.py", line 1640, in _unsloth_pre_compute_loss
        outputs = self._old_compute_loss(model, inputs, *args, **kwargs)
      File "<string>", line 36, in compute_loss
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1775, in _wrapped_call_impl
        return self._call_impl(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1786, in _call_impl
        return forward_call(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/accelerate/utils/operations.py", line 819, in forward
        return model_forward(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/accelerate/utils/operations.py", line 807, in __call__
        return convert_to_fp32(self.model_forward(*args, **kwargs))
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/amp/autocast_mode.py", line 44, in decorate_autocast
        return func(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/peft/peft_model.py", line 1923, in forward
        return self.base_model(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1775, in _wrapped_call_impl
        return self._call_impl(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1786, in _call_impl
        return forward_call(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/peft/tuners/tuners_utils.py", line 308, in forward
        return self.model.forward(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/unsloth_compiled_cache/unsloth_compiled_module_gemma3n.py", line 1925, in forward
        return Gemma3nForConditionalGeneration_forward(self, input_ids, pixel_values, input_features, attention_mask, input_features_mask, position_ids, past_key_values, token_type_ids, cache_position, inputs_embeds, labels, use_cache, output_attentions, output_hidden_states, logits_to_keep, **lm_kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/external_utils.py", line 196, in nonrecursive_disable_wrapper
        return fn(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/transformers/utils/generic.py", line 918, in wrapper
        output = func(self, *args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/unsloth_compiled_cache/unsloth_compiled_module_gemma3n.py", line 1742, in Gemma3nForConditionalGeneration_forward
        outputs = self.model(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1775, in _wrapped_call_impl
        return self._call_impl(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1786, in _call_impl
        return forward_call(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/transformers/utils/generic.py", line 918, in wrapper
        output = func(self, *args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/transformers/models/gemma3n/modeling_gemma3n.py", line 2120, in forward
        outputs = self.language_model(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1775, in _wrapped_call_impl
        return self._call_impl(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1786, in _call_impl
        return forward_call(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/unsloth_compiled_cache/unsloth_compiled_module_gemma3n.py", line 1362, in forward
        return Gemma3nTextModel_forward(self, input_ids, per_layer_inputs, attention_mask, position_ids, past_key_values, inputs_embeds, use_cache, output_attentions, output_hidden_states, cache_position, **kwargs)  
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/external_utils.py", line 196, in nonrecursive_disable_wrapper
        return fn(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/transformers/utils/generic.py", line 918, in wrapper
        output = func(self, *args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/unsloth_compiled_cache/unsloth_compiled_module_gemma3n.py", line 1240, in Gemma3nTextModel_forward
        layer_outputs = decoder_layer(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/transformers/modeling_layers.py", line 93, in __call__
        return self._gradient_checkpointing_func(partial(super().__call__, **kwargs), *args)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_compile.py", line 53, in inner
        return disable_fn(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py", line 1044, in _fn
        return fn(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/utils/checkpoint.py", line 496, in checkpoint
        return CheckpointFunction.apply(function, preserve, *args)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/autograd/function.py", line 581, in apply
        return super().apply(*args, **kwargs)  # type: ignore[misc]
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/unsloth_zoo/gradient_checkpointing.py", line 492, in forward
        outputs = run_function(*args)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1775, in _wrapped_call_impl
        return self._call_impl(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1786, in _call_impl
        return forward_call(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/transformers/utils/deprecation.py", line 172, in wrapped_func
        return func(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/transformers/models/gemma3n/modeling_gemma3n.py", line 1424, in forward
        predictions = self.altup.predict(hidden_states)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py", line 832, in compile_wrapper
        return fn(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py", line 1875, in __call__
        result = self._torchdynamo_orig_backend(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py", line 688, in __call__
        result = _compile(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py", line 1434, in _compile
        guarded_code, tracer_output = compile_inner(code, one_graph, hooks)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_utils_internal.py", line 92, in wrapper_function
        return function(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py", line 1117, in compile_inner
        return _compile_inner(code, one_graph, hooks)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py", line 1151, in _compile_inner
        dynamo_output = compile_frame(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py", line 1032, in compile_frame
        bytecode, tracer_output = transform_code_object(code, transform)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/bytecode_transformation.py", line 1592, in transform_code_object
        tracer_output = transformations(instructions, code_options)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py", line 1004, in transform
        tracer_output = trace_frame(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py", line 312, in _fn
        return fn(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py", line 815, in trace_frame
        run_tracer()
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py", line 797, in run_tracer
        tracer.run()
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 1500, in run
        while self.step():
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 1348, in step
        self.dispatch_table[inst.opcode](self, inst)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 904, in wrapper
        return inner_fn(self, inst)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 2333, in CALL_FUNCTION
        self.call_function(fn, args, {})
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 1266, in call_function
        self.push(fn.call_function(self, args, kwargs))  # type: ignore[arg-type]
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/variables/misc.py", line 1115, in call_function
        return self.obj.call_method(tx, self.name, args, kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/variables/tensor.py", line 713, in call_method
        return wrap_fx_proxy(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/variables/builder.py", line 2645, in wrap_fx_proxy
        return wrap_fx_proxy_cls(target_cls=TensorVariable, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/variables/builder.py", line 2711, in wrap_fx_proxy_cls
        return _wrap_fx_proxy(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/variables/builder.py", line 2809, in _wrap_fx_proxy
        example_value = get_fake_value(proxy.node, tx, allow_non_graph_fake=True)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/utils.py", line 3478, in get_fake_value
        raise TorchRuntimeError(str(e)).with_traceback(e.__traceback__) from None
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/utils.py", line 3376, in get_fake_value
        ret_val = wrap_fake_exception(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/utils.py", line 2864, in wrap_fake_exception
        return fn()
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/utils.py", line 3377, in <lambda>
        lambda: run_node(tx.output, node, args, kwargs, nnmodule)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/utils.py", line 3587, in run_node
        raise RuntimeError(make_error_message(e)).with_traceback(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/utils.py", line 3557, in run_node
        return getattr(args[0], node.target)(*args[1:], **kwargs)  # type: ignore[arg-type]
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/utils/_stats.py", line 28, in wrapper
        return fn(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_subclasses/fake_tensor.py", line 1376, in __torch_dispatch__
        return self.dispatch(func, types, args, kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_subclasses/fake_tensor.py", line 2096, in dispatch
        return self._cached_dispatch_impl(func, types, args, kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_subclasses/fake_tensor.py", line 1481, in _cached_dispatch_impl
        return self._dispatch_impl(func, types, args, kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_subclasses/fake_tensor.py", line 2755, in _dispatch_impl
        r = func(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_ops.py", line 841, in __call__
        return self._op(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_refs/__init__.py", line 576, in _fn
        return fn(a, *args, out=a, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_prims_common/wrappers.py", line 348, in _fn
        _safe_copy_out(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_prims_common/wrappers.py", line 224, in _safe_copy_out
        torch._check(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/__init__.py", line 1695, in _check
        _check_with(RuntimeError, cond, message)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/__init__.py", line 1677, in _check_with
        raise error_type(message_evaluated)
    torch._dynamo.exc.TorchRuntimeError: Dynamo failed to run FX node with fake tensors: call_method clamp_(*(FakeTensor(..., device='cuda:0', size=(32, 1), dtype=torch.uint8), -zf37, zf37), **{}): got RuntimeError("Attempting to cast from torch.float32 to out tensor with dtype torch.uint8, but this can't be cast because it is not safe!")
    
    from user code:
       File "/mnt/f/apps/_llm2/workspace/unsloth_compiled_cache/unsloth_compiled_module_gemma3n.py", line 821, in predict
        self.prediction_coefs.weight.data.clamp_(-self.config.altup_coef_clip, self.config.altup_coef_clip)
    
    Set TORCHDYNAMO_VERBOSE=1 for the internal stack trace (please do this especially if you're reporting a bug to PyTorch). For even more developer context, set TORCH_LOGS="+dynamo"
    
  9. mmathew23 commented on Dec 8, 2025

    @mmathew23
    Contributor

    @Tacx79 Thanks, if you could paste test.py wrapped in three backticks here I'll try to reproduce on my side.

  10. Tacx79 commented on Dec 8, 2025

    @Tacx79
    Author

    @mmathew23 it's the same code from above

    import unsloth
    from unsloth import FastLanguageModel, FastModel
    from unsloth import UnslothTrainer, UnslothTrainingArguments
    import torch
    import transformers, datasets
    import os
    
    torch._dynamo.config.recompile_limit = 64
    
    #generator, loads content of txt files and returns id, {"text": "..."}
    from dataloader import Data
    data = Data(dirlist = [
            "/mnt/f/_DATASETS/_curated"
        ]
    )
    dataset = datasets.IterableDataset(data)
    
    model, tokenizer = FastModel.from_pretrained(
        model_name = "/mnt/f/_MODELS/[BF16]_gemma_3n_e2b_it_32k_unsloth/",
        dtype = None,
        max_seq_length = 1024,
        load_in_4bit = True,
        full_finetuning = False
    )
    
    model = FastModel.get_peft_model(
        model,
        finetune_vision_layers     = False,
        finetune_language_layers   = True,
        finetune_attention_modules = True,
        finetune_mlp_modules       = True,
    
        r = 8,
        lora_alpha = 8,
        lora_dropout = 0,
        bias = "none",
        random_state = 42,
        use_gradient_checkpointing = True,
        max_seq_length = 1024,
        use_rslora = False
    )
    
    trainingArgs = UnslothTrainingArguments(
        embedding_learning_rate = 0.0001,
        learning_rate = 0.0002,
        lr_scheduler_type = 'cosine',
        warmup_ratio = 0.1,
        dataloader_drop_last = True,
        dataloader_pin_memory = False,
        label_smoothing_factor = 0.05,
        gradient_checkpointing = True,
        per_device_train_batch_size = 1,
        gradient_accumulation_steps = 1,
        optim = "adamw_8bit",
        weight_decay = 0.01,
        output_dir = "outputs",
        report_to = "none",
        max_steps = len(data)
    )
    
    trainer = UnslothTrainer(
        args = trainingArgs,
        model = model,
        tokenizer = tokenizer,
        dataset_text_field = "text",
        train_dataset = dataset,
        eval_dataset = None,
        max_seq_length = 1024,
        dataset_num_proc = 0,
    )
    trainer_stats = trainer.train()
  11. mmathew23 commented on Dec 8, 2025

    @mmathew23
    Contributor

    @Tacx79 Wait in this script what happens if you use unsloth/gemma-3n-E2B-it instead of from the mnt directory?

    Does it work? If so, then what happens if you first load from unsloth/gemma-3n-E2B-it then save it locally as /path/gemma-3n-E2B-it with

    model.save_pretrained_merged("/path/gemma-3n-E2B-it", tokenizer)
    

    Then could you try the script again with the new model path?

  12. Tacx79 commented on Dec 8, 2025

    @Tacx79
    Author

    @mmathew23 I deleted huggingface cache and tried

    model, tokenizer = FastModel.from_pretrained(
        model_name = "unsloth/gemma-3n-E2B-it",
        dtype = None,
        max_seq_length = 1024,
        load_in_4bit = True,
        full_finetuning = False
    )
    (...)
    trainer_stats = trainer.train()
    model.save_pretrained_merged("./testmodeldir/gemma-3n-E2B-it_test2", tokenizer)
    (.freshvenv) # python3 test2.py
    🦥 Unsloth: Will patch your computer to enable 2x faster free finetuning.
    🦥 Unsloth Zoo will now patch everything to make training faster!
    Dataloader got 44 examples
    ==((====))==  Unsloth 2025.12.1: Fast Gemma3N patching. Transformers: 4.57.3.
       \\   /|    NVIDIA GeForce RTX 4090. Num GPUs = 1. Max memory: 23.988 GB. Platform: Linux.
    O^O/ \_/ \    Torch: 2.9.1+cu128. CUDA: 8.9. CUDA Toolkit: 12.8. Triton: 3.5.1
    \        /    Bfloat16 = TRUE. FA [Xformers = 0.0.33.post2. FA2 = False]
     "-____-"     Free license: http://github.com/unslothai/unsloth
    Unsloth: Fast downloading is enabled - ignore downloading bars which are red colored!
    model.safetensors.index.json: 330kB [00:00, 306MB/s]
    model-00001-of-00003.safetensors: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 2.65G/2.65G [05:26<00:00, 8.11MB/s]
    model-00002-of-00003.safetensors: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 4.99G/4.99G [09:58<00:00, 8.35MB/s]
    model-00003-of-00003.safetensors: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 469M/469M [01:07<00:00, 6.96MB/s]
    Loading checkpoint shards: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 3/3 [00:02<00:00,  1.08it/s]
    generation_config.json: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 210/210 [00:00<00:00, 2.20MB/s]
    processor_config.json: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 98.0/98.0 [00:00<00:00, 951kB/s]
    chat_template.jinja: 1.63kB [00:00, 7.52MB/s]
    preprocessor_config.json: 1.09kB [00:00, 6.11MB/s]
    tokenizer_config.json: 1.20MB [00:00, 91.5MB/s]
    tokenizer.model: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 4.70M/4.70M [00:02<00:00, 2.26MB/s]
    tokenizer.json: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 33.4M/33.4M [00:03<00:00, 8.85MB/s]
    special_tokens_map.json: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 777/777 [00:00<00:00, 7.32MB/s]
    Unsloth: Making `model.base_model.model.model.language_model` require gradients
    The model is already on multiple devices. Skipping the move to device specified in `args`.
    ==((====))==  Unsloth - 2x faster free finetuning | Num GPUs used = 1
       \\   /|    Num examples = 44 | Num Epochs = 9,223,372,036,854,775,807 | Total steps = 44
    O^O/ \_/ \    Batch size per device = 1 | Gradient accumulation steps = 1
    \        /    Data Parallel GPUs = 1 | Total batch size (1 x 1 x 1) = 1
     "-____-"     Trainable parameters = 10,567,680 of 5,450,005,952 (0.19% trained)
    {'loss': 16.5807, 'grad_norm': 3285643.75, 'learning_rate': 0.0, 'epoch': 0.02}
    {'loss': 11.0012, 'grad_norm': 1715826.0, 'learning_rate': 4e-05, 'epoch': 0.05}
      5%|████████                                                                                                                                                                        | 2/44 [00:30<08:55, 12.75s/it]
    Unsloth: Will smartly offload gradients to save VRAM!
    {'loss': 7.5053, 'grad_norm': 16295.310546875, 'learning_rate': 8e-05, 'epoch': 0.07}
    {'loss': 5.5286, 'grad_norm': 2724.89111328125, 'learning_rate': 0.00012, 'epoch': 0.09}
    {'loss': 4.888, 'grad_norm': 272.74114990234375, 'learning_rate': 0.00016, 'epoch': 0.11}
    {'loss': 5.8081, 'grad_norm': 530.779541015625, 'learning_rate': 0.0002, 'epoch': 0.14}
    {'loss': 4.5153, 'grad_norm': 198.28416442871094, 'learning_rate': 0.00019967573081342103, 'epoch': 0.16}
    {'loss': 5.5131, 'grad_norm': 222.96743774414062, 'learning_rate': 0.00019870502626379127, 'epoch': 0.18}
    {'loss': 5.2202, 'grad_norm': 109.22180938720703, 'learning_rate': 0.0001970941817426052, 'epoch': 0.2}
    (...)
    {'loss': 3.5601, 'grad_norm': 31.619510650634766, 'learning_rate': 1.2949737362087156e-06, 'epoch': 0.98}
    {'loss': 3.339, 'grad_norm': 15.82259464263916, 'learning_rate': 3.2426918657900704e-07, 'epoch': 1.0}
    {'train_runtime': 78.7999, 'train_samples_per_second': 0.558, 'train_steps_per_second': 0.558, 'train_loss': 4.790641475807536, 'epoch': 1.0}
    100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 44/44 [01:18<00:00,  1.79s/it]
    config.json: 4.30kB [00:00, 726kB/s]
    Found HuggingFace hub cache directory: /root/.cache/huggingface/hub
    model.safetensors.index.json: 159kB [00:00, 106MB/s]
    Checking cache directory for required files...
    Cache check failed: model-00001-of-00003.safetensors not found in local cache.
    Not all required files found in cache. Will proceed with downloading.
    Checking cache directory for required files...
    Cache check failed: tokenizer.model not found in local cache.
    Not all required files found in cache. Will proceed with downloading.
    model-00001-of-00003.safetensors: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 3.08G/3.08G [06:04<00:00, 8.45MB/s]
    model-00002-of-00003.safetensors: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 4.98G/4.98G [09:58<00:00, 8.33MB/s]
    model-00003-of-00003.safetensors: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 2.82G/2.82G [05:50<00:00, 8.05MB/s]
    Unsloth: Preparing safetensor model files: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 3/3 [21:55<00:00, 438.62s/it]
    Unsloth: Merging weights into 16bit: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 3/3 [05:56<00:00, 118.99s/it]
    Unsloth: Merge process complete. Saved to `/mnt/f/apps/_llm2/workspace/testmodeldir/gemma-3n-E2B-it_test2`
    

    Then I tried again with the saved model

    model, tokenizer = FastModel.from_pretrained(
        model_name = "./testmodeldir/gemma-3n-E2B-it_test2",
        dtype = None,
        max_seq_length = 1024,
        load_in_4bit = True,
        full_finetuning = False
    )
    Traceback (most recent call last):
      File "/mnt/f/apps/_llm2/workspace/test2.py", line 83, in <module>
        trainer_stats = trainer.train()
      File "/mnt/f/apps/_llm2/workspace/unsloth_compiled_cache/UnslothSFTTrainer.py", line 55, in wrapper
        output = f(self, *args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/transformers/trainer.py", line 2325, in train
        return inner_training_loop(
      File "<string>", line 328, in _fast_inner_training_loop
      File "/mnt/f/apps/_llm2/workspace/unsloth_compiled_cache/UnslothSFTTrainer.py", line 1082, in training_step
        return super().training_step(*args, **kwargs)
      File "<string>", line 40, in _unsloth_training_step
      File "/mnt/f/apps/_llm2/workspace/unsloth_compiled_cache/UnslothSFTTrainer.py", line 1071, in compute_loss
        outputs = super().compute_loss(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/unsloth/models/_utils.py", line 1640, in _unsloth_pre_compute_loss
        outputs = self._old_compute_loss(model, inputs, *args, **kwargs)
      File "<string>", line 36, in compute_loss
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1775, in _wrapped_call_impl
        return self._call_impl(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1786, in _call_impl
        return forward_call(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/accelerate/utils/operations.py", line 819, in forward
        return model_forward(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/accelerate/utils/operations.py", line 807, in __call__
        return convert_to_fp32(self.model_forward(*args, **kwargs))
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/amp/autocast_mode.py", line 44, in decorate_autocast
        return func(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/peft/peft_model.py", line 1923, in forward
        return self.base_model(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1775, in _wrapped_call_impl
        return self._call_impl(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1786, in _call_impl
        return forward_call(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/peft/tuners/tuners_utils.py", line 308, in forward
        return self.model.forward(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/unsloth_compiled_cache/unsloth_compiled_module_gemma3n.py", line 1925, in forward
        return Gemma3nForConditionalGeneration_forward(self, input_ids, pixel_values, input_features, attention_mask, input_features_mask, position_ids, past_key_values, token_type_ids, cache_position, inputs_embeds, labels, use_cache, output_attentions, output_hidden_states, logits_to_keep, **lm_kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/external_utils.py", line 196, in nonrecursive_disable_wrapper
        return fn(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/transformers/utils/generic.py", line 918, in wrapper
        output = func(self, *args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/unsloth_compiled_cache/unsloth_compiled_module_gemma3n.py", line 1742, in Gemma3nForConditionalGeneration_forward
        outputs = self.model(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1775, in _wrapped_call_impl
        return self._call_impl(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1786, in _call_impl
        return forward_call(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/transformers/utils/generic.py", line 918, in wrapper
        output = func(self, *args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/transformers/models/gemma3n/modeling_gemma3n.py", line 2120, in forward
        outputs = self.language_model(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1775, in _wrapped_call_impl
        return self._call_impl(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1786, in _call_impl
        return forward_call(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/unsloth_compiled_cache/unsloth_compiled_module_gemma3n.py", line 1362, in forward
        return Gemma3nTextModel_forward(self, input_ids, per_layer_inputs, attention_mask, position_ids, past_key_values, inputs_embeds, use_cache, output_attentions, output_hidden_states, cache_position, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/external_utils.py", line 196, in nonrecursive_disable_wrapper
        return fn(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/transformers/utils/generic.py", line 918, in wrapper
        output = func(self, *args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/unsloth_compiled_cache/unsloth_compiled_module_gemma3n.py", line 1240, in Gemma3nTextModel_forward
        layer_outputs = decoder_layer(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/transformers/modeling_layers.py", line 93, in __call__
        return self._gradient_checkpointing_func(partial(super().__call__, **kwargs), *args)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_compile.py", line 53, in inner
        return disable_fn(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py", line 1044, in _fn
        return fn(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/utils/checkpoint.py", line 496, in checkpoint
        return CheckpointFunction.apply(function, preserve, *args)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/autograd/function.py", line 581, in apply
        return super().apply(*args, **kwargs)  # type: ignore[misc]
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/unsloth_zoo/gradient_checkpointing.py", line 492, in forward
        outputs = run_function(*args)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1775, in _wrapped_call_impl
        return self._call_impl(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1786, in _call_impl
        return forward_call(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/transformers/utils/deprecation.py", line 172, in wrapped_func
        return func(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/transformers/models/gemma3n/modeling_gemma3n.py", line 1424, in forward
        predictions = self.altup.predict(hidden_states)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py", line 832, in compile_wrapper
        return fn(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py", line 1875, in __call__
        result = self._torchdynamo_orig_backend(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py", line 688, in __call__
        result = _compile(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py", line 1434, in _compile
        guarded_code, tracer_output = compile_inner(code, one_graph, hooks)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_utils_internal.py", line 92, in wrapper_function
        return function(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py", line 1117, in compile_inner
        return _compile_inner(code, one_graph, hooks)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py", line 1151, in _compile_inner
        dynamo_output = compile_frame(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py", line 1032, in compile_frame
        bytecode, tracer_output = transform_code_object(code, transform)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/bytecode_transformation.py", line 1592, in transform_code_object
        tracer_output = transformations(instructions, code_options)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py", line 1004, in transform
        tracer_output = trace_frame(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py", line 312, in _fn
        return fn(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py", line 815, in trace_frame
        run_tracer()
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py", line 797, in run_tracer
        tracer.run()
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 1500, in run
        while self.step():
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 1348, in step
        self.dispatch_table[inst.opcode](self, inst)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 904, in wrapper
        return inner_fn(self, inst)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 2333, in CALL_FUNCTION
        self.call_function(fn, args, {})
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py", line 1266, in call_function
        self.push(fn.call_function(self, args, kwargs))  # type: ignore[arg-type]
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/variables/misc.py", line 1115, in call_function
        return self.obj.call_method(tx, self.name, args, kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/variables/tensor.py", line 713, in call_method
        return wrap_fx_proxy(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/variables/builder.py", line 2645, in wrap_fx_proxy
        return wrap_fx_proxy_cls(target_cls=TensorVariable, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/variables/builder.py", line 2711, in wrap_fx_proxy_cls
        return _wrap_fx_proxy(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/variables/builder.py", line 2809, in _wrap_fx_proxy
        example_value = get_fake_value(proxy.node, tx, allow_non_graph_fake=True)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/utils.py", line 3478, in get_fake_value
        raise TorchRuntimeError(str(e)).with_traceback(e.__traceback__) from None
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/utils.py", line 3376, in get_fake_value
        ret_val = wrap_fake_exception(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/utils.py", line 2864, in wrap_fake_exception
        return fn()
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/utils.py", line 3377, in <lambda>
        lambda: run_node(tx.output, node, args, kwargs, nnmodule)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/utils.py", line 3587, in run_node
        raise RuntimeError(make_error_message(e)).with_traceback(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_dynamo/utils.py", line 3557, in run_node
        return getattr(args[0], node.target)(*args[1:], **kwargs)  # type: ignore[arg-type]
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/utils/_stats.py", line 28, in wrapper
        return fn(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_subclasses/fake_tensor.py", line 1376, in __torch_dispatch__
        return self.dispatch(func, types, args, kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_subclasses/fake_tensor.py", line 2096, in dispatch
        return self._cached_dispatch_impl(func, types, args, kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_subclasses/fake_tensor.py", line 1481, in _cached_dispatch_impl
        return self._dispatch_impl(func, types, args, kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_subclasses/fake_tensor.py", line 2755, in _dispatch_impl
        r = func(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_ops.py", line 841, in __call__
        return self._op(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_refs/__init__.py", line 576, in _fn
        return fn(a, *args, out=a, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_prims_common/wrappers.py", line 348, in _fn
        _safe_copy_out(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/_prims_common/wrappers.py", line 224, in _safe_copy_out
        torch._check(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/__init__.py", line 1695, in _check
        _check_with(RuntimeError, cond, message)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/__init__.py", line 1677, in _check_with
        raise error_type(message_evaluated)
    torch._dynamo.exc.TorchRuntimeError: Dynamo failed to run FX node with fake tensors: call_method clamp_(*(FakeTensor(..., device='cuda:0', size=(32, 1), dtype=torch.uint8), -zf37, zf37), **{}): got RuntimeError("Attempting to cast from torch.float32 to out tensor with dtype torch.uint8, but this can't be cast because it is not safe!")
    
    from user code:
       File "/mnt/f/apps/_llm2/workspace/unsloth_compiled_cache/unsloth_compiled_module_gemma3n.py", line 821, in predict
        self.prediction_coefs.weight.data.clamp_(-self.config.altup_coef_clip, self.config.altup_coef_clip)
    
    Set TORCHDYNAMO_VERBOSE=1 for the internal stack trace (please do this especially if you're reporting a bug to PyTorch). For even more developer context, set TORCH_LOGS="+dynamo"
    

    I also checked saving the model without training and merging

    model, tokenizer = FastModel.from_pretrained(
        model_name = "unsloth/gemma-3n-E2B-it",
        dtype = None,
        max_seq_length = 1024,
        load_in_4bit = True,
        full_finetuning = False
    )
    model.save_pretrained("./testmodeldir/gemma-3n-E2B-it_test")
    tokenizer.save_pretrained("./testmodeldir/gemma-3n-E2B-it_test")
    model, tokenizer = FastModel.from_pretrained(
        model_name = "./testmodeldir/gemma-3n-E2B-it_test",
        dtype = None,
        max_seq_length = 1024,
        load_in_4bit = True,
        full_finetuning = False
    )
    Loading checkpoint shards: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 3/3 [00:38<00:00, 12.95s/it]Traceback (most recent call last):
      File "/mnt/f/apps/_llm2/workspace/test2.py", line 24, in <module>
        model, tokenizer = FastModel.from_pretrained(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/unsloth/models/loader.py", line 1154, in from_pretrained
        model, tokenizer = FastBaseModel.from_pretrained(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/unsloth/models/vision.py", line 661, in from_pretrained
        model = auto_model.from_pretrained(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/transformers/models/auto/auto_factory.py", line 604, in from_pretrained
        return model_class.from_pretrained(
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/transformers/modeling_utils.py", line 277, in _wrapper
        return func(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/transformers/modeling_utils.py", line 5140, in from_pretrained
        dispatch_model(model, **device_map_kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/accelerate/big_modeling.py", line 502, in dispatch_model
        model.to(device)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/transformers/modeling_utils.py", line 4343, in to
        return super().to(*args, **kwargs)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1371, in to
        return self._apply(convert)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 930, in _apply
        module._apply(fn)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 930, in _apply
        module._apply(fn)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 930, in _apply
        module._apply(fn)
      [Previous line repeated 3 more times]
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 957, in _apply
        param_applied = fn(param)
      File "/mnt/f/apps/_llm2/workspace/.freshvenv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1364, in convert
        raise NotImplementedError(
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty() instead of torch.nn.Module.to() when moving module from meta to a different device.
    

    Then I tried inference only on the trained model, loaded in 4 bit again

    model, tokenizer = FastModel.from_pretrained(
        model_name = "./testmodeldir/gemma-3n-E2B-it_test",
        dtype = None,
        max_seq_length = 1024,
        load_in_4bit = True,
        full_finetuning = False
    )
    generateSample(model, tokenizer)

    and got the same error

    torch._dynamo.exc.TorchRuntimeError: Dynamo failed to run FX node with fake tensors: call_method clamp_(*(FakeTensor(..., device='cuda:0', size=(8, 1), dtype=torch.uint8), -zf37, zf37), **{}): got RuntimeError("Attempting to cast from torch.float32 to out tensor with dtype torch.uint8, but this can't be cast because it is not safe!")
    

    but

    model, tokenizer = FastModel.from_pretrained(
        model_name = "./testmodeldir/gemma-3n-E2B-it_test2",
        dtype = None,
        max_seq_length = 1024,
        load_in_4bit = False,
        full_finetuning = False
    )
    generateSample(model, tokenizer)
    Loading checkpoint shards: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 3/3 [00:51<00:00, 17.32s/it]
    <bos>Helloworld!
    
    This is a test message to see if the system is working correctly.
    
    I hope this 
    message reaches you.
    
    Let me know if you need anything
    

    I checked huggingface cache and noticed that unsloth/gemma-3n-E2B-it | load_in_4bit downloads unsloth/gemma-3n-E2B-it-unsloth-bnb-4bit, then to save it with adapter it downloads actual unsloth/gemma-3n-E2B-it, could it be that load_in_4bit expects the model to be in 4 bit already?

  13. danielhanchen commented on Sep 9, 2026

    @danielhanchen
    Member

    Fixed! bitsandbytes' Params4bit torch_function was recursing into itself under AOT autograd, we strip it at import now.

    Please update Unsloth: uv pip install --upgrade unsloth unsloth_zoo --force-reinstall --no-cache-dir (if it's not in the current release yet it'll be in the next one). Reopen if it still happens!

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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions