Our textbook on machine learning and artificial intelligence is out

Robert Godin and I have a new book. The title is Introduction to Machine Learning and Artificial Intelligence with Python. The paperback came out today. It is 741 pages. The Kindle edition is there too.

IWe wrote the book as a first course in a college program or at university, and for a programmer who already writes Python and wants to see how to do machine learning. The emphasis is on using the methods, and on implementing them.

We begin with NumPy and with Pandas. Linear regression comes next, from the normal equations and from gradient descent. We cover the essential material such as logistic regression and decision trees.

We then build a neural network ourselves. A dense layer, the forward pass, backpropagation, mini-batches, a nonlinearity, softmax with cross-entropy, and so forth.

We move to PyTorch. The transformer is introduced.

From there the book uses the model libraries: sentiment analysis, text generation, translation, the BERT family, sentence embeddings, zero-shot classification, and fine-tuning. We cover current language models and reinforcement learning.

The last chapter is about shipping a model. We present a sentiment-analysis service in a container. The chapter also shows how torch.compile can improve the performance.

Each chapter has runnable examples and exercises, and the exercises have solutions.

The paperback is on Amazon. The Kindle edition is here.

Don’t be Andy Bernard

People seek prestige but rarely think about what prestige is.

Reputation is what enables trust between strangers. Pay on time and deliver the goods, and over time people prefer to trade with you. Reputation is valuable. Young people typically have little of it, so they struggle. Nobody trusts them yet. You acquire reputation over time, by being reliable. You can lose it quickly.

What if you want a shortcut? What if you want to quickly acquire a reputation without doing the work?

Prestige is reputation by association. It comes from elite institutions, famous collaborators, or the right signals. It is often cheaper and faster to acquire than a track record of reliability.

Prestige tends to be time-delayed. What has prestige today is where people with high reputation were in the past. But it wanes. Writing a math paper and submitting it to a journal used to be prestigious… because a math journal is/was a prestigious institution. Yet, if you tell me “I wrote this math paper” this weekend… I am not going to think very highly of you on that basis. AI has been eating up prestigious institutions by changing the rules.

We tend to forget, but when I was a teenager, being a journalist was a highly prestigious occupation. Today, the government pays their salaries in Canada because private employers don’t want to hire journalists.

Prestige is gamified and highly noisy.

“There is no relationship between where you went to school and how you did five, 10, 15 years into your career. So, we stopped looking at it.” (Laszlo Bock, Vice President of People Operations at Google)

And if you are still relying on prestige by the time you are 40, you are literally a joke. Andy Bernard in the show The Office keeps reminding people that he went to Cornell University.

People forget that reliance on prestige, beyond a certain point, is flat out a negative signal.

I have spent a great deal of time reviewing academics. Many of them cannot describe themselves beyond prestige. « I published that many papers in that prestigious venue. » Yes, but what good work have you done? Can’t you tell me?

You have the same effect elsewhere. “I work at Google” used to turn heads. I think it no longer does.

Don’t be Andy Bernard. Do good work. Build your reputation.

Command-line JSON filtering at 20 GB/s

If you work with JSON on the command line, you probably use jq. You give it a filter, a small program in its own language, and it runs that filter on each JSON document.

I generated a file of 1 GB with one tweet per line. That format is called NDJSON, and it is a common way to store logs. The file is tweets.ndjson: 230,138 tweets. Shortened, a line looks like this:

{"id":505874924095815681,"lang":"ja","retweet_count":0,"user":{"screen_name":"ayuu0123"}}

The account name is screen_name, inside the user object. This prints it for every tweet:

jq -r '.user.screen_name' tweets.ndjson

The flag -r writes the text without quotes, so the output begins ayuu0123.

I love jq. Its language is expressive and it is everywhere. But extracting that field with jq 1.8.2 takes 11.5 seconds, less than 0.1 GB/s.

We have a library, simdjson, that parses JSON at gigabytes per second. So we built sjq, a command-line tool that reads the jq language and runs on simdjson. The filters you write for jq work with sjq.

On this same file, with just one thread, sjq takes 0.31 seconds: 3.5 GB/s, about 37 times faster than jq. One thread is the default:

