Repository: huggingface/tokenizers Branch: main Commit: c4e27cfc84d7 Files: 347 Total size: 4.1 MB Directory structure: gitextract_9bwzq4yg/ ├── .github/ │ ├── conda/ │ │ ├── bld.bat │ │ ├── build.sh │ │ └── meta.yaml │ ├── stale.yml │ └── workflows/ │ ├── CI.yml │ ├── build_documentation.yml │ ├── build_pr_documentation.yml │ ├── delete_doc_comment.yml │ ├── delete_doc_comment_trigger.yml │ ├── docs-check.yml │ ├── node-release.yml │ ├── node.yml │ ├── python-release.yml │ ├── python.yml │ ├── rust-release.yml │ ├── rust.yml │ ├── stale.yml │ ├── trufflehog.yml │ └── upload_pr_documentation.yml ├── .gitignore ├── CITATION.cff ├── LICENSE ├── README.md ├── RELEASE.md ├── bindings/ │ ├── node/ │ │ ├── .cargo/ │ │ │ └── config.toml │ │ ├── .editorconfig │ │ ├── .eslintrc.yml │ │ ├── .gitattributes │ │ ├── .gitignore │ │ ├── .prettierignore │ │ ├── .taplo.toml │ │ ├── .yarn/ │ │ │ └── releases/ │ │ │ └── yarn-3.5.1.cjs │ │ ├── .yarnrc.yml │ │ ├── Cargo.toml │ │ ├── LICENSE │ │ ├── Makefile │ │ ├── README.md │ │ ├── build.rs │ │ ├── examples/ │ │ │ └── documentation/ │ │ │ ├── pipeline.test.ts │ │ │ └── quicktour.test.ts │ │ ├── index.d.ts │ │ ├── index.js │ │ ├── jest.config.js │ │ ├── lib/ │ │ │ └── bindings/ │ │ │ ├── __mocks__/ │ │ │ │ ├── merges.txt │ │ │ │ ├── vocab.json │ │ │ │ └── vocab.txt │ │ │ ├── decoders.test.ts │ │ │ ├── encoding.test.ts │ │ │ ├── models.test.ts │ │ │ ├── normalizers.test.ts │ │ │ ├── post-processors.test.ts │ │ │ ├── pre-tokenizers.test.ts │ │ │ ├── tokenizer.test.ts │ │ │ └── utils.test.ts │ │ ├── npm/ │ │ │ ├── android-arm-eabi/ │ │ │ │ ├── README.md │ │ │ │ └── package.json │ │ │ ├── android-arm64/ │ │ │ │ ├── README.md │ │ │ │ └── package.json │ │ │ ├── darwin-arm64/ │ │ │ │ ├── README.md │ │ │ │ └── package.json │ │ │ ├── darwin-x64/ │ │ │ │ ├── README.md │ │ │ │ └── package.json │ │ │ ├── freebsd-x64/ │ │ │ │ ├── README.md │ │ │ │ └── package.json │ │ │ ├── linux-arm-gnueabihf/ │ │ │ │ ├── README.md │ │ │ │ └── package.json │ │ │ ├── linux-arm64-gnu/ │ │ │ │ ├── README.md │ │ │ │ └── package.json │ │ │ ├── linux-arm64-musl/ │ │ │ │ ├── README.md │ │ │ │ └── package.json │ │ │ ├── linux-x64-gnu/ │ │ │ │ ├── README.md │ │ │ │ └── package.json │ │ │ ├── linux-x64-musl/ │ │ │ │ ├── README.md │ │ │ │ └── package.json │ │ │ ├── win32-arm64-msvc/ │ │ │ │ ├── README.md │ │ │ │ └── package.json │ │ │ ├── win32-ia32-msvc/ │ │ │ │ ├── README.md │ │ │ │ └── package.json │ │ │ └── win32-x64-msvc/ │ │ │ ├── README.md │ │ │ └── package.json │ │ ├── package.json │ │ ├── rustfmt.toml │ │ ├── src/ │ │ │ ├── arc_rwlock_serde.rs │ │ │ ├── decoders.rs │ │ │ ├── encoding.rs │ │ │ ├── lib.rs │ │ │ ├── models.rs │ │ │ ├── normalizers.rs │ │ │ ├── pre_tokenizers.rs │ │ │ ├── processors.rs │ │ │ ├── tasks/ │ │ │ │ ├── mod.rs │ │ │ │ ├── models.rs │ │ │ │ └── tokenizer.rs │ │ │ ├── tokenizer.rs │ │ │ ├── trainers.rs │ │ │ └── utils.rs │ │ ├── tsconfig.json │ │ └── types.ts │ └── python/ │ ├── .cargo/ │ │ └── config.toml │ ├── .gitignore │ ├── CHANGELOG.md │ ├── Cargo.toml │ ├── MANIFEST.in │ ├── Makefile │ ├── README.md │ ├── benches/ │ │ └── test_tiktoken.py │ ├── conftest.py │ ├── docs/ │ │ └── pyo3.md │ ├── examples/ │ │ ├── custom_components.py │ │ ├── example.py │ │ ├── train_bert_wordpiece.py │ │ ├── train_bytelevel_bpe.py │ │ ├── train_with_datasets.py │ │ └── using_the_visualizer.ipynb │ ├── py_src/ │ │ └── tokenizers/ │ │ ├── __init__.py │ │ ├── __init__.pyi │ │ ├── decoders/ │ │ │ └── __init__.py │ │ ├── decoders.pyi │ │ ├── implementations/ │ │ │ ├── __init__.py │ │ │ ├── base_tokenizer.py │ │ │ ├── bert_wordpiece.py │ │ │ ├── byte_level_bpe.py │ │ │ ├── char_level_bpe.py │ │ │ ├── sentencepiece_bpe.py │ │ │ └── sentencepiece_unigram.py │ │ ├── models/ │ │ │ └── __init__.py │ │ ├── models.pyi │ │ ├── normalizers/ │ │ │ └── __init__.py │ │ ├── normalizers.pyi │ │ ├── pre_tokenizers/ │ │ │ └── __init__.py │ │ ├── pre_tokenizers.pyi │ │ ├── processors/ │ │ │ └── __init__.py │ │ ├── processors.pyi │ │ ├── py.typed │ │ ├── tokenizers.pyi │ │ ├── tools/ │ │ │ ├── __init__.py │ │ │ ├── visualizer-styles.css │ │ │ └── visualizer.py │ │ ├── trainers/ │ │ │ ├── __init__.py │ │ │ └── __init__.pyi │ │ └── trainers.pyi │ ├── pyproject.toml │ ├── rust-toolchain │ ├── scripts/ │ │ ├── convert.py │ │ ├── sentencepiece_extractor.py │ │ └── spm_parity_check.py │ ├── setup.cfg │ ├── src/ │ │ ├── decoders.rs │ │ ├── encoding.rs │ │ ├── error.rs │ │ ├── lib.rs │ │ ├── models.rs │ │ ├── normalizers.rs │ │ ├── pre_tokenizers.rs │ │ ├── processors.rs │ │ ├── token.rs │ │ ├── tokenizer.rs │ │ ├── trainers.rs │ │ └── utils/ │ │ ├── iterators.rs │ │ ├── mod.rs │ │ ├── normalization.rs │ │ ├── pretokenization.rs │ │ ├── regex.rs │ │ └── serde_pyo3.rs │ ├── stub.py │ ├── test.txt │ ├── tests/ │ │ ├── __init__.py │ │ ├── bindings/ │ │ │ ├── __init__.py │ │ │ ├── test_decoders.py │ │ │ ├── test_encoding.py │ │ │ ├── test_models.py │ │ │ ├── test_normalizers.py │ │ │ ├── test_pre_tokenizers.py │ │ │ ├── test_processors.py │ │ │ ├── test_tokenizer.py │ │ │ └── test_trainers.py │ │ ├── documentation/ │ │ │ ├── __init__.py │ │ │ ├── test_pipeline.py │ │ │ ├── test_quicktour.py │ │ │ └── test_tutorial_train_from_iterators.py │ │ ├── implementations/ │ │ │ ├── __init__.py │ │ │ ├── test_base_tokenizer.py │ │ │ ├── test_bert_wordpiece.py │ │ │ ├── test_byte_level_bpe.py │ │ │ ├── test_char_bpe.py │ │ │ └── test_sentencepiece.py │ │ ├── test_serialization.py │ │ └── utils.py │ └── tools/ │ └── stub-gen/ │ ├── Cargo.toml │ └── src/ │ └── main.rs ├── docs/ │ ├── Makefile │ ├── README.md │ ├── source/ │ │ ├── _ext/ │ │ │ ├── entities.py │ │ │ ├── rust_doc.py │ │ │ └── toctree_tags.py │ │ ├── _static/ │ │ │ ├── css/ │ │ │ │ ├── Calibre-Medium.otf │ │ │ │ ├── Calibre-Regular.otf │ │ │ │ ├── Calibre-Thin.otf │ │ │ │ ├── code-snippets.css │ │ │ │ └── huggingface.css │ │ │ └── js/ │ │ │ └── custom.js │ │ ├── api/ │ │ │ ├── node.inc │ │ │ ├── python.inc │ │ │ ├── reference.rst │ │ │ └── rust.inc │ │ ├── components.rst │ │ ├── conf.py │ │ ├── entities.inc │ │ ├── index.rst │ │ ├── installation/ │ │ │ ├── main.rst │ │ │ ├── node.inc │ │ │ ├── python.inc │ │ │ └── rust.inc │ │ ├── pipeline.rst │ │ ├── quicktour.rst │ │ └── tutorials/ │ │ └── python/ │ │ └── training_from_memory.rst │ └── source-doc-builder/ │ ├── _toctree.yml │ ├── api/ │ │ ├── added-tokens.mdx │ │ ├── decoders.mdx │ │ ├── encode-inputs.mdx │ │ ├── encoding.mdx │ │ ├── input-sequences.mdx │ │ ├── models.mdx │ │ ├── normalizers.mdx │ │ ├── post-processors.mdx │ │ ├── pre-tokenizers.mdx │ │ ├── tokenizer.mdx │ │ ├── trainers.mdx │ │ └── visualizer.mdx │ ├── components.mdx │ ├── index.mdx │ ├── installation.mdx │ ├── pipeline.mdx │ ├── quicktour.mdx │ └── training_from_memory.mdx └── tokenizers/ ├── CHANGELOG.md ├── Cargo.toml ├── Makefile ├── README.md ├── README.tpl ├── benches/ │ ├── added_vocab_deserialize.rs │ ├── bert_benchmark.rs │ ├── bpe_benchmark.rs │ ├── common/ │ │ └── mod.rs │ ├── layout_benchmark.rs │ ├── llama3_benchmark.rs │ └── unigram_benchmark.rs ├── examples/ │ ├── encode_batch.rs │ ├── serialization.rs │ └── unstable_wasm/ │ ├── .gitignore │ ├── Cargo.toml │ ├── README.md │ ├── src/ │ │ ├── lib.rs │ │ └── utils.rs │ ├── tests/ │ │ └── web.rs │ └── www/ │ ├── .gitignore │ ├── .travis.yml │ ├── LICENSE-APACHE │ ├── LICENSE-MIT │ ├── README.md │ ├── bootstrap.js │ ├── index.html │ ├── index.js │ ├── package.json │ └── webpack.config.js ├── rust-toolchain ├── src/ │ ├── decoders/ │ │ ├── bpe.rs │ │ ├── byte_fallback.rs │ │ ├── ctc.rs │ │ ├── fuse.rs │ │ ├── mod.rs │ │ ├── sequence.rs │ │ ├── strip.rs │ │ └── wordpiece.rs │ ├── lib.rs │ ├── models/ │ │ ├── bpe/ │ │ │ ├── mod.rs │ │ │ ├── model.rs │ │ │ ├── serialization.rs │ │ │ ├── trainer.rs │ │ │ └── word.rs │ │ ├── mod.rs │ │ ├── unigram/ │ │ │ ├── lattice.rs │ │ │ ├── mod.rs │ │ │ ├── model.rs │ │ │ ├── serialization.rs │ │ │ ├── trainer.rs │ │ │ └── trie.rs │ │ ├── wordlevel/ │ │ │ ├── mod.rs │ │ │ ├── serialization.rs │ │ │ └── trainer.rs │ │ └── wordpiece/ │ │ ├── mod.rs │ │ ├── serialization.rs │ │ └── trainer.rs │ ├── normalizers/ │ │ ├── bert.rs │ │ ├── byte_level.rs │ │ ├── mod.rs │ │ ├── precompiled.rs │ │ ├── prepend.rs │ │ ├── replace.rs │ │ ├── strip.rs │ │ ├── unicode.rs │ │ └── utils.rs │ ├── pre_tokenizers/ │ │ ├── bert.rs │ │ ├── byte_level.rs │ │ ├── delimiter.rs │ │ ├── digits.rs │ │ ├── fixed_length.rs │ │ ├── metaspace.rs │ │ ├── mod.rs │ │ ├── punctuation.rs │ │ ├── sequence.rs │ │ ├── split.rs │ │ ├── unicode_scripts/ │ │ │ ├── mod.rs │ │ │ ├── pre_tokenizer.rs │ │ │ └── scripts.rs │ │ └── whitespace.rs │ ├── processors/ │ │ ├── bert.rs │ │ ├── mod.rs │ │ ├── roberta.rs │ │ ├── sequence.rs │ │ └── template.rs │ ├── tokenizer/ │ │ ├── added_vocabulary.rs │ │ ├── encoding.rs │ │ ├── mod.rs │ │ ├── normalizer.rs │ │ ├── pattern.rs │ │ ├── pre_tokenizer.rs │ │ └── serialization.rs │ └── utils/ │ ├── cache.rs │ ├── fancy.rs │ ├── from_pretrained.rs │ ├── iter.rs │ ├── mod.rs │ ├── onig.rs │ ├── padding.rs │ ├── parallelism.rs │ ├── progress.rs │ └── truncation.rs └── tests/ ├── added_tokens.rs ├── common/ │ └── mod.rs ├── documentation.rs ├── from_pretrained.rs ├── offsets.rs ├── serialization.rs ├── stream.rs ├── training.rs └── unigram.rs ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/conda/bld.bat ================================================ cd bindings\python %PYTHON% -m pip install . --prefix=%PREFIX% ================================================ FILE: .github/conda/build.sh ================================================ cd bindings/python $PYTHON -m pip install . --prefix=$PREFIX ================================================ FILE: .github/conda/meta.yaml ================================================ {% set name = "tokenizers" %} package: name: "{{ name|lower }}" version: "{{ TOKENIZERS_VERSION }}" source: path: ../../ requirements: host: - pip - python x.x - setuptools - setuptools-rust - pkg-config - openssl - maturin run: - python x.x test: imports: - tokenizers - tokenizers.models about: home: https://huggingface.co/docs/tokenizers license: Apache License 2.0 license_file: LICENSE summary: "💥 Fast State-of-the-Art Tokenizers optimized for Research and Production" ================================================ FILE: .github/stale.yml ================================================ # Number of days of inactivity before an issue becomes stale daysUntilStale: 60 # Number of days of inactivity before a stale issue is closed daysUntilClose: 7 # Issues with these labels will never be considered stale exemptLabels: - pinned - security # Label to use when marking an issue as stale staleLabel: wontfix # Comment to post when marking an issue as stale. Set to `false` to disable markComment: > This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. # Comment to post when closing a stale issue. Set to `false` to disable closeComment: false ================================================ FILE: .github/workflows/CI.yml ================================================ # This file is autogenerated by maturin v1.7.4 # To update, run # # maturin generate-ci github -m bindings/python/Cargo.toml # name: CI on: push: branches: - main - master tags: - '*' pull_request: workflow_dispatch: permissions: contents: read jobs: linux: runs-on: ${{ matrix.platform.runner }} strategy: matrix: platform: - runner: ubuntu-latest target: x86_64 - runner: ubuntu-latest target: x86 - runner: ubuntu-latest target: aarch64 - runner: ubuntu-latest target: armv7 - runner: ubuntu-latest target: s390x - runner: ubuntu-latest target: ppc64le steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: 3.x - name: Build wheels uses: PyO3/maturin-action@v1 with: target: ${{ matrix.platform.target }} args: --release --out dist --manifest-path bindings/python/Cargo.toml sccache: 'true' manylinux: auto - name: Upload wheels uses: actions/upload-artifact@v4 with: name: wheels-linux-${{ matrix.platform.target }} path: dist musllinux: runs-on: ${{ matrix.platform.runner }} strategy: matrix: platform: - runner: ubuntu-latest target: x86_64 - runner: ubuntu-latest target: x86 - runner: ubuntu-latest target: aarch64 - runner: ubuntu-latest target: armv7 steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: 3.x - name: Build wheels uses: PyO3/maturin-action@v1 with: target: ${{ matrix.platform.target }} args: --release --out dist --manifest-path bindings/python/Cargo.toml sccache: 'true' manylinux: musllinux_1_2 - name: Upload wheels uses: actions/upload-artifact@v4 with: name: wheels-musllinux-${{ matrix.platform.target }} path: dist windows: runs-on: ${{ matrix.platform.runner }} strategy: matrix: platform: - runner: windows-latest target: x64 architecture: x64 - runner: windows-latest target: x86 architecture: x86 - runner: windows-11-arm target: aarch64 architecture: arm64 steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: 3.x architecture: ${{ matrix.platform.architecture }} - name: Build wheels uses: PyO3/maturin-action@v1 with: target: ${{ matrix.platform.target }} args: --release --out dist --manifest-path bindings/python/Cargo.toml sccache: 'true' - name: Upload wheels uses: actions/upload-artifact@v4 with: name: wheels-windows-${{ matrix.platform.target }} path: dist macos: runs-on: ${{ matrix.platform.runner }} strategy: matrix: platform: - runner: macos-15-intel target: x86_64 - runner: macos-14 target: aarch64 steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: 3.x - name: Build wheels uses: PyO3/maturin-action@v1 with: target: ${{ matrix.platform.target }} args: --release --out dist --manifest-path bindings/python/Cargo.toml sccache: 'true' - name: Upload wheels uses: actions/upload-artifact@v4 with: name: wheels-macos-${{ matrix.platform.target }} path: dist sdist: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Build sdist uses: PyO3/maturin-action@v1 with: command: sdist args: --out dist --manifest-path bindings/python/Cargo.toml - name: Upload sdist uses: actions/upload-artifact@v4 with: name: wheels-sdist path: dist release: name: Release runs-on: ubuntu-latest if: ${{ startsWith(github.ref, 'refs/tags/') || github.event_name == 'workflow_dispatch' }} needs: [linux, musllinux, windows, macos, sdist] permissions: # Use to sign the release artifacts id-token: write # Used to upload release artifacts contents: write # Used to generate artifact attestation attestations: write steps: - uses: actions/download-artifact@v4 - name: Generate artifact attestation uses: actions/attest-build-provenance@v1 with: subject-path: 'wheels-*/*' - name: Publish to PyPI if: "startsWith(github.ref, 'refs/tags/')" uses: PyO3/maturin-action@v1 env: MATURIN_PYPI_TOKEN: ${{ secrets.PYPI_TOKEN_DIST}} with: command: upload args: --non-interactive --skip-existing wheels-*/* ================================================ FILE: .github/workflows/build_documentation.yml ================================================ name: Build documentation on: push: branches: - main - doc-builder* - v*-release - use_templates jobs: build: uses: huggingface/doc-builder/.github/workflows/build_main_documentation.yml@main with: commit_sha: ${{ github.sha }} package: tokenizers path_to_docs: tokenizers/docs/source-doc-builder/ package_path: tokenizers/bindings/python/ install_rust: true secrets: hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }} ================================================ FILE: .github/workflows/build_pr_documentation.yml ================================================ name: Build PR Documentation on: pull_request: concurrency: group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} cancel-in-progress: true jobs: build: uses: huggingface/doc-builder/.github/workflows/build_pr_documentation.yml@main with: commit_sha: ${{ github.event.pull_request.head.sha }} pr_number: ${{ github.event.number }} package: tokenizers path_to_docs: tokenizers/docs/source-doc-builder/ package_path: tokenizers/bindings/python/ install_rust: true ================================================ FILE: .github/workflows/delete_doc_comment.yml ================================================ name: Delete doc comment on: workflow_run: workflows: ["Delete doc comment trigger"] types: - completed jobs: delete: uses: huggingface/doc-builder/.github/workflows/delete_doc_comment.yml@main secrets: comment_bot_token: ${{ secrets.COMMENT_BOT_TOKEN }} ================================================ FILE: .github/workflows/delete_doc_comment_trigger.yml ================================================ name: Delete doc comment trigger on: pull_request: types: [ closed ] jobs: delete: uses: huggingface/doc-builder/.github/workflows/delete_doc_comment_trigger.yml@main with: pr_number: ${{ github.event.number }} ================================================ FILE: .github/workflows/docs-check.yml ================================================ name: Documentation on: push: branches: - main pull_request: jobs: build: runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v4 - name: Install Python uses: actions/setup-python@v5 with: python-version: 3.12 - name: Install dependencies run: pip install sphinx sphinx_rtd_theme setuptools-rust - name: Install Rust uses: dtolnay/rust-toolchain@stable - name: Build tokenizers working-directory: ./bindings/python run: pip install -e . - name: Build documentation working-directory: ./docs run: make clean && make html_all O="-W --keep-going" - name: Upload built doc uses: actions/upload-artifact@v4 with: name: documentation path: ./docs/build/* ================================================ FILE: .github/workflows/node-release.yml ================================================ name: Node Release env: AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} AWS_DEFAULT_REGION: us-east-1 on: push: tags: - node-v* jobs: build: env: MACOSX_DEPLOYMENT_TARGET: 10.11 strategy: matrix: settings: - host: macos-latest target: x86_64-apple-darwin - host: windows-latest target: x86_64-pc-windows-msvc - host: ubuntu-latest target: x86_64-unknown-linux-gnu runs-on: ${{ matrix.settings.host }} steps: - name: Checkout repository uses: actions/checkout@v4 - name: Install Rust uses: dtolnay/rust-toolchain@stable # Necessary for now for the cargo cache: https://github.com/actions/cache/issues/133#issuecomment-599102035 - if: matrix.os == 'ubuntu-latest' run: sudo chown -R $(whoami):$(id -ng) ~/.cargo/ - name: Cache Cargo Registry uses: actions/cache@v4 with: path: ~/.cargo/registry key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.toml') }} - name: Install Node ${{ matrix.node-version }} uses: actions/setup-node@v4 with: node-version: latest cache: yarn cache-dependency-path: ./bindings/node/ - name: Install npm dependencies working-directory: ./bindings/node run: yarn install - name: Build and package rust working-directory: ./bindings/node run: | yarn build && strip -x *.node - name: Install Python uses: actions/setup-python@v5 with: python-version: 3.x - name: Upload artifact uses: actions/upload-artifact@v4 with: name: bindings-${{ matrix.settings.target }} path: ${{ env.APP_NAME }}bindings/node/*.node if-no-files-found: error publish: name: Publish runs-on: ubuntu-latest needs: - build steps: - uses: actions/checkout@v4 - name: Setup node uses: actions/setup-node@v4 with: node-version: latest check-latest: true cache: yarn cache-dependency-path: ./bindings/node/ - name: Install dependencies working-directory: ./bindings/node run: yarn install - name: Download all artifacts uses: actions/download-artifact@v4 with: path: ./bindings/node/artifacts - name: Move artifacts working-directory: ./bindings/node run: yarn artifacts - name: List packages working-directory: ./bindings/node run: ls -R ./npm shell: bash - name: Publish working-directory: ./bindings/node run: | echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" >> ~/.npmrc npm publish --access public --tag next env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} NPM_TOKEN: ${{ secrets.NPM_TOKEN }} ================================================ FILE: .github/workflows/node.yml ================================================ name: Node on: push: branches: - main paths-ignore: - bindings/python/** pull_request: paths-ignore: - bindings/python/** jobs: build_and_test: name: Check everything builds runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v4 - name: Install Rust uses: dtolnay/rust-toolchain@stable with: components: rustfmt, clippy # Necessary for now for the cargo cache: https://github.com/actions/cache/issues/133#issuecomment-599102035 - run: sudo chown -R $(whoami):$(id -ng) ~/.cargo/ - name: Cache Cargo Registry uses: actions/cache@v4 with: path: ~/.cargo/registry key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }} - name: Install Node uses: actions/setup-node@v4 with: node-version: latest - name: Install dependencies working-directory: ./bindings/node run: yarn install - name: Build all working-directory: ./bindings/node run: yarn build - name: Lint Rust formatting uses: actions-rs/cargo@v1 with: command: fmt args: --manifest-path ./bindings/node/Cargo.toml -- --check - name: Lint Rust with Clippy uses: actions-rs/cargo@v1 with: command: clippy args: --manifest-path ./bindings/node/Cargo.toml --all-targets --all-features -- -D warnings - name: Lint TS working-directory: ./bindings/node run: yarn lint - name: Run JS tests working-directory: ./bindings/node run: make test ================================================ FILE: .github/workflows/python-release.yml ================================================ name: Python Release on: push: tags: - v* env: AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} AWS_DEFAULT_REGION: us-east-1 PYPI_TOKEN: ${{ secrets.PYPI_TOKEN_DIST }} DIST_DIR: ${{ github.sha }} jobs: lock_exists: runs-on: ubuntu-latest name: Cargo.lock steps: - uses: actions/checkout@v4 - name: Cargo.lock lock exists run: cat Cargo.lock working-directory: ./bindings/python build: name: build on ${{ matrix.platform || matrix.os }} (${{ matrix.target }} - ${{ matrix.manylinux || 'auto' }}) # only run on push to main and on release needs: [lock_exists] if: startsWith(github.ref, 'refs/tags/') || github.ref == 'refs/heads/main' || contains(github.event.pull_request.labels.*.name, 'Full Build') strategy: fail-fast: false matrix: os: [ubuntu, macos, windows] target: [x86_64, aarch64] manylinux: [auto] include: - os: ubuntu platform: linux - os: windows ls: dir interpreter: 3.9 3.10 3.11 3.12 3.13 pypy3.9 pypy3.10 - os: windows ls: dir target: x86_64 python-architecture: x64 interpreter: 3.9 3.10 3.11 3.12 3.13 - os: windows ls: dir target: i686 python-architecture: x86 python-install: | 3.9 3.10 3.11 3.12 3.13 interpreter: 3.9 3.10 3.11 3.12 3.13 - os: windows-11-arm ls: dir target: aarch64 python-architecture: arm64 python-install: | 3.11 3.12 3.13 interpreter: 3.11 3.12 3.13 # - os: windows # ls: dir # target: aarch64 # interpreter: 3.11 3.12 - os: macos target: aarch64 interpreter: 3.9 3.10 3.11 3.12 3.13 pypy3.9 pypy3.10 - os: ubuntu platform: linux target: i686 - os: ubuntu platform: linux target: aarch64 - os: ubuntu platform: linux target: armv7 interpreter: 3.9 3.10 3.11 3.12 3.13 # musllinux - os: ubuntu platform: linux target: x86_64 manylinux: musllinux_1_1 - os: ubuntu platform: linux target: aarch64 manylinux: musllinux_1_1 - os: ubuntu platform: linux target: ppc64le interpreter: 3.9 3.10 3.11 3.12 3.13 - os: ubuntu platform: linux target: s390x interpreter: 3.9 3.10 3.11 3.12 3.13 exclude: - os: windows target: aarch64 # # Optimized PGO builds for x86_64 manylinux and windows follow a different matrix, # # maybe in future maturin-action can support this automatically # - os: ubuntu # target: x86_64 # manylinux: auto # - os: windows # target: x86_64 # Windows on arm64 only supports Python 3.11+ runs-on: ${{ matrix.os == 'windows-11-arm' && matrix.os || format('{0}-latest', matrix.os) }} steps: - uses: actions/checkout@v4 - name: set up python uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-install || '3.13' }} architecture: ${{ matrix.python-architecture || 'x64' }} - run: pip install -U twine - name: build wheels uses: PyO3/maturin-action@v1 with: target: ${{ matrix.target }} working-directory: ./bindings/python manylinux: ${{ matrix.manylinux || 'auto' }} container: ${{ matrix.container }} args: --release --out dist --interpreter ${{ matrix.interpreter || '3.9 3.10 3.11 3.12 3.13 pypy3.9 pypy3.10' }} ${{ matrix.extra-build-args }} rust-toolchain: stable docker-options: -e CI - run: ${{ matrix.ls || 'ls -lh' }} dist/ working-directory: ./bindings/python - run: twine check --strict dist/* working-directory: ./bindings/python - uses: actions/upload-artifact@v4 with: name: pypi_files-${{ matrix.os }}-${{ matrix.target }}-${{ matrix.manylinux }} path: ./bindings/python/dist build-sdist: name: build sdist needs: [lock_exists] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: PyO3/maturin-action@v1 with: working-directory: ./bindings/python command: sdist args: --out dist rust-toolchain: stable - uses: actions/upload-artifact@v4 with: name: pypi_files-srt path: ./bindings/python/dist upload_package: name: Upload package to PyPi runs-on: ubuntu-latest needs: [build, build-sdist] steps: - uses: actions/checkout@v4 - name: Install Python uses: actions/setup-python@v5 with: python-version: "3.13" architecture: x64 - uses: actions/download-artifact@v4 with: path: ./bindings/python/dist merge-multiple: true # Temporary deactivation while testing abi3 CI # - name: Upload to PyPi # working-directory: ./bindings/python # run: | # pip install twine # twine upload dist/* -u __token__ -p "$PYPI_TOKEN" ================================================ FILE: .github/workflows/python.yml ================================================ name: Python on: push: branches: - main paths-ignore: - bindings/node/** pull_request: paths-ignore: - bindings/node/** jobs: build_win_32: name: Check it builds for Windows 32-bit runs-on: windows-latest strategy: matrix: python: ["3.9", "3.10", "3.11", "3.12", "3.13", "3.14", "3.14t"] steps: - name: Checkout repository uses: actions/checkout@v4 - name: Install Rust uses: actions-rs/toolchain@v1 with: toolchain: stable-i686-pc-windows-msvc override: true - name: Override toolchain shell: bash working-directory: ./bindings/python run: echo "stable-i686-pc-windows-msvc" > rust-toolchain - name: Install Python uses: actions/setup-python@v5 with: python-version: ${{ matrix.python }} architecture: x86 - name: Build uses: actions-rs/cargo@v1 with: command: build args: --manifest-path ./bindings/python/Cargo.toml build_and_test: name: Check everything builds & tests runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest, macos-latest] python: ["3.14", "3.14t"] steps: - name: Checkout repository uses: actions/checkout@v4 - name: Install Rust uses: actions-rs/toolchain@v1 with: toolchain: stable components: rustfmt, clippy - name: Install audit uses: actions-rs/cargo@v1 with: command: install args: cargo-audit - name: Install Python uses: actions/setup-python@v5 with: python-version: ${{ matrix.python }} architecture: "x64" - name: Cache Cargo Registry uses: actions/cache@v4 with: path: ~/.cargo/registry key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }} # - name: Cache Cargo Build Target # uses: actions/cache@v1 # with: # path: ./bindings/python/target # key: ${{ runner.os }}-cargo-python-build-${{ hashFiles('**/Cargo.lock') }} - name: Lint with RustFmt uses: actions-rs/cargo@v1 with: toolchain: stable command: fmt args: --manifest-path ./bindings/python/Cargo.toml -- --check - name: Lint with Clippy uses: actions-rs/cargo@v1 with: command: clippy args: --manifest-path ./bindings/python/Cargo.toml --all-targets --all-features -- -D warnings - name: Install cargo-audit run: cargo install cargo-audit - name: Run Audit uses: actions-rs/cargo@v1 with: command: audit args: -D warnings -f ./bindings/python/Cargo.lock --ignore RUSTSEC-2024-0436 --ignore RUSTSEC-2025-0014 --ignore RUSTSEC-2025-0119 --ignore RUSTSEC-2024-0436 - name: Install working-directory: ./bindings/python run: | python -m venv .env source .env/bin/activate pip install -U pip pip install pytest requests setuptools_rust numpy pyarrow datasets ty pip install -e .[dev] - name: Check style working-directory: ./bindings/python run: | source .env/bin/activate make check-style - name: Type check working-directory: ./bindings/python run: | source .env/bin/activate ty check py_src --exclude py_src/tokenizers/implementations - name: Run tests working-directory: ./bindings/python run: | source .env/bin/activate make test ================================================ FILE: .github/workflows/rust-release.yml ================================================ name: Rust Release env: CRATES_TOKEN: ${{ secrets.CRATES_TOKEN }} on: push: tags: - v* jobs: rust_publish: runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v4 - name: Install Rust uses: dtolnay/rust-toolchain@stable - name: Cache Cargo Registry uses: actions/cache@v4 with: path: ~/.cargo/registry key: ubuntu-latest-cargo-registry-${{ hashFiles('**/Cargo.toml') }} - name: Publish package rust working-directory: ./tokenizers if: ${{ !contains(github.ref, 'rc') }} run: cargo publish --token ${CRATES_TOKEN} ================================================ FILE: .github/workflows/rust.yml ================================================ name: Rust on: push: branches: - main pull_request: jobs: build: runs-on: ${{ matrix.os }} env: MACOSX_DEPLOYMENT_TARGET: 10.12 strategy: matrix: os: [ubuntu-latest, windows-latest, macOS-latest] steps: - uses: actions/checkout@v4 - name: Install Rust Stable uses: actions-rs/toolchain@v1 with: toolchain: stable components: rustfmt, clippy override: true # Necessary for now for the cargo cache: https://github.com/actions/cache/issues/133#issuecomment-599102035 - if: matrix.os == 'ubuntu-latest' run: sudo chown -R $(whoami):$(id -ng) ~/.cargo/ - name: Install cargo-readme for Ubuntu if: matrix.os == 'ubuntu-latest' uses: actions-rs/cargo@v1 with: command: install args: cargo-readme - name: Install audit uses: actions-rs/cargo@v1 with: command: install args: cargo-audit - name: Build uses: actions-rs/cargo@v1 with: command: build args: --all-targets --verbose --manifest-path ./tokenizers/Cargo.toml - name: Lint with RustFmt uses: actions-rs/cargo@v1 with: command: fmt args: --manifest-path ./tokenizers/Cargo.toml -- --check - name: Lint Benchmarks with RustFmt uses: actions-rs/cargo@v1 with: command: fmt args: --manifest-path ./tokenizers/Cargo.toml -- ./tokenizers/benches/bpe_benchmark.rs --check - name: Lint with Clippy uses: actions-rs/cargo@v1 with: command: clippy args: --manifest-path ./tokenizers/Cargo.toml --all-targets --all-features -- -D warnings - name: Run Tests if: matrix.os != 'windows-latest' shell: bash working-directory: ./tokenizers run: make test # Skip integration tests for now on Windows - name: Run lib Tests on Windows if: matrix.os == 'windows-latest' uses: actions-rs/cargo@v1 with: command: test args: --verbose --manifest-path ./tokenizers/Cargo.toml --lib - name: Run doc Tests on Windows if: matrix.os == 'windows-latest' uses: actions-rs/cargo@v1 with: command: test args: --verbose --manifest-path ./tokenizers/Cargo.toml --doc - name: Install cargo-audit run: cargo install cargo-audit - name: Run Audit uses: actions-rs/cargo@v1 with: command: audit args: -D warnings -f ./tokenizers/Cargo.lock --ignore RUSTSEC-2024-0436 --ignore RUSTSEC-2025-0014 --ignore RUSTSEC-2025-0119 # Verify that Readme.md is up to date. - name: Make sure, Readme generated from lib.rs matches actual Readme if: matrix.os == 'ubuntu-latest' shell: bash working-directory: ./tokenizers run: cargo readme > must_match_readme.md && diff must_match_readme.md README.md - name: Check semver if: matrix.os == 'ubuntu-latest' uses: obi1kenobi/cargo-semver-checks-action@v2 with: manifest-path: ./tokenizers/Cargo.toml ================================================ FILE: .github/workflows/stale.yml ================================================ name: 'Close stale issues and PRs' on: schedule: - cron: '30 1 * * *' jobs: stale: runs-on: ubuntu-latest steps: - uses: actions/stale@v9 with: stale-issue-message: 'This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.' days-before-stale: 30 days-before-close: 5 ================================================ FILE: .github/workflows/trufflehog.yml ================================================ on: push: name: Secret Leaks jobs: trufflehog: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4 with: fetch-depth: 0 - name: Secret Scanning uses: trufflesecurity/trufflehog@853e1e8d249fd1e29d0fcc7280d29b03df3d643d with: # exclude buggy postgres detector that is causing false positives and not relevant to our codebase extra_args: --results=verified,unknown --exclude-detectors=postgres ================================================ FILE: .github/workflows/upload_pr_documentation.yml ================================================ name: Upload PR Documentation on: workflow_run: workflows: ["Build PR Documentation"] types: - completed jobs: build: uses: huggingface/doc-builder/.github/workflows/upload_pr_documentation.yml@main with: package_name: tokenizers secrets: hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }} comment_bot_token: ${{ secrets.COMMENT_BOT_TOKEN }} ================================================ FILE: .gitignore ================================================ .DS_Store *~ .vim .env target .idea **/Cargo.lock /data tokenizers/data bindings/python/tests/data docs/build/ docs/make.bat __pycache__ pip-wheel-metadata *.egg-info *.so /bindings/python/examples/.ipynb_checkpoints /bindings/python/build /bindings/python/dist .vscode *.code-workspace ================================================ FILE: CITATION.cff ================================================ # This CITATION.cff file was generated with cffinit. # Visit https://bit.ly/cffinit to generate yours today! cff-version: 1.2.0 title: HuggingFace's Tokenizers message: >- Fast State-of-the-Art Tokenizers optimized for Research and Production. type: software authors: - given-names: Anthony family-names: Moi email: m.anthony.moi@gmail.com affiliation: HuggingFace - given-names: Nicolas family-names: Patry affiliation: HuggingFace repository-code: 'https://github.com/huggingface/tokenizers' url: 'https://github.com/huggingface/tokenizers' repository: 'https://huggingface.co' abstract: >- Fast State-of-the-Art Tokenizers optimized for Research and Production. keywords: - Rust - Tokenizer - NLP license: Apache-2.0 commit: 37372b6 version: 0.13.4 date-released: '2023-04-05' ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, 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 Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================
Provides an implementation of today's most used tokenizers, with a focus on performance and versatility. ## Main features: - Train new vocabularies and tokenize, using today's most used tokenizers. - Extremely fast (both training and tokenization), thanks to the Rust implementation. Takes less than 20 seconds to tokenize a GB of text on a server's CPU. - Easy to use, but also extremely versatile. - Designed for research and production. - Normalization comes with alignments tracking. It's always possible to get the part of the original sentence that corresponds to a given token. - Does all the pre-processing: Truncate, Pad, add the special tokens your model needs. ## Performances Performances can vary depending on hardware, but running the [~/bindings/python/benches/test_tiktoken.py](bindings/python/benches/test_tiktoken.py) should give the following on a g6 aws instance:  ## Bindings We provide bindings to the following languages (more to come!): - [Rust](https://github.com/huggingface/tokenizers/tree/main/tokenizers) (Original implementation) - [Python](https://github.com/huggingface/tokenizers/tree/main/bindings/python) - [Node.js](https://github.com/huggingface/tokenizers/tree/main/bindings/node) - [Ruby](https://github.com/ankane/tokenizers-ruby) (Contributed by @ankane, external repo) ## Installation You can install from source using: ```bash pip install git+https://github.com/huggingface/tokenizers.git#subdirectory=bindings/python ``` or install the released versions with ```bash pip install tokenizers ``` ## Quick example using Python: Choose your model between Byte-Pair Encoding, WordPiece or Unigram and instantiate a tokenizer: ```python from tokenizers import Tokenizer from tokenizers.models import BPE tokenizer = Tokenizer(BPE()) ``` You can customize how pre-tokenization (e.g., splitting into words) is done: ```python from tokenizers.pre_tokenizers import Whitespace tokenizer.pre_tokenizer = Whitespace() ``` Then training your tokenizer on a set of files just takes two lines of codes: ```python from tokenizers.trainers import BpeTrainer trainer = BpeTrainer(special_tokens=["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"]) tokenizer.train(files=["wiki.train.raw", "wiki.valid.raw", "wiki.test.raw"], trainer=trainer) ``` Once your tokenizer is trained, encode any text with just one line: ```python output = tokenizer.encode("Hello, y'all! How are you 😁 ?") print(output.tokens) # ["Hello", ",", "y", "'", "all", "!", "How", "are", "you", "[UNK]", "?"] ``` Check the [documentation](https://huggingface.co/docs/tokenizers/index) or the [quicktour](https://huggingface.co/docs/tokenizers/quicktour) to learn more! ================================================ FILE: RELEASE.md ================================================ ## How to release # Before the release Simple checklist on how to make releases for `tokenizers`. - Freeze `master` branch. - Run all tests (Check CI has properly run) - If any significant work, check benchmarks: - `cd tokenizers && cargo bench` (needs to be run on latest release tag to measure difference if it's your first time) - Run all `transformers` tests. (`transformers` is a big user of `tokenizers` we need to make sure we don't break it, testing is one way to make sure nothing unforeseen has been done.) - Run all fast tests at the VERY least (not just the tokenization tests). (`RUN_PIPELINE_TESTS=1 CUDA_VISIBLE_DEVICES=-1 pytest -sv tests/`) - When all *fast* tests work, then we can also (it's recommended) run the whole `transformers` test suite. - Rebase this [PR](https://github.com/huggingface/transformers/pull/16708). This will create new docker images ready to run the tests suites with `tokenizers` from the main branch. - Wait for actions to finish - Rebase this [PR](https://github.com/huggingface/transformers/pull/16712) This will run the actual full test suite. - Check the results. - **If any breaking change has been done**, make sure the version can safely be increased for transformers users (`tokenizers` version need to make sure users don't upgrade before `transformers` has). [link](https://github.com/huggingface/transformers/blob/main/setup.py#L154) For instance `tokenizers>=0.10,<0.11` so we can safely upgrade to `0.11` without impacting current users - Then start a new PR containing all desired code changes from the following steps. - You will `Create release` after the code modifications are on `master`. # Rust - `tokenizers` (rust, python & node) versions don't have to be in sync but it's very common to release for all versions at once for new features. - Edit `Cargo.toml` to reflect new version - Edit `CHANGELOG.md`: - Add relevant PRs that were added (python PRs do not belong for instance). - Add links at the end of the files. - Go to [Releases](https://github.com/huggingface/tokenizers/releases) - Create new Release: - Mark it as pre-release - Use new version name with a new tag (create on publish) `vX.X.X`. - Copy paste the new part of the `CHANGELOG.md` - ⚠️ Click on `Publish release`. This will start the whole process of building a uploading the new version on `crates.io`, there's no going back after this - Go to the [Actions](https://github.com/huggingface/tokenizers/actions) tab and check everything works smoothly. - If anything fails, you need to fix the CI/CD to make it work again. Since your package was not uploaded to the repository properly, you can try again. # Python - Edit `bindings/python/setup.py` to reflect new version. - Edit `bindings/python/py_src/tokenizers/__init__.py` to reflect new version. - Edit `CHANGELOG.md`: - Add relevant PRs that were added (node PRs do not belong for instance). - Add links at the end of the files. - Go to [Releases](https://github.com/huggingface/tokenizers/releases) - Create new Release: - Mark it as pre-release - Use new version name with a new tag (create on publish) `python-vX.X.X`. - Copy paste the new part of the `CHANGELOG.md` - ⚠️ Click on `Publish release`. This will start the whole process of building a uploading the new version on `pypi`, there's no going back after this - Go to the [Actions](https://github.com/huggingface/tokenizers/actions) tab and check everything works smoothly. - If anything fails, you need to fix the CI/CD to make it work again. Since your package was not uploaded to the repository properly, you can try again. - This CI/CD has 3 distinct builds, `Pypi`(normal), `conda` and `extra`. `Extra` is REALLY slow (~4h), this is normal since it has to rebuild many things, but enables the wheel to be available for old Linuxes # Node - Edit `bindings/node/package.json` to reflect new version. - Edit `CHANGELOG.md`: - Add relevant PRs that were added (python PRs do not belong for instance). - Add links at the end of the files. - Go to [Releases](https://github.com/huggingface/tokenizers/releases) - Create new Release: - Mark it as pre-release - Use new version name with a new tag (create on publish) `node-vX.X.X`. - Copy paste the new part of the `CHANGELOG.md` - ⚠️ Click on `Publish release`. This will start the whole process of building a uploading the new version on `npm`, there's no going back after this - Go to the [Actions](https://github.com/huggingface/tokenizers/actions) tab and check everything works smoothly. - If anything fails, you need to fix the CI/CD to make it work again. Since your package was not uploaded to the repository properly, you can try again. # Testing the CI/CD for release If you want to make modifications to the CI/CD of the release GH actions, you need to : - **Comment the part that uploads the artifacts** to `crates.io`, `PyPi` or `npm`. - Change the trigger mechanism so it can trigger every time you push to your branch. - Keep pushing your changes until the artifacts are properly created. ================================================ FILE: bindings/node/.cargo/config.toml ================================================ [target.aarch64-unknown-linux-musl] linker = "aarch64-linux-musl-gcc" rustflags = ["-C", "target-feature=-crt-static"] ================================================ FILE: bindings/node/.editorconfig ================================================ # EditorConfig helps developers define and maintain consistent # coding styles between different editors or IDEs # http://editorconfig.org root = true [*] indent_style = space indent_size = 2 end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true [*.md] trim_trailing_whitespace = false ================================================ FILE: bindings/node/.eslintrc.yml ================================================ parser: '@typescript-eslint/parser' parserOptions: ecmaFeatures: jsx: true ecmaVersion: latest sourceType: module project: ./tsconfig.json env: browser: true es6: true node: true jest: true ignorePatterns: ['index.js', 'target/'] plugins: - import - '@typescript-eslint' extends: - eslint:recommended - plugin:prettier/recommended rules: # 0 = off, 1 = warn, 2 = error 'space-before-function-paren': 0 'no-useless-constructor': 0 'no-undef': 2 'no-console': [2, { allow: ['error', 'warn', 'info', 'assert'] }] 'comma-dangle': ['error', 'only-multiline'] 'no-unused-vars': 0 'no-var': 2 'one-var-declaration-per-line': 2 'prefer-const': 2 'no-const-assign': 2 'no-duplicate-imports': 2 'no-use-before-define': [2, { 'functions': false, 'classes': false }] 'eqeqeq': [2, 'always', { 'null': 'ignore' }] 'no-case-declarations': 0 'no-restricted-syntax': [ 2, { 'selector': 'BinaryExpression[operator=/(==|===|!=|!==)/][left.raw=true], BinaryExpression[operator=/(==|===|!=|!==)/][right.raw=true]', 'message': Don't compare for equality against boolean literals, }, ] # https://github.com/benmosher/eslint-plugin-import/pull/334 'import/no-duplicates': 2 'import/first': 2 'import/newline-after-import': 2 'import/order': [ 2, { 'newlines-between': 'always', 'alphabetize': { 'order': 'asc' }, 'groups': ['builtin', 'external', 'internal', 'parent', 'sibling', 'index'], }, ] overrides: - files: - ./**/*{.ts,.tsx} rules: 'no-unused-vars': [2, { varsIgnorePattern: '^_', argsIgnorePattern: '^_', ignoreRestSiblings: true }] 'no-undef': 0 # TypeScript declare merge 'no-redeclare': 0 'no-useless-constructor': 0 'no-dupe-class-members': 0 'no-case-declarations': 0 'no-duplicate-imports': 0 # TypeScript Interface and Type 'no-use-before-define': 0 '@typescript-eslint/adjacent-overload-signatures': 2 '@typescript-eslint/await-thenable': 2 '@typescript-eslint/consistent-type-assertions': 2 '@typescript-eslint/ban-types': [ 'error', { 'types': { 'String': { 'message': 'Use string instead', 'fixWith': 'string' }, 'Number': { 'message': 'Use number instead', 'fixWith': 'number' }, 'Boolean': { 'message': 'Use boolean instead', 'fixWith': 'boolean' }, 'Function': { 'message': 'Use explicit type instead' }, }, }, ] '@typescript-eslint/explicit-member-accessibility': [ 'error', { accessibility: 'explicit', overrides: { accessors: 'no-public', constructors: 'no-public', methods: 'no-public', properties: 'no-public', parameterProperties: 'explicit', }, }, ] '@typescript-eslint/method-signature-style': 2 '@typescript-eslint/no-floating-promises': 2 '@typescript-eslint/no-implied-eval': 2 '@typescript-eslint/no-for-in-array': 2 '@typescript-eslint/no-inferrable-types': 2 '@typescript-eslint/no-invalid-void-type': 2 '@typescript-eslint/no-misused-new': 2 '@typescript-eslint/no-misused-promises': 2 '@typescript-eslint/no-namespace': 2 '@typescript-eslint/no-non-null-asserted-optional-chain': 2 '@typescript-eslint/no-throw-literal': 2 '@typescript-eslint/no-unnecessary-boolean-literal-compare': 2 '@typescript-eslint/prefer-for-of': 2 '@typescript-eslint/prefer-nullish-coalescing': 2 '@typescript-eslint/switch-exhaustiveness-check': 2 '@typescript-eslint/prefer-optional-chain': 2 '@typescript-eslint/prefer-readonly': 2 '@typescript-eslint/prefer-string-starts-ends-with': 0 '@typescript-eslint/no-array-constructor': 2 '@typescript-eslint/require-await': 2 '@typescript-eslint/return-await': 2 '@typescript-eslint/ban-ts-comment': [2, { 'ts-expect-error': false, 'ts-ignore': true, 'ts-nocheck': true, 'ts-check': false }] '@typescript-eslint/naming-convention': [ 2, { selector: 'memberLike', format: ['camelCase', 'PascalCase'], modifiers: ['private'], leadingUnderscore: 'forbid', }, ] '@typescript-eslint/no-unused-vars': [2, { varsIgnorePattern: '^_', argsIgnorePattern: '^_', ignoreRestSiblings: true }] '@typescript-eslint/member-ordering': [ 2, { default: [ 'public-static-field', 'protected-static-field', 'private-static-field', 'public-static-method', 'protected-static-method', 'private-static-method', 'public-instance-field', 'protected-instance-field', 'private-instance-field', 'public-constructor', 'protected-constructor', 'private-constructor', 'public-instance-method', 'protected-instance-method', 'private-instance-method', ], }, ] ================================================ FILE: bindings/node/.gitattributes ================================================ # Auto detect text files and perform LF normalization * text=auto *.ts text eol=lf merge=union *.tsx text eol=lf merge=union *.rs text eol=lf merge=union *.js text eol=lf merge=union *.json text eol=lf merge=union *.debug text eol=lf merge=union # Generated codes index.js linguist-detectable=false index.d.ts linguist-detectable=false ================================================ FILE: bindings/node/.gitignore ================================================ # Created by https://www.toptal.com/developers/gitignore/api/node # Edit at https://www.toptal.com/developers/gitignore?templates=node ### Node ### # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* lerna-debug.log* # Diagnostic reports (https://nodejs.org/api/report.html) report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json # Runtime data pids *.pid *.seed *.pid.lock # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage *.lcov # nyc test coverage .nyc_output # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) .grunt # Bower dependency directory (https://bower.io/) bower_components # node-waf configuration .lock-wscript # Compiled binary addons (https://nodejs.org/api/addons.html) build/Release # Dependency directories node_modules/ jspm_packages/ # TypeScript v1 declaration files typings/ # TypeScript cache *.tsbuildinfo # Optional npm cache directory .npm # Optional eslint cache .eslintcache # Microbundle cache .rpt2_cache/ .rts2_cache_cjs/ .rts2_cache_es/ .rts2_cache_umd/ # Optional REPL history .node_repl_history # Output of 'npm pack' *.tgz # Yarn Integrity file .yarn-integrity # dotenv environment variables file .env .env.test # parcel-bundler cache (https://parceljs.org/) .cache # Next.js build output .next # Nuxt.js build / generate output .nuxt dist # Gatsby files .cache/ # Comment in the public line in if your project uses Gatsby and not Next.js # https://nextjs.org/blog/next-9-1#public-directory-support # public # vuepress build output .vuepress/dist # Serverless directories .serverless/ # FuseBox cache .fusebox/ # DynamoDB Local files .dynamodb/ # TernJS port file .tern-port # Stores VSCode versions used for testing VSCode extensions .vscode-test # End of https://www.toptal.com/developers/gitignore/api/node #Added by cargo /target Cargo.lock *.node .pnp.* .yarn/* !.yarn/patches !.yarn/plugins !.yarn/releases !.yarn/sdks !.yarn/versions ================================================ FILE: bindings/node/.prettierignore ================================================ target .yarn ================================================ FILE: bindings/node/.taplo.toml ================================================ exclude = ["node_modules/**/*.toml"] # https://taplo.tamasfe.dev/configuration/formatter-options.html [formatting] align_entries = true indent_tables = true reorder_keys = true ================================================ FILE: bindings/node/.yarn/releases/yarn-3.5.1.cjs ================================================ #!/usr/bin/env node /* eslint-disable */ //prettier-ignore (()=>{var Sge=Object.create;var lS=Object.defineProperty;var vge=Object.getOwnPropertyDescriptor;var xge=Object.getOwnPropertyNames;var Pge=Object.getPrototypeOf,Dge=Object.prototype.hasOwnProperty;var J=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+r+'" is not supported')});var kge=(r,e)=>()=>(r&&(e=r(r=0)),e);var w=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ut=(r,e)=>{for(var t in e)lS(r,t,{get:e[t],enumerable:!0})},Rge=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of xge(e))!Dge.call(r,n)&&n!==t&&lS(r,n,{get:()=>e[n],enumerable:!(i=vge(e,n))||i.enumerable});return r};var Pe=(r,e,t)=>(t=r!=null?Sge(Pge(r)):{},Rge(e||!r||!r.__esModule?lS(t,"default",{value:r,enumerable:!0}):t,r));var vU=w((j7e,SU)=>{SU.exports=bU;bU.sync=$ge;var BU=J("fs");function _ge(r,e){var t=e.pathExt!==void 0?e.pathExt:process.env.PATHEXT;if(!t||(t=t.split(";"),t.indexOf("")!==-1))return!0;for(var i=0;i