Can gzip be a language model?

6 days ago (nathan.rs)

Yes: you can classify a test file by topic with gzip as follows:

  gzip -9 sports.txt   testfile.txt

  gzip -9 politics.txt testfile.txt

  gzip -9 business.txt testfile.txt

(ass. sports.txt politics.txt and business.txt are text docs pertaining from the sports, politics and business domains, respectively, and have equal size)

The test file belongs to the topic with the smallest size *.gz file.

Witten's group at Waikato uni were perhaps the first to work on this.

Also check out the Hutter prize if you are interested in this.

  • Back in the day - maybe two decades ago - I implemented language detection like this.

    I seeded gzip compressors’ dictionaries with Wikipedia articles in different languages.

    I would then try to use said dictionaries on any random text, and the one that was best able to compress it, was the correct language.

    Absolutely totally not the best approach, but very fast and super simple to implement.

  • There are some deep connections between machine learning, compression, and cryptography with information theory as a common thread.

    Also, I’ve never seen “ass.” Used to shorten “aside” — I typically use N.B. but perhaps only for important ones.

  • Nitpick: Doing it exactly like this is flawed because you let the compressibility of your references taint the result; what you would prefer is the compressed size of testfile given sports.txt/... as a dictionary without accounting for the compressed size of that, no?

    Really interesting approach though.

    • You're right, you should subtract off the compressed sizes of the respective reference files before comparing. (This suffices if we assume that later input data does not influence the compression of earlier input data, which is true except for certain unusual conditions like a repeated substring at the end of the reference data that also appears at the beginning of the test data.)

  • You might also want the topic files to be compressed against each other to get a baseline matrix and then multiply any results by the inverse, assuming equal priors on the topics.

  • I seem to remember it being shown for character recognition via JBIG. Maybe in Managing Gigabytes?

  • There would be some overlap with business sports analogies - eg team huddle.

3blue1brown did a series on this topic: https://www.youtube.com/watch?v=l6DKRf-fAAM https://www.youtube.com/watch?v=GlYgs6v2YfU (i think one more is yet to release)

  • Wonderful link. Just commenting to add: in the first video, Grant mentioned it would be a trilogy series.

    • I keep thinking that surely I missed the 3rd video in the series but no, 2 months later we are still waiting for the conclusion. I'm sure it'll be worth the wait though.

      1 reply →

    give it a normal text prompt, and it
    continues that prompt by searching
    for the byte sequences that compress
    best.

One moment, how are we supposed to know how well that search was done? There is no way to search a meaningful part of the search space.

So the result only gives us some lower bound of how well gzip works as a "plausibility tester" of a continuation of a text. The space of possible sequences is many orders of magnitude larger than what was searched. So there might be sequences in there that compress much better.

