Skip to content

Refactor Tokenizer -> BaseTokenizer - #1333

Merged
H-Huang merged 1 commit into
pytorch:mainfrom
H-Huang:tokenizer_changes
Jul 10, 2025
Merged

H-Huang merged 1 commit into
pytorch:mainfrom
H-Huang:tokenizer_changes

Conversation

@H-Huang

@H-Huang H-Huang commented Jun 24, 2025 •

Copy link
Copy Markdown
Contributor

This causes breaking changes and users will need to redownload the tokenizer files (python scripts/download_tokenizer.py ...)

  • Remove tiktoken dependency, remove tiktoken.py
  • Refactor the Tokenizer base class
  • Update config files to point to directory instead of tokenizer.model
  • Raise exception if using tokenizer.model for tokenizer_path

@facebook-github-bot facebook-github-bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jun 24, 2025
@H-Huang
H-Huang force-pushed the tokenizer_changes branch 3 times, most recently from 76476bc to 8876a97 Compare July 3, 2025 15:18
@H-Huang H-Huang changed the title [WIP] Refactor Tokenizer -> BaseTokenizer Refactor Tokenizer -> BaseTokenizer Jul 3, 2025
@H-Huang
H-Huang marked this pull request as ready for review July 3, 2025 16:20

@tianyu-l tianyu-l 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.

Looks great in general. Left some comments.

Comment thread .ci/docker/requirements.txt Resolved
Comment thread .ci/docker/requirements-dev.txt Resolved
Comment thread CONTRIBUTING.md Outdated
3. If you've changed APIs, update the documentation.
4. Ensure the test suite passes.
5. Make sure your code lints (`pre-commit run --all-files`).
5. Make sure your code lints (`pre-commit run --from-ref origin/main --to-ref HEAD`).

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.

IIUC this is restricting the linting to be changes between current main and the latest commit. Can I ask why?

@H-Huang H-Huang Jul 8, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I needed to update this because when I was running pre-commit run --all-files, it includes files not in my pending changes so I was getting a lot of errors for files under torchtitan/experiments/kernels/. I updated this it to be pre-commit run --files $(git diff --name-only HEAD~1) which is more general

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.

I was getting a lot of errors for files under torchtitan/experiments/kernels/

That sounds very bad. I'm not sure how it escaped the check in https://github.com/pytorch/torchtitan/blob/main/.github/workflows/lint.yaml#L37

I don't think we should change official CONTRIBUTING.md to accommodate bad behavior. We should either refactor the code to make sure lint passes in all conditions, or just delete those code. We can do this in separate PRs.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

That sounds very bad. I'm not sure how it escaped the check in https://github.com/pytorch/torchtitan/blob/main/.github/workflows/lint.yaml#L37

This only lints the changed files, but yeah not sure how it was checked-in in the first place. Will do that in follow up, seems doable to update

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.

what's the source of the files under tests/assets/tokenizer?
asking because not sure about legal side of things

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The old test_tiktoken.model had a truncated vocabluary of 2000 based on tokenizer.model. Likewise I chatGPTed a python script that takes tokenizer.json and reduces it to 2000 tokens.

So this isn't pulled from anywhere, but it is derived from llama-3.1-8B like before, which i assume is okay

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.

Previously the tokenizer.model is a fake one taken from some other repo.
What matters is not vocab size, but legal issue -- we can't use llama tokenizer directly due to legal reasons. If your new tokenizer is capable of dealing with .model tokenizer, could we keep the old one?

@wwwjn wwwjn Jul 9, 2025 •

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.

So we want to keep test_tiktoken.model because of CI tests? I remember CI do has access to network. Can we let integration test to download the tokenizer from Llama repo, and then run the integration test, does this sounds all right?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This PR adds tests/assets/tokenizer/tokenizer.json which is functionally the same as test_tiktoken.model and I updated the .toml and tests to reference this instead

Comment thread torchtitan/components/tokenizer.py Resolved
Comment thread torchtitan/components/tokenizer.py Resolved
@H-Huang
H-Huang force-pushed the tokenizer_changes branch from 8876a97 to 4883438 Compare July 8, 2025 19:00
@H-Huang
H-Huang force-pushed the tokenizer_changes branch 2 times, most recently from 9b2bb40 to bbdca16 Compare July 10, 2025 15:14

@tianyu-l tianyu-l 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.

