{mvGPT}
  • Episode 34
  • 50 min

Measuring and fixing our C++ BPE tokenizer

We measure episode eleven's C++ tokenizer on web pages, its memory, its time, its threads and its long chunks, and fix what we find with an LRU cache, a GIL-free encoder, a cache per call and a heap.

Watch on YouTube

Open in Colab

In this episode, we go back to the BPE tokenizer we wrote in C++ in episode eleven, and measure it on FineWeb-Edu's web pages before changing anything: its memory, where its time goes, what threads do for it, and how its time grows with the length of a chunk. Then we fix what we find, one change at a time: an LRU cache with a limit, the whole encode in C++ from bytes to a NumPy array, the GIL let go, a crash and a data race that ThreadSanitizer finds, a cache for each call, and a heap that merges a long chunk without looking at each pair again.

Topics: Performance

The code

Each step on screen is a tag in the code's repository. The code at the end of the episode is ep034/end.

  1. 3:10ep034/step-1Measuring firstBrowseChanges
  2. 15:52ep034/step-2A cache with a limitBrowseChanges
  3. 21:47ep034/step-3Bytes in, NumPy outBrowseChanges
  4. 29:29ep034/step-4Letting go of the GILBrowseChanges
  5. 33:18ep034/step-5A cache per callBrowseChanges
  6. 38:33ep034/step-6A heap for long chunksBrowseChanges
  7. 43:43ep034/step-7Short chunks and long onesBrowseChanges
  8. 47:39ep034/endShort chunks and long onesBrowseChanges

Transcript

Intro

0:00 Hi, and welcome to episode thirty-four, where we go back to the tokenizer we wrote in C++ in episode eleven, and measure it before we touch it. It has worked fine since then, as far as I could tell, so I think it's a nice case for software engineering's usual tools. I had a list of what I thought was wrong with it, and I wanted to find out how much of that list was right. First, a quick look at where we end up.

0:24 Eight threads share one tokenizer here, and encode web pages at about four hundred and thirty megabytes a second, about eleven times what the tokenizer managed when we started. Back then, more threads made it slower, and at one step on the way here, two threads crashed it.

0:42 The series has a website, with a page for each episode. The code is on GitHub, with a tag for each step, so you can check out the step you're watching and run its measurements yourself. The docs get a new page on the tokenizer, with today's numbers, and further down, there's the list of episodes, each with its chapters and its code.

1:02 A quick reminder of where we left off. Last time, we trained a sparse autoencoder on the residual stream of our web model, and read features out of it, for cities, for carbon and for the moon. That model read its web pages as token ids from the BPE tokenizer of episode eleven, which our data script ran over FineWeb-Edu in episode nineteen. The tokenizer has done that job for weeks now without me looking at it again, so today it gets a proper look.

1:32 We're going to start with a script that measures the tokenizer on real web pages, its memory, its speed, what threads do for it, and how its time grows with the length of what it encodes. Then each fix comes with a measurement of what it changed. The cache gets a limit, as a least recently used cache, and the whole encode moves into C++, from the page's bytes to a NumPy array. Then the C++ lets go of Python's global lock, two threads crash it, and ThreadSanitizer tells us why. And last, a heap that merges a long chunk without looking at each of its pairs again after each merge. Right, let's start with how the tokenizer works now.

Our tokenizer

2:09 The encoder gets a page of text as bytes, as each byte is a token to start with. It splits them into chunks that merges don't cross: a word or a run of punctuation, each with the space in front of it, or a run of whitespace. A chunk it has seen before comes from a hash map, its cache, as chunks repeat a lot on the web: the, and, of. A chunk it hasn't seen before goes through the merges instead. The encoder looks at each pair of neighbouring tokens, merges the pair that was learned first wherever it appears, and looks at all the pairs again, until no pair has a merge. And out come the chunk's token ids, which the cache keeps for next time. In episode nineteen, our data script cut each file of web pages into pieces of thirty-two megabytes, and gave them to a process per core. Each process got a new tokenizer after four pieces, and I'd written why in a comment over that line: the encoder remembers each chunk it has seen, and the web has a lot of them. I'd not measured anything to back that up, so that's where we start.

Measuring first

3:10 The first measurement needs a small addition to the C++. Hash if def apple checks at compile time whether we're building on macOS, as the two systems keep malloc's statistics in different headers, malloc slash malloc on macOS and plain malloc on Linux. Allocated returns the bytes that malloc has handed out and hasn't had back yet, which is our C++'s memory, and Python's bigger objects, which come from malloc too. Over it, we write why we'd want this, when the system already tells us how much memory a process has. A process's memory, as the system counts it, also has memory that was freed and that the allocator hasn't given back. Keep that in mind, as we're going to come back to it in a few minutes. On macOS, malloc zone statistics adds up all of malloc's zones into a struct, and size in use is the part still allocated. On Linux, mallinfo two does that for the GNU C library, and we add the bytes in use on the heap to the large blocks it maps from the system on their own. M dot def allocated makes it a function of our Python module. The measurements go in a new script, bpe measure, next to episode eleven's bpe bench. Argparse reads the command line, and resource gives us the process's peak memory. Thread pool executor runs a function on a pool of threads, and islice takes the first few items of a generator, here the first few pieces of a file. We import NumPy, our C++ module, and from our data script, its folder, its tokenizer loader and web pieces. Web pieces reads a file of FineWeb-Edu and gives it back as pieces of thirty-two megabytes, each page followed by end of text. At the top, we say what the script is for: the tokenizer on FineWeb-Edu's pages, encoded the way our data script encodes them. Pages is the first file of web pages, which data dash dash web one downloads. Tokenizer loads the web's own merges, for a vocabulary of thirty-two thousand seven hundred and sixty-eight tokens, two to the fifteen. Encode copies what the data script's encode part does with each piece. It decodes the bytes into a Python string, the tokenizer gives back a list of ids, and NumPy turns the list into an array of sixteen-bit integers, the format our token files use. I want the script to measure what the data script actually does, warts and all, and not a version of it that I've cleaned up. Peak memory reads ru max r s, the most memory the process has held at any point. It comes in bytes on macOS and in kilobytes on Linux, which is easy to get wrong, so we note it in the comment over the function. Memory makes a tokenizer, and goes through the pieces we ask for, one at a time. Two flags let us take things away to see what changes. Dash dash fresh makes a new tokenizer for each piece, so the last one and its cache are freed. Perf counter is Python's clock for timing short stretches of code, and we read it before each piece. Dash dash decode only decodes each piece and encodes nothing, which is the first thing encode part does. Without that flag, the piece goes through our encode, like in the data script. After each piece, we print its speed in megabytes a second and the process's peak. Next to them goes what malloc holds, from the allocated function we've just added to our module. Speed reads all the pieces into a list before it starts the clock, so reading the file isn't part of what we time. It encodes the pieces on one thread, with a new tokenizer for each of three runs, and keeps the quickest of the three. A list collects the seconds of each run. Each run makes a new tokenizer and reads perf counter for its start. Then it loops over the pieces and encodes them, and the seconds since the start go in the list. We print the megabytes a second of the best of the three, as the slower runs are mostly the machine doing something else. Then a small class, Timed, which stands in for the C++ encoder and adds up the time its calls take. Its getattr is called for any attribute the class doesn't have, so it can wrap whichever method we call on the encoder and time it. The time goes on its total in a finally block, so it counts even when the call raises. Then a function for where the seconds go: profile takes the first piece on its own and encodes it. We need that class because cProfile, Python's own profiler, can't see inside a call into our pybind eleven module. I tried it first, and it lost the frames around those calls too. So profile swaps the tokenizer's encoder for a timed one, and encodes the piece with perf counter around it. The timed encoder's seconds are the part spent in C++, and the rest of the total is everything around those calls. We print the piece's size and its total time, then the seconds in C++ and in Python, each with its share of the total. Threads reads the pieces and adds up their megabytes. Then it encodes them on one, two, four and eight threads. Each run gets a new tokenizer, so no run starts with what the run before it cached. Thread pool executor gives us that many threads, and pool map hands them the pieces, so all the threads share one tokenizer and its cache. We print the seconds each run takes, and its megabytes a second. Doubling looks at the length of what we encode. Re sub takes out everything that isn't a letter, a digit or part of a multi-byte character, from the first piece, and that leaves its letters and digits, as one long chunk. A language written without spaces, like Chinese, looks like that to our encoder. We cut the first kilobyte of it, then two, then four, and so on up to sixty-four. Each length is encoded three times, by a new tokenizer each time, so the cache can't hand back the chunk from the run before. The best of the three goes into milliseconds, and we print it next to how many times longer it took than the length before it. If an algorithm's time grows with the length, doubling the length doubles the time. If it grows with the square of the length, it takes four times as long. Main reads its arguments with argparse, and the description says what the script measures. The first argument picks the measurement: memory, speed, profile, threads or doubling. Dash dash pieces says how many pieces of thirty-two megabytes to read, eight by default. Then the two flags for memory, dash dash fresh and dash dash decode only. Store true makes each of them a switch, which is off unless we pass it. The parser reads them all from the command line. Then a dictionary maps each of the five measurements to its function. And we call the one we picked, passing it the arguments that argparse read. And the check at the bottom runs main when we run the script, and not when another file imports it.

9:55 Memory first, on six pieces, with one tokenizer for all of them, as the data script uses it. Each piece encodes at about forty megabytes a second. The process's peak goes from about nine hundred and twenty-four megabytes after the first piece to about two thousand and sixty-six after the sixth. That climb looks like what I was worried about when I wrote that comment in the data script. What malloc holds looks quite different, and it's the number I trust more here. It holds about one hundred and forty-two megabytes after the first piece and one hundred and ninety-seven after the sixth, so the cache grew by about fifty-five megabytes, and not by a gigabyte. Then a new tokenizer for each piece, so that each cache is freed before the next piece starts. Malloc stays at about one hundred and forty-eight megabytes now, and the process's peak still climbs, to about one thousand eight hundred and eight. So the cache does grow, but it isn't where most of this memory goes.

