Commit 98f870c22 for llama.cpp

commit 98f870c220a7d09a95e5476c1ad2cea6b2cd2c1e
Author: Adrien Gallouët <angt@huggingface.co>
Date:   Wed Nov 25 14:59:00 2026 +0100

    llama : honor metaspace_prepend_scheme for SPM (#31986)

    * llama : honor metaspace_prepend_scheme for SPM

    This fixes chat prompts for Nanbeige4.3-33B

    Signed-off-by: Adrien Gallouët <angt@huggingface.co>

    * Add global escaped_space

    Signed-off-by: Adrien Gallouët <angt@huggingface.co>

    ---------

    Signed-off-by: Adrien Gallouët <angt@huggingface.co>

diff --git a/src/llama-vocab.cpp b/src/llama-vocab.cpp
index c97fa906c..a3ddc9b38 100644
--- a/src/llama-vocab.cpp
+++ b/src/llama-vocab.cpp
@@ -28,6 +28,9 @@
 // helpers
 //

+// escaped space symbol - U+2581 (Lower One Eighth Block)
+static const std::string escaped_space = "\xE2\x96\x81";
+
 struct naive_trie {
     naive_trie() : has_value(false), value(0) {
     }
@@ -692,19 +695,18 @@ struct llm_tokenizer_bpe_session {

         if (tok_pre == LLAMA_VOCAB_PRE_TYPE_MMBERT) {
             // Metaspace pre-tokenizer: a text starts with an escaped space, and each escaped space starts a new word
-            static const std::string space = "\xe2\x96\x81";
             std::vector<std::string> words;
             for (auto & word : word_collection) {
                 if (word.find_first_not_of('\n') == std::string::npos) {
                     words.push_back(word);
                     continue;
                 }
-                if (word.compare(0, space.size(), space) != 0) {
-                    word = space + word;
+                if (word.compare(0, escaped_space.size(), escaped_space) != 0) {
+                    word = escaped_space + word;
                 }
                 size_t start = 0;
                 while (start < word.size()) {
-                    size_t end = word.find(space, start + space.size());
+                    size_t end = word.find(escaped_space, start + escaped_space.size());
                     end = end == std::string::npos ? word.size() : end;
                     words.push_back(word.substr(start, end - start));
                     start = end;
@@ -881,7 +883,7 @@ struct llm_tokenizer_wpm_session {
             }

             // prepend phantom space
-            const std::string word1 = "\xe2\x96\x81" + word;
+            const std::string word1 = escaped_space + word;
             const int n = word1.size();

             const size_t current_tokens = output.size();
@@ -1028,9 +1030,6 @@ struct llm_tokenizer_ugm : llm_tokenizer {
         unknown_token_score = min_score - unknown_token_score_penalty;
     }

-    // escaped space symbol - U+2581 (Lower One Eighth Block)
-    const std::string escaped_space = "\xE2\x96\x81";
-
     const char * prefix_replacements = NULL;
     size_t prefix_replacements_size = 0;

@@ -1176,7 +1175,7 @@ private:
         normalized->clear();
         normalized->reserve(input.size() * 3);

-        const std::string space = vocab.get_escape_whitespaces() ? tokenizer.escaped_space : " ";
+        const std::string space = vocab.get_escape_whitespaces() ? escaped_space : " ";

         const bool shall_prepend_space = !vocab.get_treat_whitespace_as_suffix() && vocab.get_add_space_prefix();
         const bool shall_append_space  =  vocab.get_treat_whitespace_as_suffix() && vocab.get_add_space_prefix();
@@ -3770,11 +3769,11 @@ std::string llama_vocab::impl::token_to_piece_for_cache(llama_token token, bool
 }

 static void llama_escape_whitespace(std::string & text) {
-    replace_all(text, " ", "\xe2\x96\x81");
+    replace_all(text, " ", escaped_space);
 }

 static void llama_unescape_whitespace(std::string & word) {
-    replace_all(word, "\xe2\x96\x81", " ");
+    replace_all(word, escaped_space, " ");
 }

 static std::string llama_decode_text(const std::string & text) {
@@ -3820,36 +3819,32 @@ std::vector<llama_token> llama_vocab::impl::tokenize(
                 // tokenizer.encode('', add_special_tokens=True)  returns [1]
                 // tokenizer.encode('', add_special_tokens=False) returns []

-                // TODO: honor metaspace_prepend_scheme (add_space_prefix currently behaves like "always")
-                bool is_prev_special = true;  // prefix with space if first token
+                const bool prepend_first = metaspace_prepend_scheme == LLAMA_METASPACE_PREPEND_SCHEME_FIRST;
+                bool prepend_space = add_space_prefix;

                 if (add_special && add_bos) {
                     GGML_ASSERT(special_bos_id != LLAMA_TOKEN_NULL);
                     output.push_back(special_bos_id);
-                    is_prev_special = true;
                 }

                 for (const auto & fragment : fragment_buffer) {
                     if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
-                        std::string text;
+                        std::string text = fragment.raw_text.substr(fragment.offset, fragment.length);
+                        llama_escape_whitespace(text);

-                        // prefix with space if previous is special
-                        if (add_space_prefix && is_prev_special) {
-                            text = ' ';
+                        if (prepend_space && (!prepend_first || text.rfind(escaped_space, 0) != 0)) {
+                            text.insert(0, escaped_space);
                         }

-                        text += fragment.raw_text.substr(fragment.offset, fragment.length);
-
 #ifdef PRETOKENIZERDEBUG
                         LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", text.length(), fragment.offset, fragment.length, text.c_str());
 #endif
-                        llama_escape_whitespace(text);
                         llm_tokenizer_spm_session session(vocab);
                         session.tokenize(text, output);
-                        is_prev_special = false;
+                        prepend_space = false;
                     } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
                         output.push_back(fragment.token);
-                        is_prev_special = true;
+                        prepend_space = add_space_prefix && !prepend_first;
                     }
                 }

@@ -3892,7 +3887,6 @@ std::vector<llama_token> llama_vocab::impl::tokenize(
                         }

                         // Metaspace prepend_scheme "first": add U+2581 only at the start of the input
-                        static const std::string escaped_space = "\xE2\x96\x81";
                         if (metaspace_prepend_scheme == LLAMA_METASPACE_PREPEND_SCHEME_FIRST &&
                             &fragment == &fragment_buffer.front() && text.rfind(escaped_space, 0) != 0) {
                             text.insert(0, escaped_space);
@@ -4234,7 +4228,8 @@ int32_t llama_vocab::impl::detokenize(

     // Metaspace prepend_scheme "first": remove the leading space of the first rendered piece, so a skipped BOS does not consume it
     // TODO: honor metaspace_prepend_scheme for the other vocab types
-    bool remove_first_space = type == LLAMA_VOCAB_TYPE_BPE && metaspace_prepend_scheme == LLAMA_METASPACE_PREPEND_SCHEME_FIRST;
+    bool remove_first_space = (type == LLAMA_VOCAB_TYPE_BPE || type == LLAMA_VOCAB_TYPE_SPM) &&
+        metaspace_prepend_scheme == LLAMA_METASPACE_PREPEND_SCHEME_FIRST;

     for (int32_t i = 0; i < n_tokens; ++i) {
         GGML_ASSERT(avail >= 0);
diff --git a/tests/test-tokenizer-1-spm.cpp b/tests/test-tokenizer-1-spm.cpp
index 8e370d2c7..f341f45d6 100644
--- a/tests/test-tokenizer-1-spm.cpp
+++ b/tests/test-tokenizer-1-spm.cpp
@@ -11,6 +11,7 @@
 #include <locale>
 #include <string>
 #include <thread>
+#include <tuple>
 #include <vector>
 #include <atomic>

@@ -119,6 +120,60 @@ int main(int argc, char ** argv) {
     llama_free(ctx);
     llama_model_free(model);

+    {
+        auto mparams = llama_model_default_params();
+        mparams.vocab_only = true;
+
+        llama_model_kv_override overrides[2] = {};
+        overrides[0].tag = LLAMA_KV_OVERRIDE_TYPE_STR;
+        snprintf(overrides[0].key, sizeof(overrides[0].key), "%s", "tokenizer.ggml.metaspace.prepend_scheme");
+        snprintf(overrides[0].val_str, sizeof(overrides[0].val_str), "%s", "first");
+        mparams.kv_overrides = overrides;
+
+        model = llama_model_load_from_file(fname.c_str(), mparams);
+        if (model == NULL) {
+            fprintf(stderr, "%s: error: failed to load vocab '%s'\n", __func__, fname.c_str());
+            return 1;
+        }
+
+        vocab = llama_model_get_vocab(model);
+        const llama_token bos = llama_vocab_bos(vocab);
+        const llama_token nl = llama_vocab_nl(vocab);
+
+        // Llama SPM token IDs and decoded text for 'Hello' with and without a leading space
+        const std::vector<std::tuple<std::string, std::vector<llama_token>, std::string>> tests = {
+            { "<s>Hello",          { bos, 10994 }, "<s>Hello" },
+            { "<s>\nHello",        { bos, nl, 10994 }, "<s>\nHello" },
+            { "Hello",             { 15043 }, "Hello" },
+            { " Hello",            { 15043 }, "Hello" },
+            { "\xE2\x96\x81Hello", { 15043 }, "Hello" },
+        };
+
+        for (const auto & [input, expected_tokens, expected_text] : tests) {
+            const auto tokens = common_tokenize(vocab, input, false, true);
+            if (tokens != expected_tokens) {
+                fprintf(stderr, "%s : error: tokenization of '%s' with metaspace prepend_scheme 'first' does not match the expected tokens\n",
+                    __func__, input.c_str());
+                return 4;
+            }
+
+            const auto text = common_detokenize(vocab, tokens);
+            if (text != expected_text) {
+                fprintf(stderr, "%s : error: detokenization of '%s' with metaspace prepend_scheme 'first' produced '%s' instead of '%s'\n",
+                    __func__, input.c_str(), text.c_str(), expected_text.c_str());
+                return 5;
+            }
+        }
+
+        const auto tokens = common_tokenize(vocab, "Hello", true, true);
+        if (common_detokenize(vocab, tokens, false) != "Hello") {
+            fprintf(stderr, "%s : error: detokenization with a skipped BOS retains the space prefix\n", __func__);
+            return 6;
+        }
+
+        llama_model_free(model);
+    }
+
     llama_backend_free();

     return 0;