LGTM, let's fix the linting thing in followup PRs.

Also please make sure CI passes / understand the error is not related.

@H-Huang

H-Huang commented Jul 10, 2025

Copy link
Copy Markdown
Contributor Author

After #1343, these changes are causing this test:

torchrun --nproc_per_node=4 --rdzv_backend c10d --rdzv_endpoint=localhost:0 --local-ranks-filter 0,1,2,3 --role rank --tee 3 -m torchtitan.train --job.config_file ./torchtitan/models/llama3/train_configs/debug_model.toml --model.name llama3_simple_fsdp --training.compile --job.dump_folder artifacts-to-be-uploaded/2d --parallelism.tensor_parallel_degree 2

to fail. The hypothesis is that embedding layer doesn't have padding and uneven sharding might result in this bug

@H-Huang
H-Huang force-pushed the tokenizer_changes branch from bbdca16 to 69dab01 Compare July 10, 2025 19:34
@H-Huang

H-Huang commented Jul 10, 2025

Copy link
Copy Markdown
Contributor Author

Update after changing the test vocab_size from 2002 -> 2000, now the test above is passing

@H-Huang
H-Huang merged commit 681df50 into pytorch:main Jul 10, 2025
name = "llama3"
flavor = "405B"
tokenizer_path = "./assets/tokenizer/original/tokenizer.model"
tokenizer_path = "./assets/tokenizer/Llama-3.1-8B"

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.

Path is inconsistent with the download path here:

python scripts/download_tokenizer.py --repo_id meta-llama/Meta-Llama-3.1-8B --hf_token=...

@H-Huang H-Huang Jul 11, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

My bad, surprisingly both of these will work:
python scripts/download_tokenizer.py --repo_id meta-llama/Llama-3.1-8B
python scripts/download_tokenizer.py --repo_id meta-llama/Meta-Llama-3.1-8B

but the README and toml are using different folder names, I will update the README to just specify meta-llama/Llama-3.1-8B, please do
python scripts/download_tokenizer.py --repo_id meta-llama/Llama-3.1-8B

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fix: #1381

H-Huang added a commit that referenced this pull request Jul 11, 2025
Fix
#1333 (comment)

Downloading from both `Meta-Llama-3.1-8B` and `Llama-3.1-8B` work, but
the README instructions and the .toml file are different. This changes
so the README matches
idoh pushed a commit to idoh/torchtitan that referenced this pull request Jul 28, 2025
This causes breaking changes and users will need to redownload the
tokenizer files (`python scripts/download_tokenizer.py ...`)

- Remove `tiktoken` dependency, remove `tiktoken.py`
- Refactor the `Tokenizer` base class
- Update config files to point to directory instead of `tokenizer.model`
- Raise exception if using `tokenizer.model` for tokenizer_path
idoh pushed a commit to idoh/torchtitan that referenced this pull request Jul 28, 2025
Fix
pytorch#1333 (comment)

Downloading from both `Meta-Llama-3.1-8B` and `Llama-3.1-8B` work, but
the README instructions and the .toml file are different. This changes
so the README matches
xrsrke pushed a commit to NousResearch/torchtitan that referenced this pull request Feb 13, 2026
This causes breaking changes and users will need to redownload the
tokenizer files (`python scripts/download_tokenizer.py ...`)

- Remove `tiktoken` dependency, remove `tiktoken.py`
- Refactor the `Tokenizer` base class
- Update config files to point to directory instead of `tokenizer.model`
- Raise exception if using `tokenizer.model` for tokenizer_path
xrsrke pushed a commit to NousResearch/torchtitan that referenced this pull request Feb 13, 2026
Fix
pytorch#1333 (comment)

Downloading from both `Meta-Llama-3.1-8B` and `Llama-3.1-8B` work, but
the README instructions and the .toml file are different. This changes
so the README matches
xrsrke pushed a commit to NousResearch/torchtitan that referenced this pull request Feb 25, 2026
This causes breaking changes and users will need to redownload the
tokenizer files (`python scripts/download_tokenizer.py ...`)

- Remove `tiktoken` dependency, remove `tiktoken.py`
- Refactor the `Tokenizer` base class
- Update config files to point to directory instead of `tokenizer.model`
- Raise exception if using `tokenizer.model` for tokenizer_path
xrsrke pushed a commit to NousResearch/torchtitan that referenced this pull request Feb 25, 2026
Fix
pytorch#1333 (comment)