sjq -r '.user.screen_name' tweets.ndjson

But wait! The sjq command line can also be multithreaded. Add -P and sjq starts one worker per available processor, up to 32. The main thread only writes the output, so more threads would not help. The server I used has 64 cores, so sjq takes 32 threads. The same filter then takes 0.05 seconds: 20 GB/s, about 210 times faster than jq.

sjq -P -r '.user.screen_name' tweets.ndjson

Pass --threads n when you want a chosen number of threads, and --threads 0 to use every processor.

1 GB of NDJSON

How is that possible? There are three reasons.

  1. Parsing JSON is the bulk of the work, and simdjson is a really fast parser.
  2. When a filter only navigates and selects, sjq parses only what the filter needs. To get .user.screen_name, it does not need to look at the text of the tweet or at its entities.
  3. Logs are made of many small documents, one per line. With -P, sjq cuts the file in pieces and filters them on several workers. The main thread writes the results in order: the output is the same as with one thread.

A file can also be a single, large document. Then sjq uses one core, but it is still 12 to 18 times faster than jq.

One 840 MB document

Is sjq really compatible with jq? We took the test suite of jq itself: sjq passes 728 of its 781 tests. The failures are mostly about modules, numbers wider than 64 bits, values nested more than 10,000 levels deep, and the wording of some error messages. The jq tutorial runs unchanged. You have function definitions, reduce and foreach, string interpolation, the @csv and @base64 formats, assignments such as |=, regular expressions, dates, --arg, --slurp, and so forth. There are differences: for example, regular expressions use the syntax of the C++ standard library, and dates are in UTC.

sjq also does something jq does not. JSON written by jq is either compact, on one line, or pretty-printed with one value per line, which can be long to read. With the --fractured option, sjq uses the FracturedJson layout instead: short arrays and objects stay on one line, and arrays of similar records become aligned tables.

$ sjq --fractured '.statuses[:4] | map({id, lang, rt: .retweet_count, user: .user.screen_name})' twitter.json
[
  {"id": 505874924095815681, "lang": "ja", "rt": 0 , "user": "ayuu0123"   },
  {"id": 505874922023837696, "lang": "ja", "rt": 82, "user": "yuttari1998"},
  {"id": 505874920140591104, "lang": "ja", "rt": 0 , "user": "ttm_protect"},
  {"id": 505874919020699648, "lang": "ja", "rt": 58, "user": "chibu4267"  }
]

You can install sjq on Linux and macOS with one command:

curl -fsSL https://raw.githubusercontent.com/simdjson/sjq/main/install.sh | sh

On Windows, in PowerShell:

irm https://raw.githubusercontent.com/simdjson/sjq/main/install.ps1 | iex

You can also use Homebrew (macOS and Linux) or Scoop (Windows):

brew install simdjson/tap/sjq
scoop bucket add sjq https://github.com/simdjson/sjq
scoop install sjq/sjq

The Linux binaries are static, so they run on any distribution. They run on any 64-bit x64 or ARM processor: simdjson detects your processor when sjq starts and picks the fastest code it supports.

sjq is new. If a jq filter does not work, or gives a different result, please report it.

My benchmark is available.

Cheaters are Innovators

If you seek approval above all else, you are unlikely to innovate outside the rigid bounds of the current system. But if you are willing to cheat, you can innovate.

  • You do not convince traditional media or academic publishers to loosen up. You start your own site or a Substack, you build the audience directly.
  • You do not convince NASA to iterate faster or accept higher risk. You build SpaceX and make the previous way of doing things look slow and expensive.
  • You do not wait for management to green-light AI. You use it.

Changing a system from the inside is inefficient. Make the old system less necessary. Test the idea yourself. Listen to objections, then decide. Work inside a company or university if you must, but do not assume that playing by the existing rules will produce the change you want.

How are you planning to cheat this year?

This post is an update on my 2009 post How things change: Cheaters are Innovators.

Seeing the machine code of your Java program, with a few lines of Java

When I want to know why some Java code is slow, I usually reach for JMH. JMH is great to time a function. But a timing tells you how slow the code is, not why. For that, you need to see the machine code that the JIT compiler produced, and where the processor spends its time in it.

Richard Startin has a new library that does exactly that: instructive. Every 10 ms of CPU time, it records which machine instruction is running. At the end, you get the hottest compiled methods and, for each of them, how many samples landed on each instruction. It might be cooler than JMH for this purpose. Let me show you.

Bitmaps and Roaring

A bitmap is a way to store a set of integers. You use one bit per possible integer: bit i is set if i is in the set. To intersect two sets, you compute the bitwise AND of the two bitmaps, 64 bits at a time. To count the elements, you count the set bits. Processors are very good at these operations, which is why databases and search engines use bitmaps everywhere: the set of all rows where the country is Canada, the set of all documents containing the word apple, and so forth.

A plain bitmap can waste a lot of memory: a set containing only the integer one billion needs a billion bits. Roaring solves this problem. It splits the integers into chunks of 65536 values. Within a chunk, a few values are stored as a sorted array, and many values are stored as a plain bitmap: 1024 64-bit words, called a bitmap container. Roaring is used by Apache Spark, Apache Hive, Apache Druid, Apache Pinot, Apache Iceberg, Apache Flink, Netflix Atlas, Google Procella (YouTube’s SQL engine) and Apache Lucene, among many others. I use the Java library, RoaringBitmap.

andCardinality

A common question is: how many elements do two sets have in common? You could compute the intersection and then count its elements, but that creates a new bitmap that you throw away. RoaringBitmap has a function that only counts: RoaringBitmap.andCardinality. When both chunks are bitmap containers, it ends up in this loop:

public int andCardinality(final BitmapContainer value2) {
  int newCardinality = 0;
  for (int k = 0; k < this.bitmap.length; ++k) {
    newCardinality += Long.bitCount(this.bitmap[k] & value2.bitmap[k]);
  }
  return newCardinality;
}

It is a simple loop: an AND and a population count (Long.bitCount) per word. I would expect it to be fast.

The program

Using instructive is simple:

Sampler.start();
// ... run the workload ...
Sampler.stop();

So what is the workload? I need two bitmaps made of bitmap containers. I consider the integers from 0 to 4,194,303: that is 64 chunks of 65536 integers. For each integer, I flip a coin, and I add the integer to the set if I get heads:

static RoaringBitmap dense(long seed) {
    Random r = new Random(seed);
    RoaringBitmap b = new RoaringBitmap();
    for (int i = 0; i < 64 * 65536; i++) {
        if (r.nextBoolean()) {
            b.add(i);
        }
    }
    return b;
}

Each chunk then contains about 32,768 integers, half of all possible values, so Roaring stores each chunk as a bitmap container. Counting the common elements of two such sets means going through 64 × 1024 = 65,536 words.

Java does not compile your code to machine code right away. It first interprets it, and it compiles a method with its optimizing compiler (C2) only after the method has been called many times. If I sampled from the start, I would mostly see the interpreter. So I first call andCardinality 10,000 times, to get the optimized machine code. Then I call it 100,000 times while the sampler runs, and I print the hottest method:

RoaringBitmap a = dense(1), b = dense(2);
long sink = 0;
for (int i = 0; i < 10_000; i++) {
    sink += RoaringBitmap.andCardinality(a, b); // warm up
}
Sampler.start();
for (int i = 0; i < 100_000; i++) {
    sink += RoaringBitmap.andCardinality(a, b);
}
Sampler.stop();
InstructionProfileFormatter formatter = new InstructionProfileFormatter();
Sampler.forEachHottestMethod(1, profile -> formatter.format(profile.snapshot(), System.out));

That is all. It is an ordinary Java program: you add the instructive jar with -javaagent and you run it.

What I found on an Apple M4

I used an Apple M4 Max with JDK 25, the current long-term-support release. Each call takes 115 µs. That is 1.75 ns per 64-bit word, or about 8 cycles per word for an AND and a population count. That is slow.

Here is part of what instructive printed (it lists only the instructions that got samples). The disassembler does not yet decode ARM vector instructions, so they appear as .word. I added what they are in comments.

org.roaringbitmap.RoaringBitmap.andCardinality(...)
  tier 4 (C2), compile id 415, 1528 bytes at 0x00000001158b6180, 1042 samples

  pc                  bytes        instruction                count
  ...
  0x00000001158b6348  50 1c 08 4e  .word 0x4e081c50              48   // mov v16.d[0], x2
  0x00000001158b6354  0b 3e 08 4e  .word 0x4e083e0b              13   // mov x11, v16.d[0]
  0x00000001158b6358  7b 27 40 f9  ldr x27, [x27, #0x48]          6
  0x00000001158b635c  d6 26 40 f9  ldr x22, [x22, #0x48]         19
  0x00000001158b6360  d6 02 1b 8a  and x22, x22, x27              1
  0x00000001158b6364  d0 1e 08 4e  .word 0x4e081ed0              48   // mov v16.d[0], x22
  0x00000001158b6368  10 5a 20 0e  .word 0x0e205a10               8   // cnt v16.8b, v16.8b
  0x00000001158b636c  10 ba 31 0e  .word 0x0e31ba10               9   // addv b16, v16.8b
  0x00000001158b6370  10 3e 08 4e  .word 0x4e083e10             182   // mov x16, v16.d[0]

ARM processors have no instruction to count the bits of a regular 64-bit register (at least not before the recent CSSC extension). So Java does it in four steps: copy the word to a vector register, count the bits of each byte (cnt), add the byte counts (addv), and copy the result back. About 80% of the samples land on the two copies.

The copies themselves are cheap. The problem is subtle. Every population count uses the same register, v16, and the first copy is an insert: it writes the low half of the 128-bit register and keeps the high half. So it must wait for the previous value of v16, that is, for the previous population count. The processor cannot work on several words at once: each word waits for the previous one. You can verify it in C with inline assembly: with an instruction that writes the whole register (fmov), the same sequence is six times faster.

With JDK 25 on the Apple M4, each population count goes through vector register v16, and the insert makes each word wait for the previous one.

With JDK 27, each call takes 15.6 µs, seven times faster. Here is an excerpt of its profile:

  0x00000001482e9058  f4 22 c0 3d  ldr q20, [x23, #0x80]         10
  0x00000001482e9064  91 22 c0 3d  ldr q17, [x20, #0x80]          9
  0x00000001482e9080  70 86 b0 0e  .word 0x0eb08670              17   // add v16.2s, v19.2s, v16.2s
  ...
  0x00000001482e909c  31 5a 20 4e  .word 0x4e205a31              10   // cnt v17.16b, v17.16b

JDK 27 vectorizes the loop. It loads two words at a time into vector registers (ldr q), computes the AND and counts the bits there, and never copies the words back and forth. So upgrading Java makes this function seven times faster on ARM. But only because the loop is vectorized. The code that JDK 27 generates for Long.bitCount itself has not changed, and when the compiler cannot vectorize the loop, it is just as slow as with JDK 25.

With JDK 27, two words are loaded into a 128-bit vector register, their bits counted with cnt, and the byte counts added in pairs until there is one count per word.

What I found on an Intel Xeon

I ran the same program on an Intel Xeon Gold 6548N (Emerald Rapids), pinned to one core. This processor supports AVX-512, including an instruction that counts the bits of eight 64-bit words at once (vpopcntq). Does Java use it?

It does, with both JDK 25 and JDK 27 (Temurin 25.0.5 and 27.0.1.1). Each call takes 10 µs, or 0.15 ns per word: faster than the Apple M4 with either version of Java. On x86, instructive decodes the vector instructions too. Here is an excerpt of the profile with JDK 25:

  pc                  bytes                             instruction                                       count
  ...
  0x00007fdda7ee9d3d  62 b1 7e 48 6f 8c da d0 01 00 00  vmovdqu32 zmm1, zmmword ptr [rdx + 8*r11 + 0x1d0]      5
  0x00007fdda7ee9d48  62 b1 75 48 db 8c d9 d0 01 00 00  vpandd zmm1, zmm1, zmmword ptr [rcx + 8*r11 + 0x1d0]   3
  0x00007fdda7ee9d53  62 f2 fd 48 55 c0                 vpopcntq zmm0, zmm0                                   2
  0x00007fdda7ee9d5f  62 f2 7e 48 35 c0                 vpmovqd ymm0, zmm0                                    1
  0x00007fdda7ee9d65  c5 fd fe c2                       vpaddd ymm0, ymm0, ymm2                               1
  ...
  0x00007fdda7ee9dd3  41 8d 5b 40                       lea ebx, [r11 + 0x40]                                 6

The loop loads eight words at a time into 512-bit registers (vmovdqu32), computes the AND (vpandd), counts the bits of each of the eight words in one instruction (vpopcntq), narrows the eight counts to 32 bits (vpmovqd), and adds them to a running total (vpaddd). It does this eight times per iteration, so each iteration handles 64 words (lea ebx, [r11 + 0x40]).

With AVX-512, one instruction counts the bits of eight words at once. Each iteration of the loop handles 64 words.

Why not JMH?

JMH can show you the same thing with its perfasm profiler. But you need to write your benchmark as a JMH project, with its annotations and its build. You need the hsdis disassembler, which you must build or find for your JDK, and you need a system profiler: perf on Linux, or DTrace with root privileges on macOS (dtraceasm).

With instructive, I added three lines to an ordinary Java program. No root, no external tool, no separate project. And because it runs inside the program, you could use it in your actual application, on your actual data, rather than in a benchmark. The profile is a Java object: you can sort it, filter it, or analyze it however you like. instructive even comes with rules that analyze the machine code and report problems such as long dependency chains and loops that were not unrolled.

My benchmark code is available.

Decoding base64 email attachments: a speed ranking of programming languages

Email attachments are base64. So are cryptographic PEM certificates. In both cases the text is broken into lines, 76 characters for email and 64 for PEM.

Skipping line endings sounds trivial. Yet many fast decoders only work on uninterrupted base64. As soon as they meet a line break, they fall back to a slow path.

How fast can we decode MIME base64 in popular programming languages? I wrote a small benchmark. I generate one megabyte of random bytes, encode it as base64 with 76-character lines ending in CRLF (1.37 MB of text) and decode it again with the standard or most popular function of each language. I check that each decoder returns the right bytes.

I use an Intel Xeon Gold 6548N (Emerald Rapids) with Linux, pinned to one core. I report speeds in gigabytes of input per second (GB/s). Each number is the median of three runs, and each run keeps the best of ten timed batches. I use the latest version of each tool.

rank system function GB/s
1 C++ (GCC 16) with simdutf 9.4 simdutf::base64_to_binary 18.4
2 PHP 8.7-dev with my pull request base64_decode 17.1
3 Python 3.15 with fastpybase64 fastpybase64.b64decode 16.4
4 Bun 1.4.4 Buffer.from(s, 'base64') 14.2
5 Node.js 26.13 Buffer.from(s, 'base64') 13.3
6 Deno 2.9.8 Uint8Array.fromBase64(s) 8.4
7 .NET 11 Base64.DecodeFromUtf8 4.9
8 Go 1.27.4 base64.StdEncoding.Decode 1.6
9 Java 27 Base64.getMimeDecoder().decode 1.2
10 Zig 0.17.1 std.base64 decoder ignoring \r\n 0.85
11 PHP 8.5.12 base64_decode 0.61

Bar chart of MIME base64 decoding speed on an Intel Xeon Gold 6548N. The six systems that use simdutf decode at 8.4 to 18.4 GB/s; the others decode at 0.61 to 4.9 GB/s.

There is a factor of thirty between the top and the bottom of the table.

The top six systems all rely on the simdutf library. The simdutf library removes the line endings inside its vector loop. A clean block of 64 characters is decoded directly. A block that contains line endings is compacted first, and decoding proceeds from a small buffer. The line endings never send the decoder to a slow path. See Lemire (2027) for the details.

PHP is the most dramatic case. With the current release, PHP is last at 0.61 GB/s, even though it decodes base64 without line endings at more than 20 GB/s on this machine. My pull request ports the simdutf decoders to PHP. It makes MIME decoding 28 times faster, and PHP moves to second place.

My source code is available.

References

Lemire, D. (2027). Fast forgiving base64 decoding with SIMD instructions. ACM Transactions on Architecture and Code Optimization, 24(1). (arXiv)

Muła, W., & Lemire, D. (2020). Base64 encoding and decoding at almost the speed of a memory copy. Software: Practice and Experience, 50(2), 89–97. (arXiv)

Java4Shell: when base64 decoding leads to remote code execution?

Let us start with an example that triggers the issue.

byte[] src = ("A".repeat(128) + "=").getBytes(StandardCharsets.US_ASCII);
Base64.getDecoder().decode(src);

One hundred and twenty-eight letters A and one =. The string is not valid base64, and a correct decoder rejects it. OpenJDK writes past the end of the array anyway. The bug is CVE-2026-114938. It has been in the JDK since 17.0.6. It was introduced in OpenJDK back in June 2021. The bad write is in hand-written assembly.

There are claims that it leads to a major security vulnerability. I have not checked. But I care about the issue because I am indirectly involved.

Base64 turns three bytes into four ASCII characters. Email attachments are base64, and a string often ends with =. Java sizes the output before it checks the input. One trailing = counts as one byte of padding, so the allocated length is

3 × ((129 + 3) / 4) − 1 = 98.

So decode allocates 98 bytes, then calls the decoding routine.

On an x86-64 machine with AVX-512 VBMI, the routine takes the first 128 characters as two blocks and writes 96 bytes. That loop follows the algorithm from Muła & Lemire (2020). The character A is the value 0, so each block becomes 48 zero bytes. The store is masked to 48 bytes. Both stay inside the array.

One character is left, the =. The tail asks how many output bytes a remainder of that length should produce. In integer arithmetic,

(1 / 4) × 3 = 0.

The last character is =, so it subtracts one. The length is now −1.

The tail writes with an AVX-512 masked store. A masked store writes a byte only when the matching bit in a mask is set. See my article Modern vector programming with masked loads and stores. The mask comes from bzhi, which keeps the low n bits of a word of ones. The count it reads is the low 8 bits of n. The low 8 bits of −1 are 255. A count of 255 is past 64, and bzhi then clears nothing: every bit stays set, and the store writes the whole 64-byte register.

The store starts where the main loop stopped, at offset 96. The array ends at offset 97. Two bytes land in the array. The other 62, offsets 98 through 159, land past the end.

A 98-byte array, and a 64-byte store that starts at offset 96. Two bytes land inside the array and 62 fall past the end.

The function then returns. Java sees a = with no data character in the current group and throws IllegalArgumentException, with the message “Input byte array has wrong 4-byte ending unit”. The write has already happened.

So that’s the bug. As you can see, it is not the fault of our fancy algorithm. Thankfully for me.

Java is somewhat behind. The fast decoder stops at a space or a line break. Email wraps every 76 characters, and crypto (PEM) every 64, so the fast path in Java ends at the first line since it cannot handle spaces or line breaks.

The algorithm in Lemire (2027) removes the ignorable characters inside the vector loop. A clean block of 64 characters is decoded directly. A block that contains whitespace is compacted, and the alphabet characters are decoded from a small buffer. Since the middle of 2025 that decoder has shipped in Safari and in the Chromium browsers (Chrome, Edge, Brave), and in Node.js 25, Deno and Bun.

I have a pull request that ports the same decoders to PHP. Decoding a 64 KiB MIME input is 30 times faster on an Intel Xeon Gold 6548N, and 39 times faster on an AMD EPYC 9R45.

References

Muła, W., & Lemire, D. (2020). Base64 encoding and decoding at almost the speed of a memory copy. Software: Practice and Experience, 50(2), 89–97. (arXiv)

Lemire, D. (2027). Fast forgiving base64 decoding with SIMD instructions. ACM Transactions on Architecture and Code Optimization, 24(1). (arXiv)

Cognitive radius

The most interesting change AI brings to software work is not faster coding. It is the expansion of context or range… what I call radius.

For decades the job was defined by the limits of what one person could hold in their head. You tended to specialize. You got good at one or two systems, one or two types of problems because keeping more than that coherent was expensive. Context switching hurt. Onboarding to a new project took days or weeks.

Simply issuing a pull request to a new open-source repository took days. You had to learn the conventions. Learn the code base. Find out how to test it. Find out how to run benchmarks.

With a good model and the right tools, you can load a large amount of relevant information into the session: the structure of several repositories, the conventions of different teams, recent issues, design decisions, performance constraints, the history of related libraries. You can ask questions across them, generate changes that stay consistent with local style, and keep more projects alive at once without the usual collapse in quality.

The unit of work stops being “the project I am currently deep in” and becomes something closer to “the set of projects I can keep coherent right now.”

This is not the same as having an assistant write code for you. It is more. The gain comes from the ability to hold and operate on a larger working set. You still decide what matters. You still check the results. What changes is how much of the surrounding system you can bring into focus at the same time.

The practical consequences are already visible for people who treat this as a skill rather than a novelty:

  • You can enter a codebase you have not touched in months and become useful again in an hour instead of a day, because the model can reconstruct the local idioms and the reasons behind them from the history and tests.
  • You can maintain consistency across languages or frameworks. The cost of switching is lower when the model carries the surface details.

None of this is automatic. The model does not magically expand your capacity. You have to learn how to feed it the right context, how to structure the questions so the answers stay grounded, and how to verify the parts that matter. The people who get the most out of it treat the model as a high-bandwidth interface to a larger set of information.

Most discussion of AI in programming still focuses on the speed of generating individual functions or on the fear that juniors will not learn. Those are real topics, but they miss the larger shift. The constraint that shaped the profession for a long time, the limited amount of context a single developer could keep active, has loosened. What you can usefully own has grown. Learning to operate at that new scale is the part that is still under-discussed and under-practiced.

The cognitive radius of an engineer is the distance (in projects, technologies, or time) over which they can still produce consistent, well-informed work. AI has increased that radius.

Reading JSON at 277 GB/s in Python

Many systems log their data as JSON, one record per line (NDJSON). GitHub, for example, publishes every public event on its site that way through GH Archive: about a gigabyte per hour. Suppose you want to know which repositories received the most stars over eight hours. That is 7.6 GB of JSON, 2.2 million events.

In Python, the obvious code reads each line with the json module:

for line in open("events.ndjson", "rb"):
    event = json.loads(line)
    if event["type"] == "WatchEvent":
        stars[event["repo"]["name"]] += 1

It runs at 0.28 GB/s: 27 seconds for this file. The orjson package is twice as fast. The msgspec package, which decodes only the fields you declare, is eight times as fast.

A server has many cores, but a Python process with the GIL runs Python code on one core at a time. The usual answer is a pool of processes: cut the file in pieces, give a piece to each process, and add up their counts. Each process returns a small table, so little has to come back.

Python 3.14 has a free-threaded build (python3.14t) without the GIL: threads run Python code at the same time. The fastsimdjson library is threaded. You give it the data and a function. It parses the records on many threads, and calls your function on the thread that parsed the record. You name the fields you want. It reads only what leads to them, and your function receives those values, not the whole record.

import collections
import fastsimdjson
def starred(event):
    kind, repo = event
    if kind == "WatchEvent":
        return repo
names = fastsimdjson.map_many(
    starred, data, threads=192,
    fields=["/type", "/repo/name"], drop_none=True)
stars = collections.Counter(names)

The variable data is the file, mapped in memory. The two paths are the event type and the repository name. The drop_none parameter leaves out the records that are not stars.

I ran this on an AWS instance (c8a.metal-48xl) with two AMD EPYC 9R45 processors, 192 cores, using Python 3.14.10, orjson 3.13 and msgspec 0.22. The file is mapped before the clock starts. On one core, fastsimdjson reads 8 GB/s, three and a half times as fast as msgspec.

Counting stars on one core

With 192 threads, fastsimdjson counts the stars in the 7.6 GB in 55 milliseconds: 138 GB/s. The best pool of msgspec processes reaches 116 GB/s, at 96 processes. More processes make it slower.

Counting stars on all cores

fastsimdjson is ahead at every worker count. The lead shrinks from three and a half times on one core to about 20%.

By number of workers

Counting is the best case for processes, because little comes back. Often you want the values themselves. I took six files of about a gigabyte from an existing benchmark (Pison), and pulled a field or two from every record. On the twitter file, fastsimdjson reaches 277 GB/s. Four of the six files pass 100 GB/s. The other two are slower: one stays near 20 GB/s, still about four times as fast as msgspec, and one is a tie.

Six queries

My source code is available.

Telling your number parser what to expect

Our fast_float library parses numbers such as -731.51 into binary floating-point values. It is part of GCC’s C++ standard library, among others. It is fast: often a few nanoseconds per number.

Parsing a number means making decisions. Is there a sign? How many digits are there? Where is the decimal point? Is the processor rounding in the default mode? Each decision is a branch in the code. Modern processors do not wait to know the outcome of a branch: they guess, and they keep working. When they guess right, the branch is nearly free. When they guess wrong, they throw away the work done since the branch, and that costs 15 to 20 cycles.

When all your numbers look alike, the processor guesses right. When they do not, it guesses wrong often. Consider a column of gains and losses: the sign is random. The processor cannot guess it, and it pays for its mistakes on about half of the numbers.

You often know things about your data that the parser cannot know. So we are adding performance hints to fast_float. You pass them as a template argument:

using fast_float::performance_hints;
double value;
auto answer = fast_float::from_chars<performance_hints::unpredictable_sign>(
    input.data(), input.data() + input.size(), value);

There are three hints, and you may combine them with |:

  • unpredictable_sign: the signs come in random order. The parser then handles the sign without a branch.
  • short_numbers: each number is given alone (the range holds just the number) and most numbers have at most 8 characters, such as 42.5 or -3.75, in varying shapes. The parser then reads all 8 characters at once with a few bitwise operations, without a branch on the number of digits or the position of the decimal point.
  • assume_round_to_nearest: your program never changes the rounding mode, so the parser does not check it.

The hints never change the results, with one exception. If you promise assume_round_to_nearest and some code in your program changes the rounding mode, some results will be wrong.

The hints work with fast_float::from_chars, fast_float::from_chars_advanced and fast_float::integer_times_pow10. Without hints, nothing changes.

How much do they help? I generated four kinds of data, 100,000 numbers each:

  • price changes, two decimals and random signs, such as -731.51 or 42.07;
  • account balances, two decimals and random signs, but longer, such as -731271.51;
  • sensor readings, all positive, but in varying shapes, such as 7, 1042, 42.5 and 0.375;
  • regular prices, always the same shape, such as 12.34.

I parse them on an Intel Xeon Gold 6338 (Ice Lake) with GCC 15, and on an Apple M4 Max with Apple clang 17. I report millions of numbers parsed per second: higher is better.

Millions of numbers per second, Intel Ice Lake, GCC 15

Millions of numbers per second, Apple M4 Max, Apple clang 17

Each kind of data has its own best combination.

Price changes have random signs and short numbers. On the Intel processor, adding unpredictable_sign and assume_round_to_nearest goes from 73 to 105 million numbers per second. All three hints do as well (104 million), and they are best on the Apple processor, going from 153 to 345 million numbers per second: more than twice as fast. Without hints, the Intel processor mispredicts a branch on 60% of the numbers. With all three hints, the mispredictions disappear.

Account balances also have random signs, but the numbers are too long for short_numbers. Here unpredictable_sign with assume_round_to_nearest is the right choice: from 61 to 82 million numbers per second on the Intel processor, and from 132 to 199 million on the Apple processor. Adding short_numbers makes things worse on the Intel processor (70 million): the hint does not apply to these numbers, yet we pay for it.

Sensor readings have no sign, but their shapes vary. Here short_numbers is the key: from 67 to 92 million numbers per second on the Intel processor, and from 123 to 250 million on the Apple processor. The hint unpredictable_sign is harmful: there is no sign to predict, and the branch-free code is more work. On the Intel processor, it goes down to 57 million.

Regular prices are the easy case: all positive, always the same shape. The processor guesses everything right. On the Intel processor, the best choice is no hint at all (152 million numbers per second), and short_numbers makes things much slower (104 million). The Apple processor is different: short_numbers still helps, from 251 to 355 million numbers per second.

With Clang 21 on the Intel processor, the results are similar: the same hints win on the same data.

So the hints are not free. They trade branches, which are cheap when the processor guesses right, for more instructions. They pay off when the processor would guess wrong.

The hints are currently in a pull request.

My source code is available.