Skip to content

Gemma2 fails saving as GGUF #785

Closed
Closed

Description

@kupletist

@danielhanchen Hi Daniel, thanks for your work!

having an error just like in the issue #275, but this time while trying to save tuned version of unsloth/gemma-2-9b-it-bnb-4bit.

model.save_pretrained_gguf("gemma_gguf_4bit", tokenizer, quantization_method = "q4_k_m")

error:

Traceback (most recent call last):
File "/content/gemma_gguf_4bit/llama.cpp/convert_hf_to_gguf.py", line 3668, in
main()
File "/content/gemma_gguf_4bit/llama.cpp/convert_hf_to_gguf.py", line 3661, in main
model_instance.write()
File "/content/gemma_gguf_4bit/llama.cpp/convert_hf_to_gguf.py", line 400, in write
self.prepare_metadata(vocab_only=False)
File "/content/gemma_gguf_4bit/llama.cpp/convert_hf_to_gguf.py", line 393, in prepare_metadata
self.set_vocab()
File "/content/gemma_gguf_4bit/llama.cpp/convert_hf_to_gguf.py", line 2514, in set_vocab
self._set_vocab_sentencepiece()
File "/content/gemma_gguf_4bit/llama.cpp/convert_hf_to_gguf.py", line 683, in _set_vocab_sentencepiece
tokens, scores, toktypes = self._create_vocab_sentencepiece()
File "/content/gemma_gguf_4bit/llama.cpp/convert_hf_to_gguf.py", line 700, in _create_vocab_sentencepiece
raise FileNotFoundError(f"File not found: {tokenizer_path}")
FileNotFoundError: File not found: gemma_gguf_4bit/tokenizer.model

RuntimeError Traceback (most recent call last)
in <cell line: 1>()
----> 1 model.save_pretrained_gguf("gemma_gguf_4bit", tokenizer, quantization_method = "q4_k_m")

1 frames
/usr/local/lib/python3.10/dist-packages/unsloth/save.py in save_to_gguf(model_type, model_dtype, is_sentencepiece, model_directory, quantization_method, first_conversion, _run_installer)
1110 )
1111 else:
-> 1112 raise RuntimeError(
1113 f"Unsloth: Quantization failed for {final_location}\n"
1114 "You might have to compile llama.cpp yourself, then run this again.\n"\

Activity

  1. danielhanchen commented on Jul 20, 2024

    @danielhanchen
    Member

    I'll investigate - thanks for reporting

  2. eliasecchig commented on Aug 22, 2024

    @eliasecchig

    +1 getting the same error with Gemma2 only models. This is not happening with LLama3

  3. eliasecchig commented on Aug 22, 2024

    @eliasecchig
  4. danielhanchen commented on Aug 24, 2024

    @danielhanchen
    Member

    Will prioritize this!

  5. kholiavko-roman commented on Sep 13, 2024

    @kholiavko-roman

    A workaround I found was to pull the tokenizer.model from HF https://huggingface.co/google/gemma-2b-it/blob/main/tokenizer.model

    @danielhanchen

    I am having the same issue with gemma2.
    Could you please clarify, do you mean to take original google model google/gemma-2b-it as a base model?

  6. kholiavko-roman commented on Sep 13, 2024

    @kholiavko-roman

    I am using gemma2 9b, and I tried to pull it from google/gemma-2-9b-it

    model, tokenizer = FastLanguageModel.from_pretrained(
        model_name = "google/gemma-2-9b-it",
        max_seq_length = max_seq_length,
        dtype = dtype,
        load_in_4bit = load_in_4bit
    )
    

    but still was not able to save fine-tuned model as GGUF.

    RuntimeError: Unsloth: Quantization failed for ./model/unsloth.Q8_0.gguf
    You might have to compile llama.cpp yourself, then run this again.
    You do not need to close this Python program. Run the following commands in a new terminal:
    You must run this in the same folder as you're saving your model.
    git clone --recursive https://github.com/ggerganov/llama.cpp
    cd llama.cpp && make clean && make all -j
    Once that's done, redo the quantization.
    
  7. kholiavko-roman commented on Sep 20, 2024

    @kholiavko-roman

    @danielhanchen any chance that this could be fixed soon?

  8. kupletist commented on Sep 26, 2024

    @kupletist
    Author

    +1...

  9. danielhanchen commented on Oct 1, 2024

    @danielhanchen
    Member
  10. kholiavko-roman commented on Oct 10, 2024

    @kholiavko-roman

    It works, thank you!

  11. kholiavko-roman commented on Oct 14, 2024

    @kholiavko-roman

    Weird, I tried before with google/gemma-2-9b-it as base model and it worked fine.

    Now my training has failed because I tried set the base model as unsloth/gemma-2-9b and I received an error while quantization:

    INFO:hf-to-gguf:output_norm.weight,                torch.bfloat16 --> F32, shape = {3584}
    INFO:hf-to-gguf:Set meta model
    INFO:hf-to-gguf:Set model parameters
    INFO:hf-to-gguf:Set model tokenizer
    Traceback (most recent call last):
      File "/content/llama.cpp/convert_hf_to_gguf.py", line 4430, in <module>
        main()
      File "/content/llama.cpp/convert_hf_to_gguf.py", line 4424, in main
        model_instance.write()
      File "/content/llama.cpp/convert_hf_to_gguf.py", line 434, in write
        self.prepare_metadata(vocab_only=False)
      File "/content/llama.cpp/convert_hf_to_gguf.py", line 427, in prepare_metadata
        self.set_vocab()
      File "/content/llama.cpp/convert_hf_to_gguf.py", line 2787, in set_vocab
        self._set_vocab_sentencepiece()
      File "/content/llama.cpp/convert_hf_to_gguf.py", line 744, in _set_vocab_sentencepiece
        tokens, scores, toktypes = self._create_vocab_sentencepiece()
      File "/content/llama.cpp/convert_hf_to_gguf.py", line 761, in _create_vocab_sentencepiece
        raise FileNotFoundError(f"File not found: {tokenizer_path}")
    FileNotFoundError: File not found: myname/myrepo/tokenizer.model
    ---------------------------------------------------------------------------
    RuntimeError                              Traceback (most recent call last)
    <ipython-input-9-128483d905ae> in <cell line: 1>()
    ----> 1 model.push_to_hub_gguf(
          2        "myname/myrepo", # Change hf to your username!
          3         tokenizer,
          4         #quantization_method = ["q5_1", "not_quantized", "fast_quantized", "quantized"],
          5         quantization_method =["q8_0", "f16"],
    
    1 frames
    /usr/local/lib/python3.10/dist-packages/unsloth/save.py in save_to_gguf(model_type, model_dtype, is_sentencepiece, model_directory, quantization_method, first_conversion, _run_installer)
       1113             )
       1114         else:
    -> 1115             raise RuntimeError(
       1116                 f"Unsloth: Quantization failed for {final_location}\n"\
       1117                 "You might have to compile llama.cpp yourself, then run this again.\n"\
    
    RuntimeError: Unsloth: Quantization failed for /content/myname/myrepo/unsloth.F16.gguf
    You might have to compile llama.cpp yourself, then run this again.
    You do not need to close this Python program. Run the following commands in a new terminal:
    You must run this in the same folder as you're saving your model.
    git clone --recursive https://github.com/ggerganov/llama.cpp
    cd llama.cpp && make clean && make all -j
    Once that's done, redo the quantization.
    
  12. danielhanchen commented on Oct 18, 2024

    @danielhanchen
    Member

    Oh so Gemma-2 Base does not work - weird I'll check

  13. danielhanchen commented on Oct 20, 2024

    @danielhanchen
    Member
  14. kholiavko-roman commented on Oct 21, 2024

    @kholiavko-roman

    Yeah, yesterday I tried unsloth/gemma-2b-it-bnb-4bit and it works okay.

  15. kholiavko-roman commented on Oct 21, 2024

    @kholiavko-roman

    Something weird is going on, I just tried to run your example received an error

    TypeError                                 Traceback (most recent call last)
    [<ipython-input-6-4a7d5b4add70>](https://localhost:8080/#) in <cell line: 5>()
          3 from unsloth import is_bfloat16_supported
          4 
    ----> 5 trainer = SFTTrainer(
          6     model = model,
          7     tokenizer = tokenizer,
    
    3 frames
    /usr/local/lib/python3.10/dist-packages/unsloth/tokenizer_utils.py in _prepare_non_packed_dataloader(self, tokenizer, dataset, dataset_text_field, max_seq_length, formatting_func, add_special_tokens, remove_unused_columns)
    
    TypeError: 'NoneType' object is not callable
    

    yesterday it worked fine.

  16. kholiavko-roman commented on Oct 21, 2024

    @kholiavko-roman

    I changed from @nightly unsloth version to
    !pip install "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
    and the previous error disappeared, but I still failed to save guff files as in my previous message :(

    INFO:hf-to-gguf:output_norm.weight,        torch.bfloat16 --> F32, shape = {2048}
    INFO:hf-to-gguf:Set meta model
    INFO:hf-to-gguf:Set model parameters
    INFO:hf-to-gguf:Set model tokenizer
    Traceback (most recent call last):
      File "/content/llama.cpp/convert_hf_to_gguf.py", line 4430, in <module>
        main()
      File "/content/llama.cpp/convert_hf_to_gguf.py", line 4424, in main
        model_instance.write()
      File "/content/llama.cpp/convert_hf_to_gguf.py", line 434, in write
        self.prepare_metadata(vocab_only=False)
      File "/content/llama.cpp/convert_hf_to_gguf.py", line 427, in prepare_metadata
        self.set_vocab()
      File "/content/llama.cpp/convert_hf_to_gguf.py", line 2736, in set_vocab
        self._set_vocab_sentencepiece()
      File "/content/llama.cpp/convert_hf_to_gguf.py", line 744, in _set_vocab_sentencepiece
        tokens, scores, toktypes = self._create_vocab_sentencepiece()
      File "/content/llama.cpp/convert_hf_to_gguf.py", line 761, in _create_vocab_sentencepiece
        raise FileNotFoundError(f"File not found: {tokenizer_path}")
    FileNotFoundError: File not found: myusername-repo/tokenizer.model
    ---------------------------------------------------------------------------
    RuntimeError                              Traceback (most recent call last)
    <ipython-input-8-51d84881c4cd> in <cell line: 8>()
          6 model.push_to_hub("myusername/test-gemma2-lora", token = "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") # Online saving
          7 
    ----> 8 model.push_to_hub_gguf(
          9        "myusername-repo", # Change hf to your username!
         10         tokenizer,
    
    1 frames
    /usr/local/lib/python3.10/dist-packages/unsloth/save.py in save_to_gguf(model_type, model_dtype, is_sentencepiece, model_directory, quantization_method, first_conversion, _run_installer)
       1118             )
       1119         else:
    -> 1120             raise RuntimeError(
       1121                 f"Unsloth: Quantization failed for {final_location}\n"\
       1122                 "You might have to compile llama.cpp yourself, then run this again.\n"\
    
    RuntimeError: Unsloth: Quantization failed for /content/myusername-repo/unsloth.F16.gguf
    You might have to compile llama.cpp yourself, then run this again.
    You do not need to close this Python program. Run the following commands in a new terminal:
    You must run this in the same folder as you're saving your model.
    git clone --recursive https://github.com/ggerganov/llama.cpp
    cd llama.cpp && make clean && make all -j
    Once that's done, redo the quantization.
    
  17. init-22 commented on Oct 22, 2024

    @init-22

    Hey there
    I tried running the above code provided by @danielhanchen in my local machine and it worked! is this problem related to colab only?

  18. kholiavko-roman commented on Oct 22, 2024

    @kholiavko-roman

    Hmmm.. probably, I just tried today but with @nightly unsloth I still not unable to run the training on the colab.

  19. init-22 commented on Oct 22, 2024

    @init-22

    yes. tried the same on colab and got the TypeError: 'NoneType' object is not callable error! I think you mentioned this can be solved with Nightly, but since this error doesnt occure in local envs probably some of the dependencies is causing the issue!

    Does it work after following the instruction in error?

    git clone --recursive https://github.com/ggerganov/llama.cpp
    cd llama.cpp && make clean && make all -j

  20. kholiavko-roman commented on Oct 23, 2024

    @kholiavko-roman

    Today I received an error TypeError: 'NoneType' object is not callable
    even with the regular, not nightly unsloth version, probably it was a new release today
    !pip install "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"

    It seems like something was broken in today's release.
    I managed to run the notebook only with prev unsloth version:
    !pip uninstall unsloth -y && pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git@1f52468"

  21. kholiavko-roman commented on Oct 23, 2024

    @kholiavko-roman

    @init-22 I tried to run

    git clone --recursive https://github.com/ggerganov/llama.cpp
    cd llama.cpp && make clean && make all -j
    

    As you suggested before saving the model, but the error is still the same, unfortunately.

    INFO:hf-to-gguf:Set model parameters
    INFO:hf-to-gguf:Set model tokenizer
    Traceback (most recent call last):
      File "/content/llama.cpp/convert_hf_to_gguf.py", line 4433, in <module>
        main()
      File "/content/llama.cpp/convert_hf_to_gguf.py", line 4427, in main
        model_instance.write()
      File "/content/llama.cpp/convert_hf_to_gguf.py", line 434, in write
        self.prepare_metadata(vocab_only=False)
      File "/content/llama.cpp/convert_hf_to_gguf.py", line 427, in prepare_metadata
        self.set_vocab()
      File "/content/llama.cpp/convert_hf_to_gguf.py", line 2787, in set_vocab
        self._set_vocab_sentencepiece()
      File "/content/llama.cpp/convert_hf_to_gguf.py", line 744, in _set_vocab_sentencepiece
        tokens, scores, toktypes = self._create_vocab_sentencepiece()
      File "/content/llama.cpp/convert_hf_to_gguf.py", line 761, in _create_vocab_sentencepiece
        raise FileNotFoundError(f"File not found: {tokenizer_path}")
    FileNotFoundError: File not found: myusername/repo/tokenizer.model
    
  22. kholiavko-roman commented on Oct 24, 2024

    @kholiavko-roman

    Today with the latest version of unsloth I finally can save my model as guff. Thank you.

  23. kholiavko-roman commented on Oct 24, 2024

    @kholiavko-roman

    But after training on my custom dataset, which I loaded from a JSON file, it failed again to save guff. Do you have any idea why?

    FileNotFoundError: File not found: username/gemma-test-gguf/tokenizer.model

  24. danielhanchen commented on Oct 27, 2024

    @danielhanchen
    Member

    @init-22 @kholiavko-roman Apologies a lot on the delay - I fixed the NoneType issue - so please update Unsloth via pip install --upgrade --no-cache-dir --no-deps unsloth

    @kholiavko-roman So it works on the first time, then fails the 2nd time for GGUF?

  25. kholiavko-roman commented on Oct 28, 2024

    @kholiavko-roman

    Thank you. I saw in Discord that the problem with NoneType was fixed.

    @kholiavko-roman So it works on the first time, then fails the 2nd time for GGUF?

    Not exactly. I tried a lot of times because I could not save my test train, and I found out that it works okay when I use the alpaca prompt from example:

    alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
    
    ### Instruction:
    {}
    
    ### Input:
    {}
    
    ### Response:
    {}"""
    
    EOS_TOKEN = tokenizer.eos_token # Must add EOS_TOKEN
    def formatting_prompts_func(examples):
        instructions = examples["instruction"]
        inputs       = examples["input"]
        outputs      = examples["output"]
        texts = []
        for instruction, input, output in zip(instructions, inputs, outputs):
            # Must add EOS_TOKEN, otherwise your generation will go on forever!
            text = alpaca_prompt.format(instruction, input, output) + EOS_TOKEN
            texts.append(text)
        return { "text" : texts, }
    pass
    
    from datasets import load_dataset
    dataset = load_dataset("yahma/alpaca-cleaned", split = "train")
    dataset = dataset.map(formatting_prompts_func, batched = True,)
    

    In this case, everything is fine, and I can save the guff.

    But if am trying to use another chat template it fails to save the GGUF

    from unsloth.chat_templates import get_chat_template
    
    tokenizer = get_chat_template(
        tokenizer,
        chat_template = "llama-3", # Supports zephyr, chatml, mistral, llama, alpaca, vicuna, vicuna_old, unsloth
        mapping = {"role" : "from", "content" : "value", "user" : "human", "assistant" : "gpt"}, # ShareGPT style
        map_eos_token = True, # Maps <|im_end|> to </s> instead
    )
    
    def formatting_prompts_func(examples):
        convos = examples["conversations"]
        texts = [tokenizer.apply_chat_template(convo, tokenize = False, add_generation_prompt = False) for convo in convos]
        return { "text" : texts, }
    pass
    
    from datasets import load_dataset
    dataset = load_dataset("philschmid/guanaco-sharegpt-style", split = "train")
    dataset = dataset.map(formatting_prompts_func, batched = True,)
    

    The most interesting thing that if I ran the alpaca_prompt first, save the model, then I can go back and edit chat template to what I want and it would be possible to save GGUF without errors. But if I tried to run the second example with llama-3 chat template first it always failed with error FileNotFoundError: File not found: username/gemma-test-gguf/tokenizer.model

    I apologize if it seems confusing at first glance, but this is what I discovered.
    It sounds like some kind of a glitch, but every time I tried on fresh instance of google colab.

  26. rolandtannous commented on Oct 15, 2025

    @rolandtannous
    Contributor

    @allohamora @elia-secchi @eliasecchig @init-22 @kholiavko-roman @kupletist

    We just pushed a major fix for llamacpp integration.

    1- Please make sure to update your local install of unsloth

    pip install --force-reinstall --no-deps unsloth-zoo unsloth
    

    If you're using a notebook on kaggle or colab, it should pull the latest version automatically.

    2- You can now use save_pretrained_gguf to quantize and save to GGUF format:

    model.save_pretrained_gguf(
                save_directory,
                tokenizer=tokenizer,
                quantization_method=quantization_method,
            )
    

    For vision/multimodal models, use tokenizer=processor

    3- You can pass it one or several quant methods (as a list):

    quantization_method = "q8_0"
    

    or

    quantization_method = ["q8_0", "q4_k_m"]
    

    We support all the quants mentioned in this page except the iq variants.

    4- If the model is supported by Ollama, it will now also automatically create a Modelfile for you that you can use to create your model in ollama using:

    ollama create model_name -f ./Modelfile
    

    5- Use push_to_hub_gguf if you want to convert to gguf and push to Huggingface Hub instead.

    6- Should work for all models supported by unsloth and ollama.

    7- It now fully supports linux debian and RPM variants. We are still testing windows (if someone has a windows machine and is on our discord channel ping me to help debug)

    Let me know how this goes for you

    Thanks!

  27. rolandtannous commented on Oct 23, 2025

    @rolandtannous
    Contributor

    Will be closing this for now as the issue has been resolved. Please make sure to follow the instructions given in my last response.

    Meanwhile , please feel free to respond if you're still having any issues.

    Thank you

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

    URGENT BUGfixed

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions