ctok-rs
Exact Rust port of ctok: the same Claude token counts, 30-60x faster, no worker pool.
Unofficial Rust port of sanderland/ctok. Not affiliated with, endorsed by, or supported by the ctok author or Anthropic.
Why
ctok reconstructs Claude token counts offline with no API calls or network access. Upstream ctok is pure Python: exact, but it counts roughly 0.3-0.5 M characters per second on a modern desktop and relies on host regex and unicodedata, so bulk counting often pushes callers toward process pools.
ctok-rs compiles the counting pipeline to Rust with embedded vocabularies and frozen Unicode tables. It returns the exact same count on a single thread, runs 30-60x faster, and needs no worker pool:
Guarantee: for every input string,
ctok_rs.token_count(text, v) == ctok.token_count(text, v)forctok1.4.0.
Only counting is ported. tokenize(), pieces(), witness(), and the ctok CLI are not part of ctok-rs.
Install
Python (wheels for Linux manylinux/musllinux x86_64 + aarch64, Windows x64, macOS x86_64 + arm64; Python >= 3.10, one abi3 wheel per platform, zero runtime dependencies):
pip install ctok-rs
Rust crate:
cargo add ctok-rs
Building the Python package from source (requires a Rust toolchain):
pip install maturin
maturin develop --release
Quick start
Python
import ctok_rs
ctok_rs.token_count("hello, world") # 10 (default "3.0")
ctok_rs.token_count("hello, world", "4.7") # 15
ctok_rs.token_count("hello, world", "4.8") # 10
# Batch counting releases the GIL while counting in Rust
ctok_rs.token_counts(["", "hello, world"], "4.8") # [6, 10]
# Inspection helpers matching ctok.normalize and ctok.marked_stream
ctok_rs.normalize("\u2018hello\u2019", "3.0") # "'hello'"
ctok_rs.marked_stream("hello, world", "3.0") # "⟨bow⟩hello⟨eow⟩,⟨eow⟩⟨bow⟩world⟨eow⟩"
# Non-str arguments raise TypeError; unknown versions raise NotImplementedError
Drop-in replacement for ctok counting imports:
# Before: from ctok import token_count
from ctok_rs.compat import token_count
token_count("hello, world", "4.8") # 10
ctok_rs.compat mirrors ctok's signatures for token_count, normalize, and marked_stream. It also exposes tokenize, pieces, and witness, which delegate to upstream ctok if installed and raise ImportError (not ported; install ctok==1.4.0) otherwise.
Rust
use ctok_rs::{token_count, Family, TokenCounter};
fn main() -> Result<(), ctok_rs::Error> {
// One-shot helper backed by a process-wide vocabulary cache
assert_eq!(token_count("hello, world", "4.7")?, 15);
// Or hold a counter directly (Send + Sync)
let counter = TokenCounter::new(Family::V4_8)?;
assert_eq!(counter.count("hello, world"), 10);
assert_eq!(counter.count_batch(&["", "hello, world"]), vec![6, 10]);
Ok(())
}
Supported versions
| Requested version | Family | Model generation |
|---|---|---|
"3.0" <= version < "4.7" |
v3 (default) |
Claude 3 through Opus 4.6 |
"4.7" <= version < "4.8" |
v4.7 |
Opus 4.7 |
version >= "4.8" |
v4.8 |
Opus 4.8, Sonnet 5, and Fable 5 (v4.7 vocabulary under a 6-token bow-less frame) |
Version routing rules match upstream ctok:
versionmust be astr(&strin Rust); passing afloatin Python raisesTypeError.- Dotted components are compared as integers, with missing trailing components treated as
0(so"5" == "5.0"and"4.10"is after"4.9"). - Versions below
"3.0"or unparseable version strings raiseNotImplementedErrorin Python andError::UnknownVersionin Rust.
Versioning policy: ctok-rs X.Y.Z tracks upstream ctok 1.4.0 (ctok_rs.UPSTREAM_CTOK_VERSION); a new upstream release ships as a new ctok-rs minor version; the patch number is for fixes of this port.
ctok-rs |
Upstream ctok |
|---|---|
0.1.x |
1.4.0 |
Accuracy
ctok-rs is verified on two axes:
- Parity with upstream
ctok1.4.0: byte-for-byte identical counts on every document of upstream's shipped corpora (UDHR 501 languages, Rosetta Code, Rosetta Code held-out, MultiPL-E) acrossv3,v4.7, andv4.8, plus the deterministic fuzz generator and an exhaustive sweep of every Unicode codepoint:
| Dataset | Texts | v3 mismatches | v4.7 mismatches | v4.8 mismatches |
|---|---|---|---|---|
| UDHR (501 languages) | 501 | 0 | 0 | 0 |
| Rosetta Code | 1,741 | 0 | 0 | 0 |
| Rosetta Code held-out | 250 | 0 | 0 | 0 |
| MultiPL-E (22 languages) | 22 | 0 | 0 | 0 |
| Fuzz (seeds 0-3, 4000 texts each) | 16,000 | 0 | 0 | 0 |
| Every codepoint: bare, in a word, after a space | 3,344,384 | 0 | 0 | 0 |
- Exact-match counts against recorded
count_tokensAPI values published by upstream (ctok-rsreproduces upstream's exact-match counts because its outputs are identical to upstream):
| Corpus | Documents | Recorded family | ctok matches recorded | ctok-rs matches recorded |
|---|---|---|---|---|
| UDHR (501 languages) | 501 | v3 | 501 / 501 | 501 / 501 |
| UDHR (501 languages) | 501 | v4.7 | 501 / 501 | 501 / 501 |
| Rosetta Code | 1741 | v3 | 1741 / 1741 | 1741 / 1741 |
| Rosetta Code | 1741 | v4.7 | 1741 / 1741 | 1741 / 1741 |
| Rosetta Code held-out | 250 | v3 | 250 / 250 | 250 / 250 |
| Rosetta Code held-out | 250 | v4.7 | 250 / 250 | 250 / 250 |
| MultiPL-E (22 languages) | 22 | v3 | 22 / 22 | 22 / 22 |
| MultiPL-E (22 languages) | 22 | v4.7 | 22 / 22 | 22 / 22 |
Reproduce the parity checks locally with upstream ctok==1.4.0 installed:
python tools/fuzz_parity.py --seeds 0-3 --n 20000
python tools/fuzz_parity.py --all-codepoints
pytest
Parity is pinned against ctok 1.4.0 running on Python 3.12 with regex 2026.5.9 and unicodedata 15.0.0 (ctok_rs.UNICODE_PROVENANCE). Because those Unicode tables are frozen at build time, results do not depend on the caller's Python or regex version. Accuracy relative to the live Claude API is identical to upstream's measured accuracy, neither better nor worse.
Performance
Measured on AMD Ryzen 7 5700X 8-Core Processor (16 logical CPUs), 47.9 GiB RAM, Windows 11, Python 3.12.10, ctok-rs 0.1.0 (release build) against ctok 1.4.0, 2026-12-05. The machine was a normal desktop with unrelated background load (roughly 45-55% CPU in total during the run); all counting is single-threaded.
| Version | Dataset | Characters | ctok-rs (chars/s) | ctok (chars/s) | Speedup |
|---|---|---|---|---|---|
| 3.0 | UDHR | 5,041,903 | 14,679,559 | 316,732 | 46.3x |
| 3.0 | Rosetta Code | 1,328,822 | 12,730,375 | 320,934 | 39.7x |
| 3.0 | Rosetta Code held-out | 197,458 | 15,478,525 | 349,300 | 44.3x |
| 3.0 | MultiPL-E | 457,800 | 18,293,560 | 395,516 | 46.3x |
| 3.0 | synthetic text | 2,000,000 | 11,481,616 | 357,960 | 32.1x |
| 4.7 | UDHR | 5,041,903 | 18,496,518 | 411,362 | 45.0x |
| 4.7 | Rosetta Code | 1,328,822 | 17,007,898 | 397,068 | 42.8x |
| 4.7 | Rosetta Code held-out | 197,458 | 17,738,191 | 403,573 | 44.0x |
| 4.7 | MultiPL-E | 457,800 | 25,185,397 | 472,405 | 53.3x |
| 4.7 | synthetic text | 2,000,000 | 13,481,022 | 428,049 | 31.5x |
| 4.8 | UDHR | 5,041,903 | 17,660,821 | 401,096 | 44.0x |
| 4.8 | Rosetta Code | 1,328,822 | 18,405,808 | 396,761 | 46.4x |
| 4.8 | Rosetta Code held-out | 197,458 | 19,400,281 | 398,975 | 48.6x |
| 4.8 | MultiPL-E | 457,800 | 25,631,551 | 429,433 | 59.7x |
| 4.8 | synthetic text | 2,000,000 | 12,700,251 | 433,077 | 29.3x |
| Cold start (import + first count, v3) | Idle RSS | Peak RSS on the UDHR corpus | |
|---|---|---|---|
| ctok-rs | 39 ms | 28.9 MiB | 59.8 MiB |
| ctok | 339 ms | 29.0 MiB | 95.5 MiB |
The synthetic text is 2,000,000 characters (deterministic mix of prose, code, JSON, numbers, URLs and several scripts); ctok counts a 500,000-character prefix of it because it is slow, so its figure is still characters per second. The upstream corpora are counted in full by both libraries.
Methodology: single-threaded, best of N runs with warm vocabularies; cold-start load latency and peak RSS memory are measured separately. Reproduce locally with:
python benchmarks/bench.py
The raw results of the run above are in benchmarks/results/ryzen7-5700x-windows11-2026-12-05.json.
How it works
Counting a single user message proceeds in three stages:
- Normalization stream: reserved-string recognition strips the reserved tool-call namespace tag when it follows
<,</, or<//before a non-bracket character (collapsing<//to</), and inv3/v4.7splitsHuman:andAssistant:immediately after two or more newlines into turn markers. Ordinary text undergoes Unicode NFC, control and private-use stripping, space-like folding, and curly-quote folding (v3only). Characters are classified into runs, case-marked (⟨shift⟩,⟨caps⟩), framed with word-boundary markers (⟨bow⟩,⟨eow⟩), and passed through a seam rewrite to yield the marked stream. - Reverse trie: the family vocabulary of 48,813 pieces (
v3) or 15,283 pieces (v4.7andv4.8) is indexed in a reverse character trie for fast suffix-to-start transitions during dynamic programming. - Minimum-cost tiling: dynamic programming finds the minimum-cost tiling over the marked stream (breaking equal-cost ties in favor of the longest first tile, while preserving right-to-left three-digit grouping on ASCII digit runs), pricing uncovered characters by UTF-8 byte length, adding the trailing-newline frame tail, and adding the fixed per-message frame overhead (
v3: 7,v4.7: 11,v4.8: 6).
Differences from upstream's implementation:
- Unicode facts and NFC data are frozen into data/unicode_tables.bin by tools/gen_unicode_tables.py, so
regexandunicodedataare not needed at run time. - Vocabularies are embedded in the binary and verified against pinned SHA-256 digests (
PIECES_V3_SHA256,PIECES_V4_7_SHA256) at load time, failing loudly on any mismatch. token_countsreleases the Python GIL while Rust processes the batch.
Limitations
- Counts only:
tokenize(),pieces(),witness(), and the CLI are not ported. - Upstream approximations apply:
ctok-rsreproducesctok1.4.0, including its documented omissions (see upstream's README, such as Opus 5 trailing-whitespace behavior and later model offsets). - Frozen Unicode tables: Unicode properties are frozen at Python 3.12 / Unicode 15.0.0 +
regex2026.5.9; codepoints assigned in newer Unicode versions follow that snapshot, whereas running upstream on a different Python/regexversion may differ on newly assigned characters. - Unofficial reconstruction: not Anthropic's tokenizer; counts for Claude models newer than upstream's tables follow upstream's families.
- Input types: accepts text only (
strin Python, with lone surrogates folded toU+FFFDas inctok;&strin Rust); version strings use ASCII-digit dotted components.
Contributing
See CONTRIBUTING.md for guidelines. Every change must preserve exact parity with upstream ctok 1.4.0 (zero mismatches across all corpus, fuzz, and codepoint checks). Run the full suite locally with:
pytest
python tools/fuzz_parity.py --seeds 0-3 --n 20000
Credits and license
ctok-rs is a Rust port of sanderland/ctok by Sander Land, based on the research documented in On the biology of Claude's tokenizer. The embedded vocabularies and counting logic are upstream's work, ported under the MIT license.
Licensed under the MIT License: Copyright (c) 2026 Sander Land and Copyright (c) 2026 StevenTran0410. See LICENSE and LICENSE.upstream.
The test corpora (UDHR, Rosetta Code, MultiPL-E) are downloaded from upstream's repository for tests and benchmarks and are not redistributed here; each remains under its own license.
Claude and Anthropic are trademarks of Anthropic, PBC and are used only to describe compatibility.
Metadata
Release files for ctok-rs 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| ctok_rs-0.1.0.tar.gz | 698.8 kB | With provenance | Details for ctok_rs-0.1.0.tar.gz |
Built distributions (wheels)
Total release size: 6.5 MB
Release files / ctok_rs-0.1.0.tar.gz
| Download URL | ctok_rs-0.1.0.tar.gz |
|---|---|
| Size | 698.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
3bc8292a99537be161fb9317fc059f856e16e3c789723737f35912d84bf55108
|
|
BLAKE2b-256 checksum How to use checksums |
fb51714191f79c707dc6e830b3be7a34101cd6893a81cc05f1065f34d537a572
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.
Transparency logRelease files / ctok_rs-0.1.0-cp310-abi3-win_amd64.whl
| Download URL | ctok_rs-0.1.0-cp310-abi3-win_amd64.whl |
|---|---|
| Size | 683.7 kB |
| Tags | CPython 3.10 Windows x86-64 abi3 |
|
SHA-256 checksum How to use checksums |
01f9b3d81b14329290cfb7c233c3ac8923c6e0aeb03af73679e0f008ca778f0a
|
|
BLAKE2b-256 checksum How to use checksums |
d24853d201bec16cd07d65d16a5f5bdea19a4fb126dd1fd8716320b5cfb0da9a
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.
Transparency logRelease files / ctok_rs-0.1.0-cp310-abi3-musllinux_1_2_x86_64.whl
| Download URL | ctok_rs-0.1.0-cp310-abi3-musllinux_1_2_x86_64.whl |
|---|---|
| Size | 1.0 MB |
| Tags | CPython 3.10 Linux musl 1.2+ x86-64 abi3 |
|
SHA-256 checksum How to use checksums |
1ffb874672d9290d34dde1d829efc1c1e6d1e8d555c78852a8757024ef349c18
|
|
BLAKE2b-256 checksum How to use checksums |
664156284b28cf91f5e34ddd9fa064d46e92b3cf6abf0d1083ae122286f43579
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.
Transparency logRelease files / ctok_rs-0.1.0-cp310-abi3-musllinux_1_2_aarch64.whl
| Download URL | ctok_rs-0.1.0-cp310-abi3-musllinux_1_2_aarch64.whl |
|---|---|
| Size | 962.2 kB |
| Tags | CPython 3.10 Linux musl 1.2+ ARM64 abi3 |
|
SHA-256 checksum How to use checksums |
50161e63df18787da2ff2a32a7df1c0b676538775d6d74c6387f3cb8f2f8a10e
|
|
BLAKE2b-256 checksum How to use checksums |
07948cd071ecbb6632fdf6e350622f506a90f4d314c94efb384529402b3b5c52
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.
Transparency logRelease files / ctok_rs-0.1.0-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
| Download URL | ctok_rs-0.1.0-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl |
|---|---|
| Size | 789.5 kB |
| Tags | CPython 3.10 Linux glibc 2.17+ x86-64 abi3 |
|
SHA-256 checksum How to use checksums |
1f0be44bab8709d5b109d17123f97b3b42244bb9d2e30524f71a9c694fea77a7
|
|
BLAKE2b-256 checksum How to use checksums |
814c5e7cc011d1c9f655322e405ac9b5069989466d11f930de0da6134183a06c
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.
Transparency logRelease files / ctok_rs-0.1.0-cp310-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl
| Download URL | ctok_rs-0.1.0-cp310-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl |
|---|---|
| Size | 783.5 kB |
| Tags | CPython 3.10 Linux glibc 2.17+ ARM64 abi3 |
|
SHA-256 checksum How to use checksums |
3a175c8c33298802632025553083c45c18c3debc7c8289a2383e7d713d15a618
|
|
BLAKE2b-256 checksum How to use checksums |
014b1a6b89d1e4da6ef12693a1b00f572962c4cd9dd4d81556d6201b41486d48
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.
Transparency logRelease files / ctok_rs-0.1.0-cp310-abi3-macosx_11_0_arm64.whl
| Download URL | ctok_rs-0.1.0-cp310-abi3-macosx_11_0_arm64.whl |
|---|---|
| Size | 807.8 kB |
| Tags | CPython 3.10 abi3 macOS 11.0+ ARM64 |
|
SHA-256 checksum How to use checksums |
8a3a5b484fb8291d81110026747b37fe8379156cca50b8f66d7731cb57265164
|
|
BLAKE2b-256 checksum How to use checksums |
eab000ae05e8afbd5f973f4390a9cf729e64e2752eed53663752524bb8266c7f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.
Transparency logRelease files / ctok_rs-0.1.0-cp310-abi3-macosx_10_12_x86_64.whl
| Download URL | ctok_rs-0.1.0-cp310-abi3-macosx_10_12_x86_64.whl |
|---|---|
| Size | 782.5 kB |
| Tags | CPython 3.10 abi3 macOS 10.12+ x86-64 |
|
SHA-256 checksum How to use checksums |
3990cf098bb048ea02a1dc6dbffc92e61132ddb676568a2c8bd5ddd0d65ad9ba
|
|
BLAKE2b-256 checksum How to use checksums |
1a6fd72abbda3ad81778e37e5a3144b62182e74008f28c89601f8ca80458dce9
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.
Transparency logSecurity for ctok-rs 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
All 8 files in this release have been uploaded with provenance metadata.
Attestation for ctok_rs-0.1.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.