Repository navigation
Closed
Description
Gemma-3-1b-it is a text generation model. I am attempting to fine-tune it for text generation. I followed the same approach that worked for LLaMA and Qwen, but training failed. Below is the code I used:
from unsloth import FastModel
import torch
model, tokenizer = FastModel.from_pretrained(
model_name = "unsloth/gemma-3-1b-it",
max_seq_length = 2048, # Choose any for long context!
load_in_4bit = True, # 4 bit quantization to reduce memory
load_in_8bit = False, # [NEW!] A bit more accurate, uses 2x memory
full_finetuning = False, # [NEW!] We have full finetuning now!
# token = "hf_...", # use one if using gated models
)
model = FastModel.get_peft_model(
model,
finetune_vision_layers = False, # Turn off for just text!
finetune_language_layers = True, # Should leave on!
finetune_attention_modules = True, # Attention good for GRPO
finetune_mlp_modules = True, # SHould leave on always!
r = 8, # Larger = higher accuracy, but might overfit
lora_alpha = 8, # Recommended alpha == r at least
lora_dropout = 0,
bias = "none",
random_state = 3407,
)
from unsloth.chat_templates import get_chat_template
tokenizer = get_chat_template(
tokenizer,
chat_template = "gemma-3",
)
from datasets import load_dataset
dataset = load_dataset("mlabonne/FineTome-100k", split = "train")
from unsloth.chat_templates import standardize_data_formats
dataset = standardize_data_formats(dataset)
dataset = dataset.train_test_split(train_size=100, test_size=100)['train'] # make dataset smaller to test code
def apply_chat_template(examples):
texts = tokenizer.apply_chat_template(examples["conversations"], return_dict=True, max_length=6000, truncation=True, padding="max_length")
return texts
pass
dataset = dataset.map(apply_chat_template, batched = True)
from trl import SFTTrainer, SFTConfig
trainer = SFTTrainer(
model = model,
tokenizer = tokenizer,
train_dataset = dataset,
eval_dataset = None, # Can set up evaluation!
args = SFTConfig(
dataset_text_field = "text",
per_device_train_batch_size = 2,
gradient_accumulation_steps = 4, # Use GA to mimic batch size!
warmup_steps = 5,
# num_train_epochs = 1, # Set this for 1 full training run.
max_steps = 30,
learning_rate = 2e-4, # Reduce to 2e-5 for long training runs
logging_steps = 1,
optim = "adamw_8bit",
weight_decay = 0.01,
lr_scheduler_type = "linear",
seed = 3407,
report_to = "none", # Use this for WandB etc
),
)
trainer_stats = trainer.train()
This code does not work. Does anyone share a proper code. And I have a more general question, when I tokenizer the dataset.
tokenizer.apply_chat_template(examples["conversations"], return_dict=True)
the output is a dictionary containing input_ids and attention_mask. However, when I try to pass the tokenized inputs to the model using:
outputs = model(**inputs)
the process fails with the following error:
outputs = model(**inputs) #model(inputs.input_ids)#
^^^^^^^^^^^^^^^
File "/home/a14-hliu/miniconda3/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1736, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/a14-hliu/miniconda3/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1747, in _call_impl
return forward_call(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/a14-hliu/miniconda3/lib/python3.12/site-packages/accelerate/utils/operations.py", line 819, in forward
return model_forward(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/a14-hliu/miniconda3/lib/python3.12/site-packages/accelerate/utils/operations.py", line 807, in __call__
return convert_to_fp32(self.model_forward(*args, **kwargs))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/a14-hliu/miniconda3/lib/python3.12/site-packages/torch/amp/autocast_mode.py", line 44, in decorate_autocast
return func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "/home/a14-hliu/miniconda3/lib/python3.12/site-packages/peft/peft_model.py", line 1719, in forward
return self.base_model(
^^^^^^^^^^^^^^^^
File "/home/a14-hliu/miniconda3/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1736, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/a14-hliu/miniconda3/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1747, in _call_impl
return forward_call(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/a14-hliu/miniconda3/lib/python3.12/site-packages/peft/tuners/tuners_utils.py", line 197, in forward
return self.model.forward(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/a14-hliu/unsloth_compiled_cache/unsloth_compiled_module_gemma3.py", line 724, in forward
return Gemma3ForCausalLM_forward(self, input_ids, attention_mask, position_ids, past_key_values, inputs_embeds, labels, use_cache, output_attentions, output_hidden_states, return_dict, cache_position, logits_to_keep, **loss_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/a14-hliu/miniconda3/lib/python3.12/site-packages/transformers/utils/deprecation.py", line 172, in wrapped_func
return func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "/home/a14-hliu/unsloth_compiled_cache/unsloth_compiled_module_gemma3.py", line 539, in Gemma3ForCausalLM_forward
outputs = self.model(
^^^^^^^^^^^
File "/home/a14-hliu/miniconda3/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1736, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/a14-hliu/miniconda3/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1747, in _call_impl
return forward_call(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/a14-hliu/miniconda3/lib/python3.12/site-packages/transformers/models/gemma3/modeling_gemma3.py", line 730, in forward
position_embeddings_global = self.rotary_emb(hidden_states, position_ids)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/a14-hliu/miniconda3/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1736, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/a14-hliu/miniconda3/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1747, in _call_impl
return forward_call(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/a14-hliu/hl542/ControlSum_v5/unsloth_compiled_cache/unsloth_compiled_module_gemma3.py", line 214, in forward
return Gemma3RotaryEmbedding_forward(self, x, position_ids)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/a14-hliu/miniconda3/lib/python3.12/site-packages/torch/_dynamo/eval_frame.py", line 465, in _fn
return fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^
File "/home/a14-hliu/miniconda3/lib/python3.12/site-packages/torch/_dynamo/external_utils.py", line 38, in inner
@functools.wraps(fn)
File "<stringsource>", line 69, in cfunc.to_py.__Pyx_CFunc_893235__29_pydevd_sys_monitoring_cython_object__lParen__etc_to_py_4code_18instruction_offset.wrap
File "_pydevd_sys_monitoring\\_pydevd_sys_monitoring_cython.pyx", line 1702, in _pydevd_sys_monitoring_cython._start_method_event
File "_pydevd_sys_monitoring\\_pydevd_sys_monitoring_cython.pyx", line 570, in _pydevd_sys_monitoring_cython._get_func_code_info
File "_pydevd_sys_monitoring\\_pydevd_sys_monitoring_cython.pyx", line 505, in _pydevd_sys_monitoring_cython._get_code_line_info
File "/home/a14-hliu/miniconda3/lib/python3.12/site-packages/torch/_dynamo/convert_frame.py", line 1269, in __call__
return self._torchdynamo_orig_callable(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/a14-hliu/miniconda3/lib/python3.12/site-packages/torch/_dynamo/convert_frame.py", line 492, in __call__
unimplemented("generator")
File "/home/a14-hliu/miniconda3/lib/python3.12/site-packages/torch/_dynamo/exc.py", line 297, in unimplemented
raise Unsupported(msg, case_name=case_name)
torch._dynamo.exc.Unsupported: generator
This works on previous model like llama and qwen. Any insights or suggestions would be greatly appreciated!
Metadata
Metadata
Assignees
Labels
No labels
Activity
SiddharthPant commentedon Apr 5, 2025
For now temporary workaround I got was this:
You can force
apply_chat_templateto not tokenize by giving ittokenize=False.This I think is hugging face library issue because it happened for me also when I was trying to just use hugging face libs without unsloth.
But now I have issue saving the model to GGUF file.
Hyfred commentedon Apr 6, 2025
This is exactly what I was struggling with. I saw the Unsloth tutorial for training Gemma 3B—they use a same way where the input is kept as words rather than tokens. But I dont want to use this way since it sacrifices flexibility. Feeding tokens into the model feels like a more fundamental and logical approach :(
But anyway, thanks for your comment. @SiddharthPant
rolandtannous commentedon Jun 30, 2025
Hello ,
You should now be able to finetune GEmma3 as we've recently improved and revamped the Gemma3 patches
Please make sure to upgrade your installation to the latest version using
pip install --upgrade unsloth-zoo
pip install --upgrade unsloth
Also please observe the new Gemma3 vision finetuning notebook: https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Gemma3_(4B)-Vision.ipynb
There is also a gemma3 language finetuning notebook:
https://github.com/unslothai/notebooks/blob/main/nb/Gemma3_(4B).ipynb
And a Gemma3 GRPO notebook:
https://github.com/unslothai/notebooks/blob/main/nb/Gemma3_(1B)-GRPO.ipynb
Use 1B for GRPO as it is a language model
Will close this for now.
Please feel free to comment back if you are still facing the same issue after trying the above.
Thank you for using Unsloth