Skip to content

Fix Chinese/Japanese output in LLMLingua-2: spurious spaces (mBERT) and empty prompts (XLM-R) - #266

Open
Cis Labs (cislabs-hub) wants to merge 2 commits into
microsoft:mainfrom
Cis-Labs-Hub:fix-cjk-spacing
Open

Cis Labs (cislabs-hub) wants to merge 2 commits into
microsoft:mainfrom
Cis-Labs-Hub:fix-cjk-spacing

Conversation

@cislabs-hub

@cislabs-hub Cis Labs (cislabs-hub) commented Nov 29, 2026 •

Copy link
Copy Markdown

Fixes #131

This PR fixes two bugs in how LLMLingua-2 handles text in scripts written without spaces (Chinese, Japanese and similar), one per commit:

  1. With mBERT, the output has a space between every Chinese/Japanese character.
  2. With XLM-RoBERTa, plain Chinese/Japanese prompts come back empty.

Output for text without such characters is unchanged.

1. Spurious spaces (mBERT)

東 京 都 議 会 は2024 年 度 予 算 案 審 議 活 用 化 推 進 論 \n 予 算 3. 5 % 増 子 育 て 支 援 重 点

The extra spaces also cost tokens. With rate=0.5, the mBERT model returned 67.5% of the original Chinese tokens. With rate=1.0, the output was 1.5x longer than the input.

Root cause (prompt_compressor.py on main):

  • The output is built with convert_tokens_to_string(keep_words) (L2463). That call joins words with a space, and the mBERT tokenizer makes every CJK ideograph its own word.
  • The chunk strings are also built with convert_tokens_to_string (L2272, L2281), so the original spacing is already lost at that point. The no-compression path returns these strings as they are (L2365).
  • With XLM-R, text after a forced token such as "\n" gets a ▁ prefix that becomes a space (\n 新闻).

Fix:

  • __chunk_context records, from the fast tokenizer's offset mapping on the original text, whether each token follows whitespace.
  • When kept words are joined (merge_words_without_space), no space is inserted if both of these hold:
    • the original had no whitespace between the two words, including inside any dropped words between them;
    • one side of the junction is a character from a script written without spaces: CJK ideographs, kana, CJK/fullwidth punctuation, Thai, Lao, Myanmar, or Khmer. Hangul is excluded because Korean uses spaces.
  • If nothing changes, or the offsets are unavailable, the previous string is used unchanged.

2. Empty prompts (XLM-RoBERTa)

PromptCompressor(
    model_name="microsoft/llmlingua-2-xlm-roberta-large-meetingbank",
    use_llmlingua2=True,
).compress_prompt(
    "委员会周二决定将明年的公共交通预算提高百分之十二,因为多个市民团体投诉郊区的公交车过于拥挤。",
    rate=0.5,
    force_tokens=["\n", "?"],
)
# compressed_prompt == "", compressed_tokens == 0

When a Chinese context is followed by an English question, the whole context is dropped and only the question is kept.

Root cause:

  • For XLM-R, is_begin_of_new_word (utils.py L90–99) starts a word only at a ▁-marked token, an ASCII punctuation token, or a force token. ▁ only follows whitespace, so a whole Chinese/Japanese sentence becomes one "word".
  • For a single-word prompt, the percentile threshold (prompt_compressor.py L2440) equals that word's probability. The strict word_prob > threshold test (L2448) then drops it.

Fix:

  • is_begin_of_new_word gets an optional prev_token. Next to characters of these scripts, every SentencePiece piece starts a word (東京, 会議, …), except right after a bare ▁ token.
  • __merge_token_to_word and __get_word_spaces both pass prev_token, so the spacing flags stay aligned with the words.
  • When a dropped gap of such characters lies between two kept ▁-model words, a ▁ is added in two cases:
    • the gap had whitespace, or
    • gluing would fuse two letters or digits. For example, without this, dropping 年 from 2024年3月 would produce 20243.
  • The ▁-model check covers the same model names as is_begin_of_new_word.

Before / after

Model Input main This PR
mBERT ja, rate=0.5 東 京 都 議 会 は2024 年 度 予 算 案 … (79 tok, 77.5%) 東京都議会は2024年度予算案審議活用化推進論\n予算3. 5 %増子育て支援重点 (49, 48.0%)
mBERT zh, issue settings (rate=0.6) 前 有 可 爱 的 小 姑 娘 … (169 tok, 84.5%) 前有可爱的小姑娘谁喜欢她奶奶要什么 奶奶送给… (119, 59.5%)
mBERT zh, rate=1.0 297 tok (input: 200) 200 tok, identical to the input
XLM-R ja, 91 tok '' 会議来年度予算教育医療支出を増やす意見大阪新しい空港建設計画発表 (43)
XLM-R zh, 54 tok '' 明年公共交通预算提高十二,市民投诉郊公交车拥挤 (27)
XLM-R zh + English question, 64 tok \n Question how much budget increase? (7) 决定明年公共交通预算提高十二,市民投诉公交车拥挤\n Question budget increase? (33)

