ctok-rs
Exact Rust port of ctok: the same Claude token counts, about 30-60x faster, no worker pool.
Install · Quick start · Performance · Accuracy · How it works
Unofficial Rust port of sanderland/ctok by Sander Land. Not affiliated with, endorsed by, or supported by the ctok author or Anthropic.
Guarantee: for every input string,
ctok_rs.token_count(text, v) == ctok.token_count(text, v)forctok1.4.0.
Why
- Exact: reconstructs Claude token counts offline with no API calls or network access, guaranteed to match
ctok1.4.0 on every input string. - Fast: compiles the counting pipeline to Rust for about 30-60x higher throughput on a single thread (versus roughly 0.3-0.5 M characters per second in pure Python
ctok), eliminating the need for process worker pools. - Light: zero runtime dependencies, embedded vocabularies, frozen Unicode tables (no host
regexorunicodedatadependency), and 8.7x faster cold start (39 ms vs. 339 ms).
Only counting is ported; tokenize(), pieces(), witness(), and the ctok CLI are not part of ctok-rs.
Install
Python (one abi3 wheel per platform for Linux manylinux/musllinux x86_64 + aarch64, Windows x64, and macOS x86_64 + arm64; Python >= 3.10, zero runtime dependencies):
pip install 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.
Use from Rust
Optional: add the crate as a git dependency in Cargo.toml.
ctok-rs = { git = "https://github.com/StevenTran0410/ctok-rs", tag = "v0.1.1" }
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(())
}
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; all counting is single-threaded. The machine was a normal desktop with unrelated background load (roughly 45-55% CPU in total during the run).
Exact numbers
| 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 |
ctok-rs is 29x to 60x faster than ctok on every corpus and version (exact speedups are in the table under the throughput chart).
Exact numbers
| 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 |
Methodology
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. Throughput is 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; raw results from the run above are in benchmarks/results/ryzen7-5700x-windows11-2026-12-05.json. Charts are generated by python benchmarks/plot.py from the committed JSON (needs matplotlib).
Accuracy
ctok-rs is verified on two axes: exact byte-for-byte parity with upstream ctok 1.4.0 across all shipped corpora, fuzz suites, and Unicode codepoints, and 100% exact-match reproduction of upstream's recorded count_tokens API values.
Exact numbers: parity with upstream ctok 1.4.0
| 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 numbers: recorded count_tokens API values
| 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.
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, while the patch number is for fixes of this port.
ctok-rs |
Upstream ctok |
|---|---|
0.1.x |
1.4.0 |
How it works
Counting a single user message proceeds in three stages:
- Normalization stream: Strips the reserved tool-call namespace tag after
<,</, or<//before a non-bracket character (collapsing<//to</), and inv3/v4.7splitsHuman:/Assistant:after two or more newlines into turn markers. Ordinary text gets Unicode NFC, control and private-use stripping, space-like folding, curly-quote folding (v3only), run classification, case marking (⟨shift⟩,⟨caps⟩), word-boundary framing (⟨bow⟩,⟨eow⟩), and a seam rewrite. - Reverse trie: Indexes the family vocabulary of 48,813 pieces (
v3) or 15,283 pieces (v4.7andv4.8) in a reverse character trie for fast suffix-to-start transitions during dynamic programming. - Minimum-cost tiling: 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), prices uncovered characters by UTF-8 byte length, and adds the trailing-newline frame tail plus 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-rsis 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.1
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.1.tar.gz | 711.6 kB | With provenance | Details for ctok_rs-0.1.1.tar.gz |
Built distributions (wheels)
Total release size: 6.5 MB
Release files / ctok_rs-0.1.1.tar.gz
| Download URL | ctok_rs-0.1.1.tar.gz |
|---|---|
| Size | 711.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a55e77955722d84e2deeead943e493f67e120773900e229dccb5366fa3c06510
|
|
BLAKE2b-256 checksum How to use checksums |
7ac1c07cde827aec83c893c94539db483320a024217fc92342b50f393877c9e6
|
| 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.1-cp310-abi3-win_amd64.whl
| Download URL | ctok_rs-0.1.1-cp310-abi3-win_amd64.whl |
|---|---|
| Size | 684.5 kB |
| Tags | CPython 3.10 Windows x86-64 abi3 |
|
SHA-256 checksum How to use checksums |
92031227c906be0d0b95297630be6a2ebb9bd143bbf063543d7fa3a37f8bc856
|
|
BLAKE2b-256 checksum How to use checksums |
4a445dd9a069601d2fff3743e920324b790978a7e2fc00e85ab187a488c447e7
|
| 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.1-cp310-abi3-musllinux_1_2_x86_64.whl
| Download URL | ctok_rs-0.1.1-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 |
7a6768cc929d5e92570ea360bdde46ec21e93b4e8e5b0f800ca1fc91fb83e6a1
|
|
BLAKE2b-256 checksum How to use checksums |
34c5351d1e71c2ec8185ed77d7104db71eb9ecead8f253101ecc30f50eef3e06
|
| 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.1-cp310-abi3-musllinux_1_2_aarch64.whl
| Download URL | ctok_rs-0.1.1-cp310-abi3-musllinux_1_2_aarch64.whl |
|---|---|
| Size | 963.1 kB |
| Tags | CPython 3.10 Linux musl 1.2+ ARM64 abi3 |
|
SHA-256 checksum How to use checksums |
d51154d9b872f4fe303f7c92853f09dc67ca88f22048db9ef620e854d0263a4c
|
|
BLAKE2b-256 checksum How to use checksums |
9eeca22035fd5bb770ce7206b52fc0ed098e936319238ea9ac95c10f7ab92a4e
|
| 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.1-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
| Download URL | ctok_rs-0.1.1-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl |
|---|---|
| Size | 790.3 kB |
| Tags | CPython 3.10 Linux glibc 2.17+ x86-64 abi3 |
|
SHA-256 checksum How to use checksums |
d2d0d91f15388b9ed5bca872e31b4b63bedbaad95643b9e498a3e203031d95cb
|
|
BLAKE2b-256 checksum How to use checksums |
9ffb1926c0384061a7807cce399b127dfa5114e936bdb23c1f9878560f9c5cfb
|
| 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.1-cp310-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl
| Download URL | ctok_rs-0.1.1-cp310-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl |
|---|---|
| Size | 784.3 kB |
| Tags | CPython 3.10 Linux glibc 2.17+ ARM64 abi3 |
|
SHA-256 checksum How to use checksums |
0714cffd29668070a8815154515ef38fdab029f45b94db9586b4d83c9d68b413
|
|
BLAKE2b-256 checksum How to use checksums |
e8018bf65befd5a813fbb38a74e290d7bee813b995f39ef8ab2450d23acb1a4c
|
| 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.1-cp310-abi3-macosx_11_0_arm64.whl
| Download URL | ctok_rs-0.1.1-cp310-abi3-macosx_11_0_arm64.whl |
|---|---|
| Size | 808.4 kB |
| Tags | CPython 3.10 abi3 macOS 11.0+ ARM64 |
|
SHA-256 checksum How to use checksums |
6a76214558ecd18ce041f33c761b701c8901586cb9394ea3f74a7e4e0367680d
|
|
BLAKE2b-256 checksum How to use checksums |
87ca9e746d016f3e8e692f506edb221cf5a50e9ddbad9d69c47b8fff6ffa6f96
|
| 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.1-cp310-abi3-macosx_10_12_x86_64.whl
| Download URL | ctok_rs-0.1.1-cp310-abi3-macosx_10_12_x86_64.whl |
|---|---|
| Size | 783.3 kB |
| Tags | CPython 3.10 abi3 macOS 10.12+ x86-64 |
|
SHA-256 checksum How to use checksums |
22130504ab716de5966a292d93d27c1c06220fbb2abf6c57f78fd58450b8bcdb
|
|
BLAKE2b-256 checksum How to use checksums |
16df63b3b3036b0cf21f202a6ed4477cda2ebd53ea449d91a7b956ee86e2ae5f
|
| 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.1
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.1.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.