10:50 To narrow it down, this run does the first thing the data script does with a piece, which is decode it into a Python string, and nothing else. Decoding goes at a few gigabytes a second, far quicker than encoding. And the peak climbs again, from about five hundred and seventy-four megabytes to about one thousand six hundred and sixty-one, with malloc at about one hundred and twenty-six the whole time. A piece is a Python string twice on its way to the tokenizer. Web pieces joins the pages as one string before turning them into bytes, and encode part decodes the bytes back into a string. Web pages have accents and emoji, and Python stores a string at four bytes a character when one of its characters needs that, so each string is a few times the piece's size. Python frees them, and malloc counts that memory as given back, but the process keeps growing, as macOS counts it. I don't know macOS's allocator well enough to say why it holds on to these blocks. Either way, most of the memory goes on strings we throw away, for bytes that were UTF-8 to begin with.

11:53 On the left, the process's peak climbs in all three runs, even in the one that decodes and does nothing else. On the right, what malloc holds stays flat for the fresh tokenizers and for decoding, and the line that rises is the one tokenizer's cache, by about fifty-five megabytes in six pieces. So I'd say my comment in the data script was half right. The cache does grow without a limit, if slowly, but the processes the data script restarted were mostly carrying decoded strings.

12:23 Next, the profile, which shows where a piece's time goes. It takes about zero point seven four seconds, about sixty-two percent of it in C++, and about thirty-eight percent in the Python around it. The Python part is the regular expression that splits out end of text, each page's text turned back into bytes, a Python list of all the ids, and NumPy copying that list into an array. More than a third of the time on glue is more than I'd guessed. Then the speed on one thread, which we're going to compare each step with: about forty-three megabytes a second, the best of three runs.

13:00 Then eight pieces on one, two, four and eight threads, all sharing a tokenizer. One thread does about thirty-nine megabytes a second. With two, it drops to about twenty-four, and with eight, to about twenty. The encoder holds Python's global lock from start to end, which we'll look at properly in a bit, so the threads take turns. My guess for the drop is the hand-overs of the lock, which also move the work from core to core. So for now, the tokenizer uses one of this Mac's twelve cores, and more threads make it slower.

13:33 And last, the length of a chunk, with one long chunk of letters. A kilobyte of it takes a little over half a millisecond to encode. Each doubling takes about two point eight times as long as the length before it, short of the four that a square would give, but well over the two of a time that grows with the length. Sixty-four kilobytes take about three hundred and seventy milliseconds, and at this rate a megabyte would take around twenty seconds. To be fair to the old code, FineWeb-Edu doesn't get close to this. I scanned a whole file of seven hundred and twenty-six thousand pages, and its longest chunk was eight hundred and ninety-nine bytes of Chinese, which takes well under a millisecond. But a tokenizer can get text from anywhere, a book in Chinese or a long hex string, and I don't want it to stall on one.

14:22 So, measuring turned up five problems with the old tokenizer. The cache grows without a limit, which I suspected, but slowly. Most of the memory goes on Python strings we don't need, which I hadn't suspected at all. More than a third of each piece's time goes on Python around the C++, threads don't help, and a long chunk costs far more than its length. Four of the five were on my list in some form, and the one that wasn't, the strings, costs the most memory. Without measuring, I'd have fixed the cache and left most of the memory where it was. We'll take them in order, starting with the cache.

A cache with a limit

15:00 The first fix is for the cache, which grows for as long as the encoder lives. When a cache has to stay within a size, your best bet is usually to drop what was used longest ago, which is called least recently used, or LRU. An LRU cache is built from two parts that point at each other. A doubly linked list keeps the chunks in the order they were used, the most recent at the front. And a hash map takes a chunk to its entry in the list, so finding a chunk doesn't mean walking the list. When a chunk is found, its entry moves to the front, which takes a couple of pointer changes, however long the list is. A new chunk goes in at the front, and when the cache is full, the entry at the back, the one used longest ago, makes room. On web pages, the chunks used most, like the, a and of, stay near the front, and a misspelt word drops off the back before long.

15:53 In the C++, list is the standard library's doubly linked list, where each entry points to the one before it and the one after. The cache becomes a class, LRU cache, and over it, we describe the diagram we just saw. It holds at most capacity chunks, and the one used longest ago makes room. The list keeps the order they were used in, and the map finds a chunk's place, so each operation takes a constant time, however full the cache is. It's marked explicit, so that a plain number can't turn into one by accident, and it keeps the capacity. Find takes a string view of the chunk, so looking it up copies nothing. The old cache built a string for each lookup. If the map doesn't have the chunk, we return a null pointer. If it has, splice moves its entry to the front of the list by relinking its neighbours, without copying it or moving it in memory, and we return a pointer to its ids. Add starts with the capacity, where zero means no cache at all, which our measurement is going to use. When the list is full, the entry at the back is the least recently used, so we erase it from the map, then pop it off the list. The new chunk goes in at the front, as a string, with its ids moved in. Then the map stores the chunk's position, at the beginning. Its key views the copy of the chunk that's in the entry, and we explain above it why that's safe. The copy stays put while we move things around, since a move relinks the nodes and leaves the data where it is. Entries is a list of pairs, a chunk and its ids. The members are the capacity, the list of entries, and places, the unordered map from a string view to a place in the list. The map's values are iterators, which is C++'s name for a pointer into a container. The encoder takes the cache's size now, and makes its cache with it. Encode asks the cache for each chunk, through Find. If it has it, its ids go on the end of ours. If not, we encode the chunk with the merges, and its ids go on the end of ours too. Then Add gets them moved in, so the ids aren't copied a second time. Down at the bottom of the class, the member becomes an LRU cache, and keeps its comment. In the binding, the constructor takes the cache size as a second argument. It's two to the sixteen, sixty-five thousand five hundred and thirty-six chunks, unless we say otherwise. I picked that from the measurement we're about to run, so I'm getting slightly ahead of myself. In bpe measure, tokenizer takes a cache size, which is none by default. The tokenizer it loads goes in a variable now, as we may change it before we return it. When it gets a size, it swaps in an encoder with a cache that size, built from the tokenizer's own merges. Cache is a new measurement, and it reads the pieces first, like speed and threads do. Each size gets a tokenizer whose cache holds at most so many chunks, and one tokenizer sees all the pieces. The rest goes in the function's comment: the sizes take turns, three rounds of them, and each keeps its quickest round, so that whatever else the machine is doing slows them all alike. I added the turns after my first recording of this, where something else on the Mac woke up halfway through, and a small cache came out slower than no cache at all. We add up the pieces' megabytes for the speed. The sizes go from no cache at all, through powers of two, up to two to the twenty, about a million chunks. Best keeps each size's quickest time, and held keeps what its cache holds. There are three rounds, and in each round, each size takes its turn. We make a tokenizer with that cache, and read what malloc holds before it starts. Then all the pieces go through it, timed with perf counter. Best keeps the smaller of the size's time so far and this round's, where infinity stands for no time yet. And held gets how much malloc's total has grown since we read it, which is the cache. Once the rounds are over, we print each size, its megabytes a second from its quickest round, and its cache's megabytes. Main gets cache as one of its choices. The help of dash dash pieces lists cache among the measurements it's for, and the dictionary maps cache to its function, over two lines now. So bpe measure cache runs it, with eight pieces unless we ask for more. And a new test checks that a small cache changes nothing in the ids we get back. It learns two hundred merges with the Python reference, like the test above it. The cache holds two chunks at most, so that most chunks push another out of it before they're seen again. The text is the last fifty thousand bytes of the sample, as before. And the C++ encoder, with its cache of two, has to give the reference's ids, so the test checks the code that makes room over and over.

20:40 First the tests, where the new one runs a cache of two chunks against the Python reference, so chunks get pushed out nearly all the time. All seven pass, the small cache's among them. Then the cache sizes, on four pieces, three rounds of them. Without a cache, the encoder does about twenty-four megabytes a second, as each chunk goes through the merges. At sixty-five thousand chunks, it does about forty-two, and the cache holds about ten megabytes. A million chunks is barely quicker, at about forty-five megabytes a second, and its cache holds about seventy-eight megabytes, as four pieces have fewer distinct chunks than a million. So sixty-five thousand gets about ninety-five percent of the speed for an eighth of the memory. And unlike the old cache, it stays that size however many pieces go through it.

21:29 As charts, the speed barely moves up to a thousand chunks, climbs most between four thousand and sixty-five thousand, and flattens out after that. The default sits at the knee of the curve, which is where I'd want it. Meanwhile the memory keeps climbing with the size, so a bigger cache buys very little here.

Bytes in, NumPy out

21:47 The profile and the decode run both point at the Python around the C++. So the whole encode moves into C++, from the piece's bytes to a NumPy array, and end of text and padding are found in C++ as well. Pybind eleven's numpy header lets the C++ make NumPy arrays. Algorithm has min element, to pick the nearest of a few positions, and map, C++'s ordered map, is how the constructor takes the reserved tokens from a Python dictionary. The encoder takes the reserved tokens, their text and their ids, and copies them into a vector of pairs. Encode takes a string view of the text now. The comment over it says what it does: the text of a reserved token, such as end of text, becomes its id, and the text between them is encoded on its own, so that no chunk crosses one. Python did this before, with a regular expression that split the text. Next holds, for each reserved token, where it's next found. We look for each one once, and look for a token again once we're past it, so each token's search goes through the text a single time, from start to end. In the loop, min element picks the reserved token that comes first, and at is its position, or n pos, C++'s value for not found, once there's none left. The text from where we are up to there goes to encode text, and if nothing is left, we stop. Otherwise, the token's id goes on the end, and we start again after its text. And each token we've passed by now gets looked for again, from here. Encode text is our loop over chunks from before, moved into a separate function, with the cache as it was. It's private, and it adds to the ids it's handed, so the return at its end goes. The private label further down goes too, as the one above encode text now covers the rest of the class. The reserved tokens are a member, a vector of pairs, next to the merges' ranks. In the binding, the constructor takes them as a dictionary, which pybind eleven turns into our map. The argument for the reserved tokens is an empty map when it isn't given, and the cache size stays at its default. The last binding gets a comment of its own: UTF-8 bytes in, a NumPy array of ids out, and the bytes are read where Python keeps them. The text reaches encode as a string view of those bytes, without copying them into a string first, as the old binding did. It gives back a NumPy array of thirty-two-bit integers, and array t copies our vector into it, in one go, where a Python list held a Python integer for each id. In the tokenizer, the regular expression that split out the two reserved tokens goes, as the C++ does that now. The line near the top of the constructor that made the C++ object goes as well. We make the encoder further down now, as it takes the reserved tokens as bytes, along with the ids set a few lines above. Over it, we note that the C++ finds padding's and end of text's own text, and gives them their ids. Encode loses its loop over the pieces that the regular expression split. It encodes the text to UTF-8 for the C++, and the array it gets back becomes a Python list, with to list. Our other scripts add lists together, like an end of text on the end of a story, so they still get a list. Encode bytes is new, for our data script. It encodes the bytes it's given as they are, and as type turns the ids into sixteen-bit integers, the way our token files store them. The reason goes in a comment above it: text that's already UTF-8 becomes ids without a Python string or a Python list on the way. In our data script, encode part hands its piece straight to encode bytes. Web pieces used to join a piece's pages into one Python string of thirty-two megabytes, then encode that to bytes, which is the memory the decode run showed us. Now each page is encoded to bytes on its own, with end of text's bytes after it, and the piece joins bytes. The comment says why, and points at our measurement. Our measuring script doesn't use NumPy any more, so its import goes. Encode calls encode bytes, like the data script now does. And memory loses its decode flag, as nothing decodes a piece any more. Threads flushes each line it prints, so the line shows up as soon as its run is done. And the decode only flag goes from main as well. The tests get NumPy, to read a token file, and from our data script, its folder and its tokenizer loader. End of text comes from the tokenizer, and the sample's path is built from the data folder now. The tests compare lists, so the arrays become lists first, with to list. A new test checks how the reserved tokens split the text. It learns its merges with the reference, and gives end of text an id far above theirs, nine thousand nine hundred and ninety-nine. The text is a story, end of text, another story, and two ends of text in a row. Our ids have to be the reference's ids for each story, with end of text's id wherever its text was. Web lists the three files the next test reads: the web's merges, the validation text, and the ids made from it. The test is skipped when they aren't there, which pytest's skip if decorator does for us, and the reason says to run data dash dash web. The one I care about most compares the held-out web pages with the token file our data script wrote for them in episode nineteen, with the tokenizer as it was then. It loads the tokenizer with the web's merges. Our web models read their pages as those ids, so the new encoder has to give back all ten million of them, one for one. It reads the pages as bytes and encodes them with encode bytes. NumPy reads the token file, and array equal compares the two, so the test fails if a single id differs, or if one array is longer.

27:44 First the tests, with the two new ones, for end of text and for the held-out web pages, which take a second or two to encode. All nine pass, so the held-out pages come back as their ten million ids, and end of text gets its id wherever its text was. Then the profile again, on the first piece of the file. The C++ now has ninety-nine point nine percent of the piece's time, and the piece takes about zero point four zero seconds, where it took about zero point seven four. The C++ part got quicker as well, as it no longer builds a Python list on its way out, and the cache looks chunks up without copying them. On one thread, that's about eighty megabytes a second, about one point nine times our first measurement. And memory, on six pieces, like the run at the start. The peak goes from about three hundred and thirty-one to five hundred and sixty-nine megabytes, where it reached about two thousand and sixty-six before, and it still creeps up a little. In a quick test of mine, reading the file without encoding it creeps up about as much, so I think that part is pyarrow and Python reading the parquet file, which I'm leaving for another day.

Letting go of the GIL

28:51 Now the threads, which made the tokenizer slower. Python has a global interpreter lock, the GIL, and a thread has to hold it to run Python code. So while one thread runs Python, the others wait for their turn. Our encoder held the GIL from start to end, which is why more threads didn't make our measurement any quicker. C++ that doesn't touch Python objects can let go of the GIL while it works, and then the threads run at once. Our trainer has done that since episode eleven, and encode didn't, which I'd simply forgotten about. Python has a build without the GIL these days, but it isn't the one we use, and I prefer fixing our module to changing interpreters.

