MoreRSS

site iconDaniel LemireModify

Computer science professor at the University of Quebec (TELUQ), open-source hacker, and long-time blogger.
Please copy the RSS to your reader, or quickly subscribe to:

Inoreader Feedly Follow Feedbin Local Reader

Rss preview of Blog of Daniel Lemire

Our textbook on machine learning and artificial intelligence is out

2026-11-27 06:30:00

Cover of Introduction to Machine Learning and Artificial Intelligence with Python, by Robert Godin and Daniel Lemire

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

2026-11-26 23:39:37

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

2026-11-25 20:55:13

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

2026-11-24 22:58:38

A closed wooden gate beside an open iron gate

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

2026-11-23 21:00:38

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

2026-11-20 20:37:52

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)