{"slug": "how-i-built-a-deterministic-neural-compressor-in-go-to-archive-audit-logs-for", "title": "How I Built a Deterministic Neural Compressor in Go to Archive Audit Logs for Years", "summary": "A developer built nzip, a zero-dependency Go compressor that uses a tiny integer-only neural network trained on a specific data format to archive audit logs and OpenTelemetry traces. The design eliminates floating-point math from the compression hot path after testing showed cross-architecture drift corrupted 3,869 of 4,096 bytes when encoding on x86 and decoding on ARM, and it predicts bytes as 8 binary decisions instead of a 256-way softmax, yielding a 25x-29x speedup to roughly 1.2-1.7 MB/s per core and 13.2 MB/s across 32 threads.", "body_md": "If you have ever been responsible for retaining years of audit logs, security events, or OpenTelemetry traces, you know the storage dilemma:\n\n`gzip`, `zstd`, `xz`) treat your logs like mystery bytes.\nEvery 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.\n\nOn 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?\n\nBecause in production, neural compression usually comes with three deal-breakers:\n\n`amd64`) and Apple Silicon/Graviton (` arm64`).\nTo 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.\n\nHere is how it works, what surprised me during benchmarking, and how you can use the same ideas for custom structured data.\n\nInstead of shipping a heavy machine learning stack into production, `nzip` splits the problem into two clean planes:\n\n```\n  [ Control Plane: Python or Pure Go ]\n  Sampled Audit Logs ──▶ Train tiny byte-level GRU ──▶ Verify on holdout ──▶ Export Model (.bin)\n                                                                                    │\n  [ Data Plane: Zero-Dependency Go ]                                                ▼\n  Live Audit Stream  ──▶ Integer GRU + Match & Context Models ──▶ Arithmetic Coder ──▶ Archive (.nzip)\n```\n\n`stream.Writer` / `stream.Reader`). No Python, no CGO, no GPU required.\nThink of it like generating a custom, learned compression dictionary on steroids.\n\nWhen you archive audit data, **decodability years later is non-negotiable**.\n\nIn 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.\n\nDuring 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.\n\nThe result? Encoding a file on an x86 machine and decoding it on an ARM machine **corrupted 3,869 out of 4,096 bytes**.\n\nTo make archives truly future-proof, `nzip` eliminates floating-point math from the compression hot path completely:\n\n`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.\n\nEarly 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**.\n\n`nzip` flips this around by breaking every byte down into **8 binary decisions** (one bit at a time, MSB to LSB):\n\n```\n  Previous Bytes ──▶ [ Integer GRU + Classic Context Models ]\n                            │\n                            ├──▶ Bit 7 (0 or 1?)\n                            ├──▶ Bit 6 (0 or 1?)\n                            │      ...\n                            └──▶ Bit 0 (0 or 1?) ──▶ Binary Arithmetic Coder\n```\n\nInstead 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).\n\nTo test `nzip` against real-world observability and audit workloads, I benchmarked it on **7.4 MB of OpenTelemetry JSON spans**.\n\nCrucially, 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.\n\n| Compressor | Compressed Size | Ratio | Bits / Byte | \n|---|---|---|---|\n| `gzip -9` | 791,211 B | 10.65% | 0.85 | \n| `xz -9e` | 670,440 B | 9.02% | 0.72 | \n| `zstd -19 --long` | 667,324 B | 8.98% | 0.72 | \n| `bzip2 -9` | 642,858 B | 8.65% | 0.69 | \n| **`nzip` (H=32, blocks)** | **611,579 B** | **8.23%** | **0.66** | \n\n`nzip` produced archives **20% smaller than `gzip -9`**, **6% smaller than `zstd -19` and `xz -9e`**, and **2% smaller than `bzip2 -9`**.\n\nHere is the most interesting lesson from building this: **if you run the neural network by itself, it actually loses to `gzip`.**\n\nWhen I isolated each component on a 1 MB test slice (`gzip -9` = 97.6 KB), the numbers told a very clear story:\n\n`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).\n\nBy 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.\n\nCompressing 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.\n\n`nzip` bakes operational safety directly into the wire format (`NGR3`) and Go API:\n\nEvery 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.\n\nAudit 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.\n\n`nzip` in CLI or Go\nYou can train a model on your own log format and benchmark it against `gzip -9` in four commands:\n\n```\n# 1. Build the zero-dependency Go binary\ngo build -o nzip ./cmd/nzip\n\n# 2. Train a schema-specific model on a sample of your logs\n./nzip train -data audit-sample.ndjson -out models/audit-v1.bin -model-id 1 -hidden 32 -epochs 6\n\n# 3. Benchmark against gzip -9 on a holdout file it has never seen\n./nzip bench -model models/audit-v1.bin -in holdout.ndjson\n\n# 4. Compress and verify with full CRC32C integrity checks\n./nzip compress -model models/audit-v1.bin -in audit.ndjson -out audit.nzip\n./nzip verify -models ./models -in audit.nzip\n```\n\nAnd if you want to embed it directly inside a Go ingestion service, it implements standard `io.Writer` and `io.Reader` interfaces:\n\n```\n// Streaming compressor: keeps model state warm across small batches\nw, err := stream.NewWriter(dst, registry, \"audit-logs\",\n    stream.WithMode(stream.ModeSession),\n    stream.WithDictionary(dict),\n)\nif err != nil {\n    log.Fatal(err)\n}\nw.Write(batch)\nw.Flush()\n\n// Streaming decompressor: looks up the exact model hash from the stream header\nr, err := stream.NewReader(src, registry)\nif err != nil {\n    log.Fatal(err)\n}\nio.Copy(out, r)\n```\n\nIf 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.\n\nYou 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.\n\nCheck out the full source code, wire format docs, and benchmarks on GitHub: [github.com/radryc/compressor](https://github.com/radryc/compressor)", "url": "https://wpnews.pro/news/how-i-built-a-deterministic-neural-compressor-in-go-to-archive-audit-logs-for", "canonical_source": "https://dev.to/radek_ryckowski_cb3149af5/how-i-built-a-deterministic-neural-compressor-in-go-to-archive-audit-logs-for-years-2j83", "published_at": "2026-11-25 08:38:48+00:00", "updated_at": "2026-11-25 08:42:25.201745+00:00", "lang": "en", "topics": ["ai-infrastructure", "neural-networks", "machine-learning", "developer-tools", "mlops"], "entities": ["nzip", "Go", "OpenTelemetry", "Python", "arm64", "amd64"], "also_reported_by": [], "takeaway": "Predicting each byte as 8 binary decisions instead of a 256-way softmax cuts neural math from 256xH to 8xH, giving a 25x-29x speedup to about 1.2-1.7 MB/s per core, and integer-only inference avoids cross-architecture FMA drift that corrupted 3,869 of 4,096 bytes.", "recommendation": {"advice": "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.", "playbook": "inference-serving", "playbook_url": "https://wpnews.pro/playbooks/inference-serving"}, "alternates": {"html": "https://wpnews.pro/news/how-i-built-a-deterministic-neural-compressor-in-go-to-archive-audit-logs-for", "markdown": "https://wpnews.pro/news/how-i-built-a-deterministic-neural-compressor-in-go-to-archive-audit-logs-for.md", "text": "https://wpnews.pro/news/how-i-built-a-deterministic-neural-compressor-in-go-to-archive-audit-logs-for.txt", "jsonld": "https://wpnews.pro/news/how-i-built-a-deterministic-neural-compressor-in-go-to-archive-audit-logs-for.jsonld"}}