Skip to content

Throw when a tokenizer needs Unicode normalization in invariant mode - #7958

Open
krwq wants to merge 8 commits into
dotnet:mainfrom
krwq:krwq-fix-7728-throw-invariant-normalization
Open

krwq wants to merge 8 commits into
dotnet:mainfrom
krwq:krwq-fix-7728-throw-invariant-normalization

Conversation

@krwq

@krwq krwq commented Nov 26, 2026

Copy link
Copy Markdown
Member

In globalization-invariant mode, string.Normalize returns its input unchanged, so BertOptions.RemoveNonSpacingMarks and the StripAccents, NFC, NFD, NFKC and NFKD normalizer steps loaded by SentencePieceTokenizer.CreateFromTokenizerJson silently skipped the Unicode normalization they rely on. For example, accents on precomposed characters were kept, so with uncased BERT vocabularies, words like "café" could become [UNK]. Creating such a tokenizer now throws PlatformNotSupportedException, pointing to https://aka.ms/GlobalizationInvariantMode.

There's no public API to detect invariant mode yet (dotnet/runtime#81429), so the check is whether string.Normalize decomposes "é".

In invariant mode, apps that use the option or these steps now fail when creating the tokenizer, instead of silently getting different tokens than with ICU. #7938 tried carrying our own Unicode data so that accent stripping works in invariant mode, and was closed in favor of failing loudly.

The NFC at the end of BertNormalizer doesn't throw, since it runs for every BertTokenizer with the default normalizer and only matters for text that isn't already NFC. #7957 proposes removing it.

Fixes #7728

krwq and others added 7 commits November 25, 2026 15:59
string.Normalize returns its input unchanged when globalization-invariant
mode is enabled, so the features relying on it silently did nothing:

- BertOptions.RemoveNonSpacingMarks kept the accents of precomposed
  characters, so with uncased vocabularies words like "café" could
  become [UNK].
- The StripAccents, NFC, NFD, NFKC and NFKD steps of a tokenizer.json
  normalizer, used by SentencePieceTokenizer.CreateFromTokenizerJson,
  were skipped.