29:30 In the binding, we start with the comment, which grows to say what changes and why it's safe. The bytes are still read where Python keeps them, and as the C++ doesn't touch Python while it encodes, it lets go of the GIL. That way, other threads can run Python meanwhile, or call encode on text of their own. Encode takes its string view of the bytes first, while it holds the GIL, and makes an empty vector for the ids. Then, in a block of its own, gil scoped release lets go of the GIL as it's created, and takes it back when the block ends, which C++ does for us as the object goes out of scope. Inside, Encode doesn't touch a single Python object. It reads the bytes, which can't change under it, as Python's bytes are immutable and we hold a reference to them. Back with the GIL, after the block, we make the array. Before we run threads on it, I want a tool that can tell us when two threads get in each other's way, and that's a sanitiser. Clang and GCC can compile checks into a program, and ThreadSanitizer is the one for data races: two threads touching one piece of memory, at least one of them writing, without anything to order them. In setup, the environment variable sanitize picks one, thread or address, and adds dash f sanitize with it, and dash g for debug information, so that its reports name our file and our lines. Without the variable, the list is empty and the build is as before. Tsan is a small shell script, and it starts by building the module with sanitize set to thread, with its output thrown away. Over that line goes what the script is for: it runs a command with the module built with ThreadSanitizer. ThreadSanitizer reports two threads touching one piece of memory without anything ordering them, and then the script builds the module as usual again. The last line of the comment is how we're going to call it, on the threads measurement with two pieces. Where the sanitiser's runtime is depends on the system, so uname tells us whether we're on macOS, which it calls Darwin. Python isn't built with ThreadSanitizer, and the sanitiser's runtime has to be in the process from the start, so it's loaded before Python starts. On macOS, that's DYLD insert libraries, with clang telling us where its runtime is, and on Linux, LD preload, from GCC. Then it runs the command, with two TSan options: halt on error, to stop at the first report, and a shorter format for each frame of a stack, its file and line, then its function. And whatever the command did, it builds the module again as usual, and exits with the command's status.

32:03 With the GIL let go, we run the threads measurement again, with one tokenizer shared by all the threads. One thread gets through its eight pieces as before. With two threads, the process dies before it prints a line. The shell calls it a trace trap here, and when I ran it again, it died each time, sometimes as a segmentation fault. A crash like this tells us that something broke in memory, and very little about what.

32:28 So we run it under ThreadSanitizer, with our tsan script. To keep the screen short, grep keeps the lines with the thread counts, the warning, the threads, and our cache's frames. Under the sanitiser, one thread is a lot slower, as each memory access is checked. With two threads, it stops at a data race. Thread T6 reads memory in our LRU cache's find, at line one hundred and forty-three of our file. Before it, thread T7 wrote to that memory in add, at line one hundred and fifty-seven, with nothing to order the two. Those lines are the map's lookup and the map's insert. One thread looks a chunk up while another adds one, and adding can grow the map's table and move what the first thread is reading. So the bug is in our cache, which both threads write to.

A cache per call

33:18 ThreadSanitizer pointed at the cache, and the cache is the part of the encoder that changes as it encodes. The merges' ranks and the reserved tokens are read and nothing more. So instead of a lock around the cache, which each lookup would have to take, each call to encode gets a cache of its own, and the threads share nothing that they write. The constructor keeps the cache's size, and makes no cache of its own. Encode makes the cache at its start, as a local variable, which goes away when the call returns, and it's marked const now. A const member function can't change its object, and the compiler checks that for us, which is a nice guarantee to have when threads share the object, so we add that to the comment. Encode text takes the cache by reference, and it's const as well. Find and add go to that cache, the member keeps the size and no cache, and the binding takes the encoder as a const reference. A disclaimer, as this has a cost: a cache doesn't last from one call to the next any more. For our data script, a call is a piece of thirty-two megabytes, and a fresh cache has the common chunks within its first few pages. For short texts encoded one at a time, such as stories for fine-tuning, each starts from an empty cache. In a test of mine, twenty thousand stories took about two and a half times as long, around twenty microseconds a story, which I'm happy to pay. With the encoder safe to share, our data script can use threads now. Deque, a queue that's quick at both ends, replaces the import of multiprocessing's pool. Encode part and start worker go, as no process needs a tokenizer of its own any more. In order is new, a generator that takes a pool, a function, the items, and how many of them to read ahead. Waiting is a deque of futures, the results to come, in the order we submitted them. Above it, we write what in order gives us: f of each item, on the pool's threads, given back in the items' order. At most ahead of the items are read and waiting at a time, so a file of two gigabytes isn't read into memory before the first piece is written. The pool's own map would do that, as it reads all of its items before handing back the first result. For each item, we submit it to the pool and put its future at the back. Once ahead of them are waiting, we take the oldest from the front, wait for its result and yield it, then read on. And when the items run out, we yield the rest, in order. In the build of all of TinyStories, the comment over the pieces now ends with a piece per thread, not per core. The pool of processes goes, with its worker that loaded a tokenizer in each process. The pieces get a name now, a generator that cuts each one out of the text as it's needed. A thread pool executor gets a thread per core, and in order hands them the tokenizer's encode bytes, with two pieces read ahead per thread. The web build's comment gets a piece per thread too. And the part about a fresh tokenizer after four pieces goes, as no process holds on to a cache any more. Instead, the threads share the tokenizer, and the reason goes on the next line of the comment. Each call to the C++ encoder has its own cache, of at most sixty-five thousand five hundred and thirty-six chunks. Its pool of processes goes too, for a thread pool with a thread per core. And each file's pieces go through in order, to encode bytes, with two per thread read ahead.

36:39 First, the sanitiser on the new step, with two pieces. It runs all four thread counts, slowly, as it checks each memory access, and this time it has nothing to report. Then the threads without the sanitiser, on eight pieces. One thread does about eighty-two megabytes a second, and eight do about four hundred and thirty-nine, about five point three times as much. That's about eleven times our first single thread, where eight threads ran slower than one. I'd hoped for closer to eight from eight threads, and I've not dug into where the rest goes. I suspect part of it is that the threads share one memory system, and share the cores with whatever else the Mac is doing.

37:20 Side by side, the first measurement slopes down as we add threads, and today's climbs with each one. We moved the work out of Python and let go of the GIL, and that alone crashed the process on two threads, until each call got its own cache.

A heap for long chunks

37:36 The last problem is the merge loop, which looks at each pair of the chunk after each merge. A merge changes the tokens where its pair was and no others, so nearly all of that looking finds what it found the time before. The chunk's tokens become a linked list, kept in arrays of positions, where each token points at the one before it and the one after, so joining two neighbours moves nothing else. And a heap holds the pairs of neighbours that have a merge, ordered by the merge's rank, and then by position, as the old loop merged from left to right. We take the pair off the top, the next merge to make. An earlier merge may have changed one of its tokens since it went on, and then it's stale, and we skip it. Otherwise, the two tokens become one, and the pairs it makes with its new neighbours go on the heap. So a merge costs a couple of pushes onto the heap, and a push grows with the log of the heap's size, where the old loop made a pass over the whole chunk.

38:34 The merge loop in encode chunk is rewritten from scratch. Over it, we start with what stays as it was: the merges go in the order they were learned, the lowest rank first, and of pairs with that rank, the leftmost first. Then we describe the linked list and the heap from the diagram, where the heap holds each pair of neighbours that has a merge. A merge changes the pairs on either side of it and no others, so it costs two pushes onto the heap, where looking at each pair again costs the chunk's length. The old loop goes, as it looked at all the pairs again after each merge, to find the lowest rank. N is the chunk's length, as an int, as positions are ints here. Three vectors of that length hold the list, one for the tokens, and two for the positions of each token's neighbours. In the loop, each token starts as its byte, read as an unsigned char, so that it's between zero and two hundred and fifty-five. Prev points at the one before it, and next at the one after. Position n is past the last token, so it stands for the end of the list. Candidate is a struct, a plain group of fields: the merge's rank, the position of the pair's left token, and the two tokens as they were when it went on the heap. Why we keep those goes in a comment above it: a merge can change either token after the push, and then the candidate is stale, and it's skipped when it comes off. Later is a lambda that orders two candidates. C++'s priority queue puts the largest on top, so we tell it which candidate comes later, the one with the higher rank, or with an equal rank, further right, and the earliest one comes out first. Push looks at the token at i and the one after it. At the end of the list, there's no pair. Otherwise, we look the pair up in the merges' ranks, and if it has a merge, it goes on the heap. Each neighbouring pair is pushed once to start. Then, while the heap has candidates, we take the top one. If the token at its left position has changed, or has no neighbour now, or a different one, the candidate is stale and we skip it. Otherwise, the left token becomes the new token, two hundred and fifty-six plus the rank, as the first two hundred and fifty-six ids are the bytes. The right token gets minus one, and beside it, we note that it's merged into its left neighbour, and gone from the list. The left token's next skips over it, and the token after it, if there is one, points back to the left one. Then the pairs that changed go on the heap: the one ending at our new token, if there's a token before it, and the one starting at it. Out follows the list from position zero, which a merge keeps, as it takes out the right-hand token. Before trusting this, we should check that a merge can't make a pair with a lower rank than the one it just made, which the old loop would have taken next. It can't, as a merge that uses the new token was learned after that token existed, so its rank is higher. So taking candidates off the heap in rank order gives the old loop's ids. This is the kind of code where an off-by-one can hide for a long time, so the tests compare it with the Python reference on random texts, and random is Python's module for random numbers. We train five hundred merges on the sample with the C++ trainer. The texts are built from what I'd expect to trip a merge loop. There are runs of one letter, which merge with themselves, and words without spaces, which make long chunks. Accents, Chinese and an emoji take several bytes each, and there are spaces and punctuation here and there. Then we make an encoder without a cache, so that each chunk goes through the merges. The pieces list holds those cases, from a, two a's and four a's, up to forty x's in a row. The random generator has a fixed seed, so a failure shows up again on the next run. We build five hundred texts of up to sixty pieces each, encoded as UTF-8. Each is compared with the reference, and the assertion prints the text when they differ, so a failure says what to look at. The test is a simple form of fuzzing, with random inputs, and a second implementation to check against. The last test checks a long chunk against the reference, with five hundred merges again. Its text is the sample's letters, the first three thousand of them, and without spaces or punctuation between them, they make a single chunk.

42:49 First the tests, with the five hundred random texts and the long chunk, each checked against the Python reference. All eleven pass, so on each of them, the heap gives the reference's ids. Then the doubling again, on the long chunk of letters. Each doubling takes about two point two times as long now, close to the two of a linear algorithm, with the heap's log on top. Sixty-four kilobytes take about eight point two milliseconds, where they took about three hundred and seventy. But the speed on web pages went down, to about seventy-two megabytes a second from about eighty, about ten percent slower. I didn't expect the heap to cost us anything on web pages. Most chunks on the web are a few bytes long, and for those, setting up three arrays and a heap costs more than the old loop's pass over a couple of pairs. So I'd like to keep the heap for long chunks, and go back to the old loop for the short ones.

Short chunks and long ones

43:43 The encoder takes one more argument, heap from, the length from which a chunk is merged off the heap, and keeps it. Encode chunk picks the way, and the comment says why: the heap costs more to set up than a pass over a few pairs, and most chunks are a few bytes long. So a chunk shorter than heap from is scanned, and the heap takes the longer ones. The choice is a single comparison of the chunk's size with heap from, so it costs next to nothing. Encode short is our old loop from episode eleven, back as it was. Its comment is the old one too: it applies the merges in the order they were learned, the pair with the lowest rank, until none is left. Ids starts as a copy of the chunk's bytes, made unsigned, as a char can be negative. While there are two tokens or more, we look for the pair to merge next. Best starts at minus one, which means that we've not found one yet. The inner loop looks up each pair of neighbours in the merges' ranks. It keeps the pair with the lowest rank it finds, and that's the merge learned first. If no pair has a merge, the chunk is done, and we break out of the loop. Otherwise, merge replaces the pair with its new token everywhere it appears, left to right, and we look again. Each pass costs the chunk's length, which is cheap when the chunk is a few bytes long. The heap version from before is renamed encode long, and is otherwise untouched. The member keeps heap from, next to the cache's size. In the binding, the constructor takes a fourth argument now, a second size, and its arguments go over three lines, with heap from last, at sixteen unless we say otherwise. Above it, we note where that default comes from: it's the length where the two ways cross, on this Mac, an M4 Pro. Sixteen bytes is longer than most chunks, so most of them still take the scan. In bpe measure, lengths is a new measurement, to find where the two ways cross. Re sub keeps the letters of the first piece and nothing else, up to two megabytes of them. Above it goes the plan: chunks of one length at a time, each on a line of its own, and encoded without a cache. Scanning looks at all the pairs on each pass, and the other way takes them off the heap. The merges come from our tokenizer, the web's own. The lengths go from four bytes up to two hundred and fifty-six, doubling each time. Each length's text is the letters cut into pieces of that length, joined by newlines, so that the pretokenizer splits them apart. We count the chunks, to give the time per chunk. Then we encode the text both ways, and a heap from of two to the thirty keeps the heap out of it, while zero uses the heap for all of them. Each way gets an encoder without a cache, so that each chunk goes through the merges. We time three runs and keep the best, and turn it into microseconds per chunk. It prints the microseconds per chunk for each way, next to the length. And main gets lengths as a choice, and in its dictionary.

46:41 Lengths first, chunks of one length at a time, without a cache. At four bytes, scanning takes about a tenth of a microsecond a chunk, and the heap more than twice that. At sixteen bytes they cross, at a little over a microsecond each, and at two hundred and fifty-six bytes, the heap is about three and a half times as fast. That's where the sixteen in heap from comes from. On web pages, one thread is back at about eighty-two megabytes a second, about one point nine times where we started. And a long chunk still goes off the heap, with sixty-four kilobytes in about eight point three milliseconds, about forty-five times quicker than at the start.

47:20 On the left, the two ways by a chunk's length, with the heap below the scan from sixteen bytes on. On the right, a long chunk at the start of the episode and now, where the line for now barely leaves the bottom of the chart. I like this pair of charts, as the left one shows why we kept the old loop at all.

47:39 The docs get a page of their own on today's work, with each measurement before and after its fix, from these recordings, and the commands that run them, so you can measure your own machine. The docs' index links to it, and so does the site's navigation. And the README lists the new commands: the measurements, one thread's speed, and the threads under the sanitiser.

Wrap-up

48:00 So, this is one thread's speed on web pages, from the first step to the last. Moving the work out of Python nearly doubled it, the heap for all chunks cost about ten percent of that, and scanning the short chunks again won it back, at about eighty-two megabytes a second.

48:17 We measured the tokenizer before touching it, and two of my guesses were off: the cache grew slowly, and most of the memory went on Python strings. The cache has a limit now, sixty-five thousand five hundred and thirty-six chunks, the one used longest ago making room. The whole encode is in C++, from bytes to a NumPy array, about one point nine times as fast on one thread, and it gives back the ten million ids of our held-out pages, one for one. With the GIL let go and a cache for each call, eight threads do about five point three times what one does, after a crash that ThreadSanitizer explained in two lines. And a long chunk merges off a heap, from sixteen bytes up, so sixty-four kilobytes take about eight milliseconds instead of about three hundred and seventy. Your takeaway, I hope, is to check what a tool can see before trusting it. cProfile, the profiler you'd reach for first, couldn't see inside our C++ module, and the process's memory pointed at the cache, while malloc's count showed that the cache was a small part of it.

49:20 Let me know in the comments which of these tools you reach for first when something is slow, as I'd like to hear what I'm missing. And if you'd like to follow along, subscribe to the channel. I hope you find this useful, and thanks for watching.