In the mBERT Chinese example, the space after 什么 is correct: the original has 。 一次 there.

Space-delimited languages are unchanged

I compared main and this branch on four models:

  • both Microsoft LLMLingua-2 models;
  • two additional fine-tuned checkpoints of the same two architectures.

Prompts covered English, German, Russian, Arabic, Hindi, Korean, Thai, Chinese and Japanese, plus multi-chunk prompts. Each was run with six configurations, all with return_word_label=True:

  • rate 0.5 / 0.33 / 1.0
  • the issue's settings, including drop_consecutive=True
  • force_reserve_digit=True
  • multi-context use_context_level_filter=True

Results (364 runs):

  • English, German, Russian, Arabic, Hindi: 134/134 identical in every returned field (compressed_prompt, fn_labeled_original_prompt, token counts, rate).
  • mBERT models: fn_labeled_original_prompt is identical in every language (192/192).
  • Korean: compressed_prompt is identical in 22/24 runs. The two differences are Hanja at rate=1.0 with mBERT: ( 會 議 ) → (會議).
  • Empty outputs: 24 on main, all Chinese/Japanese with XLM-R; 0 with this PR.
  • Existing golden outputs in tests/test_llmlingua2.py: the English, GSM8K and MeetingBank expectations are byte-identical.
  • LongBench expectation (Chinese, XLM-R): regenerated. All 800 of its non-space characters match the source text, in order. Of its 17 spaces, 14 stand where the source has whitespace, and 3 separate digits across a dropped CJK character (2007 10 21至24日). compressed_tokens goes from 870 to 917 (target 1,000).

Tests

  • tests/test_llmlingua2_spacing.py:
    • Model-free tests of merge_words_without_space.
    • An end-to-end mBERT test: no spaces in zh/ja output, word labels match the output, rate=1.0 returns zh/ja unchanged, and the English output equals main.
  • tests/test_llmlingua2_xlmr_cjk.py:
    • Model-free tests of the XLM-R word boundaries and dropped-gap handling.
    • An end-to-end XLM-R test: zh/ja output is non-empty and near the requested rate, a Chinese context with an English question keeps Chinese text, and the English output equals main.
  • The end-to-end CJK tests fail on main and pass here.
  • pytest tests/test_llmlingua2.py tests/test_llmlingua2_spacing.py tests/test_llmlingua2_xlmr_cjk.py: 19 passed on CPU (transformers 4.46.3, torch 2.5.1).

Notes

  • Latin-script spacing from convert_tokens_to_string (GPT - 4, \n Question) is unchanged on purpose, to keep space-delimited output identical.
  • With slow (non-fast) tokenizers, mBERT keeps the previous behaviour. For ▁ models, the ▁ marker is used instead of offsets.
  • Fix: remove spurious spaces between CJK characters when compressing (#131) #255 addresses the spacing issue with a regex that removes a space between any two CJK/Hangul characters in keep_str. That also removes spaces present in the original text, such as Korean word spacing (서울시는 예산안을 → 서울시는예산안을). It does not cover the rate=1 or XLM-R cases.

🤖 Generated with Claude Code

…oft#131)

LLMLingua-2 builds the compressed text with
tokenizer.convert_tokens_to_string(keep_words), which joins words with a
space. The mBERT tokenizer splits every CJK ideograph into its own word,
so Chinese and Japanese outputs became "東 京 会 議". The chunk strings
are also rebuilt with convert_tokens_to_string, so the original spacing
is gone by the time the output is built, and the rate=1 /
use_token_level_filter=False path returned the same spaced text. With
XLM-RoBERTa, text after a forced token such as "\n" gets a "▁" prefix,
which became a space ("\n 新闻").

Record, from the tokenizer offset mapping of the original context,
whether each token is preceded by whitespace, and when joining kept
words do not insert a space if the original had no whitespace between
them (including any dropped words in between) and one side of the
junction is a character of a script written without spaces (CJK
ideographs, kana, CJK/fullwidth punctuation, Thai, Lao, Myanmar,
Khmer). Hangul is excluded because Korean uses spaces. If no word is
merged, or offsets are unavailable (slow tokenizers), the output is
exactly what it was before, so space-delimited languages are unchanged.
Word labels (return_word_label) are unchanged.

Update the LongBench expectation (21 spurious spaces removed) and add
tests for the word grouping and an end-to-end mBERT test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With the XLM-RoBERTa models, a word starts only at a token with the
SentencePiece "▁" marker (or ASCII punctuation / a force token). "▁"
only follows whitespace, so a Chinese or Japanese sentence becomes one
or two "words". Compression then keeps or drops whole sentences: a
prompt that is a single word gets threshold == its probability and is
dropped by the strict `word_prob > threshold` test, so the compressed
prompt is empty, and a Chinese context followed by an English question
loses the whole context.

Start a new word at token boundaries next to characters of scripts
written without spaces, except right after a bare "▁" token
(is_begin_of_new_word gets an optional prev_token, passed by
__merge_token_to_word and __get_word_spaces so word boundaries and
spacing flags stay aligned). In merge_words_without_space, keep a
dropped gap of such characters from fusing the neighbouring kept words
of "▁"-marked models: add "▁" if the gap had whitespace, or if two
letters/digits would be joined ("2024" + "3" when "年" is dropped).
The "▁"-model check is shared (is_sentencepiece_model) and covers the
same model names as is_begin_of_new_word. Without offsets, "▁" is used
as the whitespace flag for these models.

Text without such characters gets the same words, labels and output as
before. Regenerate the LongBench (Chinese) expectation and add tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@cislabs-hub Cis Labs (cislabs-hub) changed the title Fix extra spaces between CJK characters in LLMLingua-2 output (#131) Fix Chinese/Japanese output in LLMLingua-2: spurious spaces (mBERT) and empty prompts (XLM-R) Nov 30, 2026
@cislabs-hub

Copy link
Copy Markdown
Author

I've added a second commit (efdaeac) that fixes a related Chinese/Japanese bug in the XLM-RoBERTa models, which return an empty compressed prompt for text such as 委员会周二决定…拥挤。. Because ▁ only marks words after whitespace, a whole sentence was treated as a single word, and the percentile threshold then dropped it. Mixed prompts were affected too: a Chinese context followed by an English question lost the entire context. The commit splits words at token boundaries for scripts written without spaces, keeps dropped gaps from fusing numbers (2024 3月, not 20243月), and shares the spacing helper from the first commit so word boundaries and spacing flags stay aligned. Output for text without such characters is unchanged in all four models I compared (134/134 space-delimited runs identical, empty outputs 24 → 0), and the description above has been updated with the details and the regenerated LongBench expectation.

@microsoft-github-policy-service

Copy link
Copy Markdown

Cis Labs (@cislabs-hub) please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"
Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”),
and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your
contributions to Microsoft open source projects. This Agreement is effective as of the latest signature
date below.

  1. Definitions.
    “Code” means the computer software code, whether in human-readable or machine-executable form,
    that is delivered by You to Microsoft under this Agreement.
    “Project” means any of the projects owned or managed by Microsoft and offered under a license
    approved by the Open Source Initiative (www.opensource.org).
    “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
    Project, including but not limited to communication on electronic mailing lists, source code control
    systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
    discussing and improving that Project, but excluding communication that is conspicuously marked or
    otherwise designated in writing by You as “Not a Submission.”
    “Submission” means the Code and any other copyrightable material Submitted by You, including any
    associated comments and documentation.
  2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
    Project. This Agreement covers any and all Submissions that You, now or in the future (except as
    described in Section 4 below), Submit to any Project.
  3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
    Should You wish to Submit materials that are not Your original work, You may Submit them separately
    to the Project if You (a) retain all copyright and license information that was in the materials as You
    received them, (b) in the description accompanying Your Submission, include the phrase “Submission
    containing materials of a third party:” followed by the names of the third party and any licenses or other
    restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
    guidelines concerning Submissions.
  4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
    for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
    Submission is made in the course of Your work for an employer or Your employer has intellectual
    property rights in Your Submission by contract or applicable law, You must secure permission from Your
    employer to make the Submission before signing this Agreement. In that case, the term “You” in this
    Agreement will refer to You and the employer collectively. If You change employers in the future and
    desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
    and secure permission from the new employer before Submitting those Submissions.
  5. Licenses.
  • Copyright License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
    Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
    the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
    parties.
  • Patent License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
    Your patent claims that are necessarily infringed by the Submission or the combination of the
    Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
    import or otherwise dispose of the Submission alone or with the Project.
  • Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
    No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
    granted by implication, exhaustion, estoppel or otherwise.
  1. Representations and Warranties. You represent that You are legally entitled to grant the above
    licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
    have disclosed under Section 3). You represent that You have secured permission from Your employer to
    make the Submission in cases where Your Submission is made in the course of Your work for Your
    employer or Your employer has intellectual property rights in Your Submission by contract or applicable
    law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
    have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
    You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
    REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
    EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
    PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
    NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
  2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
    You later become aware that would make Your representations in this Agreement inaccurate in any
    respect.
  3. Information about Submissions. You agree that contributions to Projects and information about
    contributions may be maintained indefinitely and disclosed publicly, including Your name and other
    information that You submit with Your Submission.
  4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
    the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
    Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
    exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
    defenses of lack of personal jurisdiction and forum non-conveniens.
  5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
    supersedes any and all prior agreements, understandings or communications, written or oral, between
    the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: When I use Chinese prompt, the compressed prompt has extra spaces.

1 participant