Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Gemma GGUF chat templates work! (#246)
Daniel Han990c7a809c5f
diff --git a/unsloth/chat_templates.py b/unsloth/chat_templates.pyindex 7d205ebc5f5..da469727504 100644--- a/unsloth/chat_templates.py+++ b/unsloth/chat_templates.py@@ -15,12 +15,15 @@__all__ = ["get_chat_template","test_chat_templates",+ "fix_sentencepiece_tokenizer",]from transformers import StoppingCriteria, StoppingCriteriaListfrom torch import LongTensor, FloatTensorfrom transformers.models.llama.modeling_llama import loggerfrom .models._utils import patch_tokenizer+import os+import shutilCHAT_TEMPLATES = {}@@ -239,14 +242,75 @@ CHAT_TEMPLATES["gemma"] = (gemma_template, gemma_eos_token,)# Gemma with ChatML instead+# We find using <eos> is still more appropriate!gemma_chatml_template = "{{ bos_token }}" + chatml_templategemma_chatml_eos_token = (- {"<start_of_turn>" : "<|im_start|>", "<end_of_turn>" : "<|im_end|>"},+ {"<start_of_turn>" : "<|im_start|>", "<eos>" : "<|im_end|>"},"<|im_end|>",)CHAT_TEMPLATES["gemma_chatml"] = (gemma_chatml_template, gemma_chatml_eos_token,)+def fix_sentencepiece_tokenizer(+ old_tokenizer,+ new_tokenizer,+ token_mapping,+ temporary_location = "_unsloth_sentencepiece_temp",+):+ # From https://github.com/google/sentencepiece/issues/121+ # We need to manually edit the sentencepiece tokenizer!+ try:+ import sentencepiece.sentencepiece_model_pb2 as sentencepiece_model_pb2+ except:+ if not os.path.exists(temporary_location):+ os.system("git clone https://github.com/google/sentencepiece.git unsloth_sentencepiece_temp")+ os.system(f"cd {temporary_location}/src && protoc --python_out=. sentencepiece_model.proto")+ shutil.rmtree(temporary_location)+ pass+ import sentencepiece.sentencepiece_model_pb2 as sentencepiece_model_pb2+ pass++ if not os.path.exists(temporary_location):+ os.makedirs(temporary_location)+ pass++ # First save the old tokenizer+ old_tokenizer.save_pretrained(temporary_location)++ from sentencepiece import SentencePieceProcessor+ tokenizer_file = sentencepiece_model_pb2.ModelProto()+ tokenizer_file.ParseFromString(open(f"{temporary_location}/tokenizer.model", "rb").read())++ # Now save the new tokenizer+ new_tokenizer.save_pretrained(temporary_location)++ # Now correct the old tokenizer's .model file+ for old_token, new_token in token_mapping.items():+ ids = old_tokenizer([old_token], add_special_tokens = False).input_ids+ ids = ids[0]+ if (len(ids) != 1):+ # Skip this token!+ print(f"Skip mapping {old_token} to {new_token} since {new_token} is already in the tokenizer!")+ continue+ pass+ ids = ids[0]+ tokenizer_piece = tokenizer_file.pieces[ids]+ assert(tokenizer_piece.piece == old_token)+ tokenizer_piece.piece = new_token+ pass++ # And now write it+ with open(f"{temporary_location}/tokenizer.model", "wb") as file:+ file.write(tokenizer_file.SerializeToString())+ pass++ # And load it!+ from transformers import AutoTokenizer+ tokenizer = AutoTokenizer.from_pretrained(temporary_location, eos_token = new_tokenizer.eos_token)+ return tokenizer+pass++def get_chat_template(tokenizer,chat_template = "chatml",@@ -290,11 +354,13 @@ def get_chat_template(string_vocab = tokenizer._tokenizer.to_str()+ skipped = 0for old_token, new_token in token_mapping.items():old_count = string_vocab.count(f'"{old_token}"')new_count = string_vocab.count(f'"{new_token}"')if new_count != 0:print(f"{new_token} is already a token. Skipping.")+ skipped += 1elif old_count == 0:raise RuntimeError(f"{old_token} was not part of the tokenizer!")else:@@ -308,8 +374,14 @@ def get_chat_template(string_vocab = string_vocab.replace(tokenizer.eos_token, stop_word)pass- new_tokenizer = tokenizer._tokenizer.from_str(string_vocab)- tokenizer = tokenizer.__class__(tokenizer_object = new_tokenizer, eos_token = stop_word)+ if skipped != len(token_mapping):+ new_tokenizer = tokenizer._tokenizer.from_str(string_vocab)+ new_tokenizer = tokenizer.__class__(tokenizer_object = new_tokenizer, eos_token = stop_word)++ # Must fix the sentence piece tokenizer since there's no tokenizer.model file!+ tokenizer = fix_sentencepiece_tokenizer(tokenizer, new_tokenizer, token_mapping,)+ else:+ passelif stop_word != "eos_token":logger.warning_once(f"Unsloth: Will map {stop_word} to EOS = {tokenizer.eos_token}.")