Skip to content

[LLM:Bugfix] Buffer split Unicode tokenizer output - #4789

Merged
wangzhaode merged 2 commits into
alibaba:masterfrom
primorLee:codex/fix-tokenizer-partial-unicode
Sep 14, 2026
Merged

wangzhaode merged 2 commits into
alibaba:masterfrom
primorLee:codex/fix-tokenizer-partial-unicode

Conversation

@primorLee

@primorLee primorLee commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Description

Decode partial tokenizer output through the same tokenizer decode() API as the normal path. Keep at most three pending token IDs after each call, emit the oldest undecodable token when the bound is reached, and retain the suffix needed to finish a four-byte UTF-8 character.

Flush pending output before a normal decoded word and at both stop-token and maximum-length exits. Reset the buffer at the start of the next response. Literal replacement characters and malformed bytes can no longer hold later output indefinitely.

The unwired mocked tokenizer test has been removed as requested in review.

Module

LLM

Type

  • Bugfix

Tests

  • An offline probe using real Transformers 4.57.6 and tokenizers 0.22.2 passed 11 cases: split CJK, four-byte emoji, invalid/literal replacement prefixes, ASCII after pending bytes, bounded malformed input, final flushing, and the token-conversion fallback. This was a local probe; no new CI job is claimed.
  • python -m compileall -q transformers/llm/export/utils/tokenizer.py transformers/llm/export/llmexport.py
  • python -m tabnanny transformers/llm/export/utils/tokenizer.py transformers/llm/export/llmexport.py
  • git diff --check

Checklist

  • Commit follows the module/type convention.
  • Changed Python files compile.
  • The reported behavior was reproduced and the corrected paths were verified.

@CLAassistant

CLAassistant commented Aug 20, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@wangzhaode wangzhaode self-assigned this Sep 11, 2026
@wangzhaode

Copy link
Copy Markdown
Collaborator

Thanks for digging into this — the diagnosis is correct on both counts, and both are real latent bugs:

  1. self.decode_buffer was never initialized on the tokenizer. llmexport.py was setting self.model.decode_buffer (wrong object), so the buffering branch in id_to_str would have raised AttributeError through __getattr__ if it were ever reached. Moving the buffer onto LlmTokenizer.__init__ is the right fix.
  2. For byte-level BPE tokenizers (Qwen / GPT2 family), tokenizer.decode() does bytes.decode('utf-8', errors='replace') internally and never raises, so the whole buffering block inside except: was dead code and half a CJK character leaked out as \uFFFD. Hoisting the check out of the try/except is what actually makes it work.

I have one blocking concern before this can be merged, plus two smaller notes.

Blocking: the buffer is unbounded and never flushed

I replayed the new id_to_str logic against a small byte-level fake vocab:

input sequence output leftover buffer
split CJK (\xe4\xbd + \xa0) 你 [] — intended fix, works
a token whose text really is \uFFFD, then hello hello [4]
lone continuation byte 0x80, then hello twice hellohello [5]
lone continuation byte 0x80, then split CJK `` (empty) [5, 1, 2]

The last row is a regression. Once an ID that can never form valid UTF-8 enters the buffer (a stray continuation byte, a genuine \uFFFD token, <unk>), the buffer is never cleared, so every subsequent multi-byte character is appended and returns '' — the rest of the response is silently swallowed. Today the same input prints garbage, which is ugly but at least visible; after this change it becomes silent data loss, which is much harder to diagnose.

Row 3 is also not quite clean: while a pending ID sits in the buffer, a following well-formed token is emitted without flushing the pending bytes, so they linger and can later concatenate with unrelated IDs.

A UTF-8 scalar is at most 4 bytes, so capping the buffer is enough:

def id_to_str(self, token_id):
    token_id = int(token_id)
    try:
        word = self.tokenizer.decode(token_id)
    except Exception:
        word = self.tokenizer.convert_tokens_to_string(
            self.tokenizer._convert_id_to_token(token_id))
    if '\uFFFD' not in word:
        if self.decode_buffer:
            # pending bytes can never complete; emit them instead of dropping
            word = self._flush_decode_buffer() + word
        return word
    # Smollm-style tokenizers can emit half of a CJK character.
    self.decode_buffer.append(token_id)
    buffer_txt = self.tokenizer.decode(self.decode_buffer)
    if '\uFFFD' not in buffer_txt or len(self.decode_buffer) >= 4:
        self.decode_buffer.clear()
        return buffer_txt
    return ''

Note 1: keep the retry on the same API as the fast path

The primary path uses tokenizer.decode(), but the buffered retry uses convert_tokens_to_string(convert_ids_to_tokens(...)). The latter bypasses the decoder pipeline and options such as clean_up_tokenization_spaces, so the two paths can disagree on the same text. Since decode() is what produced the partial output, self.tokenizer.decode(self.decode_buffer) is the consistent choice; convert_tokens_to_string is still a reasonable fallback when decode() raises.

Note 2: the new test will not run anywhere

transformers/llm/export/tests/ has no __init__.py or conftest.py, so from utils.tokenizer import ... only resolves when the working directory happens to be transformers/llm/export. There is also no pytest in transformers/llm/export/requirements.txt and no export test stage in test.sh / test_stages.json, so nothing in CI will execute it. Combined with the note in the PR description that the run used an import stub because transformers was not installed, the committed test has not actually been exercised against real transformers.

Also, the mock's decode() always returns \uFFFD, so the "decode succeeds" fast path and the cross-response reset that the llmexport.py change addresses are both uncovered.

Either wire the case into an existing CI stage (and add the pytest dependency), or drop the test from this PR and land it separately — the code fix is valuable on its own and I would rather not block it on test infrastructure.

Minor

except: is carried over from the old code; except Exception: would be slightly better while you are in there. Hoisting int(token_id) and removing the three nested closures is a nice readability win.

Could you add the buffer cap and the pending-flush, and switch the retry to decode()? Happy to merge once those are in.

@wangzhaode wangzhaode added the awaiting contributor Waiting for contributor to address review comments or rebase label Sep 11, 2026
@wangzhaode
wangzhaode merged commit dd72dfd into alibaba:master Sep 14, 2026
1 check passed
ZedingZhang pushed a commit to ZedingZhang/MNN that referenced this pull request Sep 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting contributor Waiting for contributor to address review comments or rebase

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants