Skip to content

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.

fix: patch CONTROL type for special tokens in sentencepiece GGUF export (#5080)

Octopus72c1c3b254cd
diff --git a/tests/saving/test_fix_sentencepiece_gguf_robustness.py b/tests/saving/test_fix_sentencepiece_gguf_robustness.py
new file mode 100644
index 00000000000..49bd70fa2fe
--- /dev/null
+++ b/tests/saving/test_fix_sentencepiece_gguf_robustness.py
@@ -0,0 +1,132 @@
+import ast
+import json
+import os
+
+os.environ.setdefault("PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION", "python")
+
+from transformers.utils import sentencepiece_model_pb2
+
+from unsloth.tokenizer_utils import fix_sentencepiece_gguf
+
+
+NORMAL, CONTROL, USER_DEFINED = 1, 3, 4
+
+_SAVE_PY = os.path.abspath(
+ os.path.join(os.path.dirname(__file__), "..", "..", "unsloth", "save.py")
+)
+_TOK_PY = os.path.abspath(
+ os.path.join(os.path.dirname(__file__), "..", "..", "unsloth", "tokenizer_utils.py")
+)
+
+
+def _build(pieces):
+ m = sentencepiece_model_pb2.ModelProto()
+ for piece, score, typ in pieces:
+ p = m.pieces.add()
+ p.piece = piece
+ p.score = score
+ p.type = typ
+ return m.SerializeToString()
+
+
+def _read(path):
+ m = sentencepiece_model_pb2.ModelProto()
+ with open(path, "rb") as f:
+ m.ParseFromString(f.read())
+ return [(p.piece, p.type) for p in m.pieces]
+
+
+def test_user_defined_special_piece_is_not_retyped(tmp_path):
+ pieces = [
+ ("<s>", 0.0, CONTROL),
+ ("a", -1.0, NORMAL),
+ ("<ud_special>", -1.0, USER_DEFINED),
+ ]
+ (tmp_path / "tokenizer.model").write_bytes(_build(pieces))
+ (tmp_path / "tokenizer.json").write_text(
+ json.dumps(
+ {"added_tokens": [{"id": 2, "content": "<ud_special>", "special": True}]}
+ )
+ )
+ fix_sentencepiece_gguf(str(tmp_path))
+ got = dict(_read(str(tmp_path / "tokenizer.model")))
+ assert got["<ud_special>"] == USER_DEFINED
+
+
+def test_malformed_entry_missing_id_does_not_raise(tmp_path):
+ pieces = [("<s>", 0.0, CONTROL), ("a", -1.0, NORMAL), ("<sot>", -1.0, NORMAL)]
+ (tmp_path / "tokenizer.model").write_bytes(_build(pieces))
+ (tmp_path / "tokenizer.json").write_text(
+ json.dumps(
+ {
+ "added_tokens": [
+ {"content": "no_id_entry", "special": True},
+ {"id": 2, "content": "<sot>", "special": True},
+ ]
+ }
+ )
+ )
+ fix_sentencepiece_gguf(str(tmp_path))
+ got = dict(_read(str(tmp_path / "tokenizer.model")))
+ assert got["<sot>"] == CONTROL
+
+
+def test_entry_with_non_int_id_is_skipped(tmp_path):
+ pieces = [("<s>", 0.0, CONTROL), ("a", -1.0, NORMAL)]
+ (tmp_path / "tokenizer.model").write_bytes(_build(pieces))
+ (tmp_path / "tokenizer.json").write_text(
+ json.dumps({"added_tokens": [{"id": "oops", "content": "x", "special": True}]})
+ )
+ before = (tmp_path / "tokenizer.model").read_bytes()
+ fix_sentencepiece_gguf(str(tmp_path))
+ after = (tmp_path / "tokenizer.model").read_bytes()
+ assert before == after
+
+
+def test_save_py_except_clause_is_broad_exception():
+ with open(_SAVE_PY) as f:
+ tree = ast.parse(f.read())
+ for node in ast.walk(tree):
+ if (
+ isinstance(node, ast.FunctionDef)
+ and node.name == "unsloth_save_pretrained_gguf"
+ ):
+ for subnode in ast.walk(node):
+ if isinstance(subnode, ast.Try):
+ body_src = "\n".join(ast.unparse(s) for s in subnode.body)
+ if "fix_sentencepiece_gguf(" not in body_src:
+ continue
+ handler = subnode.handlers[0]
+ assert handler.type is not None
+ assert isinstance(handler.type, ast.Name)
+ assert handler.type.id == "Exception"
+ return
+ raise AssertionError(
+ "fix_sentencepiece_gguf try block not found in unsloth_save_pretrained_gguf"
+ )
+
+
+def test_tokenizer_utils_uses_import_protobuf_fallback_pattern():
+ with open(_TOK_PY) as f:
+ src = f.read()
+ tree = ast.parse(src)
+ for node in ast.walk(tree):
+ if isinstance(node, ast.FunctionDef) and node.name == "fix_sentencepiece_gguf":
+ fn_src = ast.unparse(node)
+ assert "import_protobuf" in fn_src
+ return
+ raise AssertionError("fix_sentencepiece_gguf not found in tokenizer_utils.py")
+
+
+def test_all_special_tokens_are_gated_by_tokenizer_json_not_by_type(tmp_path):
+ pieces = [
+ ("<s>", 0.0, CONTROL),
+ ("a", -1.0, NORMAL),
+ ("<n1>", -1.0, NORMAL),
+ ("<u1>", -1.0, USER_DEFINED),
+ ]
+ (tmp_path / "tokenizer.model").write_bytes(_build(pieces))
+ fix_sentencepiece_gguf(str(tmp_path))
+ got = dict(_read(str(tmp_path / "tokenizer.model")))
+ assert got["<n1>"] == NORMAL
+ assert got["<u1>"] == USER_DEFINED
diff --git a/unsloth/save.py b/unsloth/save.py
index 4e9e1bfe112..df3df13a04f 100644
--- a/unsloth/save.py
+++ b/unsloth/save.py
@@ -2288,6 +2288,15 @@ def unsloth_save_pretrained_gguf(
quant_method = "q8_0"
quantization_methods.append(quant_method.lower())
+ try:
+ from .tokenizer_utils import fix_sentencepiece_gguf
+
+ fix_sentencepiece_gguf(save_directory)
+ except Exception as e:
+ logger.warning(
+ f"Unsloth: fix_sentencepiece_gguf skipped ({type(e).__name__}): {e}"
+ )
+
try:
all_file_locations, want_full_precision, is_vlm_update = save_to_gguf(
model_name = model_name,
diff --git a/unsloth/tokenizer_utils.py b/unsloth/tokenizer_utils.py
index 85b3c5308b1..130894e3855 100644
--- a/unsloth/tokenizer_utils.py
+++ b/unsloth/tokenizer_utils.py
@@ -434,8 +434,25 @@ def fix_sentencepiece_gguf(saved_location):
Fixes sentencepiece tokenizers which did not extend the vocabulary with
user defined tokens.
Inspiration from https://github.com/ggerganov/llama.cpp/blob/master/convert_hf_to_gguf.py
+
+ Also fixes special tokens (e.g. Gemma 3's <start_of_turn>/<end_of_turn>) that are
+ already present in the sentencepiece model but are incorrectly typed as NORMAL instead
+ of CONTROL. This causes them to be written to GGUF with token_type=1 (NORMAL) instead
+ of token_type=3 (CONTROL), which breaks chat inference in llama.cpp since parse_special
+ only matches CONTROL tokens.
"""
from copy import deepcopy
+ import sys
+
+ try:
+ from transformers.convert_slow_tokenizer import import_protobuf
+
+ sys.modules.setdefault(
+ "transformers.utils.sentencepiece_model_pb2",
+ import_protobuf(),
+ )
+ except Exception:
+ pass
from transformers.utils import sentencepiece_model_pb2
import json
from enum import IntEnum
@@ -457,12 +474,45 @@ def fix_sentencepiece_gguf(saved_location):
)
sentence_piece_size = len(tokenizer_file.pieces)
+ # Build a set of token IDs that are marked as special in tokenizer.json.
+ # These tokens should use CONTROL type in the sentencepiece model so that
+ # llama.cpp writes them as CONTROL (type=3) in the GGUF token_type array.
+ special_token_ids = set()
+ if os.path.isfile(f"{saved_location}/tokenizer.json"):
+ with open(f"{saved_location}/tokenizer.json", "r", encoding = "utf-8") as f:
+ tokenizer_json = json.load(f)
+ for entry in tokenizer_json.get("added_tokens", []):
+ token_id = entry.get("id")
+ if entry.get("special", False) and isinstance(token_id, int):
+ special_token_ids.add(token_id)
+
+ # Fix existing sentencepiece tokens that are marked as special in tokenizer.json
+ # but have the wrong type (NORMAL instead of CONTROL) in the sentencepiece model.
+ patched = 0
+ for token_id in special_token_ids:
+ if 0 <= token_id < sentence_piece_size:
+ piece = tokenizer_file.pieces[token_id]
+ if piece.type == SentencePieceTokenTypes.NORMAL:
+ piece.type = SentencePieceTokenTypes.CONTROL
+ patched += 1
+ if patched > 0:
+ logger.warning(
+ f"Unsloth: Patched {patched} special token(s) in {saved_location}/tokenizer.model "
+ f"from NORMAL to CONTROL type so llama.cpp / GGUF chat inference works correctly."
+ )
+
# Load added_tokens_json
if not os.path.isfile(f"{saved_location}/added_tokens.json"):
+ if patched > 0:
+ with open(f"{saved_location}/tokenizer.model", "wb") as file:
+ file.write(tokenizer_file.SerializeToString())
return
with open(f"{saved_location}/added_tokens.json", "r", encoding = "utf-8") as file:
added_tokens_json = json.load(file)
if len(added_tokens_json) == 0:
+ if patched > 0:
+ with open(f"{saved_location}/tokenizer.model", "wb") as file:
+ file.write(tokenizer_file.SerializeToString())
return
added_tokens_json = dict(
@@ -472,10 +522,20 @@ def fix_sentencepiece_gguf(saved_location):
# Confirm added_tokens_json is correct
added_tokens_ids = np.array(list(added_tokens_json.values()))
+ _real_added_tokens_ids = added_tokens_ids
+ if len(added_tokens_ids) < 2:
+ added_tokens_ids = np.array([sentence_piece_size, sentence_piece_size + 1])
diff = np.diff(added_tokens_ids)
if diff.min() != 1 or diff.max() != 1:
+ if patched > 0:
+ with open(f"{saved_location}/tokenizer.model", "wb") as file:
+ file.write(tokenizer_file.SerializeToString())
return
+ added_tokens_ids = _real_added_tokens_ids
if added_tokens_ids.min() != sentence_piece_size:
+ if patched > 0:
+ with open(f"{saved_location}/tokenizer.model", "wb") as file:
+ file.write(tokenizer_file.SerializeToString())
return
# Edit sentence piece tokens with added_tokens_json
@@ -485,10 +545,16 @@ def fix_sentencepiece_gguf(saved_location):
f"But we need to extend to sentencepiece vocab size ({new_size})."
)
new_tokens = deepcopy(tokenizer_file.pieces[-len(added_tokens_ids) :])
- for new_token, added_token in zip(new_tokens, added_tokens_json.keys()):
- new_token.piece = added_token.encode("utf-8")
+ for new_token, added_token_str in zip(new_tokens, added_tokens_json.keys()):
+ added_token_id = added_tokens_json[added_token_str]
+ new_token.piece = added_token_str.encode("utf-8")
new_token.score = -1000.0
- new_token.type = SentencePieceTokenTypes.USER_DEFINED
+ # Use CONTROL type for tokens marked as special in tokenizer.json,
+ # otherwise fall back to USER_DEFINED.
+ if added_token_id in special_token_ids:
+ new_token.type = SentencePieceTokenTypes.CONTROL
+ else:
+ new_token.type = SentencePieceTokenTypes.USER_DEFINED
tokenizer_file.pieces.extend(new_tokens)