Creating such a tokenizer now throws PlatformNotSupportedException,
naming the option or step and how to fix it. There's no public API to
detect invariant mode yet (dotnet/runtime#81429), so the check is
whether string.Normalize decomposes "é".

Fixes dotnet#7728

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Describe the steps that are rejected in invariant mode as those relying on
Unicode normalization, so the remarks stay accurate when steps change.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Building the messages from English fragments would make them hard to
localize. UnicodeNormalization now only tells whether string.Normalize
works, and each call site throws its own complete message, with only
identifiers inserted.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Like the runtime's own invariant-mode error, end the messages with a link
to https://aka.ms/GlobalizationInvariantMode rather than a specific fix,
such as the InvariantGlobalization property or a container image, which
doesn't suit every app and can go out of date.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Rather than Build checking a list of tokenizer.json normalizer types, the
steps that call string.Normalize now throw from their constructors when
it isn't supported. Build creates every step when the tokenizer is
created, including those in a Sequence, so creating the tokenizer still
fails.

StripAccentsStep is no longer a static singleton, since an exception from
the static instance's constructor would leave the type unusable for the
rest of the process.

The exception and its message don't change.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
UnicodeStep no longer takes the step name only for the exception message.
The message names the NormalizationForm that the step uses instead, for
example FormKD for an NFKD step, or FormD for StripAccents.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
The message text doesn't change. The tokenizer.json message keeps its
literal file name, as nothing defines a constant for it.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues remain for the change to explicitly reject tokenizer configurations requiring unavailable Unicode normalization.

No open issues 🎉

What changed in this PR

This PR addresses #7728 by making tokenizer creation fail explicitly when required Unicode normalization is unavailable in globalization-invariant mode, rather than silently producing different tokens.

Changes:

  • Adds a shared normalization-support check and construction-time guards for BERT accent stripping and SentencePiece Unicode normalization steps.
  • Documents the new exceptions and the BERT options that bypass the default normalizer.
  • Adds isolated-process tests for rejected configurations and configurations that remain supported.
File Description
test/​Microsoft.ML.Tokenizers.Tests/​Utils.cs Adds helpers for invariant-mode test processes.
test/​Microsoft.ML.Tokenizers.Tests/​UnigramTests.cs Tests rejected normalization steps and supported charsmap processing.
test/​Microsoft.ML.Tokenizers.Tests/​BertTokenizerTests.cs Tests BERT factory exceptions and default-normalizer bypasses.
src/​Microsoft.ML.Tokenizers/​Utils/​UnicodeNormalization.cs Adds a cached check for Unicode normalization support.
src/​Microsoft.ML.Tokenizers/​Normalizer/​SentencePieceNormalizationStep.cs Rejects steps requiring unavailable Unicode normalization.
src/​Microsoft.ML.Tokenizers/​Normalizer/​BertNormalizer.cs Rejects accent stripping when normalization is unavailable.
src/​Microsoft.ML.Tokenizers/​Model/​SentencePieceTokenizer.cs Documents invariant-mode restrictions for JSON normalizers.
src/​Microsoft.ML.Tokenizers/​Model/​BertTokenizer.cs Documents the new exception on tokenizer factory methods.
src/​Microsoft.ML.Tokenizers/​Model/​BertOptions.cs Documents accent-stripping requirements and bypass conditions.

Review effort: Balanced

Microsoft.ML.Tokenizers.Data.Tests also compiles Utils.cs, but doesn't
reference Microsoft.DotNet.RemoteExecutor, so it failed to build. Move
the helpers to a file that only Microsoft.ML.Tokenizers.Tests compiles.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@codecov

codecov Bot commented Nov 26, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 70.90%. Comparing base (755131b) to head (3348439).
⚠️ Report is 5 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7958      +/-   ##
==========================================
+ Coverage   70.89%   70.90%   +0.01%     
==========================================
  Files        1421     1423       +2     
  Lines      280129   280248     +119     
  Branches    27601    27605       +4     
==========================================
+ Hits       198602   198721     +119     
+ Misses      73392    73388       -4     
- Partials     8135     8139       +4     
Flag Coverage Δ
Debug 70.90% <100.00%> (+0.01%) ⬆️
production 64.34% <100.00%> (+<0.01%) ⬆️
test 90.75% <100.00%> (+0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/Microsoft.ML.Tokenizers/Model/BertOptions.cs 100.00% <ø> (ø)
src/Microsoft.ML.Tokenizers/Model/BertTokenizer.cs 65.98% <ø> (+1.52%) ⬆️
...soft.ML.Tokenizers/Model/SentencePieceTokenizer.cs 74.48% <ø> (ø)
...crosoft.ML.Tokenizers/Normalizer/BertNormalizer.cs 82.40% <100.00%> (+3.23%) ⬆️
...izers/Normalizer/SentencePieceNormalizationStep.cs 77.27% <100.00%> (+4.94%) ⬆️
...rosoft.ML.Tokenizers/Utils/UnicodeNormalization.cs 100.00% <100.00%> (ø)
...icrosoft.ML.Tokenizers.Tests/BertTokenizerTests.cs 100.00% <100.00%> (ø)
...soft.ML.Tokenizers.Tests/InvariantGlobalization.cs 100.00% <100.00%> (ø)
test/Microsoft.ML.Tokenizers.Tests/UnigramTests.cs 97.62% <100.00%> (+0.08%) ⬆️

... and 12 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@krwq

krwq commented Nov 26, 2026

Copy link
Copy Markdown
Member Author

I think failures I've seen here were unrelated but it feels more red than usual so investigating if there is any correlation between these and if maybe this makes test more flaky than it was (it might make it easier to investigate in such case)

@krwq

krwq commented Nov 26, 2026

Copy link
Copy Markdown
Member Author

So apparently #7906 made it a bit more frequent but it's within noise range

Comment on lines +70 to +71
/// throws <see cref="System.PlatformNotSupportedException"/>, unless <see cref="ApplyBasicTokenization"/> is <see langword="false"/>
/// or <see cref="WordPieceOptions.Normalizer"/> is set, as the option only applies to the default normalizer.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just curious, how can the non-default normalizers remove non-spacing marks without globalization enabled?

{
if (!UnicodeNormalization.IsSupported)
{
throw new PlatformNotSupportedException(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we consider this as a breaking change and document it properly for next release?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can document it, it was previously not working as expected for many scenarios but in many other scenarios it probably didn't matter.

{
public static readonly StripAccentsStep Instance = new StripAccentsStep();
// Not a singleton: if a static instance's constructor threw, the type would stay unusable for the rest of the process.
public StripAccentsStep() => ThrowIfUnicodeNormalizationNotSupported(NormalizationForm.FormD);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we have to throw for strip accents also? I think we should be able to drop some accents even without running NFD. However, it would be good to align this with HuggingFace behavior.

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.

BertTokenizer: RemoveNonSpacingMarks = true fails to strip accents from precomposed characters under invariant globalization

3 participants