# How I Built a Deterministic Neural Compressor in Go to Archive Audit Logs for Years

> Source: <https://dev.to/radek_ryckowski_cb3149af5/how-i-built-a-deterministic-neural-compressor-in-go-to-archive-audit-logs-for-years-2j83>
> Published: 2026-11-25 08:38:48+00:00

**Recommendation:** Replace 256-way softmax byte prediction with 8 binary decisions and keep the compression hot path integer-only to get bit-identical archives across x86 and ARM.
More in the playbook "Inference and self-hosting": <https://wpnews.pro/playbooks/inference-serving>

If you have ever been responsible for retaining years of audit logs, security events, or OpenTelemetry traces, you know the storage dilemma:

`gzip`, `zstd`, `xz`) treat your logs like mystery bytes.
Every single time `gzip` or `zstd` compresses a batch of audit logs, it starts from scratch. It has no idea that `"actor_type":"service_account"` or `"status":{"code":1}` appears ten thousand times an hour in your system. It has to rediscover your schema on every single file.

On the flip side, modern **neural compressors** can learn your exact data schema and squeeze out dramatically better compression ratios. So why doesn't everyone use them for long-term archives?

Because in production, neural compression usually comes with three deal-breakers:

`amd64`) and Apple Silicon/Graviton (` arm64`).
To solve this, I built **[nzip](https://github.com/radryc/compressor)**—a zero-dependency Go compressor powered by a tiny, **100% integer-only neural network** trained on your specific data format.

Here is how it works, what surprised me during benchmarking, and how you can use the same ideas for custom structured data.

Instead of shipping a heavy machine learning stack into production, `nzip` splits the problem into two clean planes:

```
  [ Control Plane: Python or Pure Go ]
  Sampled Audit Logs ──▶ Train tiny byte-level GRU ──▶ Verify on holdout ──▶ Export Model (.bin)
                                                                                    │
  [ Data Plane: Zero-Dependency Go ]                                                ▼
  Live Audit Stream  ──▶ Integer GRU + Match & Context Models ──▶ Arithmetic Coder ──▶ Archive (.nzip)
```

`stream.Writer` / `stream.Reader`). No Python, no CGO, no GPU required.
Think of it like generating a custom, learned compression dictionary on steroids.

When you archive audit data, **decodability years later is non-negotiable**.

In neural compression, the encoder and decoder both run the exact same model step-by-step to predict the probability of the next byte. If the decoder's math differs from the encoder's by even `0.000001`, their probability tables drift out of sync—and every byte after that turns into garbage.

During early testing, I ran into a classic systems trap: **floating-point contraction**. On `arm64`, compilers fuse `a * b + c` into a single hardware FMA (Fused Multiply-Add) instruction with one rounding step. On `amd64`, it executes as two separate instructions with two rounding steps.

The result? Encoding a file on an x86 machine and decoding it on an ARM machine **corrupted 3,869 out of 4,096 bytes**.

To make archives truly future-proof, `nzip` eliminates floating-point math from the compression hot path completely:

`int16` and `int32`).` sigmoid`, `tanh`, `exp`) are replaced with `SSE2` on Whether you decompress an archive tomorrow on an Intel laptop or in 2033 on an ARM server, the output is guaranteed to be bit-for-bit identical.

Early versions of neural compressors tried to predict all **256 possible values** of the next byte at once using a `softmax` layer. That required `256 × H` matrix multiplications plus 256 `exp()` calls *for every single byte*. Throughput crawled at **0.05 MB/s per core**.

`nzip` flips this around by breaking every byte down into **8 binary decisions** (one bit at a time, MSB to LSB):

```
  Previous Bytes ──▶ [ Integer GRU + Classic Context Models ]
                            │
                            ├──▶ Bit 7 (0 or 1?)
                            ├──▶ Bit 6 (0 or 1?)
                            │      ...
                            └──▶ Bit 0 (0 or 1?) ──▶ Binary Arithmetic Coder
```

Instead of asking *"Which of these 256 characters comes next?"*, the engine asks *"Is the next bit a 1 or a 0?"* eight times in a row. That shrinks the neural network math from `256 × H` down to `8 × H`—a **25×–29× speedup**, pushing throughput to **~1.2–1.7 MB/s per core** (and **13.2 MB/s** across 32 threads).

To test `nzip` against real-world observability and audit workloads, I benchmarked it on **7.4 MB of OpenTelemetry JSON spans**.

Crucially, these logs contained **random hex `traceId` and `spanId` values**. Roughly 25% of the raw file was pure cryptographic randomness—which is mathematically impossible to compress. All the real savings had to come from exploiting structure.

| Compressor | Compressed Size | Ratio | Bits / Byte | 
|---|---|---|---|
| `gzip -9` | 791,211 B | 10.65% | 0.85 | 
| `xz -9e` | 670,440 B | 9.02% | 0.72 | 
| `zstd -19 --long` | 667,324 B | 8.98% | 0.72 | 
| `bzip2 -9` | 642,858 B | 8.65% | 0.69 | 
| **`nzip` (H=32, blocks)** | **611,579 B** | **8.23%** | **0.66** | 

`nzip` produced archives **20% smaller than `gzip -9`**, **6% smaller than `zstd -19` and `xz -9e`**, and **2% smaller than `bzip2 -9`**.

Here is the most interesting lesson from building this: **if you run the neural network by itself, it actually loses to `gzip`.**

When I isolated each component on a 1 MB test slice (`gzip -9` = 97.6 KB), the numbers told a very clear story:

`bzip2`, Why? Because a small neural network is great at learning **global schema structure** (like JSON syntax and field transitions), while classic statistical models are much better at memorizing **exact repeated strings** that just appeared 500 bytes ago (like a repeated `service.name` or user UUID).

By feeding the neural network's predictions alongside a multi-length match finder, an order-2 context table, and a run-length tracker into a lightweight mixer, each predictor covers the others' blind spots.

Compressing one giant static file is easy. Production audit pipelines rarely work like that—they push thousands of tiny batches over the network, schemas drift over time, and files get corrupted on disk.

`nzip` bakes operational safety directly into the wire format (`NGR3`) and Go API:

Every compressed stream header records the **Model ID** and the **CRC32C content hash** of the exact model artifact used to write it. When you retrain a model next month, the pipeline publishes a new content-addressed artifact without deleting old ones—so archives written last year never break.

Audit schemas evolve when developers add new fields. `nzip` includes a rolling EWMA drift monitor (`drift.Monitor`) that watches your live compression ratio in bits-per-byte and triggers an alert (or automated retrain) if compression degrades past your threshold.

`nzip` in CLI or Go
You can train a model on your own log format and benchmark it against `gzip -9` in four commands:

```
# 1. Build the zero-dependency Go binary
go build -o nzip ./cmd/nzip

# 2. Train a schema-specific model on a sample of your logs
./nzip train -data audit-sample.ndjson -out models/audit-v1.bin -model-id 1 -hidden 32 -epochs 6

# 3. Benchmark against gzip -9 on a holdout file it has never seen
./nzip bench -model models/audit-v1.bin -in holdout.ndjson

# 4. Compress and verify with full CRC32C integrity checks
./nzip compress -model models/audit-v1.bin -in audit.ndjson -out audit.nzip
./nzip verify -models ./models -in audit.nzip
```

And if you want to embed it directly inside a Go ingestion service, it implements standard `io.Writer` and `io.Reader` interfaces:

```
// Streaming compressor: keeps model state warm across small batches
w, err := stream.NewWriter(dst, registry, "audit-logs",
    stream.WithMode(stream.ModeSession),
    stream.WithDictionary(dict),
)
if err != nil {
    log.Fatal(err)
}
w.Write(batch)
w.Flush()

// Streaming decompressor: looks up the exact model hash from the stream header
r, err := stream.NewReader(src, registry)
if err != nil {
    log.Fatal(err)
}
io.Copy(out, r)
```

If you are archiving homogeneous, high-volume structured records—audit trails, telemetry spans, financial event logs—general-purpose compression algorithms leave real storage savings on the table.

You don't need a massive LLM or a GPU cluster to take advantage of learned compression. A tiny, integer-only neural network combined with classic context modeling gives you **better-than-`bzip2` ratios**, **multi-core Go performance**, and **deterministic cross-CPU safety** you can trust years down the road.

Check out the full source code, wire format docs, and benchmarks on GitHub: [github.com/radryc/compressor](https://github.com/radryc/compressor)
