Rust: speeding up Python with PyO3 and maturin

The slow part of a Python program moved into a Rust extension one measured step at a time: one function, conversions and NumPy, errors, classes, the GIL and threads, free-threaded Python, then stubs, tests and wheels anyone can pip install. Every output is a real run (CPython 3.14.8 and 3.14.8t, Rust 1.99.0, PyO3 0.29.3, maturin 1.15.0) on an Apple M1 Pro. A child of Rust: the essentials. Data as of October 2026. Reading: 38 min, plus 13 in closed details.

A Rust extension pays off only when the whole hot path crosses into Rust in one big call, borrowing Python's memory instead of copying it and releasing the GIL while it works; moving one function inside a Python loop leaves the program waiting on the Python that is left.

You need: ownership, borrowing and Result from Rust: the essentials; String against &str, Result and ? from Rust: enums, traits, errors and iterators; lifetimes, Mutex and Send from Rust: lifetimes, smart pointers, threads and unsafe. On the Python side, profiling and why the interpreter is slow are Python: CPython internals and performance; the GIL and the free-threaded build are Python: concurrency, asyncio and the GIL; wheel tags and publishing are Python: typing, uv, packaging and the toolchain.

Extension module
a compiled shared library (.so, .pyd on Windows) that import loads like a .py file; NumPy, PyTorch and orjson are extension modules.
PyO3
a Rust crate that wraps CPython's C API: Rust types for Python objects, conversions, and macros that make a Rust function callable from Python.
maturin
the build tool: compiles the crate with cargo and packs it into a wheel; also a PEP 517 build backend.
Crossing
one call from Python into Rust: argument checks and conversions in, the result converted back out.
Borrowed, owned
an argument Rust reads in place in Python's memory (a view), or copies into its own value.
Detach
py.detach(...): release the GIL while pure-Rust work runs (called allow_threads before PyO3 0.26).
#[pyclass]
a Rust struct that Python sees as a class, so state stays in Rust between calls.
abi3, abi3t
CPython's stable ABI: one wheel for many Python versions; abi3t is the version free-threaded builds can load (3.15+).

Moving only the token loop made the program 3x faster; moving the parsing too, on 8 threads, made it 23x

The running example: the root page's count_tokens program on a 200,000-line JSONL chat log (38.8 MB), cut into phases and timed inside the process (milliseconds, medians of 5, code/ladder.py --phases), all four bars on one scale measured. In the second bar the token loop has shrunk from ms to ms, and json.loads (still Python) is now most of the bar. The third bar moves the parsing into Rust too; the fourth releases the GIL and splits the work over 8 threads. Section 10 walks every step.

In one screen

Each row: one idea, the number that shows it on this M1 Pro, and what it changes in the code you write.

IdeaMeasured hereWhat to do
Profile before you portMoving only the token loop: that loop x faster, the program only xMove the whole hot path, not one function inside it
Every call crosses a boundaryAn empty Rust function costs ns per callCall once per batch, not once per element
Borrow, do not copyA str as &str: ns; copied into a String: nsTake &str, &[u8] and NumPy views
NumPy arrays cross for freeA float from a list: ns; from an array: ns; NumPy's own dot beat bothPass arrays; never rewrite what NumPy already does
Release the GIL for long work4 threads calling Rust: ms with the GIL held, ms releasedWrap pure-Rust work in py.detach(...)
Free-threaded Python changes the rules8 threads sharing one &mut self object on 3.14t: 13% of calls raised Already borrowed#[pyclass(frozen)] plus a Mutex
The ladderWhole program: s in Python, ms with parsing and counting in Rust on 8 threadsProfile, port the path, batch, borrow, detach
Ship wheelsOne abi3 wheel loaded on CPython 3.12, 3.13 and 3.14 and was refused by 3.14t; an abi3t wheel loaded on both 3.15 buildsBuild abi3 plus a 3.14t wheel in CI with maturin-action
Rust is not the only wayCython, Numba and Rust within 2x of each other on this loop; mypyc xPick by what else the native code must do
How everything on this page was measured

