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.
.so, .pyd on Windows) that import loads like a .py file; NumPy, PyTorch and orjson are extension modules.py.detach(...): release the GIL while pure-Rust work runs (called allow_threads before PyO3 0.26).#[pyclass]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.
Each row: one idea, the number that shows it on this M1 Pro, and what it changes in the code you write.
| Idea | Measured here | What to do |
|---|---|---|
| Profile before you port | Moving only the token loop: that loop x faster, the program only x | Move the whole hot path, not one function inside it |
| Every call crosses a boundary | An empty Rust function costs ns per call | Call once per batch, not once per element |
| Borrow, do not copy | A str as &str: ns; copied into a String: ns | Take &str, &[u8] and NumPy views |
| NumPy arrays cross for free | A float from a list: ns; from an array: ns; NumPy's own dot beat both | Pass arrays; never rewrite what NumPy already does |
| Release the GIL for long work | 4 threads calling Rust: ms with the GIL held, ms released | Wrap pure-Rust work in py.detach(...) |
| Free-threaded Python changes the rules | 8 threads sharing one &mut self object on 3.14t: 13% of calls raised Already borrowed | #[pyclass(frozen)] plus a Mutex |
| The ladder | Whole program: s in Python, ms with parsing and counting in Rust on 8 threads | Profile, port the path, batch, borrow, detach |
| Ship wheels | One 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 builds | Build abi3 plus a 3.14t wheel in CI with maturin-action |
| Rust is not the only way | Cython, Numba and Rust within 2x of each other on this loop; mypyc x | Pick by what else the native code must do |
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.
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.
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).
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).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.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.__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).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.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.[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
[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:
🐍 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.22features = ["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.target/wheels/ (or -o dir): what you ship (section 12).uv pip install . calls maturin as the build backend, so users with a Rust toolchain can build from source.#[pyfunction], #[pymodule]Step 1 of the token counter: the root program's token loop as plain Rust, and a thin function Python can call.
/// 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 }
/// 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:
#[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.
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__)
7 3 <class 'builtin_function_or_method'> Step 1: one message per call. `&str` borrows the Python string's UTF-8 bytes. (text)
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.
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.
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}")
tokrs.count_tokens(5)
-> TypeError: 'int' object is not an instance of 'str' (while processing 'text')
tokrs.count_tokens(b"raw bytes")
-> TypeError: 'bytes' object is not an instance of 'str' (while processing 'text')
tokrs.count_tokens(text="keyword works")
-> 2
tokrs.count_many(["fine", 3])
-> TypeError: 'int' object is not an instance of 'str'
tokrs.count_many(("a", "tuple"))
-> TypeError: 'tuple' object is not an instance of 'list' (while processing 'texts')
tokrs.count_many_owned(("a", "tuple"))
-> [1, 1]
tokrs.count_many_owned("abc")
-> TypeError: Can't extract `str` to `Vec` (while processing 'texts')
tokrs.count_bytes("a str")
-> TypeError: 'str' object is not an instance of 'bytes' (while processing 'data')
tokrs.count_tokens("\ud800 lone surrogate")
-> UnicodeEncodeError: 'utf-8' codec can't encode character '\ud800' in position 0: surrogates not allowed (while processing 'text') (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.
| Rust type | What it is | Python 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>.
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:
&str from a str, &[u8] from bytes, a NumPy array view. No allocation, no copy, but the view only lives for the call.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.
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.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.&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.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.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.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.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 Rust | ns per item | What 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 views | Type 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 strings | A 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 slice | A view of NumPy's buffer; the cost is the sum itself | |
dict[str, int] as HashMap | A new String per key, a new hash table | |
dict iterated in place | Read each value where it is | |
return Vec<u64> as a list | Extra 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).
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:
/// 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.
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.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)))
55.0 55.0 array([2, 1, 0], dtype=uint64) False True float32 array -> TypeError: 'ndarray' object is not an instance of 'ndarray' (while processing 'xs') every 2nd element a[::2] -> TypeError: The given array is not contiguous or is misaligned. np.ascontiguousarray(a[::2]) -> 20.0 a Python list -> TypeError: 'list' object is not an instance of 'ndarray' (while processing 'xs') int64 array to Vec<f64> -> 5.0
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.
PanicExceptionReturn 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:
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.
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__)
('u0029', 5)
MalformedLine: invalid type: integer `17`, expected a string at line 1 column 11
MalformedLine: EOF while parsing a string at line 1 column 36
ValueError: empty line
(<class 'tokrs.MalformedLine'>, <class 'Exception'>, <class 'BaseException'>, <class 'object'>)
FileNotFoundError: No such file or directory (os error 2)
5
thread '<unnamed>' (16677647) panicked at src/lib.rs:285:10:
index out of bounds: the len is 0 but the index is 0
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
only caught by except BaseException: PanicException | index out of bounds: the len is 0 but the index is 0
(<class 'pyo3_runtime.PanicException'>, <class 'BaseException'>, <class 'object'>)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.
#[pyclass] keeps Rust state between callsWhen 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.
/// 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.
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}")
Counter(users=2, lines=3, tokens=13) 2 13
[('u0029', 10), ('u0005', 3)] [('u0029', 10)]
c.total = 0 -> AttributeError: attribute 'total' of 'tokrs.Counter' objects is not writable
c.extra = 1 -> AttributeError: 'tokrs.Counter' object has no attribute 'extra' and no __dict__ for setting new attributes
class Mine(tokrs.Counter): pass -> TypeError: type 'tokrs.Counter' is not an acceptable base type
c.add('u1') -> TypeError: Counter.add() missing 1 required positional argument: 'text'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.
add_many over add).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.
/// 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) }
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).
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()) }
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 errorThe 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?
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.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).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).tally_bytes again, on python3.14t: there is no GIL to wait for, so the four calls overlap without detach: 32 ms.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.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:
/// 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/// 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 }
sys.settrace, fork) for every other thread (PyO3 free-threading guide).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).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:
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:
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:
/// 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).
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.
The phases (from ladder.py --phases): the Rust part fell from ms to ms (x on a busy laptop with 2 of its 10 cores slower efficiency cores). What did not shrink is everything else in the process: starting Python and importing tokrs ( ms on its own, measured with hyperfine), reading the file, building the result dict and printing. Amdahl again.
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
if step == "python": counts = [py_tokens(s) for s in texts]
elif step == "percall": counts = [tokrs.count_tokens(s) for s in texts]
/// 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()) }
elif step == "owned": counts = tokrs.count_many_owned(texts)
/// Step 2a: one call for a list. `Vec<String>` copies every string into a new Rust allocation. #[pyfunction] fn count_many_owned(texts: Vec<String>) -> Vec<u64> { texts.iter().map(|t| tokens(t.as_bytes())).collect() } /// Step 2b: the same list, borrowed: each item is viewed in place, nothing is copied. #[pyfunction] fn count_many(texts: &Bound<'_, PyList>) -> PyResult<Vec<u64>> { let mut out = Vec::with_capacity(texts.len()); for item in texts.iter() { let s = item.cast::<PyString>()?; // TypeError if an item is not a str out.push(tokens(s.to_str()?.as_bytes())); } Ok(out) } /// Conversion alone (no token loop): total UTF-8 length, borrowed ... #[pyfunction] fn total_len(texts: &Bound<'_, PyList>) -> PyResult<usize> { let mut n = 0; for item in texts.iter() { n += item.cast::<PyString>()?.to_str()?.len(); } Ok(n) } /// ... and copied into Strings first. #[pyfunction] fn total_len_owned(texts: Vec<String>) -> usize { texts.iter().map(|t| t.len()).sum() }
else:
counts = tokrs.count_many(texts)/// Step 2a: one call for a list. `Vec<String>` copies every string into a new Rust allocation. #[pyfunction] fn count_many_owned(texts: Vec<String>) -> Vec<u64> { texts.iter().map(|t| tokens(t.as_bytes())).collect() } /// Step 2b: the same list, borrowed: each item is viewed in place, nothing is copied. #[pyfunction] fn count_many(texts: &Bound<'_, PyList>) -> PyResult<Vec<u64>> { let mut out = Vec::with_capacity(texts.len()); for item in texts.iter() { let s = item.cast::<PyString>()?; // TypeError if an item is not a str out.push(tokens(s.to_str()?.as_bytes())); } Ok(out) } /// Conversion alone (no token loop): total UTF-8 length, borrowed ... #[pyfunction] fn total_len(texts: &Bound<'_, PyList>) -> PyResult<usize> { let mut n = 0; for item in texts.iter() { n += item.cast::<PyString>()?.to_str()?.len(); } Ok(n) } /// ... and copied into Strings first. #[pyfunction] fn total_len_owned(texts: Vec<String>) -> usize { texts.iter().map(|t| t.len()).sum() }
if step in ("bytes", "parallel"): with open(path, "rb") as f: data = f.read() t.append(time.perf_counter()) if step == "bytes": res = tokrs.tally_bytes(data)
/// The typed parse of one JSONL line (same as the root's Rosetta Rust program): /// serde checks that `user` and `text` exist and are strings while it parses. #[derive(Deserialize)] struct Message { user: String, text: String, }
/// Step 3: the whole file in one call. Python reads the bytes; Rust parses and counts. /// The GIL (or, on free-threaded Python, the thread's attachment) is held throughout. #[pyfunction] fn tally_bytes<'py>(py: Python<'py>, data: &[u8]) -> PyResult<Report<'py>> { let t = tally(data, 1); to_python(py, t) }
else:
res = tokrs.tally_bytes_parallel(data, 8)/// 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) }
Full sources: src/rb/code/ladder.py and src/rb/ext/src/lib.rs. The output every step prints:
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
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
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:
"""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.
"""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
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)
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)
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.
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.
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)
................ [100%] 16 passed in 0.09s
................ [100%] 16 passed in 0.11s
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):
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.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.abi3), which requires a GIL-enabled interpreter". abi3 assumes the GIL build's object layout.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.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.🐍 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.whlArchive: 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)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:
🐍 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.whlPython 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).
The same calls against both builds on 3.14 (ns per item, medians; code/c9_abi_cost.py):
| Call | cp314 build | abi3 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:
🐍 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.whlPython 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.
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.
| Job (maturin 1.15.0) | Targets |
|---|---|
| linux (manylinux) | x86_64, x86, aarch64, armv7, s390x, ppc64le |
| musllinux | x86_64, x86, aarch64, armv7 |
| windows | x64, x86, aarch64 |
| macos | x86_64 (Intel runner), aarch64 |
| sdist | The source distribution, for anyone with no matching wheel (they need Rust) |
| release | On a git tag: attest the artifacts and upload everything to PyPI |
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 }}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.
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.
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.
| Tool | You write | Wins when | Costs |
|---|---|---|---|
| Cython (3.3.0) | Python with C type declarations, compiled to C | Speeding up existing Python a function at a time; wrapping C libraries | A 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 call | Numeric loops over NumPy arrays, no build step | First 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, unchanged | Whole 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, pybind11 | C++ with binding declarations | You already have C++ (an inference engine, CUDA kernels); see C++: the essentials | C++'s memory and thread safety are on you; CMake |
| cffi | Python plus a C header; calls an existing C library | Wrapping a C library without writing extension code | You still need the C library; each call is a crossing |
| Rust, PyO3 | Rust | New native code that must be correct under threads; the Rust ecosystem (serde, rayon, regex) | Learning Rust; compile times |
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.
| Project | What is in Rust | How 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_json | PyO3 0.29 with abi3-py310 (Cargo.toml) |
| polars | The whole query engine; Python is a thin API | The 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-core | Pydantic'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) |
| orjson | A 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 program | No 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.
Cargo, ownership and borrowing: what every section here assumes.
String against &str, Result and ?: the Rust side of sections 4 and 6.
Lifetimes (the 'py in section 3), Send, Sync and Mutex (sections 8 and 9).
The other way to ship Rust to Python users: a service or a binary.
Profiling and the cheap wins to try before a port; why the interpreter loop is slow.
The GIL and the free-threaded build in full; the C-extension version of section 9's GIL opt-out, and which popular packages ship free-threaded wheels.
Wheel and platform tags, cibuildwheel, trusted publishing, and abi3t from the packaging side.
The root: Benchmark (every language and binding on the same token counter), Toolchain atlas (the recorded maturin new walkthrough), Rosetta.
nanobind and pybind11; what the CPU does under these loops (why np.dot beat the Rust sum).
CI and what to test; measuring performance properly.
Why floating-point sums cannot be reordered freely.
Functions, classes, conversions, parallelism, free-threading. about 2 hours for the core chapters
Project layouts, stubs, cross-compiling, CI. 30 minutes
Array views and borrows; parallel iterators. 20 and 15 minutes
Porting extensions and the readiness tracker. 30 minutes for the porting pages
The stable ABIs, from the source. 20 and 15 minutes
Publishing from CI without a stored token. 10 minutes
The tokenizers, polars and orjson build files linked in section 13, then their src/ folders: the best examples of large PyO3 APIs, abi3 wheels and the raw-FFI alternative. an hour each, browsing
Sources and reproduction: src/rb/ in this page's folder (run_all.sh reruns every measurement; check_outputs.py proves the page embeds the recorded outputs).