Fix thread-unsafe fast tokenizer usage in Tokenize - #59
Merged
Conversation
…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.
This reverts commit 8ec87e2.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
__call__(e.g.set_truncation_and_padding), which is not safe when the same tokenizer instance is called concurrently from multiple threads.DiskCacherunsTokenize.get_itemfrom aThreadPoolExecutor, and this race manifested asRuntimeError: Already borrowedduring Krea 2 training (which calls the tokenizer twice per item forsuffix_text, widening the race window).threading.Lock, stored on the tokenizer instance itself (so it's shared across anyTokenizenode reusing the same tokenizer), and wraps all tokenizer-touching code inget_itemwith it.Test plan
AutoTokenizer.from_pretrained("bert-base-uncased")fast tokenizer from 16 threads raisedRuntimeError: Already borrowedon 3988/4000 calls; with the lock applied, 0/4000 errors.Drafted by Claude