Downloading from both `Meta-Llama-3.1-8B` and `Llama-3.1-8B` work, but
the README instructions and the .toml file are different. This changes
so the README matches
weifengpy added a commit that referenced this pull request Aug 21, 2026
Every non-debug Kimi config fails while building its tokenizer. Moonshot
publishes vocabularies as ``tiktoken.model``, and torchtitan's tokenizer reads
``tokenizer.json`` or a vocab/merges pair, so ``moonlight_16b_a3b``,
``kimi_vl_a3b`` and ``kimi_k2_5`` all raise "No supported tokenizer files
found". Only the debug model works, because it points at the bundled test
tokenizer. This has been true since #3532 added those configs, 12 months after
#1333 removed tiktoken support and standardized on HuggingFace tokenizers.

Rebuild the equivalent tokenizer.json during ``download_hf_assets.py`` rather
than teaching the runtime a second vocabulary format, which keeps #1333's
decision intact.

Reading the tiktoken format and recovering BPE merge pairs from its ranks is
delegated to ``transformers.convert_slow_tokenizer.TikTokenConverter``, so
neither becomes torchtitan's to track as tiktoken evolves. The pre-tokenizer
regex is read from the model's own tokenizer module via its
``tokenizer_config.json`` auto_map, not hardcoded here, so it cannot silently
drift from upstream; ``--pattern`` overrides it for models that expose none.
That leaves one thing upstream cannot supply: special-token ids.
``added_tokens_decoder`` names only some reserved slots -- Moonlight names 9
across ids 163584-163839 -- and the unnamed ones still occupy ids, so they are
filled with placeholders.

Conversion happens at download rather than at tokenizer load because every rank
builds a tokenizer; converting at load would have them race to write the same
file, and guarding that needs process-group awareness the tokenizer component
should not have.

``transformers`` and ``tiktoken`` are needed to run the script. Both are
already used under scripts/ -- numerical_tests_kimi.py imports transformers and
documents needing tiktoken -- and trust_remote_code is already used there for
this same model family. tiktoken joins requirements-dev.txt so CI exercises the
conversion. Nothing reaches the training runtime, which still reads only
tokenizer.json.

Test plan:
- pytest tests/unit_tests/test_convert_tiktoken.py -- 10 passed. Special-token
  id placement is covered without any optional dependency; the conversion tests
  skip when transformers/tiktoken are absent.
- Cross-checked against reference tiktoken on the real Moonlight vocabulary:
  812 strings from repo sources plus CJK, emoji, whitespace and literal
  special-token text encode to identical ids, 0 mismatches.
- The delegated output was also compared against a hand-rolled implementation
  of the same conversion over 667 strings: 0 mismatches, and the regex read
  from the model matched the published pat_str exactly.
- Converted vocabulary is 163840 tokens, matching moonlight_16b_a3b's
  decoder_vocab_size; moonlight_16b_a3b().tokenizer.build() now succeeds from
  its own hf_assets_path with bos=163584 eos=163585.
- End to end: `download_hf_assets.py --repo_id moonshotai/Moonlight-16B-A3B
  --assets tokenizer` fetches tiktoken.model plus the tokenization module and
  writes tokenizer.json.

ghstack-source-id: 77a1c96
Pull-Request: #4262
weifengpy added a commit that referenced this pull request Aug 21, 2026
Kimi's non-debug configs cannot build a tokenizer. Moonshot ships vocabularies
as ``tiktoken.model``, and torchtitan reads ``tokenizer.json`` or a
vocab/merges pair, so ``moonlight_16b_a3b``, ``kimi_vl_a3b`` and
``kimi_k2_5`` all raise "No supported tokenizer files found". Only the debug
model works, because it points at the bundled test tokenizer. That has been
true since #3532 added them, a year after #1333 dropped tiktoken and
standardized on HuggingFace tokenizers.

Convert during ``download_hf_assets.py``. Nothing is added to the runtime, the
install, or the dev requirements -- the conversion uses ``tokenizers``, already
required, and ``tiktoken`` stays gone.

Two things the file does not store have to be reconstructed. A BPE model needs
the pair each token was merged from, but tiktoken records only the rank it was
learned at; replaying the merge loop over a token's own bytes, stopping below
its rank, leaves the two halves. And ``tokenizers`` keys its vocabulary by
``str`` where tiktoken uses bytes, so the usual byte-to-character mapping
applies. The pre-tokenizer regex is not in the file either and is
model-specific, so Moonshot's is a named constant.

Special tokens keep their configured ids: ``added_tokens_decoder`` names only
some reserved slots, and the unnamed ones still occupy ids, so they are filled
with placeholders.

Test plan:
- pytest tests/unit_tests/test_convert_tiktoken.py -- 3 passed.
- Cross-checked against reference tiktoken on the real Moonlight vocabulary:
  812 strings from repo sources plus CJK, emoji, whitespace and literal
  special-token text encode to identical ids, 0 mismatches. tiktoken was
  installed locally for that check only.
- 163840 tokens, matching moonlight_16b_a3b's decoder_vocab_size;
  ``moonlight_16b_a3b().tokenizer.build()`` now succeeds from its own
  hf_assets_path with bos=163584 eos=163585.

ghstack-source-id: da16c92
Pull-Request: #4262
weifengpy added a commit that referenced this pull request Aug 21, 2026
Kimi's non-debug configs cannot build a tokenizer. The Kimi family ships its
vocabulary as ``tiktoken.model``, and torchtitan reads ``tokenizer.json`` or a
vocab/merges pair, so ``kimi_k2_5``, ``kimi_vl_a3b`` and ``moonlight_16b_a3b``
all raise "No supported tokenizer files found". Only the debug model works,
because it points at the bundled test tokenizer. That has been true since #3532
added them, a year after #1333 dropped tiktoken and standardized on HuggingFace
tokenizers.

Convert during ``download_hf_assets.py``. Nothing is added to the runtime, the
install, or the dev requirements -- the conversion uses ``tokenizers``, already
required, and ``tiktoken`` stays gone.

Two things the file does not store have to be reconstructed. A BPE model needs
the pair each token was merged from, but tiktoken records only the rank it was
learned at; replaying the merge loop over a token's own bytes, stopping below
its rank, leaves the two halves. And ``tokenizers`` keys its vocabulary by
``str`` where tiktoken uses bytes, so the usual byte-to-character mapping
applies. The pre-tokenizer regex is not in the file either, so Kimi's is a
named constant.

Special tokens keep their configured ids: ``added_tokens_decoder`` names only
some reserved slots, and the unnamed ones still occupy ids, so they are filled
with placeholders.

Test plan:
- pytest tests/unit_tests/test_convert_tiktoken.py -- 3 passed.
- Cross-checked against reference tiktoken on the real Kimi vocabulary: 812
  strings from repo sources plus CJK, emoji, whitespace and literal
  special-token text encode to identical ids, 0 mismatches. tiktoken was
  installed locally for that check only.
- 163840 tokens, matching the Kimi decoder_vocab_size;
  ``moonlight_16b_a3b().tokenizer.build()`` now succeeds from its own
  hf_assets_path with bos=163584 eos=163585.

ghstack-source-id: 9b29e5e
Pull-Request: #4262
weifengpy added a commit that referenced this pull request Aug 21, 2026
Kimi's non-debug configs cannot build a tokenizer. The Kimi family ships its
vocabulary as ``tiktoken.model``, and torchtitan reads ``tokenizer.json`` or a
vocab/merges pair, so ``kimi_k2_5``, ``kimi_vl_a3b`` and ``moonlight_16b_a3b``
all raise "No supported tokenizer files found". Only the debug model works,
because it points at the bundled test tokenizer. That has been true since #3532
added them, a year after #1333 dropped tiktoken and standardized on HuggingFace
tokenizers.

Convert during ``download_hf_assets.py``. Nothing is added to the runtime, the
install, or the dev requirements -- the conversion uses ``tokenizers``, already
required, and ``tiktoken`` stays gone.

Two things the file does not store have to be reconstructed. A BPE model needs
the pair each token was merged from, but tiktoken records only the rank it was
learned at; replaying the merge loop over a token's own bytes, stopping below
its rank, leaves the two halves. And ``tokenizers`` keys its vocabulary by
``str`` where tiktoken uses bytes, so the usual byte-to-character mapping
applies. The pre-tokenizer regex is not in the file either, so Kimi's is a
named constant.

Special tokens keep their configured ids: ``added_tokens_decoder`` names only
some reserved slots, and the unnamed ones still occupy ids, so they are filled
with placeholders.

