{"course":{"slug":"maths-you-need","title":"The Maths You Actually Need","url":"https://addaly.com/learn/maths-you-need","level":"intermediate","track":"deep"},"lesson":{"slug":"integers-overflow-and-the-size-of-things","title":"Integers, overflow, and the token id that would not fit","url":"https://addaly.com/learn/maths-you-need/integers-overflow-and-the-size-of-things","position":70,"of":76,"minutes":8,"answer":"Fixed-width integers are exact inside their range and wrap silently outside it, so counts, offsets and products of sizes belong in int64, pixels and ids belong in the smallest type that fits.","keyIdea":"Fixed-width integers are exact inside their range and wrap silently outside it, so counts, offsets and products of sizes belong in int64, pixels and ids belong in the smallest type that fits, and a result of exactly 2,147,483,647, 255 or 16,777,216 is a limit rather than a value."},"body":{"format":"markdown","text":"## Integers are exact, until they are not\n\nAn integer type stores a whole number exactly, with no rounding, within a fixed range set by its width:\n\n```\nuint8    0 to 255\nint8     −128 to 127\nint16    −32,768 to 32,767\nint32    −2,147,483,647 to 2,147,483,647   (about ±2.1 billion)\nint64    about ±9.2 × 10^18\n```\n\nInside the range, every operation is exact, which is why counters, indices, ids and pixel values are integers. Outside it, the behaviour is not an error. In NumPy and most compiled code, an int32 that passes 2,147,483,647 **wraps** to −2,147,483,648, and the program continues with a negative number where a large positive one should be. Python's own `int` grows without limit, so this never happens in plain Python; it happens the moment data enters a NumPy array, a PyTorch tensor, a database column or a file format, all of which have fixed widths.\n\n## Where 2.1 billion arrives\n\nTwo billion sounds large until you count tokens. A training corpus of a trillion tokens has positions up to `10^12`, and an int32 offset into it wraps at the second billion. A dataset index built with `np.arange(len(corpus))` on a platform whose default integer is 32 bits, which Windows NumPy was until recently, produced negative positions past 2.1 billion tokens, and negative indices in NumPy are legal: they count from the end. The bug did not crash; it read the wrong tokens.\n\nThe same limit appears in file sizes (a 32-bit length field caps at 2 GB, the reason older formats could not store a file larger than that), in a `sum` over an int32 column of byte counts, and in any `count × size` multiplication where both are int32: `50,000 × 50,000 = 2.5 × 10^9` overflows before it is assigned to the int64 you were about to store it in.\n\n```python\nimport numpy as np\na = np.int32(50_000)\nprint(a * a)         # -1794967296, with at most a warning\n```\n\nThe fix is a word: `int64` for anything that counts tokens, bytes, rows or products of sizes. Vocabulary ids are safe in int32, since no vocabulary approaches two billion; positions, offsets and totals are not.\n\n## Small integers are where the memory goes\n\nAt the other end, small integer types are how large data fits. An image is stored as uint8: 256 levels per channel, one byte per value, and a 224 × 224 colour image is 150 KB rather than the 600 KB of float32. A million such images are 150 GB, which is the figure module 7 used. Token ids fit in uint16 when the vocabulary is under 65,536 and in int32 otherwise, and a billion tokens are 2 or 4 GB accordingly. Labels for a thousand classes fit in uint16.\n\nThe habit that goes with this: convert to float only at the point of computation, not at the point of loading. A pipeline that decodes images to float32 on disk has quadrupled its storage for nothing.\n\n## uint8 arithmetic is a trap of its own\n\nSubtracting two uint8 pixels, `100 − 150`, does not give −50. It wraps to 206. Adding two, `200 + 100`, gives 44. Image code that computes a difference between frames in uint8 produces bright artefacts where it should show darkness, and the code looks correct. Cast to int16 or float32 before any subtraction, and back to uint8, with clipping, only for storage.\n\n## Products of small integers\n\nQuantised inference, the next lesson, multiplies int8 weights by int8 activations. Each product can be as large as `127 × 127 = 16,129`, which does not fit in int8 or int16 once you add four thousand of them together. The accumulation is therefore done in int32, and the result rescaled. If you ever write such a loop yourself, the accumulator's width is the first thing to get right; the hardware's integer matrix units get it right for you.\n\n## Integers inside floats\n\nThe previous lessons showed that float32 represents integers exactly only up to `2^24 = 16.8` million, and float64 up to `2^53 = 9 × 10^15`. A record id above 16.8 million stored in a float32 column is rounded to an even number, and two distinct customers become one. This happens when a CSV with a missing value in an id column is loaded, because a column with a NaN cannot be integer, so the loader silently promotes it to float. Check `dtype` on id columns after loading, and store ids as strings if the values can be large.\n\n## Booleans and bits\n\nA boolean is one byte in NumPy, not one bit; a mask over a billion tokens is a gigabyte. Packed bit arrays, `np.packbits`, are eight times smaller and are what Bloom filters and large masks use. And a `sum` over a boolean array counts the Trues, which is the fastest way to count anything in NumPy, provided the accumulator is not a uint8: `np.sum(mask, dtype=np.int64)` if there are more than 255 of them.\n\n## The rule\n\nCount in int64. Store in the smallest type the values fit, and know what that type's range is. Never subtract in uint8. And when a number is exactly `2,147,483,647`, `−2,147,483,648`, `65,535`, `255` or `16,777,216`, you are looking at a limit, not a measurement."},"check":{"question":"A frame-differencing script subtracts consecutive video frames stored as uint8 arrays and shows bright speckles where the scene is static. What is happening?","options":[{"text":"Sensor noise is being amplified by the subtraction.","correct":false,"tempting":"Noise would produce small values near zero, not bright ones; the bright artefacts are the signature of wrapping, which turns a small negative into a large positive."},{"text":"uint8 cannot store the difference, so the array was silently promoted to float and rescaled.","correct":false,"tempting":"NumPy does not promote uint8 minus uint8; it stays uint8 and wraps, which is exactly what produces the artefacts."},{"text":"A slightly darker pixel gives a negative difference that wraps to near 255.","correct":true},{"text":"The frames are misaligned by one pixel, producing edge artefacts across the image.","correct":false,"tempting":"Misalignment would show structured edges, not speckles across static regions; the pattern here follows the arithmetic, not the geometry."}]},"prev":{"slug":"cancellation-and-summation-order","title":"Catastrophic cancellation, and why a sum depends on its order","url":"https://addaly.com/learn/maths-you-need/cancellation-and-summation-order"},"next":{"slug":"quantisation-as-rounding","title":"Quantisation is rounding with a scale: int8, int4 and the outlier problem","url":"https://addaly.com/learn/maths-you-need/quantisation-as-rounding"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Integers, overflow, and the token id that would not fit', in The Maths You Actually Need. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/maths-you-need/integers-overflow-and-the-size-of-things (Accessed: 29 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Integers, overflow, and the token id that would not fit","courseTitle":"The Maths You Actually Need","module":{"index":8,"slug":"numbers-in-a-machine","title":"Numbers inside a machine"},"answer":null,"keyIdea":"Fixed-width integers are exact inside their range and wrap silently outside it, so counts, offsets and products of sizes belong in int64, pixels and ids belong in the smallest type that fits, and a result of exactly 2,147,483,647, 255 or 16,777,216 is a limit rather than a value.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"integers-are-exact-until-they-are-not","runs":[{"text":"Integers are exact, until they are not"}]},{"t":"p","runs":[{"text":"An integer type stores a whole number exactly, with no rounding, within a fixed range set by its width:"}]},{"t":"code","lang":"","label":"Text","text":"uint8    0 to 255\nint8     −128 to 127\nint16    −32,768 to 32,767\nint32    −2,147,483,647 to 2,147,483,647   (about ±2.1 billion)\nint64    about ±9.2 × 10^18"},{"t":"p","runs":[{"text":"Inside the range, every operation is exact, which is why counters, indices, ids and pixel values are integers. Outside it, the behaviour is not an error. In NumPy and most compiled code, an int32 that passes 2,147,483,647 "},{"text":"wraps","b":true},{"text":" to −2,147,483,648, and the program continues with a negative number where a large positive one should be. Python’s own "},{"text":"int","code":true},{"text":" grows without limit, so this never happens in plain Python; it happens the moment data enters a NumPy array, a PyTorch tensor, a database column or a file format, all of which have fixed widths."}]},{"t":"h2","id":"where-2-1-billion-arrives","runs":[{"text":"Where 2.1 billion arrives"}]},{"t":"p","runs":[{"text":"Two billion sounds large until you count tokens. A training corpus of a trillion tokens has positions up to "},{"text":"10^12","code":true},{"text":", and an int32 offset into it wraps at the second billion. A dataset index built with "},{"text":"np.arange(len(corpus))","code":true},{"text":" on a platform whose default integer is 32 bits, which Windows NumPy was until recently, produced negative positions past 2.1 billion tokens, and negative indices in NumPy are legal: they count from the end. The bug did not crash; it read the wrong tokens."}]},{"t":"p","runs":[{"text":"The same limit appears in file sizes (a 32-bit length field caps at 2 GB, the reason older formats could not store a file larger than that), in a "},{"text":"sum","code":true},{"text":" over an int32 column of byte counts, and in any "},{"text":"count × size","code":true},{"text":" multiplication where both are int32: "},{"text":"50,000 × 50,000 = 2.5 × 10^9","code":true},{"text":" overflows before it is assigned to the int64 you were about to store it in."}]},{"t":"code","lang":"python","label":"Python","text":"import numpy as np\na = np.int32(50_000)\nprint(a * a)         # -1794967296, with at most a warning"},{"t":"p","runs":[{"text":"The fix is a word: "},{"text":"int64","code":true},{"text":" for anything that counts tokens, bytes, rows or products of sizes. Vocabulary ids are safe in int32, since no vocabulary approaches two billion; positions, offsets and totals are not."}]},{"t":"h2","id":"small-integers-are-where-the-memory-goes","runs":[{"text":"Small integers are where the memory goes"}]},{"t":"p","runs":[{"text":"At the other end, small integer types are how large data fits. An image is stored as uint8: 256 levels per channel, one byte per value, and a 224 × 224 colour image is 150 KB rather than the 600 KB of float32. A million such images are 150 GB, which is the figure module 7 used. Token ids fit in uint16 when the vocabulary is under 65,536 and in int32 otherwise, and a billion tokens are 2 or 4 GB accordingly. Labels for a thousand classes fit in uint16."}]},{"t":"p","runs":[{"text":"The habit that goes with this: convert to float only at the point of computation, not at the point of loading. A pipeline that decodes images to float32 on disk has quadrupled its storage for nothing."}]},{"t":"h2","id":"uint8-arithmetic-is-a-trap-of-its-own","runs":[{"text":"uint8 arithmetic is a trap of its own"}]},{"t":"p","runs":[{"text":"Subtracting two uint8 pixels, "},{"text":"100 − 150","code":true},{"text":", does not give −50. It wraps to 206. Adding two, "},{"text":"200 + 100","code":true},{"text":", gives 44. Image code that computes a difference between frames in uint8 produces bright artefacts where it should show darkness, and the code looks correct. Cast to int16 or float32 before any subtraction, and back to uint8, with clipping, only for storage."}]},{"t":"h2","id":"products-of-small-integers","runs":[{"text":"Products of small integers"}]},{"t":"p","runs":[{"text":"Quantised inference, the next lesson, multiplies int8 weights by int8 activations. Each product can be as large as "},{"text":"127 × 127 = 16,129","code":true},{"text":", which does not fit in int8 or int16 once you add four thousand of them together. The accumulation is therefore done in int32, and the result rescaled. If you ever write such a loop yourself, the accumulator’s width is the first thing to get right; the hardware’s integer matrix units get it right for you."}]},{"t":"h2","id":"integers-inside-floats","runs":[{"text":"Integers inside floats"}]},{"t":"p","runs":[{"text":"The previous lessons showed that float32 represents integers exactly only up to "},{"text":"2^24 = 16.8","code":true},{"text":" million, and float64 up to "},{"text":"2^53 = 9 × 10^15","code":true},{"text":". A record id above 16.8 million stored in a float32 column is rounded to an even number, and two distinct customers become one. This happens when a CSV with a missing value in an id column is loaded, because a column with a NaN cannot be integer, so the loader silently promotes it to float. Check "},{"text":"dtype","code":true},{"text":" on id columns after loading, and store ids as strings if the values can be large."}]},{"t":"h2","id":"booleans-and-bits","runs":[{"text":"Booleans and bits"}]},{"t":"p","runs":[{"text":"A boolean is one byte in NumPy, not one bit; a mask over a billion tokens is a gigabyte. Packed bit arrays, "},{"text":"np.packbits","code":true},{"text":", are eight times smaller and are what Bloom filters and large masks use. And a "},{"text":"sum","code":true},{"text":" over a boolean array counts the Trues, which is the fastest way to count anything in NumPy, provided the accumulator is not a uint8: "},{"text":"np.sum(mask, dtype=np.int64)","code":true},{"text":" if there are more than 255 of them."}]},{"t":"h2","id":"the-rule","runs":[{"text":"The rule"}]},{"t":"p","runs":[{"text":"Count in int64. Store in the smallest type the values fit, and know what that type’s range is. Never subtract in uint8. And when a number is exactly "},{"text":"2,147,483,647","code":true},{"text":", "},{"text":"−2,147,483,648","code":true},{"text":", "},{"text":"65,535","code":true},{"text":", "},{"text":"255","code":true},{"text":" or "},{"text":"16,777,216","code":true},{"text":", you are looking at a limit, not a measurement."}]}],"check":{"question":[{"text":"A frame-differencing script subtracts consecutive video frames stored as uint8 arrays and shows bright speckles where the scene is static. What is happening?"}],"options":[{"text":[{"text":"Sensor noise is being amplified by the subtraction."}],"correct":false,"tempting":[{"text":"Noise would produce small values near zero, not bright ones; the bright artefacts are the signature of wrapping, which turns a small negative into a large positive."}]},{"text":[{"text":"uint8 cannot store the difference, so the array was silently promoted to float and rescaled."}],"correct":false,"tempting":[{"text":"NumPy does not promote uint8 minus uint8; it stays uint8 and wraps, which is exactly what produces the artefacts."}]},{"text":[{"text":"A slightly darker pixel gives a negative difference that wraps to near 255."}],"correct":true,"tempting":null},{"text":[{"text":"The frames are misaligned by one pixel, producing edge artefacts across the image."}],"correct":false,"tempting":[{"text":"Misalignment would show structured edges, not speckles across static regions; the pattern here follows the arithmetic, not the geometry."}]}],"order":[0,3,2,1],"why":null},"prev":{"slug":"cancellation-and-summation-order","title":"Catastrophic cancellation, and why a sum depends on its order","minutes":9},"next":{"slug":"quantisation-as-rounding","title":"Quantisation is rounding with a scale: int8, int4 and the outlier problem","minutes":10}}}