Every code block is a file in src/rb/ of this page's folder and every output block is its real output, recorded on 2026-10-05 on an Apple M1 Pro (8 performance and 2 efficiency cores, macOS 27) with CPython 3.14.8, Rust 1.99.0, PyO3 0.29.3 and maturin 1.15.0 (exact versions in src/rb/versions.txt; src/rb/run_all.sh reproduces everything in about 10 minutes). Timings are medians of 7 runs with the spread beside them; the laptop was in normal use (load average 9 to 12 on 10 cores during the recorded runs, up to 26 during earlier trial runs), so read the second digit of any timing as noise. The 200,000-line input is regenerated from the root's rosetta/data/gen_chat.py --lines 200000 --seed 7 (same sha256 as the root's benchmark). tokrs, the extension built here, was not published to PyPI.

1. Is it worth it? Profile, then do the arithmetic

On import, CPython calls a function in an extension module named PyInit_<name>, which hands back a module object whose functions are machine code. Writing one costs a second language, a compiler in your build and a wheel per platform (section 12), so do it only when a profile says so. Finding the hot function and trying the cheap wins first (a better algorithm, a built-in such as re or collections.Counter, NumPy, an existing library) is Python: CPython internals and performance; Rust comes after those, for a hot loop that is left and that no library already does.

The hero's first two bars are Amdahl's law: if a fraction p of the time is sped up s times, the whole program speeds up 1 / ((1 - p) + p/s). The token loop was % of the pure-Python run (p = ), so even an infinitely fast loop leaves the other % and the best this change alone can give is 1 / (1 - p) = x; we measured x end to end. To go further, the parsing has to move too.

Worth it when
a profile shows one hot path you own, it is not array arithmetic NumPy already does, it runs often (a tokenizer, a parser, a sampler, a graph walk), and you can pass it big batches.
Not worth it when
the time is in I/O or the network, a library already does it (orjson, polars, pyarrow), or the hot code calls back into Python objects on every step.
What it costs
A Rust toolchain in your build (about 10 s for a clean build here), wheels per platform, and a team that can read Rust.

2. Your first extension: PyO3 and maturin

PyO3's macros (code generators run by the compiler, written #[...]) turn an ordinary Rust function into a Python-callable one; maturin compiles the crate and packs the library into a wheel (the .whl zip pip installs). The root page's Toolchain atlas tab has the first run recorded: maturin new --bindings pyo3 tokrs writes Cargo.toml, pyproject.toml, src/lib.rs and a GitHub Actions workflow. This page's project, tokrs, grew from that skeleton.

The stage (Fig. 1) follows tokrs from its source files to import tokrs; every name and number in the steps is from the recorded build (outputs/b1_develop.txt, b3_wheel.txt, b4_wheel_files.txt).

  1. The crate. Three files: Cargo.toml (the Rust package: crate-type = ["cdylib"] and its five dependencies), pyproject.toml (names maturin as the build backend) and src/lib.rs, the code. The hand-written stub tokrs.pyi sits beside them (section 11).
  2. cargo compiles everything once. maturin runs cargo, which compiles PyO3, the NumPy bindings, rayon, serde and lib.rs in release mode: Finished `release` profile [optimized] target(s) in 9.25s on a clean build, 10.32 s for the whole command. After that an edit to lib.rs rebuilds in a few seconds.
  3. One shared library. The result is tokrs.cpython-314-darwin.so, 1,012,496 bytes of machine code. otool -L lists only libiconv and libSystem: it does not link to libpython, and finds Python's C API in the process that loads it.
  4. maturin packs a wheel. A zip of 8 files: the library, __init__.py, the stub as __init__.pyi, py.typed, and the metadata (METADATA, WHEEL, RECORD and a software bill of materials). Its name carries the tags pip matches: tokrs-0.1.0-cp314-cp314-macosx_11_0_arm64.whl (section 12).
  5. Installed into the venv. maturin develop installs that wheel into the active virtual environment as editable (Installed tokrs-0.1.0); maturin build --release writes it to dist/ instead, which is what you ship.
  6. import tokrs. CPython finds the library in site-packages/tokrs/ and calls its PyInit_tokrs, which returns a module whose functions are machine code. After each Rust change, rerun maturin develop and restart the interpreter or notebook kernel: a process cannot unload a shared library it has loaded, so importlib.reload will not pick up the new build.
The two configuration files, and what each line is for
Cargo.toml
[package]
name = "tokrs"
version = "0.1.0"
edition = "2024"

[lib]
name = "tokrs"
crate-type = ["cdylib"]

[dependencies]
pyo3 = "0.29.3"
numpy = "0.29.0"
rayon = "1.12.0"
serde = { version = "1", features = ["derive"] }
serde_json = "1"

[profile.release]
opt-level = 3
pyproject.toml
[build-system]
requires = ["maturin>=1.15,<2.0"]
build-backend = "maturin"

[project]
name = "tokrs"
version = "0.1.0"
description = "count_tokens from the Rust page, Part 2: a PyO3 extension built step by step"
requires-python = ">=3.10"
dependencies = ["numpy>=2"]

[tool.maturin]
module-name = "tokrs"

crate-type = ["cdylib"] asks for a C-compatible dynamic library, the only kind Python can load. The other four dependencies are numpy (rust-numpy, section 5), rayon (parallel loops, section 8), and serde with serde_json (typed JSON parsing, section 10).

[profile.release] settings apply to --release builds; without --release you get a debug build that is often 10 to 50 times slower, and timing it is the most common beginner mistake. A clean release build, installed into the virtual environment:

$ maturin develop --release (clean, under /usr/bin/time -p)
🐍 Found CPython 3.14 at <pl>/rb/venv314/bin/python
🔗 Found pyo3 bindings
Using Python 3.14.8 environment at: <pl>/rb/venv314
Checked 1 package in 12ms
    Finished `release` profile [optimized] target(s) in 9.25s
📖 Found type stub file at tokrs.pyi
📦 Built wheel for CPython 3.14 to <tmp>/tokrs-0.1.0-cp314-cp314-macosx_11_0_arm64.whl
✏️ Setting installed package as editable
🛠 Installed tokrs-0.1.0
real 10.32
user 34.79
sys 4.22
Correction to older guides (and to the root's benchmark crate)
Older tutorials add features = ["pyo3/extension-module"] under [tool.maturin]. PyO3 now marks that feature deprecated: maturin 1.9.4 and later set the environment variable PYO3_BUILD_EXTENSION_MODULE, which does the same job (stop linking to libpython) (PyO3 features guide). tokrs leaves it out; the root's src/bench/ext_rust/ still has it, which is harmless.
maturin develop
Build and install into the current venv: your edit, compile, test loop.
maturin build --release
Write a wheel into target/wheels/ (or -o dir): what you ship (section 12).
pip / uv
uv pip install . calls maturin as the build backend, so users with a Rust toolchain can build from source.

3. Functions and modules: #[pyfunction], #[pymodule]

Step 1 of the token counter: the root program's token loop as plain Rust, and a thin function Python can call.

ext/src/lib.rs
/// Tokens = maximal runs of ASCII letters or digits (rule 3 of PROGRAM.md).
/// Non-ASCII characters are UTF-8 bytes >= 0x80, so a byte loop gives the char answer.
fn tokens(s: &[u8]) -> u64 {
    let mut n = 0;
    let mut inside = false;
    for &b in s {
        let t = b.is_ascii_alphanumeric();
        if t && !inside {
            n += 1;
        }
        inside = t;
    }
    n
}
ext/src/lib.rs
/// Step 1: one message per call. `&str` borrows the Python string's UTF-8 bytes.
#[pyfunction]
fn count_tokens(text: &str) -> u64 {
    tokens(text.as_bytes())
}

#[pyfunction] generates the glue: a C-level function that takes Python's argument objects, converts each to the Rust parameter type (&str here), calls your function, and converts the u64 result back into a Python int. The /// doc comment becomes the docstring. The module lists what it exports:

ext/src/lib.rs
#[pymodule]
mod tokrs {
    #[pymodule_export]
    use super::{
        count_bytes, count_bytes_owned, count_many, count_many_owned, count_tokens, counts_array,
        counts_list, dict_total, dict_total_owned, first_token_len, noop, parse_line, sum_sq_array, sum_sq_list, tally_bytes,
        tally_bytes_detached, tally_bytes_parallel, tally_file, total_len, total_len_owned, SharedCounter, Counter, MalformedLine,
    };
}

The #[pymodule] name (mod tokrs), the library name in Cargo.toml and module-name in pyproject.toml must agree, because CPython looks for PyInit_tokrs when you import tokrs; a mismatch makes the import fail.

c1_first.py
import tokrs

print(tokrs.count_tokens("Hello from hello-tokens, x86_64 café!"))
print(tokrs.count_tokens("日本語 v2.1 C++"))
print(type(tokrs.count_tokens))
print(tokrs.count_tokens.__doc__)
print(tokrs.count_tokens.__text_signature__)
Predict, then reveal: what does it print? Decide before you click.

Rule 3 of the program, checked: x86_64 is 2 tokens and café is 1 (caf), and 日本語 v2.1 C++ has 3 (v2, 1, C: the Japanese characters, the dot and the plus signs all separate). The function is a builtin_function_or_method, exactly like len, and PyO3 wrote its signature (text) from the Rust parameter name, so keyword calls work.

What Python sees when the types are wrong

Python has no compiler to stop count_tokens(5), so the glue checks every argument at run time and raises TypeError. Nine wrong and right calls, run for real, gave four lessons.

Predict the nine calls, then reveal the real output
c2_types.py
import tokrs

calls = [
    'tokrs.count_tokens(5)',
    'tokrs.count_tokens(b"raw bytes")',
    'tokrs.count_tokens(text="keyword works")',
    'tokrs.count_many(["fine", 3])',
    'tokrs.count_many(("a", "tuple"))',
    'tokrs.count_many_owned(("a", "tuple"))',
    'tokrs.count_many_owned("abc")',
    'tokrs.count_bytes("a str")',
    'tokrs.count_tokens("\\ud800 lone surrogate")',
]
for c in calls:
    try:
        r = eval(c)
        print(f"{c}\n  -> {r!r}")
    except Exception as e:
        notes = "".join(f" ({n})" for n in getattr(e, "__notes__", []))
        print(f"{c}\n  -> {type(e).__name__}: {e}{notes}")
Predict, then reveal: what does it print? Decide before you click.

(1) PyO3 adds a note naming the parameter (while processing 'text', shown by Python 3.11+ as an exception note). (2) &Bound<PyList> accepts exactly a list, so a tuple is refused, while Vec<String> accepts any sequence but deliberately refuses a str, which is also a sequence and a classic bug. (3) Inside count_many the item check runs after argument parsing, so its error has no note: say which item failed in your own messages. (4) A str holding a lone surrogate (legal in Python, not in UTF-8) cannot become &str and raises UnicodeEncodeError.

The types in those signatures

Rust typeWhat it isPython analogy
Python<'py>A zero-size token proving this thread is attached to the interpreter (holds the GIL on a normal build). You get it as a parameter or from a Bound.Being inside the interpreter at all
Bound<'py, T>A strong reference to a Python object of type T (PyList, PyDict, PyAny), usable only while attached. Dropping it decrements the refcount.Any ordinary variable holding an object
Py<T>The same reference without the 'py lifetime: can be stored in a struct or sent to another thread; call .bind(py) to use it.An object kept in a global or a queue
PyResult<T>Result<T, PyErr>: Err becomes a raised exception (section 6).return or raise

The 'py is a lifetime (Rust: lifetimes, smart pointers, threads and unsafe): the compiler uses it to stop a Bound escaping the region where the interpreter is attached. You rarely write it except in return types like Bound<'py, PyDict>.

4. Crossing the boundary: what each conversion costs

A Python str is an object on Python's heap with a refcount, a length and its characters in one fixed width (1, 2 or 4 bytes each, whichever fits the widest character; PEP 393). A Rust &str is just a pointer and a length into UTF-8 bytes. So every argument crosses in one of two ways:

  • Borrowed (a view): Rust gets a pointer into memory Python owns: &str from a str, &[u8] from bytes, a NumPy array view. No allocation, no copy, but the view only lives for the call.
  • Owned (a copy): Rust builds its own value: String, Vec<T>, HashMap<K, V>, one allocation per string and one conversion per element. The value can then outlive the call, move to another thread, be stored in a struct.

The stage (Fig. 2) sends one call across the boundary in each of four signatures, with three illustrative items: the strings of rule 3 and three small floats. The objects follow what PyO3 0.29 and CPython 3.14 do (the UTF-8 cache is filled by PyUnicode_AsUTF8AndSize); the towers on the boundary are the measured cost per item from the table below, not the cost of these three items.

  1. Two heaps and a boundary. Python's objects sit on the left plate: a list holding three str objects ("café", "x86_64", "v2.1 C++"). Rust works on the right plate, inside the call. Crossing costs something even with nothing to convert: an empty call, noop(), took 25.9 ns.
  2. Copied: Vec<String>. count_many_owned(texts: Vec<String>): PyO3 visits each str, asks CPython for its UTF-8 bytes (ASCII text already is UTF-8; "café" is encoded once, 5 bytes, and the copy cached inside the object), allocates a Rust String and copies the bytes in: three allocations, 19 bytes. Measured: 72.7 ns per string.
  3. Borrowed: &str views. count_many(texts: &Bound<PyList>): Rust gets a pointer and a length into each string's UTF-8 bytes, inside the Python objects. No allocation, no copy: 9.4 ns per string, 8x less than the copy. The views end with the call, and the compiler will not let one escape.
  4. A list of floats: unbox every object. sum_sq_list(xs: Vec<f64>): a list of floats is an array of pointers to separate 24-byte objects (a refcount, a type pointer, the 8-byte double). PyO3 visits each object and copies its double into one new Vec: 6.70 ns per float.
  5. A NumPy array: one buffer, one pointer. sum_sq_array(xs: PyReadonlyArray1<f64>): the array is a small header plus one contiguous buffer of raw f64 values. rust-numpy checks the dtype once and as_slice() hands Rust a pointer and a length; nothing crosses per element. 0.97 ns per float, and most of that is the sum itself.
  6. The result crosses back. Rust's answer becomes new Python objects on the left: the Vec<u64> of token counts (1, 2, 3) a new list of ints (small ints come from CPython's cache, so no new int objects), the sum of squares (8.75) one new float.
  7. The copies are freed. When the call returns, Rust drops the Strings and the Vec it built for this call; the views simply end. Python's objects are untouched either way.

Measured with timeit on the first 20,000 messages of the log (code/c3_convert.py; nanoseconds per item, medians of 7):

Python to Rustns per itemWhat happens
an empty call, noop()The crossing alone: argument parsing, the call, returning None
one str per call, count_tokens(t)Crossing plus about 40 ns of token counting on a 125-character message
list[str] as &str viewsType check, then a pointer to the UTF-8 bytes
list[str] as Vec<String>One heap allocation and a byte copy per string
list[str] views of fresh stringsA non-ASCII str has no UTF-8 form yet: CPython encodes it and caches the copy inside the object (here % of messages)
bytes as &[u8] (per byte)A view; the cost is the token loop over 38.8 MB
bytes as Vec<u8> (per byte)One memcpy of 38.8 MB first: fast, but double the memory
list[float] as Vec<f64>Unbox each Python float object (section 5)
NumPy float64 array as a sliceA view of NumPy's buffer; the cost is the sum itself
dict[str, int] as HashMapA new String per key, a new hash table
dict iterated in placeRead each value where it is
return Vec<u64> as a listExtra cost over counting alone; small because CPython caches the int objects -5 to 256 and most counts are small

Defaults reproduce the root's Benchmark tab independently: there the empty PyO3 call took ns (separate run, same machine). Pure Python for comparison: sum(x*x for x in xs) costs ns per float.

Three rules fall out. Batch: one crossing costs about as much as counting a whole message, so call once per list, not once per item. Borrow: a copy costs x a view per string; take &str, &[u8], &Bound<PyList> and array views unless Rust must keep the data. Convert once, at the edge: if the data goes back and forth, keep it on one side (as a Rust object behind a #[pyclass], section 7, or as a NumPy array). Copy anyway when Rust must keep the data after the call (store it in a #[pyclass], or hand it to a thread that outlives the call); views of immutable str and bytes may even be read with the GIL released, as tally_bytes_detached does (section 8).

5. NumPy arrays without copies (rust-numpy)

A Python list of floats is an array of pointers to separate float objects, each 24 bytes with its own refcount; converting it visits every object. A NumPy array is one contiguous block of raw f64 values plus a small header (shape, strides, dtype). The numpy crate (rust-numpy 0.29.0, the release matching PyO3 0.29) lets Rust read that block in place:

ext/src/lib.rs
/// Sum of squares from a Python list: every float is converted into a new Vec<f64>.
#[pyfunction]
fn sum_sq_list(xs: Vec<f64>) -> f64 {
    xs.iter().map(|x| x * x).sum()
}

/// The same from a NumPy array: a read-only view of NumPy's own buffer, zero copies.
#[pyfunction]
fn sum_sq_array(xs: PyReadonlyArray1<'_, f64>) -> PyResult<f64> {
    let s = xs.as_slice()?; // error if the array is not contiguous
    Ok(s.iter().map(|x| x * x).sum())
}

/// Returning results: a Vec<u64> becomes a Python list (one int object per element) ...
#[pyfunction]
fn counts_list(texts: &Bound<'_, PyList>) -> PyResult<Vec<u64>> {
    count_many(texts)
}

/// ... or a NumPy array that takes over the Vec's buffer without copying it.
#[pyfunction]
fn counts_array<'py>(py: Python<'py>, texts: &Bound<'py, PyList>) -> PyResult<Bound<'py, PyArray1<u64>>> {
    Ok(count_many(texts)?.into_pyarray(py))
}

/// Dicts: `HashMap<String, u64>` copies every key into a new String ...
#[pyfunction]
fn dict_total_owned(d: HashMap<String, u64>) -> u64 {
    d.values().sum()
}

/// ... while iterating the `PyDict` in place only reads the values.
#[pyfunction]
fn dict_total(d: &Bound<'_, PyDict>) -> PyResult<u64> {
    let mut s = 0;
    for (_k, v) in d.iter() {
        s += v.extract::<u64>()?;
    }
    Ok(s)
}

PyReadonlyArray1<f64> checks the dtype and takes a shared borrow of the array (rust-numpy tracks borrows so Rust cannot write to an array Python code also holds as read-only); as_slice() gives a plain &[f64] when the memory is contiguous. On a million floats: list ns per element, array ns. Returning works the other way: into_pyarray hands a Vec's buffer to NumPy without copying.

Rust lost to NumPy here, and that is the lesson
np.dot(x, x) took ns per element, x faster than the Rust loop. The Rust compiler may not reorder floating-point additions (the result would change in the last bits; Numerical computing says why), so .sum() runs one add at a time; NumPy calls a BLAS routine that keeps several partial sums in SIMD registers. Do not port what NumPy, PyTorch or polars already do; port the loops they cannot express.
The failure modes, recorded: wrong dtype, strided views, lists, and who owns a returned array
c4_numpy.py
import numpy as np
import tokrs

a = np.arange(6, dtype=np.float64)
print(tokrs.sum_sq_array(a), tokrs.sum_sq_list(a.tolist()))
counts = tokrs.counts_array(["one two", "three", "日本語"])
print(repr(counts), counts.flags["OWNDATA"], counts.flags["WRITEABLE"])

def attempt(label, f):
    try:
        print(label, "->", f())
    except Exception as e:
        notes = "".join(f" ({n})" for n in getattr(e, "__notes__", []))
        print(label, "->", f"{type(e).__name__}: {e}{notes}")

attempt("float32 array", lambda: tokrs.sum_sq_array(a.astype(np.float32)))
attempt("every 2nd element a[::2]", lambda: tokrs.sum_sq_array(a[::2]))
attempt("np.ascontiguousarray(a[::2])", lambda: tokrs.sum_sq_array(np.ascontiguousarray(a[::2])))
attempt("a Python list", lambda: tokrs.sum_sq_array([1.0, 2.0]))
attempt("int64 array to Vec<f64>", lambda: tokrs.sum_sq_list(np.arange(3)))
Predict, then reveal: what does it print? Decide before you click.

The float32 message ('ndarray' object is not an instance of 'ndarray') is confusing: it means "not an ndarray of the dtype I asked for". A strided view (a[::2]) is refused by as_slice; either copy it with np.ascontiguousarray on the Python side or use xs.as_array(), an ndarray view that handles strides. Vec<f64> accepted an int64 array because it converts element by element, at list speed. The array returned by into_pyarray has OWNDATA False: it points at Rust's allocation, and its base is a small Python object (PySliceContainer) that owns the buffer and frees it when the array is collected.

6. Errors become exceptions; panics become PanicException

Return PyResult<T> and an Err(PyErr) is raised as an exception when the call returns. Many Rust errors convert by themselves: std::io::Error becomes the matching OSError subclass (FileNotFoundError, PermissionError), a failed UTF-8 decode becomes UnicodeDecodeError. For your own error kinds, declare a Python exception class from Rust:

ext/src/lib.rs
create_exception!(tokrs, MalformedLine, PyException, "A JSONL line that is not a chat message.");

/// Parse one line or raise. `?` turns each Rust error into a Python exception.
#[pyfunction]
fn parse_line(line: &str) -> PyResult<(String, u64)> {
    if line.trim().is_empty() {
        return Err(PyValueError::new_err("empty line"));
    }
    let m: Message = serde_json::from_str(line)
        .map_err(|e| MalformedLine::new_err(format!("{e}")))?;
    Ok((m.user, tokens(m.text.as_bytes())))
}

/// A bug, not an error: a Rust panic reaches Python as pyo3_runtime.PanicException.
#[pyfunction]
fn first_token_len(text: &str) -> usize {
    let words: Vec<&str> = text.split(|c: char| !c.is_ascii_alphanumeric()).filter(|w| !w.is_empty()).collect();
    words[0].len() // panics on a text with no tokens: index out of bounds
}

map_err turns serde's error into a MalformedLine carrying serde's message; ? then raises it. A panic is different: Rust's reaction to a bug (an index out of bounds, an unwrap() on None), not an expected failure. PyO3 catches it at the boundary so it cannot unwind into C code, and raises pyo3_runtime.PanicException.

c5_errors.py
import tokrs

good = '{"user": "u0029", "text": "attention is all you need"}'
print(tokrs.parse_line(good))
for line in ['{"user": 17, "text": "hi"}', '{"user": "u1", "text": "unterminated', "   "]:
    try:
        tokrs.parse_line(line)
    except tokrs.MalformedLine as e:
        print("MalformedLine:", e)
    except ValueError as e:
        print("ValueError:", e)
print(tokrs.MalformedLine.__mro__)

try:
    tokrs.tally_file("no_such_file.jsonl")
except OSError as e:
    print(f"{type(e).__name__}: {e}")

print(tokrs.first_token_len("hello world"))
try:
    tokrs.first_token_len("!!!")
except Exception as e:
    print("caught by except Exception:", type(e).__name__)
except BaseException as e:
    print("only caught by except BaseException:", type(e).__name__, "|", e)
    print(type(e).__mro__)
Predict, then reveal: what does it print? Decide before you click.

The last two lines: PanicException derives from BaseException, not Exception, so except Exception: does not catch it (PyO3's source says why: "Like SystemExit, this exception is derived from BaseException so that it will typically propagate all the way through the stack and cause the Python interpreter to exit", src/panic.rs). Rust's panic handler also printed its own three lines to stderr (thread '<unnamed>' ... panicked at src/lib.rs) before Python saw the exception. Treat a PanicException in production as a bug report: fix the Rust (return a PyResult instead), do not catch it. The FileNotFoundError message is Rust's (No such file or directory (os error 2)), not Python's usual wording.

7. Classes: #[pyclass] keeps Rust state between calls

When data goes back and forth, keep it on one side. A #[pyclass] is a Rust struct that Python sees as a class: the Python object owns the struct, methods run on it in place, and the per-user table never crosses the boundary until you ask for a result.

ext/src/lib.rs
/// A running per-user counter that lives across calls.
#[pyclass(module = "tokrs")]
struct Counter {
    per_user: HashMap<String, u64>,
    lines: u64,
}

#[pymethods]
impl Counter {
    #[new]
    fn new() -> Self {
        Counter { per_user: HashMap::new(), lines: 0 }
    }

    /// Add one message. `&mut self`: PyO3 checks at run time that nobody else holds it.
    fn add(&mut self, user: &str, text: &str) {
        self.lines += 1;
        *self.per_user.entry(user.to_owned()).or_insert(0) += tokens(text.as_bytes());
    }

    /// The n heaviest users, ties by id (rule 5).
    #[pyo3(signature = (n=5))]
    fn top(&self, n: usize) -> Vec<(String, u64)> {
        let mut v: Vec<(String, u64)> = self.per_user.iter().map(|(u, c)| (u.clone(), *c)).collect();
        v.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
        v.truncate(n);
        v
    }

    #[getter]
    fn total(&self) -> u64 {
        self.per_user.values().sum()
    }

    fn __len__(&self) -> usize {
        self.per_user.len()
    }

    fn __repr__(&self) -> String {
        format!("Counter(users={}, lines={}, tokens={})", self.per_user.len(), self.lines, self.total())
    }
}

#[new] is __init__ (strictly __new__), #[getter] makes a read-only property, and methods named like Python's special methods (__len__, __repr__) become them. &self methods read; &mut self methods write. Python has no borrow checker, so PyO3 enforces Rust's rule (many readers or one writer) at run time with a flag in each object.

c6_class.py
import tokrs

c = tokrs.Counter()
c.add("u0029", "attention is all you need")
c.add("u0005", "x86_64 café")
c.add("u0029", "v2.1 of the model")
print(c, len(c), c.total)
print(c.top(), c.top(n=1))
for stmt in ["c.total = 0", "c.extra = 1", "class Mine(tokrs.Counter): pass", "c.add('u1')"]:
    try:
        exec(stmt)
        print(stmt, "-> ok")
    except Exception as e:
        print(stmt, "->", f"{type(e).__name__}: {e}")
Predict, then reveal: what does it print? Decide before you click.

Unlike a Python class, a #[pyclass] has no __dict__ (no new attributes), its getters are read-only, and it cannot be subclassed unless you write #[pyclass(subclass)]. Its fields cannot be Bound (no lifetimes in a pyclass): store Py<T> if it must hold Python objects. On a normal build the GIL serialises calls, so the borrow flag never trips; section 9 shows what happens on free-threaded Python.

Solves
State that lives across calls without re-converting it: a tokenizer's vocabulary, a parser's buffers, an index.
Costs
Each method call is still a crossing (about 30 to 70 ns); keep methods coarse (add_many over add).
Mistake
Returning a large Rust collection from a getter on every access: it is converted (copied) each time.

8. Releasing the GIL, and parallel Rust with rayon

On the normal build only the thread holding the GIL may touch Python objects (Python: concurrency, asyncio and the GIL owns the lock itself). While your Rust function runs, the calling thread still holds it, so four Python threads calling the same Rust function take turns. But a function that only touches Rust data (bytes already borrowed, a Vec, a HashMap) does not need the interpreter: py.detach(closure) releases the GIL, runs the closure, and takes it back.

ext/src/lib.rs
/// Step 4: the same work with the GIL released. `py.detach` runs the closure
/// detached from the interpreter, so other Python threads keep running.
#[pyfunction]
fn tally_bytes_detached<'py>(py: Python<'py>, data: &[u8]) -> PyResult<Report<'py>> {
    let t = py.detach(|| tally(data, 1));
    to_python(py, t)
}
Name check (PyO3 0.26 and later)
This method was called allow_threads until PyO3 0.26 (2025-08-29) renamed it detach; the token type once described as "holding the GIL" is now described as being "attached" to the interpreter, because on free-threaded Python there is no GIL to hold (PyO3 changelog). Code and answers written before mid-2025 say allow_threads.

Can you touch a Python object inside detach by mistake? No: the compiler refuses. The closure must be Ungil (on normal builds the same as Send: safe to use from another thread), and a Bound deliberately is not. In C you would find this bug as a crash under load; here it is a compile error. To use Python data inside detach, copy what you need into Rust values first (a reason to own, section 4).

The deliberately wrong function and the real compile error
lib.rs
use pyo3::prelude::*;
use pyo3::types::PyList;

/// Wrong on purpose: reads a Python list while detached from the interpreter.
#[pyfunction]
fn count_detached(py: Python<'_>, texts: Bound<'_, PyList>) -> usize {
    py.detach(|| texts.len())
}
$ cargo build --release (the real error, first part)
error[E0277]: `*mut pyo3::Python<'static>` cannot be shared between threads safely
   --> src/lib.rs:7:15
    |
  7 |     py.detach(|| texts.len())
    |        ------ ^^^^^^^^^^^^^^ `*mut pyo3::Python<'static>` cannot be shared between threads safely
    |        |
    |        required by a bound introduced by this call
    |
    = help: within `pyo3::Bound<'_, PyList>`, the trait `Sync` is not implemented for `*mut pyo3::Python<'static>`
note: required because it appears within the type `PhantomData<*mut pyo3::Python<'static>>`
   --> <rustc>/library/core/src/marker.rs:811:11
note: required because it appears within the type `pyo3::marker::NotSend`
   --> <registry>/pyo3-0.29.3/src/marker.rs:362:8
    |
362 | struct NotSend(PhantomData<*mut Python<'static>>);
    |        ^^^^^^^
note: required because it appears within the type `PhantomData<pyo3::marker::NotSend>`
   --> <rustc>/library/core/src/marker.rs:811:11
note: required because it appears within the type `pyo3::Python<'_>`
   --> <registry>/pyo3-0.29.3/src/marker.rs:358:12
    |
358 | pub struct Python<'py>(PhantomData<&'py AttachGuard>, PhantomData<NotSend>);
    |            ^^^^^^
note: required because it appears within the type `pyo3::Bound<'_, PyList>`
   --> <registry>/pyo3-0.29.3/src/instance.rs:73:12
    |
 73 | pub struct Bound<'py, T>(Python<'py>, ManuallyDrop<Py<T>>);
    |            ^^^^^
    = note: required for `&pyo3::Bound<'_, PyList>` to implement `Send`
note: required because it's used within this closure
   --> src/lib.rs:7:15
    |
  7 |     py.detach(|| texts.len())
    |               ^^
    = note: required for `{closure@src/lib.rs:7:15: 7:17}` to implement `Ungil`
note: required by a bound in `pyo3::Python::<'py>::detach`
   --> <registry>/pyo3-0.29.3/src/marker.rs:564:12
    |
562 |     pub fn detach<T, F>(self, f: F) -> T
    |            ------ required by a bound in this associated function
563 |     where
564 |         F: Ungil + FnOnce() -> T,
    |            ^^^^^ required by this bound in `Python::<'py>::detach`

For more information about this error, try `rustc --explain E0277`.
error: could not compile `send_err` (lib) due to 1 previous error

The error chain reads bottom-up: detach needs F: Ungil; the closure captures &Bound<PyList>; Bound contains a Python token, which contains a raw pointer marker (NotSend) that is never Sync.

The stage (Fig. 3) replays the real calls. Four Python threads each call Rust on one quarter of the log (9.7 MB each). Each bar is a real call, from the moment its Python code started it to the moment it returned (time.perf_counter, the median of 7 runs, code/c7_gil.py), on one time axis in every step measured. The orange token is the GIL, drawn on the thread that holds it: a thread needs the GIL to start a call, and tally_bytes does not give it up, so the holder is the thread whose call started last. Predict first: with the GIL held, do four threads finish sooner than one thread making four calls?

  1. One thread, four calls. One Python thread calls tally_bytes on each quarter in turn (CPython 3.14). The calls run back to back and the thread holds the GIL throughout: 117 ms.
  2. Four threads, GIL held. Each thread calls tally_bytes on its own quarter. A call can only start when the GIL comes free, so the calls start one after another, at 28, 50 and 72 ms: 94 ms in all, in the range of one thread doing all four (90 to 191 ms over 7 runs on the busy laptop).
  3. Four threads, GIL released. tally_bytes_detached wraps the same work in py.detach: the token leaves the threads during the Rust work, all four calls start within 0.2 ms and overlap. 35 ms, 2.7x faster on 4 threads (not 4x: the machine was busy, and building the result dict at the end needs the GIL again).
  4. Free-threaded 3.14t: no token at all. The GIL-holding tally_bytes again, on python3.14t: there is no GIL to wait for, so the four calls overlap without detach: 32 ms.
  5. One call, four rayon threads. A single Python thread makes one call, tally_bytes_parallel(data, 4): Rust releases the GIL and rayon splits the whole log into 4 chunks at newlines, inside the call (below). 47 ms. Only the call as a whole was timed; the four strands show what the code does, not measured spans.

Parallelism inside one call: rayon

If the caller is single-threaded, Rust can split the work itself. rayon turns an iterator into a parallel one (.into_par_iter()) and runs it on a pool of OS threads, one per core by default; reduce merges the partial tallies:

ext/src/lib.rs
/// Step 5: detached and parallel. rayon splits the chunks over its thread pool.
#[pyfunction]
#[pyo3(signature = (data, threads=8))]
fn tally_bytes_parallel<'py>(py: Python<'py>, data: &[u8], threads: usize) -> PyResult<Report<'py>> {
    let t = py.detach(|| {
        chunks(data, threads)
            .into_par_iter()
            .map(|(part, first)| tally(part, first))
            .reduce(Tally::default, merge)
    });
    to_python(py, t)
}

tally takes only &[u8] and returns plain Rust data, so it is safe on any thread, and the compiler checks that too (rayon requires Send). The split (chunks, in lib.rs) cuts at newlines and remembers each chunk's first line number so "first malformed line" stays exact; the pytest suite (section 11) checks the parallel result equals the serial one for 1, 2, 3, 8 and 64 chunks.

tally: the serde parse and per-user count that every thread runs
ext/src/lib.rs
/// Pure Rust, no Python objects: safe to run without the GIL and on many threads.
fn tally(data: &[u8], first_lineno: u64) -> Tally {
    let mut t = Tally::default();
    for (i, line) in data.split_inclusive(|&b| b == b'\n').enumerate() {
        t.lines += 1;
        match serde_json::from_slice::<Message>(line) {
            Ok(m) => {
                t.ok += 1;
                *t.per_user.entry(m.user).or_insert(0) += tokens(m.text.as_bytes());
            }
            Err(_) => {
                t.bad += 1;
                if t.first_bad == 0 {
                    t.first_bad = first_lineno + i as u64;
                }
            }
        }
    }
    t
}

