Skip to content

gh-163220: Improve scaling of tokenizer - #163221

Draft
johng wants to merge 1 commit into
python:mainfrom
johng:ft-tokenize-make
Draft

johng wants to merge 1 commit into
python:mainfrom
johng:ft-tokenize-make

Conversation

@johng

@johng johng commented Dec 5, 2026 •

Copy link
Copy Markdown
Contributor

Improve the performance of tokenize.tokenize
and tokenize.generate_tokens. This is primarily
for improved FT scaling however non GIL also benefits too.

Micro benchmark

import io
import sys
import threading
import time
import tokenize

SOURCE = '''\
def f(a, b=1, *args, c: int = 2, **kwargs):
    """Docstring."""
    x = [i * 2 for i in range(10) if i % 3]
    return {"a": a, "b": b, "x": x}  # comment
''' * 50

REPEAT = 200


def work():
    for _ in range(REPEAT):
        for _ in tokenize.generate_tokens(io.StringIO(SOURCE).readline):
            pass


def throughput(nthreads):
    """Total sources tokenized per second over nthreads worker threads."""
    threads = [threading.Thread(target=work) for _ in range(nthreads)]
    start = time.perf_counter()
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    return nthreads * REPEAT / (time.perf_counter() - start)


def main():
    nthreads = int(sys.argv[1]) if len(sys.argv) > 1 else 4
    one = throughput(1)
    many = throughput(nthreads)
    print(f"1 thread:  {one:8.0f} sources/s")
    print(f"{nthreads} threads: {many:8.0f} sources/s total  = {many / one:.2f}x")


if __name__ == "__main__":
    main()

On macos m5 --enable-optimizations --with-lto

Build Version 1 thread 4 threads 4 threads vs 1 thread
Free-threaded main 1,793-1,854 1,364-1,386 0.74-0.77x
Free-threaded fix 2,308-2,459 (1.33x) 9,186-9,589 (6.9x) 3.85-3.98x
Default (GIL) main 1,908-1,925 1,891-1,955 0.98-1.02x
Default (GIL) fix 2,444-2,508 (1.28x) 2,466-2,510 1.00-1.02x

Improve the performance of tokenize.tokenize
and tokenize.generate_tokens. This is primarily
for improved FT scaling however non GIL also benefits
too.
@johng

johng commented Dec 5, 2026

Copy link
Copy Markdown
Contributor Author

This does have some downsides if TokenInfo is changes in the future to no longer be a tuple and we loose some of the make checks that protect internal C calls.

I think the alternative for this issue is to improve the scaling of make which is a much more involved change. Happy to discuss in the issue!

@johng
johng marked this pull request as draft December 5, 2026 23:08
@johng

johng commented Dec 5, 2026

Copy link
Copy Markdown
Contributor Author

Marking draft on reflection until there's some issue discussion!

Comment thread Lib/tokenize.py
try:
for info in it:
yield TokenInfo._make(info)
yield tuple.__new__(TokenInfo, info)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In general, I think we should aim to make pure-Python code scale well on the free-threaded build without changes. Is it possible to avoid refcount contention without relying on hacks like this (such as by using DRC in C code)?

@johng johng Dec 6, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In general I think this comes to optimising closures in FT, if we were to make no python changes. Each closure cell requires a shared ref increment, and also nested functions are not enabled for deferred reference counting, resulting in another shared ref access. So yes essentially DRC is likely fix for those however likely some considerations to resolve these properly.

#148610 would also be required to speedup TokenInfo._make (with the above optimised) however a simple hoist would be sufficient with the closure optimisations, but that seems easier said then done due to the wider impact.

An alternative is to avoid the use of closures of the namedtuple._make and instead create it from module-level code, so it isn't a nested function. Currently I think this requires using exec to construct the _make function inside namedtuple() which does come with a slight performance penalty (of about 2%) for class construction.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants