pr0h0

fm4: storing a file as one number

I tried to store files as a single fraction. It never compressed anything, but a model-picked number does: how that idea became fm4, a context-mixing compressor that beats xz, FLAC and JPEG XL on size.

Abdulah Proho 6 min read

It started with a question that sounds like it should work: can you store a whole file as one fraction?

Write the file's bytes as a long string of digits. Then search for two integers, N and D, whose division N / D starts with exactly those digits. 1/7 is 0.142857…, so the six digits 142857 fit in two tiny numbers. With a good search (continued fractions, a Stern–Brocot walk), maybe any file has a short fraction hiding somewhere.

It doesn't. I built the search, and on real data the fraction was never shorter than the data. The ratio was 1.00x, every time. In hindsight that's counting, not bad luck: there are only so many short pairs (N, D), and far more files than that. Most files have no short fraction, and an encoder that only works on files it happens to like is no encoder.

But the idea had one good bone in it. A number in [0, 1) is a perfectly fine way to store a file, if you pick the number cleverly. That clever picking has a name, and the project became fm4: a lossless compressor that turns a whole file into one number, chosen by a model that learns as it reads.

The code is open source: github.com/pr0h0/fm-codec, and there's a project page with the details.

From a fraction to a model#

The trick is to stop asking for the digits of a fixed fraction and to let each digit's interval change width.

Code the file one bit at a time. Before each bit, a model predicts the probability that it is a 1, say 90%. The coder keeps an interval inside [0, 1) and splits it 90/10. If the bit really is a 1, it keeps the big part and the interval shrinks only a little. That costs about 0.15 bits of output. If the model was wrong, it keeps the small part and pays more than 3 bits.

After the last bit, the interval's width is the probability the model gave the whole file. Any number inside it identifies the file, and you need about log2(1/P) bits to write one down. Good predictions mean a wide interval and a short number.

That's arithmetic coding, and it moves the whole problem to the model. The decoder runs the same model on the bits it has decoded so far, so it makes the same predictions and gets back the same file. Nothing about the model is stored.

What the model looks at#

fm4 is a context-mixing compressor, in the family of PAQ and cmix. For every bit it asks many small models at once and lets a learned mixer weigh their opinions:

  • Order-n contexts. The last 1, 2, 3 … 7 bytes, hashed into tables of adaptive counters. Each counter remembers how often a 1 followed this context, plus a short history of recent bits.
  • Match models. Find the longest earlier stretch of the file that ends the same way, and bet on the byte that came next. That's what makes repeated text nearly free.
  • Words, columns, sparse and indirect contexts for text and code. E8/E9 filtering for x86 machine code, which turns relative call addresses into absolute ones, so repeated calls look alike.
  • Images (raw RGB) predict each pixel from its neighbours with several predictors at once, including an online least-squares filter, and code the error.
  • Audio (16-bit PCM) predicts each sample from the channel's past samples and the neighbouring channel's.
  • Video adds the same pixel in the previous frame.

All these predictions go into small neural networks: logistic mixers that retrain themselves after every bit. A few refinement stages (APM/SSE) then correct what's left. There are six levels, from 0 (store) to 5, and each adds models.

Does it work?#

Compressed size divided by original size, so smaller is better. One thread on an Intel i7-6700:

Python source, 4 MB x86-64 code, 4 MB Photo-like image, 2048×1152
fm4 level 4 0.094 0.270 0.336
fm4 level 5 0.092 0.265 0.332
xz -9e 0.134 0.363 0.665
zstd -19 0.137 0.381 0.742
PNG (max) 0.549
JPEG XL lossless (effort 7) 0.352

At level 4 that's about 30% smaller than xz on source code, 26% smaller on machine code, and 5% smaller than JPEG XL on the photo. On 12 audio clips it beat flac -8 on every one, by 6–45%. On short video clips it beat x264 lossless, FFV1 and xz on screen recordings, animation and even camera footage. Camera footage was the closest race, since there's no motion compensation.

The price is speed. fm4 runs at 0.3 to 2.7 MB/s per core, depending on level, where zstd does hundreds. Decoding is just as slow, because the decoder has to run the same model. And a level-5 process wants about 600 MB of memory.

Three implementations, one output#

fm4 exists three times:

  • C (c/fm4.c): the reference, and the spec.
  • BPL native: a port to BPL3, my own programming language, compiled to native code.
  • BPL → WebAssembly: the same port compiled for the browser, with a small JS host that runs segments in Web Workers.

All three have to write byte-identical files: same input, same level, same bytes, on Linux, macOS and Windows. The test suite locks SHA-256 hashes of the output, and any difference fails it.

That's harder than it sounds, because some of the predictors use floating point. Identical output depends on plain IEEE-754 doubles: fused multiply-add disabled (-ffp-contract=off), and from the math library only sqrt and floor, the two functions IEEE defines exactly. Everything else in the model is integer arithmetic.

The port also turned out to be a good test of BPL itself. Keeping two implementations bit-for-bit equal finds compiler bugs fast, and it found several. The BPL build now runs within about 2% of the C build in every mode, and the WebAssembly build at about half native speed.

Making it fast enough, and safe#

Two changes did most of the speed work:

  • Segments. Inputs of 128 MB and more are cut into 64 MB runs, which are coded in parallel. The cut depends only on the data, so the output is the same for any thread count. 256 MB of mixed data went from 158 s to 62 s, for 1.9% more size.
  • One compiled model per level. The model's feature switches became compile-time constants, so the compiler builds a specialized copy for each level and mode. Level 1 got about 35% faster, levels 2–5 10–16%, and the output stayed exactly the same.

The decoder reads untrusted input, so I treated it like an attack surface. Every file carries CRC-32s of its header and of the original data. A forged length is rejected before anything is allocated. The decoder accepts only parameter sets the encoder actually writes, and it stops as soon as it reads past the payload. libFuzzer harnesses run it under AddressSanitizer, UBSan and MemorySanitizer. The files that ever broke a decoder are kept as regression tests.

Caveats#

fm4 is a research codec that grew up, not a zstd replacement.

  • Slow and memory-hungry, as above.
  • The format is fixed, the code isn't. v0.1.0 froze format 1: files you write today stay readable by every future version. If the format ever changes, the new one gets a new version number, and format 1 is still decoded.
  • Raw media only. The image, audio and video modes take raw RGB or PCM; convert with ffmpeg first. Archives handle WAV, BMP and PPM themselves.
  • Whole files only. No streaming, no stdin/stdout, no random access.

If you want to try it, grab the v0.1.0 release, which includes a prebuilt WebAssembly build, or build the C version, which is one file with no dependencies:

git clone https://github.com/pr0h0/fm-codec && cd fm-codec
make c
c/fm4 enc 4 bytes notes.txt notes.fm4
c/fm4 dec notes.fm4 notes.out

The fraction idea was wrong. But following it carefully led somewhere: a number in [0, 1) was a fine way to store a file all along. It just needed a model to pick the number.