Skip to content

Fix thread-unsafe fast tokenizer usage in Tokenize - #59

Merged
dxqb merged 4 commits into
Nerogar:masterfrom
dxqb:fix/tokenizer-thread-safety
Jul 5, 2026
Merged

Fix thread-unsafe fast tokenizer usage in Tokenize#59
dxqb merged 4 commits into
Nerogar:masterfrom
dxqb:fix/tokenizer-thread-safety

Conversation

@dxqb

@dxqb dxqb commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Fast (Rust-backed) tokenizers mutate shared internal state on every __call__ (e.g. set_truncation_and_padding), which is not safe when the same tokenizer instance is called concurrently from multiple threads. DiskCache runs Tokenize.get_item from a ThreadPoolExecutor, and this race manifested as RuntimeError: Already borrowed during Krea 2 training (which calls the tokenizer twice per item for suffix_text, widening the race window).
  • Adds a threading.Lock, stored on the tokenizer instance itself (so it's shared across any Tokenize node reusing the same tokenizer), and wraps all tokenizer-touching code in get_item with it.

Test plan

  • Reproduced the race locally: hammering a shared AutoTokenizer.from_pretrained("bert-base-uncased") fast tokenizer from 16 threads raised RuntimeError: Already borrowed on 3988/4000 calls; with the lock applied, 0/4000 errors.

Drafted by Claude

dxqb added 4 commits July 5, 2026 12:52
…em calls

Fast tokenizers mutate shared Rust-side state on every call
(set_truncation_and_padding), which races under multi-threaded
dataloader caching and raises RuntimeError: Already borrowed.
Krea 2 doubles the per-item tokenizer calls (suffix_text), which
surfaced the race in practice.
The prior hasattr/setattr check-then-act on the tokenizer instance
wasn't actually guaranteed atomic just because it's Python; a
module-level lock now guards that registration step.
@dxqb
dxqb merged commit 3a6994a into Nerogar:master Jul 5, 2026
1 check failed
@dxqb
dxqb deleted the fix/tokenizer-thread-safety branch July 5, 2026 11:28
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.

1 participant