fn merge(mut a: Tally, b: Tally) -> Tally {
    a.lines += b.lines;
    a.ok += b.ok;
    a.bad += b.bad;
    if a.first_bad == 0 {
        a.first_bad = b.first_bad;
    }
    for (u, n) in b.per_user {
        *a.per_user.entry(u).or_insert(0) += n;
    }
    a
}
Detach when
the Rust work is long-running and touches no Python objects. Do it on free-threaded Python too: there, a thread that stays attached through long work can stall the interpreter's stop-the-world pauses (garbage collection, sys.settrace, fork) for every other thread (PyO3 free-threading guide).
Mistakes
Detaching around a tiny function (all overhead, no gain); initialising a std::sync::OnceLock or LazyLock with code that calls Python, which can deadlock against the GIL (PyO3's FAQ: use PyOnceLock); starting a rayon pool in a process that already runs one worker per core (oversubscription).

9. Free-threaded Python: what an extension must declare and protect

CPython 3.14 officially supports a build without the GIL, python3.14t (PEP 779); what it costs and what it breaks is Python: concurrency, asyncio and the GIL. For an extension author it changes two things.

1. A module must declare that it is safe without the GIL, or importing it turns the GIL back on for the whole process. Since PyO3 0.28 (2026-02-01) every PyO3 module declares itself safe by default; you opt out with #[pymodule(gil_used = true)] (from 0.23 to 0.27 it was the other way round). A one-function module that opts out (code/gilused/), imported after tokrs on 3.14t:

$ python3.14t c10_ft.py
GIL enabled at start: False
after import tokrs: False
after import gilused: True
RuntimeWarning: The global interpreter lock (GIL) has been enabled to load module 'gilused.gilused', which has not declared that it can run safely without the GIL. To override this behavior and keep the GIL disabled (at your own risk), run with PYTHON_GIL=0 or -Xgil=0.

2. Calls really do run at the same time, so state shared between threads must be protected by Rust, not by the GIL. tokrs functions that only read their arguments are fine. The Counter class of section 7 is not: its add takes &mut self, and PyO3's run-time borrow flag now sees two threads asking for it at once. Eight threads, one shared Counter, 20,000 add calls each:

$ python3.14t c13_ft_borrow.py, then python3.14 c13_ft_borrow.py
GIL enabled: False
Counter: 160000 calls, added 139164, raised 20836 Already borrowed
SharedCounter: 160000 calls, added 160000, raised 0
GIL enabled: True
Counter: 160000 calls, added 160000, raised 0
SharedCounter: 160000 calls, added 160000, raised 0

Nothing was corrupted (Rust's guarantee held: added plus raised equals 160,000), but on 3.14t 13% of the calls failed (22% to 27% in three earlier runs of the same script) with RuntimeError: Already borrowed, and the same script on the GIL build never fails, which is how this bug hides in testing. The fix is the Rust way of sharing: make the class frozen (no &mut self, so no borrow flag) and put the mutable part behind a Mutex (or atomics), which makes threads wait their turn instead of failing:

ext/src/lib.rs
/// The thread-safe version: `frozen` means no `&mut self` ever, so PyO3 needs no
/// run-time borrow flag; the mutable state sits behind a Mutex that threads queue on.
#[pyclass(module = "tokrs", frozen)]
struct SharedCounter {
    per_user: std::sync::Mutex<HashMap<String, u64>>,
}

#[pymethods]
impl SharedCounter {
    #[new]
    fn new() -> Self {
        SharedCounter { per_user: std::sync::Mutex::new(HashMap::new()) }
    }

    fn add(&self, user: &str, text: &str) {
        let n = tokens(text.as_bytes()); // count outside the lock
        *self.per_user.lock().unwrap().entry(user.to_owned()).or_insert(0) += n;
    }

    #[getter]
    fn total(&self) -> u64 {
        self.per_user.lock().unwrap().values().sum()
    }
}

The token counting happens before lock(), so threads only queue for the short dictionary update. PyO3's guide has the full checklist (free-threading, pyclass thread safety), and py-free-threading.github.io tracks which libraries are ready. PyO3 0.29 supports 3.14t and later only (it dropped 3.13t, which CPython never declared supported).

10. The token counter, step by step: the optimisation ladder

Now the whole program, end to end, as the user runs it: python ladder.py STEP chat200k.jsonl, timed by hyperfine (7 runs after a warm-up, including interpreter start-up), each step printing exactly the expected output of the root's PROGRAM.md (checked byte for byte: outputs/ladder_check.txt). Pick a step in Fig. 5 to see what changed, what it bought end to end, and where the remaining time goes.

Read it as a story. Steps 1 to 3 move only the token loop: a 3x gain. Step 1 calls Rust 199,992 times (once per message); step 2 makes one call but Vec<String> copies all 25 million characters first, so its counting phase is slower than step 1's and end to end the two are within noise; step 3 borrows &str views and barely beats step 1, because once the loop is in Rust the program is waiting on json.loads. Step 4 moves the parsing too: Python reads the file as bytes and makes one call; serde parses each line straight into a typed struct, and the program runs times faster than the Python version. Step 5 releases the GIL and splits the file over 8 rayon threads. The root's own whole-file PyO3 variant measured s (one thread) and s (4 threads), in line with steps 4 and 5.

Predict: step 5 runs on 8 threads. Why is it about 2x faster than step 4 and not 8x?
The code that changed in the step picked in Fig. 5
ladder.py
def py_tokens(text):
    """The Rosetta Python token loop."""
    n, inside = 0, False
    for ch in text:
        is_tok = ch.isascii() and ch.isalnum()
        if is_tok and not inside:
            n += 1
        inside = is_tok
    return n
ladder.py
        if step == "python":
            counts = [py_tokens(s) for s in texts]

Full sources: src/rb/code/ladder.py and src/rb/ext/src/lib.rs. The output every step prints:

real output (identical for all six steps)
lines 200000  ok 199992  malformed 8 (first at line 6685)
users 200  tokens 4413871
top 5 users by tokens:
 1. u0029  939855
 2. u0005  433400
 3. u0042  279373
 4. u0169  204481
 5. u0082  159042

Fig. 5 · Batching and borrowing barely help while json.loads is in Python; moving the parsing is the big step

Seconds end to end, median of 7 (the dark tick shows min to max) measured. Grey: the root's Benchmark (separate run, same machine), where a standalone Rust binary does the whole job in s.

Where the time goes, milliseconds inside the process (start-up excluded), this step against

11. Type stubs and tests

A compiled module has no Python source, so mypy, ty and your editor cannot see its signatures. You give them a stub file (.pyi): Python syntax with ... for bodies, read only by type checkers. For a Rust-only project like this one, maturin picks up <module>.pyi next to Cargo.toml and adds it to the wheel with a py.typed marker (maturin: adding Python type information). The hand-written one, abridged:

tokrs.pyi
"""Type stubs for the tokrs extension: what mypy, ty and your editor see."""
import os

import numpy as np
import numpy.typing as npt

Report = tuple[int, int, int, int, dict[str, int]]

def noop() -> None: ...
def count_tokens(text: str) -> int: ...
def count_many(texts: list[str]) -> list[int]: ...
def count_many_owned(texts: list[str]) -> list[int]: ...
def total_len(texts: list[str]) -> int: ...
def total_len_owned(texts: list[str]) -> int: ...

A script with four mistakes (code/c11_typed.py: a bytes argument, a float32 array, an int assigned to a str, a misspelt keyword) checked three ways: without the stub, mypy cannot check any call into tokrs (missing library stubs or py.typed marker); with it, mypy catches three mistakes and ty catches all four, including the float32 array that mypy let through. A stub can drift out of date, since nothing checks it against the Rust code: test it with mypy.stubtest.

The script and the three real checker outputs
c11_typed.py
"""Calls that run, and calls a type checker should reject before they run."""
import numpy as np
import tokrs

n: int = tokrs.count_tokens("attention is all you need")
counts = tokrs.count_many(["a b", "c"])
top: list[tuple[str, int]] = tokrs.Counter().top()

tokrs.count_tokens(b"bytes, not str")          # wrong argument type
tokrs.sum_sq_array(np.arange(3, dtype=np.float32))  # float32 array where float64 is expected
label: str = tokrs.count_bytes(b"abc")          # returns int, not str
tokrs.tally_file("chat.jsonl", thread=4)        # misspelt keyword
$ mypy --strict c11_typed.py (wheel without the stub)
c11_typed.py:3: error: Skipping analyzing "tokrs": module is installed, but missing library stubs or py.typed marker  [import-untyped]
c11_typed.py:3: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
Found 1 error in 1 file (checked 1 source file)
$ mypy --strict c11_typed.py (with the stub)
c11_typed.py:9: error: Argument 1 to "count_tokens" has incompatible type "bytes"; expected "str"  [arg-type]
c11_typed.py:11: error: Incompatible types in assignment (expression has type "int", variable has type "str")  [assignment]
c11_typed.py:12: error: Unexpected keyword argument "thread" for "tally_file"; did you mean "threads"?  [call-arg]
c11_typed.py:12: note: "tally_file" defined in "tokrs"
Found 3 errors in 1 file (checked 1 source file)
$ ty check c11_typed.py (with the stub)
c11_typed.py:9:20: error[invalid-argument-type] Argument to function `count_tokens` is incorrect: Expected `str`, found `Literal[b"bytes, not str"]`
c11_typed.py:10:20: error[invalid-argument-type] Argument to function `sum_sq_array` is incorrect: Expected `NDArray[float64]`, found `_Array1D[floating[_32Bit]]`
c11_typed.py:11:14: error[invalid-assignment] Object of type `int` is not assignable to `str`
c11_typed.py:12:32: error[unknown-argument] Argument `thread` does not match any known parameter of function `tally_file`
Found 4 diagnostics

PyO3 is building automatic stubs (experimental-inspect feature, maturin generate-stubs, labelled "still in active development"). On this crate they were close but had gaps: count_many(texts: list) lost the element type (PyO3 cannot see inside a Bound<PyList>), NumPy arrays became Incomplete, MalformedLine was missing, and the file ends with a catch-all def __getattr__(name: str) -> Incomplete. It did show something true: count_bytes_owned(data: Sequence[int]), because a Vec<u8> parameter accepts any sequence of ints, not only bytes. For now, write the stub by hand.

Part of the generated stub
b9_stubs_auto.pyi
def count_bytes_owned(data: Sequence[int]) -> int:
    """
    `Vec<u8>` from `bytes`: a fresh copy of the whole buffer first.
    """

def count_many(texts: list) -> list[int]:
    """
    Step 2b: the same list, borrowed: each item is viewed in place, nothing is copied.
    """

def count_many_owned(texts: Sequence[str]) -> list[int]:
    """
    Step 2a: one call for a list. `Vec<String>` copies every string into a new Rust allocation.
    """

def count_tokens(text: str) -> int:
    """
    Step 1: one message per call. `&str` borrows the Python string's UTF-8 bytes.
    """

def counts_array(texts: list) -> Incomplete:
    """
    ... or a NumPy array that takes over the Vec's buffer without copying it.
    """

Tests call the extension the way users do: from Python. The pytest suite (ext/tests/test_tokrs.py, 16 tests) checks the rule 3 examples, equality with the Python reference on all 1,992 messages of the root's small log, the whole-file result against PROGRAM.md, the parallel split against the serial one, that errors arrive as the right exception types, and eight threads sharing nothing. It passes on 3.14.8 and on 3.14t; run it on the free-threaded build too, because the Already borrowed failure of section 9 only shows there. Rust-only helpers (tokens, chunks) can also have #[test] functions run by cargo test; tests that call into Python need an interpreter linked in, which is why most PyO3 projects test from pytest. What to test and CI in general is Testing and quality.

Three of the tests, and both runs
test_tokrs.py
def test_matches_python_on_every_message():
    texts = []
    for line in CHAT.read_text(encoding="utf-8").splitlines():
        try:
            rec = json.loads(line)
        except ValueError:
            continue
        if isinstance(rec, dict) and isinstance(rec.get("text"), str):
            texts.append(rec["text"])
    assert tokrs.count_many(texts) == [py_tokens(t) for t in texts]


def test_whole_file_matches_program_md():
    lines, ok, bad, first_bad, per_user = tokrs.tally_file(CHAT)
    assert (lines, ok, bad, first_bad) == (2000, 1992, 8, 53)
    assert sum(per_user.values()) == 44698 and per_user["u0029"] == 9491


@pytest.mark.parametrize("threads", [1, 2, 3, 8, 64])
def test_parallel_split_is_exact(threads):
    data = CHAT.read_bytes()
    assert tokrs.tally_bytes_parallel(data, threads) == tokrs.tally_bytes(data)
$ python -m pytest -q tests (CPython 3.14.8)
................                                                         [100%]
16 passed in 0.09s
$ python3.14t -m pytest -q tests (free-threaded)
................                                                         [100%]
16 passed in 0.11s

12. Wheels: abi3, abi3t, CI and publishing

Users should never need Rust to install your package: they need a wheel built for their Python and their machine, which pip or uv picks from PyPI by the tags in its file name (Python: typing, uv, packaging and the toolchain owns wheel tags, platform tags such as manylinux, and the four packaging layers). maturin build --release wrote tokrs-0.1.0-cp314-cp314-macosx_11_0_arm64.whl: CPython 3.14's full C ABI (it loads on 3.14 only; a free-threaded build would say cp314t), macOS 11 or later on Apple silicon. Inside: the compiled library, the stub and py.typed, metadata, and a software bill of materials (sboms/, the Rust crates compiled in, written by maturin). otool -L (macOS's ldd) shows the library does not link to libpython: it finds Python's C API symbols in the process that loads it, which is what lets one wheel work with any CPython 3.14 binary.

The stage (Fig. 4) carries three wheels built from the same crate to the interpreters they were installed into, in fresh virtual environments (outputs/b3_wheel.txt and b5 to b8):

  1. A cp314 wheel: one interpreter. The wheel above is built against CPython 3.14's full C ABI, so it is for 3.14 alone; every other version, and the free-threaded 3.14t, needs a wheel of its own.
  2. An abi3 wheel: one file, three versions. Built with --features pyo3/abi3-py310, the file is tokrs-0.1.0-cp310-abi3-macosx_11_0_arm64.whl. The same file loaded on Python 3.12.15, 3.13.16 and 3.14.8, each printing loads tokrs.abi3.so -> 3.
  3. Refused by 3.14t. uv would not install it on free-threaded 3.14: "the wheel was built for the stable ABI (abi3), which requires a GIL-enabled interpreter". abi3 assumes the GIL build's object layout.
  4. An abi3t wheel: both 3.15 builds. Built with --features pyo3/abi3t-py315 against 3.15.0rc3: tokrs-0.1.0-cp315-abi3.abi3t-macosx_11_0_arm64.whl. The tag abi3.abi3t means one file for both builds, and it loaded with the GIL disabled and with it enabled.
  5. What to ship today. Until you can require 3.15: the abi3 wheel for every GIL build from 3.10 on, plus a cp314t wheel (dashed: not built here) for the free-threaded build, per platform.
The build output and the wheel's contents
$ maturin build --release -o dist
🐍 Found CPython 3.14 at <pl>/rb/venv314/bin/python
🔗 Found pyo3 bindings
💻 Using `MACOSX_DEPLOYMENT_TARGET=11.0` for aarch64-apple-darwin by default
    Finished `release` profile [optimized] target(s) in 0.03s
📖 Found type stub file at tokrs.pyi
📦 Built wheel for CPython 3.14 to <pl>/rb/dist/tokrs-0.1.0-cp314-cp314-macosx_11_0_arm64.whl
$ unzip -l dist/*.whl; otool -L tokrs/*.so
Archive:  tokrs-0.1.0-cp314-cp314-macosx_11_0_arm64.whl
  Length      Date    Time    Name
---------  ---------- -----   ----
      103  01-01-1980 00:00   tokrs/__init__.py
     1642  01-01-1980 00:00   tokrs/__init__.pyi
        0  01-01-1980 00:00   tokrs/py.typed
  1012496  01-01-1980 00:00   tokrs/tokrs.cpython-314-darwin.so
      183  01-01-1980 00:00   tokrs-0.1.0.dist-info/METADATA
      105  01-01-1980 00:00   tokrs-0.1.0.dist-info/WHEEL
    46021  01-01-1980 00:00   tokrs-0.1.0.dist-info/sboms/tokrs.cyclonedx.json
      615  01-01-1980 00:00   tokrs-0.1.0.dist-info/RECORD
---------                     -------
  1061165                     8 files
tokrs/tokrs.cpython-314-darwin.so:
	@rpath/tokrs.cpython-314-darwin.so (compatibility version 0.0.0, current version 0.0.0)
	/usr/lib/libiconv.2.dylib (compatibility version 7.0.0, current version 7.0.0)
	/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1319.0.0)

abi3: one wheel for many Python versions

A wheel per Python version per platform multiplies fast. CPython's stable ABI (the "limited API", PEP 384) is a subset of the C API promised not to change; an extension that uses only that subset gets the abi3 tag and loads on that version and every later one. In PyO3 it is a feature flag, pyo3/abi3-py310 (minimum Python 3.10). Built once, installed into fresh virtual environments:

$ maturin build --release --features pyo3/abi3-py310
🐍 Found CPython 3.14 at <pl>/rb/venv314/bin/python
🔗 Found pyo3 bindings with abi3-py3.10 support
💻 Using `MACOSX_DEPLOYMENT_TARGET=11.0` for aarch64-apple-darwin by default
    Finished `release` profile [optimized] target(s) in 1.29s
📖 Found type stub file at tokrs.pyi
📦 Built wheel for abi3 Python ≥ 3.10 to <pl>/rb/dist_abi3/tokrs-0.1.0-cp310-abi3-macosx_11_0_arm64.whl
one abi3 wheel on CPython 3.12, 3.13, 3.14 and 3.14t
Python 3.12.15 loads tokrs.abi3.so -> 3
Python 3.13.16 loads tokrs.abi3.so -> 3
Python 3.14.8 loads tokrs.abi3.so -> 3
$ uv pip install (3.14t) tokrs-0.1.0-cp310-abi3-macosx_11_0_arm64.whl
Using Python 3.14.8 environment at: abi_314t
Resolved 2 packages in 1ms
error: Failed to determine installation plan
  cause: A path (dist_abi3/tokrs-0.1.0-cp310-abi3-macosx_11_0_arm64.whl) dependency is incompatible with the current platform

hint: You're using free-threaded CPython 3.14 (`cp314t`), but the wheel was built for the stable ABI (`abi3`), which requires a GIL-enabled interpreter

At run time abi3 can cost a little: under the limited API, PyO3 must call real C functions where the full API uses inline macros (list item access, string data).

What abi3 cost here, call by call (noisy; read with the caveat)

The same calls against both builds on 3.14 (ns per item, medians; code/c9_abi_cost.py):

Callcp314 buildabi3 build

Measured on a busy laptop (load average about 10) and the spread between runs was wide; only the total_len gap (reading items from a list) repeated across runs here (9.5 ns against 14.8 ns per item in this run). PyO3's changelog lists such cases, for example "Optimize PyBytes::as_bytes() when not using abi3 or abi3t" (0.29.3).

abi3t is the stable ABI for free-threaded builds, PEP 803 (status Final, Python 3.15), supported by PyO3 0.29 through the abi3t-py315 feature. Built against the 3.15 release candidate:

$ maturin build --release --features pyo3/abi3t-py315 -i python3.15t
🐍 Found CPython 3.15t at <pl>/py/cpython-3.15.0rc3+freethreaded-macos-aarch64-none/bin/python3.15t
🔗 Found pyo3 bindings with abi3t-py3.15 support
💻 Using `MACOSX_DEPLOYMENT_TARGET=11.0` for aarch64-apple-darwin by default
    Finished `release` profile [optimized] target(s) in 1.30s
📖 Found type stub file at tokrs.pyi
📦 Built wheel for abi3t Python ≥ 3.15 to <pl>/rb/dist_abi3t/tokrs-0.1.0-cp315-abi3.abi3t-macosx_11_0_arm64.whl
the abi3t wheel on CPython 3.15.0rc3, free-threaded and with the GIL
Python 3.15.0rc3 GIL enabled: False loads tokrs.abi3t.so -> 3
Python 3.15.0rc3 GIL enabled: True loads tokrs.abi3t.so -> 3

Until you can require 3.15, ship an abi3 wheel plus a cp314t wheel per platform (tokenizers, safetensors and polars build abi3-py310 today); shipping only an abi3 wheel leaves free-threaded users unable to install.

Building for every platform in CI

You cannot build Windows or Linux wheels on a Mac without cross-compilers, so CI builds them on each platform. maturin generate-ci github writes a complete GitHub Actions workflow (186 lines; PyO3/maturin-action does the builds): every build job runs maturin build --release --out dist --find-interpreter, one wheel per Python found (one in total with abi3), and a release job uploads everything to PyPI on a git tag.

What the generated workflow builds, and its release job verbatim
Job (maturin 1.15.0)Targets
linux (manylinux)x86_64, x86, aarch64, armv7, s390x, ppc64le
musllinuxx86_64, x86, aarch64, armv7
windowsx64, x86, aarch64
macosx86_64 (Intel runner), aarch64
sdistThe source distribution, for anyone with no matching wheel (they need Rust)
releaseOn a git tag: attest the artifacts and upload everything to PyPI
b10_ci.yml
  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@v7
      - name: Generate artifact attestation
        uses: actions/attest@v4
        with:
          subject-path: 'wheels-*/*'
      - name: Install uv
        if: ${{ startsWith(github.ref, 'refs/tags/') }}
        uses: astral-sh/setup-uv@v7
      - name: Publish to PyPI
        if: ${{ startsWith(github.ref, 'refs/tags/') }}
        run: uv publish 'wheels-*/*'
        env:
          UV_PUBLISH_TOKEN: ${{ secrets.PYPI_API_TOKEN }}
Change one thing before you use it
The generated job uploads with a long-lived PYPI_API_TOKEN secret. With trusted publishing you register the repository and workflow on PyPI once, the job (which already has id-token: write) receives a short-lived token from GitHub, and uv publish needs no credentials (uv packaging guide, PyPI trusted publishers). Delete the env: lines after setting it up.

cibuildwheel is the other route: one tool that builds wheels for every CPython on every platform for any build backend, including maturin; for Rust it must install a Rust toolchain inside its Linux containers (cibuildwheel FAQ, "Building Rust wheels"). maturin-action is simpler for a Rust-only package; cibuildwheel suits projects that run test suites per wheel or mix C, C++ and Rust.

13. Alternatives, measured on the same loop

Rust is one of several ways to make a Python loop fast. The token count of the same 20,000 messages, one batch call each, every tool's result checked equal to the Python loop first (code/c8_alts.py and code/alts/; nanoseconds per message, medians of 7; Fig. 6):

Cython with C types, Numba and Rust are to times faster than the Python loop, while mypyc gains x. The differences that decide are not on this chart: what else the native code must do (parse JSON, run threads, hold state), what your team can maintain, and which ecosystem has the libraries you need.

Fig. 6 · Cython, Numba and Rust land within 2x of each other; compiling the same Python with mypyc gains little

Log scale measured. nanobind and pybind11 (C++) are the root's Benchmark figures for the same batch call (separate run, same machine); cffi was not measured.

ToolYou writeWins whenCosts
Cython (3.3.0)Python with C type declarations, compiled to CSpeeding up existing Python a function at a time; wrapping C librariesA dialect; C's lack of memory safety once you use pointers; a C compiler in the build
Numba (0.68.0)Plain Python numeric code with @njit, compiled by LLVM at first callNumeric loops over NumPy arrays, no build stepFirst call compiles ( ms here); a subset of Python; strings had to become a byte array plus offsets ( ns per message to prepare)
mypyc (mypy 2.4.0)Your type-annotated Python, unchangedWhole typed code bases (mypy compiles itself with it)Modest gains when the work is on str objects: it still calls the same str methods
nanobind, pybind11C++ with binding declarationsYou already have C++ (an inference engine, CUDA kernels); see C++: the essentialsC++'s memory and thread safety are on you; CMake
cffiPython plus a C header; calls an existing C libraryWrapping a C library without writing extension codeYou still need the C library; each call is a crossing
Rust, PyO3RustNew native code that must be correct under threads; the Rust ecosystem (serde, rayon, regex)Learning Rust; compile times
Who ships Rust to Python users, and how (read from each project's build files on 2026-10-05)

The pattern is the one this page built: PyO3 for the bindings, maturin for the wheels, abi3-py310 to cut the wheel count. The links go to the build file.

ProjectWhat is in RustHow it is bound and built
tokenizers (Hugging Face)The whole tokenizer pipeline (normalise, pre-tokenise, BPE/WordPiece/Unigram, batch encode on all cores)PyO3 0.29 with abi3-py310 and the numpy crate, maturin, module tokenizers.tokenizers inside a Python package (Cargo.toml, pyproject.toml; the main branch is a 1.0 rework "not for release yet")
safetensors (Hugging Face)Reading and writing tensor files, header parsing with serde_jsonPyO3 0.29 with abi3-py310 (Cargo.toml)
polarsThe whole query engine; Python is a thin APIThe polars package is pure Python and depends on a separate compiled runtime, polars-runtime-32 (with -64 and -compat variants), built by maturin from the polars-python crate: PyO3 0.29 with abi3-py310, numpy 0.29, rayon (py-polars, polars-python; version 2.0.0rc2 on main)
pydantic-corePydantic's validation and serialisation; JSON parsing through jiter (also Rust)PyO3 0.29.2. Moved into the pydantic repository; the old pydantic-core repository is archived (Cargo.toml)
orjsonA JSON library, with SIMD UTF-8 validation (simdutf8)Not PyO3's high-level API: only pyo3-ffi, the raw declarations of CPython's C API, for full control; built with maturin (Cargo.toml)
uv, ruff (Astral)The whole programNo extension module at all: maturin with bindings = "bin" packs the compiled executable into a wheel, so pip install ruff installs a native binary (ruff, uv pyproject.toml)

The old Notion page also named hf_transfer (Hugging Face's Rust download accelerator) in this list; it was not re-checked.