Skip to content

[Bug] Unable to export models on Google Colab #2478

Closed

Description

@Sweaterdog

Description
When I run the following code:

if True:
    model.push_to_hub_gguf(
        "my/Repo",
        tokenizer,
        quantization_method = ["q4_k_m", "q8_0", "q5_k_m",],
        token = "hf_myTokenIputHere",
    )
  1. Environment Setup:
    • Google Colab
    • Environment setup:
%%capture
import os
if "COLAB_" not in "".join(os.environ.keys()):
    !pip install unsloth
else:
    # Do this only in Colab notebooks! Otherwise use pip install unsloth
    !pip install --no-deps bitsandbytes accelerate xformers==0.0.29.post3 peft trl==0.15.2 triton cut_cross_entropy unsloth_zoo
    !pip install sentencepiece protobuf datasets huggingface_hub hf_transfer
    !pip install --no-deps unsloth
  1. Dataset Details:
    • Dataset Name: Sweaterdog/Andy-4-FT
    • Data Preprocessing Steps: ChatML setup, with ShareGPT style dataset
# Load the first dataset and map it to the ShareGPT format
from unsloth.chat_templates import get_chat_template

tokenizer = get_chat_template(
    tokenizer,
    chat_template = "chatml", # 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("Sweaterdog/Andy-4-FT", split = "train")
dataset = dataset.map(formatting_prompts_func, batched = True,)
  1. Model Details:

    • Model ID: unsloth/llava-v1.6-mistral-7b-hf-bnb-4bit
    • Model Configuration: Only fine tuning text layer. LoRA rank of 32, LoRA alpha of 128
  2. Training Configuration:

    • Trainer Args: SFTConfig
from transformers import TrainingArguments
from trl import SFTTrainer
from unsloth import is_bfloat16_supported

trainer = SFTTrainer(
   model=model,
   tokenizer=tokenizer,
   train_dataset=dataset,
   dataset_text_field="text",
   max_seq_length=max_seq_length,
   dataset_num_proc=6,            # Increase CPU processing for faster data loading/preprocessing
   packing=False,
   args=TrainingArguments(
       per_device_train_batch_size=2,
       gradient_accumulation_steps=2,
       warmup_ratio = 0.1,
       num_train_epochs=0.05,
       learning_rate=4e-5,
       fp16= not is_bfloat16_supported(),
       bf16= is_bfloat16_supported(),
       logging_steps= 100,
       optim="adamw_8bit",
       weight_decay=0.01,
       lr_scheduler_type="cosine",
       seed=3407,
       output_dir = "outputs",
       save_steps = 5000,
   ),
)
  1. Reproduction Steps:

  2. Expected Behavior:

    • Save the model to huggingface, instead of producing an error.
  3. Actual Behavior:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-bfda09c104fc> in <cell line: 0>()
     1 if True:
----> 2     model.push_to_hub_gguf(
     3         "Sweaterdog/llava-GGUF",
     4         tokenizer,
     5         quantization_method = ["q4_k_m", "q8_0", "q5_k_m",],

/usr/local/lib/python3.11/dist-packages/torch/utils/_contextlib.py in decorate_context(*args, **kwargs)
   114     def decorate_context(*args, **kwargs):
   115         with ctx_factory():
--> 116             return func(*args, **kwargs)
   117 
   118     return decorate_context

TypeError: save_to_gguf_generic() got an unexpected keyword argument 'quantization_method'
  1. Additional notes:
    • This same code worked in the past, then it didn't, then it did work for a bit, and now it doesn't.

Activity

  1. Sweaterdog commented on May 5, 2025

    @Sweaterdog
    Author

    I should note I was able to get the code to get further on my PC, running Linux Mint, but it got this error, of which said to report immediately.

    make: Entering directory '/home/sweaterdog/Desktop/Python Projects/Unsloth PPO/llama.cpp'
    make: Leaving directory '/home/sweaterdog/Desktop/Python Projects/Unsloth PPO/llama.cpp'
    Makefile:2: *** The Makefile build is deprecated. Use the CMake build instead. For more details, see https://github.com/ggml-org/llama.cpp/blob/master/docs/build.md.  Stop.
    sh: 1: cmake: not found
    ---------------------------------------------------------------------------
    RuntimeError                              Traceback (most recent call last)
    Cell In[17], line 2
          1 if True:
    ----> 2     model.push_to_hub_gguf(
          3         "Sweaterdog/Andy-4-micro",
          4         tokenizer,
          5         quantization_method = ["f16", "q8_0", "q5_k_m",],
          6         token = "hf_haHaIReplacedMyToken", # Get a token at https://huggingface.co/settings/tokens
          7     )
    
    File ~/Desktop/Python Projects/Unsloth PPO/.venv/lib/python3.12/site-packages/unsloth/save.py:1984, in unsloth_push_to_hub_gguf(self, repo_id, tokenizer, quantization_method, first_conversion, use_temp_dir, commit_message, private, token, max_shard_size, create_pr, safe_serialization, revision, commit_description, tags, temporary_location, maximum_memory_usage)
       1982 python_install = install_python_non_blocking(["gguf", "protobuf"])
       1983 git_clone.wait()
    -> 1984 makefile = install_llama_cpp_make_non_blocking()
       1985 new_save_directory, old_username = unsloth_save_model(**arguments)
       1986 python_install.wait()
    
    File ~/Desktop/Python Projects/Unsloth PPO/.venv/lib/python3.12/site-packages/unsloth/save.py:786, in install_llama_cpp_make_non_blocking()
        784 check = os.system("cmake llama.cpp -B llama.cpp/build -DBUILD_SHARED_LIBS=OFF -DGGML_CUDA=OFF -DLLAMA_CURL=ON")
        785 if check != 0:
    --> 786     raise RuntimeError(f"*** Unsloth: Failed compiling llama.cpp using os.system(...) with error {check}. Please report this ASAP!")
        787 pass
        788 # f"cmake --build llama.cpp/build --config Release -j{psutil.cpu_count()*2} --clean-first --target {' '.join(LLAMA_CPP_TARGETS)}",
    
    RuntimeError: *** Unsloth: Failed compiling llama.cpp using os.system(...) with error 32512. Please report this ASAP!
    
  2. edoproch commented on May 7, 2025

    @edoproch

    Hi @Sweaterdog! On colab I think that you can try with

    model.save_pretrained_gguf(
    save_directory = "folder_name",
    quantization_type='Q8_0')

    (add repo id and token to push on HF)

  3. Sweaterdog commented on May 7, 2025

    @Sweaterdog
    Author

    I've tried that too, but to no avail. For me, exporting GGUF files to Huggingface just does not work.

  4. edoproch commented on May 7, 2025

    @edoproch

    @Sweaterdog Yesterday I wrote on discord to one of the developers. He said that they are working to implement into unsloth the new classes of llama.cpp
    I guess we have to be a little patient

  5. Jordinia commented on May 12, 2025

    @Jordinia

    I have the same issue. I have finished training Qwen3 4B and Llama 3.2 3B but I have not found a way to export to GGUF. I don't know if its my skill issue but I tried on almost everything it does not work.

    Hardware config I have tried out:

    • Arch Linux (3090Ti)
    • Ubuntu (4090)
    • Windows & WSL (3090)

    When I run model.save_pretrained_gguf here is the error I got (on Windows, different error on WSL Ubuntu and Arch):
    Windows

    ---------------------------------------------------------------------------
    RuntimeError                              Traceback (most recent call last)
    Cell In[3], line 1
    ----> 1 model.save_pretrained_gguf(
          2     "model/netpro-qwen3-0505-fp16-gguf",
          3     tokenizer,
          4     quantization_method = "f16",  # or "q4_k_m" for quantization
          5 )
    
    File c:\Users\rizky\.conda\envs\unsloth\Lib\site-packages\unsloth\save.py:1806, in unsloth_save_pretrained_gguf(self, save_directory, tokenizer, quantization_method, first_conversion, push_to_hub, token, private, is_main_process, state_dict, save_function, max_shard_size, safe_serialization, variant, save_peft_format, tags, temporary_location, maximum_memory_usage)
       1804 python_install = install_python_non_blocking(["gguf", "protobuf"])
       1805 git_clone.wait()
    -> 1806 makefile = install_llama_cpp_make_non_blocking()
       1807 new_save_directory, old_username = unsloth_save_model(**arguments)
       1808 python_install.wait()
    
    File c:\Users\rizky\.conda\envs\unsloth\Lib\site-packages\unsloth\save.py:786, in install_llama_cpp_make_non_blocking()
        784 check = os.system("cmake llama.cpp -B llama.cpp/build -DBUILD_SHARED_LIBS=OFF -DGGML_CUDA=OFF -DLLAMA_CURL=ON")
        785 if check != 0:
    --> 786     raise RuntimeError(f"*** Unsloth: Failed compiling llama.cpp using os.system(...) with error {check}. Please report this ASAP!")
        787 pass
        788 # f"cmake --build llama.cpp/build --config Release -j{psutil.cpu_count()*2} --clean-first --target {' '.join(LLAMA_CPP_TARGETS)}",
    
    RuntimeError: *** Unsloth: Failed compiling llama.cpp using os.system(...) with error 1. Please report this ASAP!
    

    Arch

    ---------------------------------------------------------------------------
    RuntimeError                              Traceback (most recent call last)
    Cell In[2], line 1
    ----> 1 model.save_pretrained_gguf(
          2     "model/netpro-qwen3-0505-fp16-gguf",
          3     tokenizer,
          4     quantization_method = "f16",  # or "q4_k_m" for quantization
          5 )
    
    File ~/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/unsloth/save.py:1857, in unsloth_save_pretrained_gguf(self, save_directory, tokenizer, quantization_method, first_conversion, push_to_hub, token, private, is_main_process, state_dict, save_function, max_shard_size, safe_serialization, variant, save_peft_format, tags, temporary_location, maximum_memory_usage)
       1854 is_sentencepiece_model = check_if_sentencepiece_model(self)
       1856 # Save to GGUF
    -> 1857 all_file_locations, want_full_precision = save_to_gguf(
       1858     model_type, model_dtype, is_sentencepiece_model,
       1859     new_save_directory, quantization_method, first_conversion, makefile,
       1860 )
       1862 # Save Ollama modelfile
       1863 modelfile = create_ollama_modelfile(tokenizer, all_file_locations[0])
    
    File ~/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/unsloth/save.py:1086, in save_to_gguf(model_type, model_dtype, is_sentencepiece, model_directory, quantization_method, first_conversion, _run_installer)
       1084     quantize_location = "llama.cpp/llama-quantize"
       1085 else:
    -> 1086     raise RuntimeError(
       1087         "Unsloth: The file ('llama.cpp/llama-quantize' or 'llama.cpp/llama-quantize.exe' if you are on Windows WSL) or 'llama.cpp/quantize' does not exist.\n"\
       1088         "But we expect this file to exist! Maybe the llama.cpp developers changed the name or check extension of the llama-quantize file."
       1089     )
       1090 pass
       1092 # See https://github.com/unslothai/unsloth/pull/730
       1093 # Filenames changed again!
    
    RuntimeError: Unsloth: The file ('llama.cpp/llama-quantize' or 'llama.cpp/llama-quantize.exe' if you are on Windows WSL) or 'llama.cpp/quantize' does not exist.
    But we expect this file to exist! Maybe the llama.cpp developers changed the name or check extension of the llama-quantize file.
    

    I remember getting the similar TypeError: save_to_gguf_generic() got an unexpected keyword argument 'quantization_method' previously.

    I did able to export lora adapter using

    model.save_pretrained(config.get('lora_model', 'outputs'))
    tokenizer.save_pretrained(config.get('lora_model', 'outputs'))
    

    and I can reload it consistently using this code:

    from unsloth import FastLanguageModel
    from peft import PeftModel
    import torch
    import re
    import json
    
    model, tokenizer = FastLanguageModel.from_pretrained(
        model_name = "unsloth/Qwen3-4B-unsloth-bnb-4bit",  # Must match training
        max_seq_length = 30000, 
        load_in_4bit = True,   
        device_map = "auto",
    )
    
    model = PeftModel.from_pretrained(
        model,
        model_id = "model/netpro-qwen3-0505-lora",
        adapter_name = "web_classifier",
        is_trainable = False,  # Crucial for inference
    )
    
    # 3. Merge and optimize (reduces VRAM by ~30%)
    model = model.merge_and_unload()
    

    and if I want to inference, I can just call model = FastLanguageModel.for_inference(model) and try inference as usual.

    The problem comes when I try to convert to GGUF to test it on Ollama. model.save_pretrained_gguf("dir", tokenizer, quantization_method = "f16") does not work anywhere I tried, and I'm unable to replicate it in Google Colab since the default Nvidia T4 does not support BF16. I do follow the tutorial to manually save GGUF by using llama.cpp (building llama.cpp is horrible on WIndows) but I managed to run something like this:

    model.save_pretrained_merged("model/netpro-qwen3-0505-fp16-hf", tokenizer, save_method = "merged_16bit",)
    !python "C:\Users\user\Documents\Projects\llama.cpp\convert_hf_to_gguf.py" model\netpro-qwen3-0505-fp16-hf --outfile qwen3-0505-fp16.gguf --outtype f16
    

    I tried loading it to Ollama and running directly on llama.cpp but the result is bad, and I think the model corrupted in the process of either saving to hf or converting to GGUF. I don't know what configuration I'm missing or since I'm training with 4bit should I change the save_method or quantization I'm also not sure. Any help would be much appreciated.🙏

  6. rolandtannous commented on Jun 8, 2025

    @rolandtannous
    Contributor

    @Sweaterdog we're currently fixing this. meanwhile , push_to_hub() or if you need to merge push_to_hub_merged()

  7. github-actions commented on Jul 1, 2025

    @github-actions
    Contributor

    Is this issue still important to you? Apologies in advance we might have missed this issue as well. For faster response times, please post on our Reddit server - https://www.reddit.com/r/unsloth or our Discord - https://discord.com/invite/unsloth

  8. Padmanaba231 commented on Jul 17, 2025

    @Padmanaba231

    i still have the same problem.

    when i tried run:
    model.save_pretrained_gguf("ocr_model", tokenizer, quantization_method="f16")

    i always get error:
    TypeError: save_to_gguf_generic() got an unexpected keyword argument 'quantization_method'. i am confused, i just follow the tutorial in documentation and its cleary instruct to use argument quantization_method. Is theres a way to fix this?

  9. rolandtannous commented on Jul 17, 2025

    @rolandtannous
    Contributor

    @Padmanaba231

    we still have not yet fixed save_pretrained_gguf,
    sorry for the bot. It was an experiment. We stopped it and I removed the inactive tag.

  10. Sweaterdog commented on Jul 17, 2025

    @Sweaterdog
    Author

    Totally fine, thanks for fixing the exports! It has been a huge bummer to not be able to export any of my models.

  11. wooihaw commented on Jul 24, 2025

    @wooihaw

    I am facing an error when running the following in Google Colab:
    model.save_pretrained_gguf("custom_gemma3_1b_q_8", tokenizer, quantization_method = "q8_0")

    Error:
    TypeError: save_to_gguf_generic() got multiple values for argument 'quantization_method'

    Previously, it would complain that 'quantization_method' was an unexpected keyword argument.

    By the way, I am using unsloth 2025.7.9

  12. Sweaterdog commented on Jul 24, 2025

    @Sweaterdog
    Author

    I am facing an error when running the following in Google Colab:
    model.save_pretrained_gguf("custom_gemma3_1b_q_8", tokenizer, quantization_method = "q8_0")

    Error:
    TypeError: save_to_gguf_generic() got multiple values for argument 'quantization_method'

    Previously, it would complain that 'quantization_method' was an unexpected keyword argument.

    By the way, I am using unsloth 2025.7.9

    Yeah, I am also getting the same issue when exporting models still, even on the latest version.

  13. manu-one commented on Jul 30, 2025

    @manu-one
  14. rolandtannous commented on Oct 15, 2025

    @rolandtannous
    Contributor

    @Jordinia @Padmanaba231 @Sweaterdog @edoproch @github-actions @manu-one @wooihaw

    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

    Thanks!

  15. 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

Labels

bugfixed

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions