Find out about my work
By Marek Oerlemans December 2026
Much of deep learning on whole-slide pathology images rests on one small model: ABMIL. It takes the tens of thousands of tiles of one slide and turns them into predictions, such as the risk that a patient’s cancer comes back. It does little work per tile, but there are so many tiles that training still means waiting.
This is similar to attention in language models, where FlashAttention was introduced to speed it up. I wrote custom GPU kernels for ABMIL based on the same idea: do ABMIL’s attention steps in one go, instead of saving every intermediate result to memory and reading it back for the next step. On large inputs, the model’s forward and backward pass now run about 2× faster than in plain PyTorch and need less memory. At the end I look at a real training run, data loading included, and at when PyTorch’s own compiler already gets you most of the way.
The code is open source: github.com/moerlemans/flashabmil. It computes the same model as the common gated-attention ABMIL encoder (mathematically identical; results match plain PyTorch up to tiny rounding differences), so trained weights still work.
A whole-slide image (WSI) is a digital scan of a complete tissue slide at microscope resolution, often 100,000 × 100,000 pixels or more. That is far too large to fit into GPU memory and feed to a neural network in one go. The usual approach therefore has two stages:
ABMIL, short for attention-based deep multiple-instance learning (Ilse et al., 2018), handles stage 2 in four steps:
(For ML readers: the pooling is a softmax attention over the tiles, which is why FlashAttention’s tricks carry over.) People train it either on a random subset of tiles per slide (say 1,000) or on all tiles of each slide.
Where the time goes. On a GPU, arithmetic is cheap and moving data in and out of memory is expensive. ABMIL does very little arithmetic per tile, but it does it for hundreds of thousands of tiles per training step.
In plain PyTorch every operation is a separate step: multiply, tanh, sigmoid, softmax, weighted sum, and all of them again for the backward pass. Each step reads a big table with one row per tile from GPU memory and writes a new table back. So the GPU spends most of its time moving these tables around, not computing.
The fix is to fuse the operations into one GPU program (a “kernel”). It loads a block of tiles into the chip’s fast on-chip memory, does all the steps there, and writes back only the small result. I wrote these kernels in Triton, a Python-like language for GPU programming. The softmax is what makes this hard.
The softmax problem. Each tile’s weight is exp(score) divided by the sum of exp(score) over all tiles in the slide. That sum is the bottleneck: you can’t calculate it until you have passed every tile, and without it you can’t compute a single weight. So the obvious way goes over all tiles twice: once to score them and build the sum, and once more to compute the weighted average, with all the per-tile tables kept in memory in between. With 100,000 tiles that is a lot of extra memory traffic.
The FlashAttention trick: running totals. You don’t need the final sum before you start pooling. Walk through the tiles block by block and keep two running totals:
exp(score);exp(score).At the end, divide the first by the second. That is exactly the weighted average, but every tile is read only once, and only one score per tile is kept (for the backward pass). This is called “online softmax” (Milakov and Gimelshein, 2018). (To keep the numbers from overflowing, the kernel also subtracts the largest score seen so far before taking exp, and rescales the running totals whenever that maximum changes.)
Running totals have a second useful property: two partial totals can be merged. So a large slide is cut into chunks, each group of GPU cores handles its own chunk, and the pieces are merged at the end (the same trick as Flash-Decoding for language models). The whole GPU works on one slide at once.
Training needs gradients too. Normally the backward pass reuses intermediate values that the forward pass stored, which means writing and re-reading more big tables. My backward kernel instead recomputes the gate values (the tanh and sigmoid outputs) on the fly from the tile embeddings. Recomputing them is cheaper than storing them, because arithmetic is cheap and memory traffic is not.
Folding away a layer. The embedding network’s last layer is purely linear, so I merge it into the score network and apply it once to the slide summary instead of to every tile: the same math, but its per-tile output is never computed.
I leave the first and largest layer (1,536 → 128) to NVIDIA’s standard matrix-multiply library, which already runs it efficiently.
“FlashABMIL” below means ABMIL with the fused kernels described above, wrapped in torch.compile (PyTorch’s built-in compiler) as in the example further down. All timings are for the model alone (forward and backward pass, no data loading) on random input, on a single RTX A6000, using 16-bit (bf16) numbers, the GPU’s fast reduced-precision mode.
| tiles per training step | plain PyTorch | FlashABMIL | speedup |
|---|---|---|---|
| 1 bag of 262,000 tiles | 9.2 ms | 4.4 ms | 2.1× |
| 32 slides × 40,000 tiles | 43.7 ms | 20.8 ms | 2.1× |
The GPU memory the model needs on top of its input drops from 2.6 GB to 1.5 GB in the second case. The first row is a stress test, about ten typical slides’ worth of tiles in one bag. Most of the remaining time is the big 1,536 → 128 layer, which reads every tile’s features.
pip install git+https://github.com/moerlemans/flashabmil
import torch
from flashabmil import FlashABMILEncoder
# ABMIL encoder: 1,536 → 128 → 128 embedding, gated attention of width 128
enc = FlashABMILEncoder(feature_dim=1536, attention_dim=128, embed_mlp_hidden=[128]).cuda()
enc = torch.compile(enc) # many small bags (e.g. 16 × 1,000): torch.compile(enc, mode="reduce-overhead")
features = torch.randn(4, 20000, 1536, device="cuda") # 4 slides × up to 20,000 tiles
mask = torch.ones(4, 20000, dtype=torch.bool, device="cuda")
mask[1, 12000:] = False # slide 2 has only 12,000 tiles
slide_vectors = enc(features, mask) # (4, 128), feed to your classifier
The mask marks which tiles are real, so slides of different sizes can share a batch. Gradients flow as usual. The model is the standard gated ABMIL encoder (an embedding network that ends in a linear layer, then gated attention), so a checkpoint of that layout loads with load_state_dict. Other layouts, such as CLAM’s or the original of Ilse et al. (an embedding that ends in a ReLU), or layers wider than 256, still run but fall back to plain PyTorch, without a speed-up.
torch.compileA model step is only part of training. I also timed a full ABMIL classifier training loop on foundation-model features of TCGA breast-cancer slides (with random labels, since I only measure speed). All features are preloaded into RAM, and the next batch is copied to the GPU while the current one trains. FlashABMIL again runs inside torch.compile.
| training setup | plain PyTorch | FlashABMIL | speedup |
|---|---|---|---|
| one whole slide per step (typically ~20,000 tiles) | 7.9 ms | 4.7 ms | 1.7× |
| 16 slides × 1,000 random tiles per step | 7.4 ms | 5.3 ms | 1.4× |
| 16 whole slides per step | 49.2 ms | 46.4 ms | 1.06× |
| 16 whole slides per step, features already on the GPU | 28.0 ms | 16.1 ms | 1.7× |
The first caveat is data loading: if your data loading is not good, the gain disappears. With many whole slides per step, copying the features to the GPU already takes longer than training on them (third row). Streaming features from disk instead of RAM is more than 10× slower again, and then no speedup is visible at all.
The second caveat is torch.compile itself. On a standard ABMIL it also fuses many of the small steps, so at typical step sizes (1,000–20,000 tiles) it is about as fast as my kernels, and once data loading is taken into account the difference is negligible. My kernels give the best speed, but they only pull clearly ahead from about 100,000 tiles per step.
ABMIL is limited by memory traffic, not by arithmetic, which makes it a natural fit for FlashAttention-style fusion. With fused kernels, the model’s forward and backward pass run about twice as fast as in plain PyTorch on large inputs and need less memory, with the same math and the same trained weights. However, data loading might be a bigger bottleneck, and many of the savings can already be made with torch.compile. If you are trying to optimise the last one percent, this is for you. Otherwise, I hope you learned something.
It needs an NVIDIA Ampere GPU or newer (RTX 30-series, A100 and later), an embedding that ends in a linear layer, and layer widths up to 256; otherwise it falls back to plain PyTorch. Top-k attention is not supported. Installation, a usage example, full benchmark tables and limitations are on GitHub.