[Fix] Special token encoding in MistralCommonBackend
Author: adi776borate
Pull request: yes

# What does this PR do?

<!--
Congratulations! You've made it this far! You're not quite done yet though.

Once merged, your PR is going to appear in the release notes with the title you set, so make sure it's a great title that fully reflects the extent of your awesome contribution.

Then, please replace this with a description of the change and which issue is fixed (if applicable). Please also include relevant motivation and context. List any dependencies (if any) that are required for this change.

Once you're done, someone will review your PR shortly (see the section "Who can review?" below to tag some potential reviewers). They may suggest changes to make the code even better. If no one reviewed your PR after a week has passed, don't hesitate to post a new comment @-mentioning the same persons---sometimes notifications get lost.
-->

<!-- Remove if not applicable -->

Fixes #43110 

This PR fixes an issue in the `MistralCommonBackend` tokenizer where special tokens (such as `[IMG]`, `
`, `[TOOL_CALLS]`) were incorrectly being split into multiple tokens instead of being mapped to their single, corresponding special token ID.

## Problem
The `MistralCommonBackend` wrapper was passing input text directly to the underlying `mistral_common` tokenizer's encode method. Unlike the `PythonBackend` or `Fast` tokenizers, it lacked a pre-tokenization step to identify and isolate special tokens. As a result, model-specific/extra special tokens were treated as regular string content and fragmented, leading to [this error](https://github.com/huggingface/transformers/issues/43110#issuecomment-3717684309).

<details>
<summary> Independent Reproduction Script </summary>

```python

import unittest
from transformers import AutoTokenizer
from transformers.tokenization_mistral_common import MistralCommonBackend
from transformers.utils import is_mistral_common_available

if not is_mistral_common_available():
    print("Mistral Common is not available. Skipping verification.")
    exit(0)

class Verification(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.repo_id = "RedHatAI/Mistral-Small-3.2-24B-Instruct-2506-NVFP4"
        print(f"Loading tokenizer from {cls.repo_id}...")
        cls.tokenizer = AutoTokenizer.from_pretrained(
            cls.repo_id, 
            trust_remote_code=True, 
            tokenizer_type="mistral"
        )
        print(f"Loaded backend: {type(cls.tokenizer).__name__}")

    def test_special_token_handling(self):
        print("\nRunning test_special_token_handling...")
        special_tokens_to_test = ["[IMG]", "
", "
"]
        
        vocab = self.tokenizer.get_vocab()
        available_special_tokens = [t for t in special_tokens_to_test if t in vocab]
        
        print(f"Testing with special tokens: {available_special_tokens}")

        for special_token in available_special_tokens:
            special_token_id = self.tokenizer.convert_tokens_to_ids(special_token)
            print(f"---\nTesting token: '{special_token}' (ID: {special_token_id})")
            
            # Case 1: Special token alone
            tokens = self.tokenizer.encode(special_token, add_special_tokens=False)
            print(f"Encoded '{special_token}' (add_special_tokens=False) -> {tokens}")
            
            self.assertEqual(len(tokens), 1, f"Failed: {special_token} was split into {len(tokens)} tokens: {tokens}")
            self.assertEqual(tokens[0], special_token_id, f"Failed: Token ID mismatch. Expected {special_token_id}, got {tokens[0]}")
            
            # Case 2: check with add_special_tokens=True (Should be [BOS, TOKEN])
            tokens_with_special = self.tokenizer.encode(special_token, add_special_tokens=True)
            print(f"Encoded '{special_token}' (add_special_tokens=True)  -> {tokens_with_special}")
            self.assertEqual(len(tokens_with_special), 2, "Expected exactly 2 tokens (BOS + SPECIAL)")
            self.assertEqual(tokens_with_special[1], special_token_id)

            # Case 3: Special token in sentence
            text = f"Hello {special_token} world"
            tokens = self.tokenizer.encode(text, add_special_tokens=False)
            print(f"Encoded '{text}' -> {tokens}")
            self.assertIn(special_token_id, tokens, f"Failed to find {special_token} ID in tokens")
            
            # Decode check
            decoded = self.tokenizer.decode(tokens)
            print(f"Decoded -> '{decoded}'")
            self.assertIn(special_token, decoded)

        # Case 4: Mixed special tokens
        if len(available_special_tokens) >= 2:
            t1 = available_special_tokens[0]
            t2 = available_special_tokens[1]
            t1_id = self.tokenizer.convert_tokens_to_ids(t1)
            t2_id = self.tokenizer.convert_tokens_to_ids(t2)
            
            text = f"{t1} text {t2}"
            print(f"---\nTesting mixed: '{text}'")
            tokens = self.tokenizer.encode(text, add_special_tokens=False)
            print(f"Encoded -> {tokens}")
            self.assertEqual(tokens[0], t1_id)
            self.assertEqual(tokens[-1], t2_id)
        
        print("\nSUCCESS: All special token tests PASSED.")

if __name__ == "__main__":
    unittest.main()
```
</details>

## Solution
I have aligned the `MistralCommonBackend` implementation with the `PythonBackend`'s strategy for handling special tokens which is uses Trie-based pre-splitting. The input text is now split using the Trie and segments matching a special token are converted directly to their ID using a new `_special_token_to_id` helper.

## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [x] Did you read the [contributor guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#create-a-pull-request),
      Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the [forum](https://discuss.huggingface.co/)? Please add a link
      to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes? Here are the
      [documentation guidelines](https://github.com/huggingface/transformers/tree/main/docs), and
      [here are tips on formatting docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [x] Did you write any new necessary tests?


## Who can review?
@ArthurZucker @juliendenize 
Anyone in the community is free to review the PR once the tests have passed.

<!-- Your PR will be replied to more quickly if you can figure out the right person to tag with @

 If you know how to use git blame, that is the easiest way, otherwise, here is a rough guide of **who to tag**.
 Please tag fewer than 3 people.

Models:

- text models: @ArthurZucker @Cyrilvallez
- vision models: @yonigozlan @molbap
- audio models: @eustlb @ebezzam @vasqu
- multimodal models: @zucchini-nlp
- graph models: @clefourrier

Library:

- generate: @zucchini-nlp (visual-language models) or @gante (all others)
- continuous batching: @remi-or @ArthurZucker @McPatate
- pipelines: @Rocketknight1
- tokenizers: @ArthurZucker and @itazap
- trainer: @SunMarc
- attention: @vasqu @ArthurZucker @CyrilVallez
- model loading (from pretrained, etc): @CyrilVallez
- distributed: @3outeille @ArthurZucker
- CIs: @ydshieh

Integrations:

- ray/raytune: @richardliaw, @amogkam
- Big Model Inference: @SunMarc
- quantization: @SunMarc @MekkCyber
- kernels: @MekkCyber @drbh
- peft: @BenjaminBossan @githubnemo

Devices/Backends:

- AMD ROCm: @ivarflakstad
- Intel XPU: @IlyasMoutawwakil
- Ascend NPU: @ivarflakstad 

Documentation: @stevhliu

Research projects are not maintained and should be taken as is.

 -->


Comments:
Hello, this is not a bug but a feature. In mistral-common we never encode special tokens manually and will never allow it.