diff --git a/core/text/tokenizer.cpp b/core/text/tokenizer.cpp index 7cfeee0e..3be3237b 100644 --- a/core/text/tokenizer.cpp +++ b/core/text/tokenizer.cpp @@ -1470,9 +1470,10 @@ std::string Tokenizer::piece_at(int32_t id, bool render_special, At at) const { if (b >= 0) return std::string(1, (char)b); std::string s = v_->text(id); - /* User-defined and control tokens are stored as literal text; only normal tokens are in the - * vocab's own encoding and need the decoder chain. */ - if (t == RAD_TT_CONTROL || t == RAD_TT_UNKNOWN || t == RAD_TT_USER_DEFINED) return s; + /* Control tokens are stored as literal text. A user-defined (added, non-special) token goes + * through the decoder chain like a normal one, as HuggingFace decodes every token it keeps: + * Gemma's whitespace runs are added tokens spelled in U+2581 ("\u2581\u2581" is two spaces). */ + if (t == RAD_TT_CONTROL || t == RAD_TT_UNKNOWN) return s; /* No declared decoder means the tokens are already text (true for unigram and wordpiece, not * byte-level BPE). rad-convert emits the chain it read, so the absence is declared. */ diff --git a/tests/tokenizer_test.cpp b/tests/tokenizer_test.cpp index 358be069..c20f303a 100644 --- a/tests/tokenizer_test.cpp +++ b/tests/tokenizer_test.cpp @@ -1020,4 +1020,35 @@ TEST(the_token_view_gives_grammars_the_decoded_bytes) { CHECK_EQ(tv.token_piece(world[0])[0], ' '); } +/* Gemma's tokenizer.json: whitespace runs are added tokens, not special, spelled in U+2581, and + * the decoder replaces U+2581 with a space. HuggingFace decodes them to spaces; returned literally, + * an indented line came out as "▁▁- web-a" (TranslateGemma, 18. 10. 2026). */ +TEST(an_added_whitespace_run_decodes_to_spaces_as_huggingface_does) { + auto v = from_json(R"JSON({ + "normalizer": { "type": "Replace", "pattern": { "String": " " }, "content": "▁" }, + "decoder": { "type": "Sequence", "decoders": [ + { "type": "Replace", "pattern": { "String": "▁" }, "content": " " }, + { "type": "ByteFallback" }, { "type": "Fuse" } ] }, + "model": { "type": "BPE", "byte_fallback": true, + "vocab": {"": 0, "▁": 1, "-": 2, "▁▁": 3, "": 4, "▁▁▁▁": 5}, + "merges": ["▁ ▁", "▁▁ ▁▁"] }, + "added_tokens": [ + {"id": 3, "content": "▁▁", "special": false, "normalized": false}, + {"id": 5, "content": "▁▁▁▁", "special": false, "normalized": false}, + {"id": 4, "content": "", "special": true} ] + })JSON"); + REQUIRE(v != nullptr); + Tokenizer t; + CHECK_OK(t.init(v)); + CHECK_EQ(t.piece(3, false), std::string(" ")); + CHECK_EQ(t.piece(5, false), std::string(" ")); + CHECK_EQ(t.decode({ 3, 2, 5, 2 }, false), std::string(" - -")); + /* A control token still renders as written. */ + CHECK_EQ(t.piece(4, true), std::string("")); + + TokenView tv; + CHECK_OK(tv.init(v)); + CHECK_EQ(tv.token_piece(3), std::string(" ")); +} + RAD_TEST_MAIN()