The text mentions beamsearch, but I don't see a discussion about how well beamsearch performs in finding the global optima when it comes to gzip compressibility of a text?

  • That's a fair question. Suppose we have a way to find a byte sequence x that globally minimises len(gzip(context + prompt + x)) over all sequences x of length n. Here + denotes string concatenation.

    It's unclear if this is very useful.

    The reason it may not be very useful is that one of Deflate's ingredients is a pass that replaces repeated substrings with backreferences to the earlier occurrence in the plaintext input stream.

    E.g. suppose we want to find an n=200 byte sequence x that minimises len(gzip(context+prompt+x)).

    If there exists any 200 byte sequence y such that prompt+y is a substring of context, then Deflate can encode prompt+y as a backreference to that earlier sequence - it needs to store a match-length & a distance-length, encoded using its Huffman trees. This candidate solution y may not be a global minima to our stated objective function, but if not, it's probably going to be a very good near-optimal approximate solution.

    Taking a step back, repeating huge chunks of the input context produces something that's great for minimising compressed output size but doesn't seem particularly helpful as a generative model.

    edit:

    Yep, I tried it out by running an experiment. Searching for the prompt in the context & then copying the following text as the solution produces solutions that are much better, in the sense of minimising the compressed output length, than beam search, while also being unhelpful as a generative tool.

    With the same example as the blog post:

      context: first 30,000 bytes of tinyshakespeare.txt
      prompt: 'MENENIUS:\n'
    

    Let x denote a solution, x is a string of length 200.

    Let L(x) denote len(gzip(context+prompt+x)), our objective function

    Let's call the proposed search method of searching for the prompt in the input rfind (after python's str.rfind).

    Then we have

       search method      soln               soln length   feasible?     objective value      search time (wall clock, s)
       -------------      ----               -----------   ---------     ---------------      ---------------------------
       emptystring        ""                          0          no              13,023                     0.04s
       gzipt beam search  see blog post             200         yes              13,051                    11.93s
       rfind              see below                 200         yes              13,026                     0.04s
    
    

    So 'rfind' is finding a solution that does a better job of minimising the objective function -- it only takes 3 bytes more to encode than the infeasible emptystring solution, and costs 25 fewer bytes than the solution found by the beam search implemented by gzipt per the blog post.

    Here's the solution 'generated' by rfind copying and pasting from the input context, starting from the rightmost occurrence of "MENENIUS:"

       MENENIUS:
       O, true-bred!
       
       First Senator:
       Your company to the Capitol; where, I know,
       Our greatest friends attend us.
       
       TITUS:
       
       COMINIUS:
       Noble Marcius!
       
       First Senator:
       
       MARCIUS:
       Nay, let them follow:
       The Volsces 
    
    

    Here's the code for 'rfind' - our complete 'generative algorithm':

        def find_candidate_solution_from_context(context, prompt, length):
            n = len(context)
            i = context.rfind(prompt, 0, n-length)
            if i < 0:
                return b''
            i += len(prompt)
            return context[i:i+length]
    
    

    Can hook it into gzipt.py by adding this line after out is defined, but before the beam search begins

        out += find_candidate_solution_from_context(corpus_window, prompt, length)

  • Read to the end: they aren't actually looking for the best-compressing output, because this quickly devolves into aaaaaaaaaaa. They keep a sliding window over a small portion of recent text and use that.

    Basically I think the entire premise falls apart due to that choice--they forced an interesting-looking outcome by adjusting the algorithm until gzip started picking random slabs of letters instead of ever-larger repeating runs.

Good article.

Compression is a property of language.

A seemingly simple sentence like "I had lunch" has enormous amount of information compressed inside it.

The word lunch is a compressed form of "having food at noon" while "noon" in turn is a compressed form of "Sun's position against Earth's rotation" and so on and so forth.

Every sentence has layers of compressed sentences. How many layers one chooses to decompress is up to the person.