Test plan:
- Cross-checked against reference tiktoken on the real Kimi vocabulary: 812
  strings from repo sources plus CJK, emoji, whitespace and literal
  special-token text encode to identical ids, 0 mismatches. tiktoken was
  installed locally for that check only.
- 163840 tokens, matching the Kimi decoder_vocab_size;
  ``moonlight_16b_a3b().tokenizer.build()`` now succeeds from its own
  hf_assets_path with bos=163584 eos=163585.

ghstack-source-id: c4b9ef6
Pull-Request: #4262
weifengpy added a commit that referenced this pull request Aug 21, 2026
Kimi's non-debug configs cannot build a tokenizer. The Kimi family ships its
vocabulary as ``tiktoken.model``, and torchtitan reads ``tokenizer.json`` or a
vocab/merges pair, so ``kimi_k2_5``, ``kimi_vl_a3b`` and ``moonlight_16b_a3b``
all raise "No supported tokenizer files found". Only the debug model works,
because it points at the bundled test tokenizer. That has been true since #3532
added them, a year after #1333 dropped tiktoken and standardized on HuggingFace
tokenizers.

Convert during ``download_hf_assets.py``. Nothing is added to the runtime, the
install, or the dev requirements -- the conversion uses ``tokenizers``, already
required, and ``tiktoken`` stays gone.

Two things the file does not store have to be reconstructed. A BPE model needs
the pair each token was merged from, but tiktoken records only the rank it was
learned at; replaying the merge loop over a token's own bytes, stopping below
its rank, leaves the two halves. And ``tokenizers`` keys its vocabulary by
``str`` where tiktoken uses bytes, so the usual byte-to-character mapping
applies. The pre-tokenizer regex is not in the file either, so Kimi's is a
named constant.

Special tokens keep their configured ids: ``added_tokens_decoder`` names only
some reserved slots, and the unnamed ones still occupy ids, so they are filled
with placeholders.

Test plan:
- Cross-checked against reference tiktoken on the real Kimi vocabulary: 812
  strings from repo sources plus CJK, emoji, whitespace and literal
  special-token text encode to identical ids, 0 mismatches. tiktoken was
  installed locally for that check only.
- 163840 tokens, matching the Kimi decoder_vocab_size;
  ``moonlight_16b_a3b().tokenizer.build()`` now succeeds from its own
  hf_assets_path with bos=163584 eos=163585.

ghstack-source-id: 8e87830
Pull-Request: #4262
weifengpy added a commit that referenced this pull request Aug 21, 2026
Kimi's non-debug configs cannot build a tokenizer. The Kimi family ships its
vocabulary as ``tiktoken.model``, and torchtitan reads ``tokenizer.json`` or a
vocab/merges pair, so ``kimi_k2_5``, ``kimi_vl_a3b`` and ``moonlight_16b_a3b``
all raise "No supported tokenizer files found". Only the debug model works,
because it points at the bundled test tokenizer. That has been true since #3532
added them, a year after #1333 dropped tiktoken and standardized on HuggingFace
tokenizers.

Convert during ``download_hf_assets.py``. Nothing is added to the runtime, the
install, or the dev requirements -- the conversion uses ``tokenizers``, already
required, and ``tiktoken`` stays gone.

Two things the file does not store have to be reconstructed. A BPE model needs
the pair each token was merged from, but tiktoken records only the rank it was
learned at; replaying the merge loop over a token's own bytes, stopping below
its rank, leaves the two halves. And ``tokenizers`` keys its vocabulary by
``str`` where tiktoken uses bytes, so the usual byte-to-character mapping
applies. The pre-tokenizer regex is not in the file either, so Kimi's is a
named constant.

Special tokens keep their configured ids: ``added_tokens_decoder`` names only
some reserved slots, and the unnamed ones still occupy ids, so they are filled
with placeholders.

Test plan:
- Cross-checked against reference tiktoken on the real Kimi vocabulary: 812
  strings from repo sources plus CJK, emoji, whitespace and literal
  special-token text encode to identical ids, 0 mismatches. tiktoken was
  installed locally for that check only.
- 163840 tokens, matching the Kimi decoder_vocab_size;
  ``moonlight_16b_a3b().tokenizer.build()`` now succeeds from its own
  hf_assets_path with bos=163584 eos=163585.

ghstack-source-id: 8e87830
Pull-Request: #4262
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants