fix(base): suppress fastokens per-load print, log once instead (#61)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s

This commit is contained in:
hallerite
2026-05-24 13:29:35 +02:00
committed by GitHub
parent 3ae276c446
commit 1831bcc50c
2 changed files with 74 additions and 2 deletions
+32 -2
View File
@@ -1,6 +1,8 @@
from __future__ import annotations
import contextlib
import enum
import io
import logging
import queue
import threading
@@ -1049,6 +1051,10 @@ FASTOKENS_INCOMPATIBLE: frozenset[str] = frozenset(
)
_FASTOKENS_PATCH_LOCK = threading.Lock()
_FASTOKENS_ANNOUNCED = False
def _patched_load(model_name_or_path: str, **kwargs):
"""Run ``AutoTokenizer.from_pretrained`` with fastokens patched in
process-locally — patch around the load, unpatch right after.
@@ -1058,15 +1064,39 @@ def _patched_load(model_name_or_path: str, **kwargs):
fastokens for ``encode``/``decode`` while subsequent
``AutoTokenizer.from_pretrained`` calls (outside our control) go
back to vanilla. This keeps the global side effect minimal.
fastokens itself prints ``[fastokens] patch_transformers: ...`` to
stdout on every patch/unpatch call. Building a pool of size N would
therefore emit ~N lines (more under thread contention, where some
threads see ``already patched``). We swallow those prints under a
lock — ``contextlib.redirect_stdout`` swaps ``sys.stdout``
process-wide, so the lock keeps unrelated stdout writes from other
threads from disappearing into our buffer. The patch/unpatch calls
are cheap; only the brief patch+unpatch is serialized, the actual
``from_pretrained`` still runs concurrently across pool slots. A
single ``logger.info`` is emitted on the first patch so the fast
path is still discoverable in logs.
"""
import fastokens
from transformers import AutoTokenizer
fastokens.patch_transformers()
global _FASTOKENS_ANNOUNCED
with _FASTOKENS_PATCH_LOCK:
with contextlib.redirect_stdout(io.StringIO()):
fastokens.patch_transformers()
if not _FASTOKENS_ANNOUNCED:
logger.info(
"fastokens enabled — tokenizers load through the Rust BPE "
"fast path (~10x encode speedup)."
)
_FASTOKENS_ANNOUNCED = True
try:
return AutoTokenizer.from_pretrained(model_name_or_path, **kwargs)
finally:
fastokens.unpatch_transformers()
with _FASTOKENS_PATCH_LOCK:
with contextlib.redirect_stdout(io.StringIO()):
fastokens.unpatch_transformers()
def load_tokenizer(
+42
View File
@@ -167,3 +167,45 @@ def test_fallback_on_fastokens_load_error(monkeypatch):
assert "Shim" not in _backend_class_name(tok)
# Still works.
assert len(tok.encode("hi", add_special_tokens=False)) > 0
# ---------------------------------------------------------------------------
# Print suppression: fastokens itself prints "[fastokens]
# patch_transformers: ..." on every patch/unpatch call. Building a
# RendererPool of size N would emit ~N lines (the pool factory calls
# load_tokenizer once per slot). load_tokenizer swallows that stdout
# chatter and emits a single INFO log on the first patch instead.
# ---------------------------------------------------------------------------
def test_no_fastokens_stdout_chatter(capsys, caplog):
"""``load_tokenizer`` must not leak ``[fastokens]`` prints onto
stdout, and must emit exactly one INFO log per process announcing
the fast path (not once per call)."""
import logging
import renderers.base as rb
# Reset the process-wide "announced" flag so this test sees the
# first-call log even if another test loaded a tokenizer earlier.
rb._FASTOKENS_ANNOUNCED = False
with caplog.at_level(logging.INFO, logger="renderers.base"):
load_tokenizer(_FAST_MODEL)
load_tokenizer(_FAST_MODEL)
captured = capsys.readouterr()
assert "[fastokens]" not in captured.out, (
f"fastokens print leaked to stdout: {captured.out!r}"
)
assert "[fastokens]" not in captured.err, (
f"fastokens print leaked to stderr: {captured.err!r}"
)
fastokens_info = [
r for r in caplog.records if "fastokens enabled" in r.getMessage()
]
assert len(fastokens_info) == 1, (
f"expected exactly one fastokens INFO log across two loads, "
f"got {len(fastokens_info)}"
)