Repository navigation
Avoid full vocab clone in get_vocab_size() - #2074
Conversation
|
The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update. |
59d1e77 to
0fa29b9
Compare
ArthurZucker
left a comment
There was a problem hiding this comment.
Thanks for catching this!
Benchmarked locally on the llama-3 tokenizer (vocab=128,256, added=256), PR cuts get_vocab_size(true) from ~5.70 ms → ~1.35 µs (≈4220×).
Since non_overlapping = added.len() - overlapping is fully determined by what we've already inserted, we can cache it as a counter on AddedVocabulary
get_vocab_size(true) in O(1) without iterating added tokens at all.
Will let add_tokens skip added_tokens_map_r.keys().max().
Benched and: get_vocab_size(true) drops further to ~786 ps on llama-3.
The counter is model-dependent / stateful so we might want to do that another time as there are some edgecases.
|
Can you pull latest from main BTW ! |
|
Thanks for the review and the benchmark numbers! Rebased on latest main (1da56fa) — already up to date. The caching idea with a counter on AddedVocabulary sounds great for a follow-up. |
The Benchmarks workflow ran on the shared `ubuntu-latest` (2 vCPU) runner, whose timings vary run-to-run by ~10-35%. That noise produced spurious "regressions" in the stored baselines on hf-internal-testing/tokenizers-bench (e.g. #2074 showed +8-17% across batch/serialization benches while single-encode got faster — a runner artifact, not a code change, since that PR only touches get_vocab_size which is off every measured hot path). Pin both the Rust and Python benchmark jobs to `ubuntu-latest-8-cores` for stable, comparable baselines. NOTE: the `ubuntu-latest-8-cores` label must be provisioned in the org Actions runner settings; adjust if the available label differs.
|
Hey @ArthurZucker, thanks again for reviewing and merging this. I've been looking for more ways to contribute to tokenizers — are there any open issues or areas of the codebase that could use extra hands? Happy to pick something up. |
get_vocab_size(true)was callingget_vocab(true).len(), which clones the entire model vocabulary into a newHashMapjust to count entries.For large vocabularies (e.g. LLaMA-3 128k tokens) this allocates ~10MB on every call.
Fix by computing
base + added.len() - overlappingdirectly, whereoverlappingcounts added tokens already present in the model viatoken_to_id. Zero allocation.Applies the same fix to the Node binding, which had the identical pattern.
Adds a test covering the overlap scenario (token in both model vocab and added_vocabulary).