6 ms·
GigaToken: ~1000x faster Language model tokenization
- vmware508 2mo agoWe should just rewrite everything in Rust, especially bloated Python code, and the world would be a better place. ;) Disclosure: I'm a Rust advocate!
- SOLAR_FIELDS 2mo ago1 year ago everyone would have called you insane for suggesting this. Now we all shrug and say yeah maybe we can do this and it’s actually a good idea?
- minimaxir 2mo agoBoth the example libraries compared (tokenizers and tiktoken) are Rust-based with Python bindings. There's just a few levers in Rust that can speed it up even more particularly with LLM assistance as the AI Use Discloure here notes: > Final profiling stages and the last ~4x worth of performance from eliminating branching and improving the pretoken cache hierarchy
- deleted 2mo ago[deleted]
- weberer 2mo agoWe should rewrite all Rust code in Python. Not for any technical reason. I'm just sick of the Rust cult at this point.
- fwip 2mo agoWhat sort of setups do people have that are bounded by the speed of the tokenizer?
- rhdunn 2mo agoIt can be useful for checking input token usage before sending it to the model, e.g. preventing calls above a given token bound or grouping requests into batches. It can also be used by the LLMs to provide the input and output token counts on the different APIs, though I'm not sure if this is how llama.cpp or other OpenAI-like APIs calculate the input/output tokens of a request.
- charcircuit 2mo agoBut are those bounded on the speed of tokenization?
- andersa 2mo agoWait, since when does it matter whether something being hyper-optimized is useful? The computer going brrrr on an interesting problem is in itself the goal!
- fwip 2mo agoThat's fair, I just figure there are useful scenarios as well. Apologies if I came off as dismissive!
- ac2u 2mo agoIt didn’t come off as dismissive to me. I was curious as well as to where such optimizing helps and knew that the answers to your question would help me discover use cases I didn’t think of
- marcelroed 2mo agoAuthor here! In my case it's mostly pretraining experiments, where you might want to change your data mixture/filtering/processing of training data, and splits are usually done at a token-level instead of a text level. In this case we usually run for days on a huge number of CPUs to finish tokenizing something like DCLM. From what I can tell it's also useful for inference when considering time-to-first-token (TTFT) as reported by fastokens.[0] I'm not sure about the proprietary inference engines, but in the open source ones tokenization is done before looking up if a text sequence is present in the KV-cache. If you have a long prefix that's been seen before (say a system prompt), the time for tokenizing that will be a large part of your TTFT. The tokenizer cache should be warmed up in this case, so the throughput for Gigatoken would be significantly higher than reported in the repo. [0] https://github.com/crusoecloud/fastokens https://github.com/crusoecloud/fastokens
- lostmsu 2mo agoCan't you tokenize in preloading on demand?
- marcelroed 2mo agoYou can, but this usually results in sequences with padding/truncation, since you won't know how many tokens your inputs map to before you actually tokenize them. This also makes shuffling difficult. In practice every training project I've worked on does tokenization in a separate data processing phase.
- fwip 2mo agoVery cool, thanks.
- wren6991 2mo ago> I'm not sure about the proprietary inference engines, but in the open source ones tokenization is done before looking up if a text sequence is present in the KV-cache Is this necessary? Tokenisation is deterministic, so for a hit/miss check you can lookup on (a hash of) the source text instead of the tokens. You only need the tokens once you're seeking for the exact token index having determined there is a hit. That means tokenisation can proceed in parallel with your cache query, and since these caches are distributed in production systems I imagine the query itself could be slow. I'm not trying to undermine the utility, and this is obviously excellent work. Being able to tokenise faster on the client also seems useful (precise token counts for context pruning heuristics, instead of `chars / 4`), and on a phone your work translates directly to energy savings. I'm just curious about the cache lookup point.
- imperio59 2mo agoPre-training data is pre-tokenized ahead of time before being used to not waste any GPU compute. A massive speedup like this is a nice efficiency savings on some of these data pipelines for sure.
- janalsncm 2mo agoIf you are training an LLM, you need to tokenize the text before it’s trained on. A lot of time this can be done in parallel with the GPU though. I have spent way too much time waiting 10-15 minutes tokenizing my training dataset only for the run to crash over some minor bug after that. (If I was smarter, I’d test on a smaller batch first.)
- avereveard 2mo agoI've data where i cannot store metadata that i need to search semantically so i embed it on the fly at every search with static embedding and tokenizing was more than 99% of the cpu time. Granted that was due the naive implementation of the default tokenizer which was o^2 with document length and just switching to a proper scanner solved most of it without going to simd and whatnot, but still.
- SnowflakeOnIce 2mo agoI worked on a system a couple years ago with a BERT-based model (64M parameters) used for classification. The rest of the system could process data at gigabytes per second, and so here tokenization at a measly few megabytes per second really slowed things down. The model inference was more expensive than tokenization, but tokenization was still >10% of total runtime.
- maxdo 2mo agoInteresting : Q: Did you just way over-optimize for a specific CPU and tokenizer? How is it so fast? No, I way over-optimized for every combination of these! The results are very consistent across CPUs (modern x86 and ARM), and across specific tokenizers. The major improvements are in optimizing heavily an implementation that usually is outsourced to a Regex engine (pretokenization) using SIMD, minimizing branching and other tricks, as well as heavily optimizing caching of pretoken mappings (if a word has been seen before, look it up its encoded tokens efficiently). Caching is a very hard problem in this domain since the cache grows very quickly, and pretoken distributions are very long-tailed. Finally, interactions with Python are minimized, and threads have minimal interactions with each other.
- sashank_1509 2mo agoThis is really cool, great work!
- 0xnyn 2mo agoI had to stare at that chart for a minute just to let the numbers sink in. It's genuinely mind-bending, incredible ship OP
- onlyrealcuzzo 2mo agoThis is awesome, but tokenization is typically <0.1% of total inference time. Presumably there's a host of applications that just need to tokenize, though, and this would be great for those!
- GenerocUsername 2mo agoAlways good to make it 0.001%
- pipsterwo 2mo ago1/1000 of inference compute is a non-trivial workload at scale. Gartner estimates ~$28B in inference spend for 2026 making this a $28 million dollar per year workload (edit: based on the assumption above) Source: https://www.gartner.com/en/newsroom/press-releases/2026-07-20-gartner-forecasts-worldwide-ai-platforms-and-models-market-to-grow-63-percent-in-2026 https://www.gartner.com/en/newsroom/press-releases/2026-07-2...
- boroboro4 2mo agoThe issue is it’s cpu compute which is underutilized in gpu clusters anyway, so practically it’s not really 1/1000.
- pipsterwo 2mo agoTotally, edited my comment to specify "based on the assumption above." The main takeaway I was going for was 0.1% is not a small number in this context
- scottcha 2mo agoI run an AI platform and we need to tokenize fast and early to make a lot of decisions on the subsequent steps (things like routing, rate limiting and such). Its really important to do this efficiently even though its not a large % of total end to end time for the request.
- 2mo ago
- semiinfinitely 2mo agoquite excellent software
- zerolines 2mo agowow, best release all week.
- dmezzetti 2mo agoVery interesting project! Are there benchmarks for the "compatibility mode" or are all the numbers for the Gigatoken API?
- marcelroed 2mo agoNumbers are for the Gigatoken API, but compatibility mode just means eating a bunch of Python overhead (creating lists, reading strings to bytes). You can expect a modest ~200-300x speedup with compatibility mode depending on how you use it.
- robotresearcher 2mo ago> a modest ~200-300x speedup with compatibility mode marcelroed is modest, this speedup is not. Good work.
- marcelroed 2mo agoI can add some benchmarks for compatibility mode in the future. I have a little more juice to squeeze out of the Python interop though, so not quite ready for it yet.
- anonymousmoos 2mo agoQuality software here.
- swiftcoder 2mo agoSo the question becomes, how many other parts of the inference pipeline have left 1000x optimization opportunities lying on the table?
- fastball 2mo agoThe problem with the rest of inference is that changes are not trivially correct or incorrect, as they are with the tokenization layer.
- nixon_why69 2mo agoEh, linear algebra changes are still easy to measure correctness, it's just that you're competing with 50 years of research for most of them, less low hanging fruit.
- michaelmior 2mo agoSome changes certainly can be. If the model produces the exact same output for a fixed seed across a variety of inputs after a code change, I think it's reasonable to expect that the change is correct. There are also mathematical transformations that can be applied in some cases that are provably correct. (Not suggesting there's necessarily anything of this nature that will lead to 1,000x improvement though.)
- janwas 2mo agohm, maybe not so trivially correct here. Do I understand correctly that incorrect results can happen as a result of a 42-bit hash collision? That could happen after less than one MB of input, given the simple one-mul hash. BTW throughput is measured for a 12 GiB file. Would be interesting to see the throughput for something more like 32 KiB, with cold start (token cache not yet populated).
- parineum 2mo agoI'm sure there's been a lot more effort put into the other, more consequential, portions of inference time.
- ProofHouse 2mo ago
- luciana1u 2mo ago[flagged]
- michaelmior 2mo agoThis depends on what your workflow is. There are use cases for tokenization that don't always involve immediately feeding the text into a model.
- casey2 2mo agoThere are more usecases, for this class of tokenizer, now that it's 1000x faster as well. RAG being one example.
- piker 2mo ago"The pursuit of excellence does not need justification." https://x.com/mitchellh/status/2074225453217505494 https://x.com/mitchellh/status/2074225453217505494
- alansaber 2mo agoIt's pretty funny but then again, why not if it's as trivial to simplify as it appears
- Cthulhu_ 2mo agoI don't think this was particularly trivial, but I do think that thanks to AI assisted coding there's more capacity for making improvements that "don't seem worth it" at first or when you look at it as a percentage of total. But look at e.g. Biome; optimizing the formatter didn't seem worth it for a long time because it only took <1s to format most files. But it's <1s times millions of files, billions of times a day when you add up every developer that used Prettier for their code formatting - it adds up. And I'm convinced Biome triggered or was part of a bigger effort to convert JS based tools to native code. This saved time and energy, which in turn allows for faster and / or more feedback loops, which in turn allows faster turnaround cycles for software development (bet it human or LLM assisted), etc. It's a compound effect. I don't know enough about tokenization or whatever to judge this one, but if it's 1000x as fast as it used to be, there will be less need to try and avoid or minimize tokenization which may lead to new applications.
- chocrates 2mo agoPractically I would need to wait for hugging face models to adopt this? My harness tokenizer is just an estimate since the model tokenizes on my api calls?
- apollopower 2mo agoCool stuff. From my understanding, this is less valuable at inference time and more useful when running offline pre-training data prep. When tokenizing terabytes of text for your training corpus, the speedup here is probably doing real work in saving you time (and money?). You get a faster iteration cycle when figuring out and adjusting your datasets.
- Ey7NFZ3P0nzAe 2mo agoAlso for embeddings model
- luck7710 2mo ago[dead]
- kiaansaraiya 2mo ago[dead]
- zX41ZdbW 2mo agoThis is exactly what we need! Will try: https://github.com/ClickHouse/ClickHouse/issues/108247 https://github.com/ClickHouse/ClickHouse/issues/108247 It will be nicer if the README focuses more on per-core performance. About the actual algorithm - will something like matching in a perfect hash table help?
- nxpnsv 2mo agoSurely it should be kilotoken
- hansvm 2mo agoFor the lazy among us (not me of course), is there a small number of core techniques which enabled this for even a single architecture and single CPU core?
- cschmidt 2mo agoCan I say this seems to be fantastic work. I cloned your repo earlier today after seeing it on the tokenization discord. I know everyone in the tokenization community wants to absorb the lessons of how you got such a speedup. The caching and replacing the regex for pretokenization seem like generally useful ideas. And screw all the 0.1% haters on here, this is great stuff.
- asdf88990 2mo ago[flagged]
- cschmidt 2mo agoI’m not sure why you think this is ai slop. I work on tokenization research full time. My name is Craig Schmidt and I have a number of papers in the field. This researcher has done some very impressive work and I’m trying to defend him from the HN dismissive hoards. There is a serious research community on tokenization, and we are quite interested in this work.
- asdf88990 2mo agoWhich part of “doesn’t seem to be aislop signs” made you think I believe your comment was aislop? As I said, It just might be the low information density approach to talking recently that seems off to me. To explain a bit more, I kept reading and waiting for the penny drop but nothing. “I cloned your repo” — okay then what happened? Nothing? I put my shoes on this morning. “I know the tokrniziation community wants to absord tje lessons” okay? Tell me the point please! I know the AI community wants to understand the universe. “These are useful ideas”. Yes. Of course, you could argue that my comment falls in the same category in the sense that I am not actually contributing to the topic at hand but I am peeved with all low the information noise.
- cs702 2mo agoThat is my reaction too. It looks like great work! Valuable not only for inference, but for training too (think proprietary datasets). I would add, a single individual did this. One person can make a difference :-)
- deleted 2mo ago[deleted]
- mcpindex-ai 2mo agoTokenization is one of the most under appreciated and under optimized part of the agentic stack- not sure if this is truly production grade, and applicable across all hardware+stack combo but this for sure can help inspire a lot of that work. Good work!
- phplovesong 2mo agoIs tokenizing really the bottleneck? If we go from 20ms to 15ms does it really matter?
- gnabgib 2mo agoYou sound like someone who used to write fastruby
- phplovesong 2mo agoNever heard of fast ruby. My point is tokenizing is rarely a bottleneck, as 99% of time is spent in inference. So you speed up 1% of the pipeline by some factor, and the end result is unobservable for a human.
- antonvs 2mo agoTime to first token is observable by a human, and they’re reporting up to 10% reduction there. Plus, inference is not the only place tokenization happens. This can make a big difference during development of ML models.
- wacjiomv 2mo ago[flagged]
- marcelroed 2mo agoThe output tokens are identical in either case, but there are quite a few additional settings and formats that huggingface compat mode can generate. In general it also requires inputting Python lists of Python strings. The Gigatoken API instead prefers input bytes or paths to iterate, and returns an Awkward array by default. Again, no difference in correctness.
- ubedan 2mo agoSpectacular... Reminds me of the SimdJson algorithm in terms of jaw dropping nearly unbelievable speeds through creative programming. I hope this code get popular, as it will save tons of electricity, money, CO2, etc. Have you considered publishing a rust crate as well? (If not, I volunteer.)
- bob1029 2mo ago> I hope this code get popular, as it will save tons of electricity, money, CO2, etc. I don't think tokenization has ever been a meaningful bottleneck. JSON being fast falls into the same bucket much of the time. We spend way more energy on I/O and storage than we do on serialization and tokenization. If you are concerned with economics and the environment, request batching would make a bigger impact. The most expensive part of this whole thing is GPU underutilization. You can save 50% with OAI right now if you can figure out how to make your workload fit the batch pattern. Do your users always need answers right now or can we afford to wait a few days in some cases? Tool calling doesn't "time out". Wall clock does not exist in the LLM. It took me a while to get used to this.
- a_c 2mo agoIs there any write up regarding the SimdJson Algo? Definitely love to read more of it!
- ubedan 2mo agoGithub: https://github.com/simdjson/simdjson https://github.com/simdjson/simdjson It showcases an especially ingenious scheme for escaping json strings, as well as the other tokens necessary to parse json. Daniel Lemire - One of the authors at QCon 2019: https://www.youtube.com/watch?v=wlvKAT7SZIQ https://www.youtube.com/watch?v=wlvKAT7SZIQ Another Youtube video that explains it: https://www.youtube.com/watch?v=vd9J9PPmAMM https://www.youtube.com/watch?v=vd9J9PPmAMM
- o_m 2mo agoAccording to Jevons paradox this will likely lead to more electricity used and more CO2 being released to the atmosphere, because it makes it more profitable to build another data center.
- wacjiomv 2mo ago[dead]
- saschag 2mo ago[flagged]
- sghn 2mo ago[flagged]
- Antibabelic 2mo ago"AI Use Disclosure: A majority of this code base was crafted by hand without any use of AI (which can be seen from the project's Git history)." So much for "human programming is obsolete".
- Cthulhu_ 2mo agoNobody except people trying to sell AI are claiming human programming is obsolete though.
- porridgeraisin 2mo agoFor context: In the final stages of the project, AI was used to assist: Implementing the user-facing API Widening of compatibility, for instance generalizing and porting the pretokenizer implementations to support more tokenizers, less interesting features like padding/truncation/unicode normalization Porting SIMD strategies between AVX512/AVX2/NEON Final profiling stages and the last ~4x worth of performance from eliminating branching and improving the pretoken cache hierarchy Refactoring and code reuse
- XCSme 2mo agoCongrats, I love performance optimizations! Hardware nowadays is so powerful, but our code so inefficient... I think most libraries/apps could easily be 10x-100x faster if we really try to optimize them. The good thing is, that now with AI, we'll probably have the time to implement those optimizations rather quickly.
- embedding-shape 2mo ago> The good thing is, that now with AI, we'll probably have the time to implement those optimizations rather quickly. Haha, yeah, product/executives will surely now see the benefits of optimizations instead of piling new features on top of new features with no cohesive idea about the design or architecture :)
- XCSme 2mo agoIn my experience, when adding new features with LLMs, most of those optimizations come automatically. Good models now already follow best practices when implementing, better than junior devs. I wrote a bit about this, I call it "AI slap", lol: https://x.com/XCSme/status/2079115230567686263?s=20 https://x.com/XCSme/status/2079115230567686263?s=20
- embedding-shape 2mo ago> most of those optimizations come automatically We're clearly thinking of very different "optimizations" here I think :) Do you have any concrete examples of this sort of optimizations you'd get automatically? In my experience, you get what you prompt for, if I don't include to think about performance, they won't think about performance, not sure what model would automatically consider things like that. Most of the time I use whatever SOTA OpenAI has on maximum reasoning level, fwiw.
- XCSme 2mo agoNot only performance optimizations, but also UI/UX. If you ask to implement a custom dropdown that does something, it often comes with good spacing, aria-accessible tags, keyboard accessibility, etc. A junior dev wouldn't think of all of those. Also, it will probably choose the right HTML elements to use for it (i.e. maybe the modern native popover functionality instead of implementing it with custom JS, which would indeed be more efficient and less code). I am not saying it would add caching by default (even though, it might suggest that), but it's more likely to choose whatever the best options are and to use them as they should, including going around knowing limitations and gotchas.
- Timmyzzz 2mo ago[flagged]
- histiq 2mo ago[dead]
- fenestella 2mo ago[flagged]
- tim_tihub 2mo ago[dead]
- BLACKCRAB 2mo ago[dead]