This is fun, but historically people have gone a bit overboard with saying that models like this, or n-gram language models, are anywhere close to large neural network models. There is certainly a connection though.

  • Yes, but it is a useful insight that both methods try to solve the same mathematical problem. It's better than thinking of LLMs as magic.

    When you say "cross-entropy loss" people without stats background go to Wikipedia, take a glance, and adjust their mental model to "inscrutable magic".

    Thinking of the main difference as the trade-off in how much CPU, memory and storage is allowed is not really wrong.

    The part that is wrong is to think of gzip as a method that might reach similar complexity or generalization. And more importantly, to ignore the advanced way how training data gets curated or generated for (instructed, chain-of-thought) LLMs. But even then. The mental model that the LLM's goal is text compression is not wrong. The question to ask next is what kind of text it is expecting to compress.

    • Yep agree, good details, and this doesn't contradict my point above, about people going "overboard" with the comparison.

      I do think when making these comparisons, it is worth emphasising that neural nets are really different. E.g. I used to see people equating LLMs to n-gram models, etc. which is overly simplistic, (especially in the early days when the models weren't as good).

I'm more interested in the converse question: how well does an LLM perform as a compressor, compared to gzip (ignoring its insanely lower speed)?

I think language itself is compression, so the arxiv paper tracks for me.

Viz. if Language is compression (of thought / culture / the tacit je ne sait quois of being-to-being communication etc.), then definitionally, Language Modelling must also be Compression.

Except, language is an arbitrarily lossy compressor, who's "compression-prediction equivalence" is indeterminate and unstable, because Language co-evolves constantly; both as a function of or response to culture, as well as an influencer of culture.

So, the subjective-objective goodness of Language Models (of any kind of language) would be, at best, upper-bounded by the compression-prediction equivalence of the Languages corpus itself. And that is assuming the language corpus is perfect in every way---it captures all knowledge expressible by language and it is always in-sync with live evolution of all language expression and evolution (i.e. LLM training is not a batch job, but a real-time present continuous process).

For example, to my layperson eyes, the mathematical language of proofs actively weeds out ambiguity of subjective interpretation. Ideally, a proof ought to lead to the exact same conclusion on every single reading by any reader who can follow the steps. A proof also holds only if the rest of the formal, explicit, inviolable, internally-consistent set of axioms and results holds.

So it stands to reason that mathematical prose of proofs, being optimised as mechanical procedure of taking an open question to a deterministically closed solution, has better odds of approximating the tacit aspects of mathematical derivation.

Which makes an LLM able to construct a mathematical proof, which is mind-melting to say the least.

However, I wonder, can LLMs dream of mathematical sheep?

  • Language is compression of a sort. A dictionary is a decompressor. You look up one word, and you may get a paragraph about its meaning. An encyclopedia can be thought of as roughly the same with more detail for some nouns.

    It makes a lot of sense why dictionary-based compression is named the way it is. A shorter symbol is used to store information that would take more symbols in the uncompressed corpus, if the shorter symbol hadn't been assigned to represent it. That's in a way just what an actual dictionary on your English professor's shelf does. The big difference is your compressor is coining new short symbols all the time.

    • I'd say the bigger difference is the lack of homophones in a compressor.

      Languages add new words constantly, albeit slower than a computer does compressing a new file.

I was curious to see how this would work with bzip2 and zstd. The source is public at https://github.com/nathanrs/gzipt, and I asked MiMo-V2.6-Flash to fork and modify it in a straightforward way. The answer is that bzip2 produces sequences that don't resemble human language:

  gzipt \
      --corpus data/tinyshakespeare.txt \  
      --prompt $'MENENIUS:\n' \
      --length 200 \
      ;
  
  MENENIUS:
  MtLUMSeptuttyyyxyxyxyxyvyyyxyxyxyxyvyyyxyxyxyxywyvzyxyxyx
  yyxyyyxyxyxyxyxPlyxyxyxyxyxyxyxyxyxtoxzfTUS.zxzzzyzzzvzzz
  vzzzxvzyvyxyxyxyvyxyxyxyvy--,Vdvyxyxyxyxyxyxyxyxyxxy!zFlx
  zzyyxyxyxyvyxyxyxyvyySPffuyuy

Line breaks added. This looks roughly optimized for the most repetitive Burrows-Wheeler transform (https://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transf...). Why are they runs of alternating symbols and not one symbol?

Zstandard produces whitespace with the occasional letter thrown in. To quote MiMo: "As you can see, zstd does not speak Shakespeare. ... zstd encodes a run of one repeated byte as a near-free run-length sequence, and space and newline are the cheapest literals in the corpus: ten newlines cost about the same to append ten bytes of genuine corpus text and less than nonsense does."

  • Did you check MiMo correctly performed this unfamiliar task before posting this comment?

    • I did. I read the code to make sure the quality of MiMo's work matched mine for a quick experiment, though not that the code was free from subtle bugs.

      This was the main change for bzip2:

        @@ -33,19 +34,16 @@ def candidate_lengths(
             level: int = 9,
             pool: ThreadPoolExecutor | None = None,
         ) -> list[int]:
        -    """Compressed length of ``context + seq`` for each seq, sharing the context.
        +    """Compressed length of ``context + seq`` for each seq.
        
        -    Compresses ``context`` once into a ``compressobj``, then clones its encoder
        -    state per candidate and feeds only that candidate. Identical to
        -    ``len(zlib.compress(context + seq, level))`` for each seq, but the expensive
        -    match search over ``context`` happens a single time.
        +    Unlike ``zlib``'s ``compressobj``, Python's ``BZ2Compressor`` cannot be
        +    snapshotted mid-stream, and bzip2's move-to-front + Huffman stages see the
        +    whole block, so every candidate recompresses the full context. Threads
        +    still scale because ``bz2`` releases the GIL.
             """
        -    base = zlib.compressobj(level)
        -    head = len(base.compress(context))
        
             def length_for(seq: bytes) -> int:
        -        clone = base.copy()
        -        return head + len(clone.compress(seq) + clone.flush(zlib.Z_FINISH))
        +        return len(bz2.compress(context + seq, level))
        
             if pool is not None:
                 return list(pool.map(length_for, sequences))

      2 replies →

  • So, you had an AI write code you don't understand, then posted output you don't understand in a comment on the internet for other humans to read?

    • No, they used AI to write code they do understand, then posted interesting results they (partially) don't understand for other humans to see.

      1 reply →

I've been pondering on something related: can an LLM be a chat?

Some models are reproducible, in that the same prompt will generate the same output. Say that we could wire up such a model to generate some code.

In that case, we could create a prompt that generates, say, an entire codebase, or a large piece of text. The prompt (or really, the tokens) would then be the compressed version of the codebase or the text.

I am not talking about an "AI agent", but really a model that we call in a reproducible manner. Preferably one call, with one prompt. An agent could just run `git clone` to "decompress" a codebase, which conflates the idea of compression. If that were compression, then the "compressed version of the git kernel" would be a single line of text: `git clone https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/lin...`. I am really talking about having an LLM re-generate text based on a prompt.

Does that make sense? I can imagine that this is highly impractical and inefficient. But would this count as "compression" at all?

  • You sound a bit confused.

    A large language model itself (the network) give you the probabilities for the next token given some prefix of tokens so far. You can use arithmetic coding to go from these probabilities to a deterministic compression / decompression algorithm.

    When you use an LLM to generate text, you sample from that probability distribution. You can use a true random sample. Or you can make it trivially deterministic by using a seeded pseudo-random-number-generator or you just pick the highest probability each time. But that's all a red herring; really, what you want is arithmetic coding.

    https://en.wikipedia.org/wiki/Arithmetic_coding

  • >I've been pondering on something related: can an LLM be a chat?

    A chat?

    >I am not talking about an "AI agent", but really a model that we call in a reproducible manner.

    An LLM is just as deterministic as any other computer program. For identical inputs (which includes the PRNG seed) it produces identical outputs.

    >compressed version of the git kernel

    The git kernel, got it.

    >But would this count as "compression" at all?

    Yes. The decompressor is several tens of gigabytes though.

    • >An LLM is just as deterministic as any other computer program. For identical inputs (which includes the PRNG seed) it produces identical outputs.

      This is not really true in practice because of multi-threading and out-of-order execution. Mathematically equivalent orderings of operations are not equivalent when dealing with floating point values, so most practical LLM implementations end up being non-deterministic.

      3 replies →

  • It makes a lot of sense. I thought about it in the context of pull requests or change sets: if the text-to-code process is reliable, why don't you give me prompts instead of code? Code becomes just an intermediate representation.

Would this work with video compression? Video codecs encode a lot of meaning; they use motion vectors to track the movement of objects on screen, for example.

Funny, this kind of knowledge used to be a common theme in ML/DS roles. Funny to see that people are thinking about it now by talking to AI (the article does look very AI written). Funny that people can enter very deep rabbit holes because they didn’t study something and guess they are making progress on something that is commonly known. Dunning Krueger prime time 2026

R. Hendricks, D. Chugtai, and J. Dunn, "Lossless compression via optimized middle-out bitstream processing," Pied Piper Inc., Palo Alto, CA, Tech. Rep. 42, Apr. 2014.

My goodness, gzip is intelligent! Enjoy your job while you have it; put on some hip hop music and practice your pivoting.

Fun topic but generated article text and then not even actually using gzip? Rubs me in a weird way.

Will Wright once described the same connection from the opposite direction: compression as procedural content generation.

In the 2023 discussion of "Demoscene accepted as UNESCO cultural heritage in The Netherlands" I posted a transcript from a video of Will Wright discussing the demo scene:

https://news.ycombinator.com/item?id=36613058

[...] Here's a simple low-tech pre-LLM example that shows the equivalence of compression and procedural content generation:

Take a huge text file of HN postings, and compress it with gzip or compress or some other robust compression algorithm. The better the algorithm, the more the output will look like random noise. Then slice the compressed file in half, and replace the second half with random numbers. Then uncompress it. You'll find that at the point you sliced it, it keeps on writing out almost plausible text for a while, consisting of highly probably snippets of commonly encountered words and phrases, then goes downhill towards incoherence. It's not as coherent or confident as an LLM, but the point is to show how low the bar is for using compression for procedural content generation.

LLMs are essentially a form of compression of the world's knowledge or whatever they're trained on, not just word frequencies or pixel patterns, but also concepts and ideas. [...]

Yay, another mostly AI authored piece with vibe-coded aesthetics.

Some will say that I should 'judge the idea, not the form'.

But if the author didn't find enough strength to write alone a short ~700 words summary about his work, it means he himself isn't that interested or enthusiastic about it. Why should others bother then? Particularly since low-effort like that signals possibility the whole work is superficial and derivative.

  • Say you have been working on a multi year project writing code and putting in a lot of effort.

    If you then use AI to write a product page documentation and proof read it for correctness, would that constitute to signaling that the whole effort is superficial?

    Some work may be left to AI while you focus on the more important aspects of the work.

    Surprisingly people have got it completely backwards where they want AI to generate code and humans to write documentation.

    • > If you then use AI to write a product page documentation and proof read it for correctness, would that constitute to signaling that the whole effort is superficial?

      It would constitute signalling possibility the whole effort is superficial.

      Look around at the amount of slop that is thrown out there using low-effort methods.

      I haven't order the work that is being presented here, I'm in no need to guarantee its correctness. I'm only bystander whose attention the OP is trying to grab by posting it on the HN. I don't know if his project is multi year or only multi prompt. The burden of proof lays on him to show he is not one of those another guys who hide emptiness behind AI generated text. Earlier the grammatically correct and carefully laid out blog post was in itself a proof that at least some effort was exerted. Now that important signal is worthless and when it's clearly written by AI it becomes an anti-signal.

      At least according to me, because the front page of the last year shows surprisingly big number people love superficial slop.

      I'll reiterate, I don't know if the work here is legit or not (and after seeing that ai documentation I have no desire to check that). Demanding from the reader to carefully look past the generated documentation and meticulously analyse the actual content is more time consuming than before and opens the gates for AI slop.

      And that attitude also makes people who are not experts on the subject more defenceless against hoaxes and deceit. If both frauds and legit createor look superficially identical, because they use the same chatbot, then whom should the member of general public trust, eh?

      3 replies →

  • [dead]

    • > I'm judging the ideas in your post, not its form.

      and simultaneously you write that 'my form is lackluster' and that 'an LLM could have written your comment and improved its form without losing anything distinctive'. We are having ourselves a small contradiction, aren't we.

      Be my guest, enjoy chatbot writing and drowning in slop. But don't encroach upon my freedom to protest it.

      3 replies →

Not without attention or something approximating it.

The fact that gzip is relatively fast should be your first clue that something important is missing.

Gzip is great at predicting the next token for one very specific narrative. LLMs can predict next tokens for entire universes of narratives. Searching for the correct next token across this space scales ~quadratically with the input size. Gzip scales linearly. I can gzip a one terabyte file. Imagine feeding that much into an LLM. These are wildly different animals that happen to overlap in a very small way. Equating compression to intelligence looks increasingly silly to me.

If we must compare language models to compression, they are much more like jpeg and mp3 than they are gzip and flac. I can go fuck with a jpeg file pretty severely at the bitstream level and still have something resembling performance on the other side. Gzip cannot remotely approach this.

  • > Gzip scales linearly. I can gzip a one terabyte file.

    In part because gzip only has a 32KiB window size, and I think it'd be at least quadratic within that window if you were going for optimal compression.

    • I'll concede the window part, but Gzip runs within the physical confines of a single cpu core and is typically entirely resident in local caches. The point is not just the quadratic scaling but also what it scales with.

      Show me an LLM that can run at 300 megabytes per second. Even dedicated ASICs with weights burned in will never move this fast.

      1 reply →

    • Match-finding does not need to be quadratic. However, truly optimal gzip block splitting is very slow, indeed.

I think not. it's true that a large language model compresses knowledge and allows us to decompress knowledge. but gzip compresses data and not knowledge. with a LM you can decompress various forms of knowledge from the same data. gzip is a 1 to 1 kind of decompression where as an LM is a 1 to infinity kind of decompression.