On a weird day I posed the following question:
"Let's have a discussion about efficient communication with LLMs. Increasingly, agentic systems fetch memories via RAG or memory modules at runtime and inject them into the prompt. Effectiveness relies heavily on context window behavior, and we know LLMs degrade as context size grows. While methods like RLMs isolate context into a REPL and decompose recursively, what is the most information-dense representation we can feed an LLM directly at runtime—denser than verbose English, without leaving the distribution the model already understands?"
Here is a cleaner framing of that question and the experiment that followed.
The Problem
In agentic systems, RAG-retrieved memories and growing histories rapidly bloat prompts, and LLMs degrade as context length increases. Is verbose natural language the optimal encoding for machine reasoning, or can we strip its human-centric redundancy—syntactic scaffolding, transitions, explicit connectives—while preserving semantic payload?
Natural language excels at human error-correction and social signaling. LLMs have already internalized those structures during pre-training. That overhead may be unnecessary when the reader is another model (memory to agent).
The Idea
A lightweight semantic compression middleware: a small local model ingests verbose natural language or code (memories, documents, agent histories) and outputs a dense, telegraphic representation—stripped grammar, relational shorthand, abbreviations, and pipe/arrow notation. The result stays inside the LLM's natural-language manifold while shedding ~48% of tokens on average.
For example:
- Verbose text:
Anon is currently working on transitioning from Azure OpenAI to Google's Gemini models through LOL company's custom enterprise endpoints, and he has been implementing OAuth2 authentication along with LiteLLM configurations for corporate proxy integration. - Compressed text (telegraphic):
Anon | migrating Azure-OpenAI → Gemini | LOL-enterprise-endpoints | impl: OAuth2, LiteLLM, corp-proxy
Can LLMs reason equally well over compressed, dense representations as they can over verbose natural language? If yes, we can cut token counts—and thus cost and latency—without sacrificing task performance.
The Exploration
What format should the compressed representation take? I tested three before landing on telegraphic notation:
1. Structured JSON
{"agent": "Anon", "task": "infra_migration", "from": "azure_openai", "to": "gemini", "auth": "oauth2"}
JSON quickly turns into verbose text wearing brackets, quotes, commas, and colons—all of which cost tokens and can even expand short inputs. It also forces complex thoughts into rigid schemas.
2. Semantic Triples
(Anon, working_on, llm_migration)
(llm_migration, from, azure_openai)
(llm_migration, to, gemini)
(llm_migration, involves, [oauth2, litellm])
Unambiguous relationships, but repeating entity names across triples trades natural-language redundancy for structural redundancy.
3. Telegraphic Reduction
Anon | migrating Azure-OpenAI → Gemini | LOL-enterprise-endpoints | impl: OAuth2, LiteLLM, corp-proxy
Closest to technical notes, commit messages, and log files already abundant in pre-training data—and it extends cleanly to code:
# Verbose code
def process_user_data(raw_data, config):
"""Process raw user data by filtering inactive users,
normalizing email addresses, and computing engagement scores."""
filtered = [user for user in raw_data if user.get("active", False)]
for user in filtered:
user["email"] = user["email"].strip().lower()
user["engagement"] = (
user.get("logins", 0) * 0.4
+ user.get("actions", 0) * 0.6
)
return sorted(filtered, key=lambda u: u["engagement"], reverse=True)
# Real compressed output
fn:process_user_data(raw_data, config)->list
filter→active users | normalize email→strip+lower
engagement = logins*0.4 + actions*0.6
sort↓engagement
Methodology
- Wrapper architecture: Retrieved context → local compressor (
Qwen3-8BLoRA trained on bootstrapped synthetic pairs) → compressed sequence → frontier LLM. - Cross-model validation: Evaluated across Claude Sonnet, GPT-4o-mini, and Gemini 2.0 Flash so the compressor cannot exploit single-model quirks.
- Data pipeline: Raw NL and code corpora → ~35k synthetic
(verbose, compressed)pairs via iterative adapter → filtered for token-ratio bounds → 80/10/10 split (published on Hugging Face). - Training: LoRA on
Qwen3-4B(local MLX) andQwen3-8B(cloud Tinker), reaching0.2845validation loss after early stopping. Full code is in Sudhendra/compression-layer.
Metrics
Standard surface-overlap metrics like BLEU and ROUGE are wrong here: measuring word overlap penalizes the compressor for stripping the exact redundancy it is meant to remove. Instead, evaluation measures behavioral equivalence—whether downstream LLMs produce the same task outputs given compressed vs. verbose context.
Compression Ratio (Token-based)
Worst-Model Equivalence Score
Both verbose and compressed contexts are fed to each evaluator model across tasks (QA, reasoning, summarization, code), taking the minimum across models (Claude, GPT, Gemini) so shortcuts that fail on even one model get penalized:
Task-Level & LLM-Judge Scoring
Prose tasks score output embedding cosine similarity; code tasks blend AST structural similarity (0.5) with embedding cosine similarity (0.5). When the LLM judge is enabled, judge score is weighted 0.6 and cosine similarity 0.4:
| Symbol | Meaning |
|---|---|
i ∈ {1, …, n} | Example index in dataset of size n |
m ∈ M | Evaluator model (Claude Sonnet, GPT-4o-mini, Gemini 2.0 Flash) |
t ∈ T | Task (QA, reasoning, summarization, code) |
CR_i | Token compression ratio N_c / N_v for example i |
Equiv_i | Worst-case equivalence score across all evaluator models |
s_AST | AST structural similarity for generated code |
s_judge | LLM-judge semantic equivalence score |
Results (8B Model, Full Test Set)
| Run | Split Size | Evaluated | Avg Compression Ratio | Avg Token Reduction | Median CR |
|---|---|---|---|---|---|
| Tinker Qwen3-8B tightened eval | 2,497 | 2,497 | 0.5207 | 47.93% | 0.5847 |
| Run | Threshold | Judge | Evaluated | Avg Min-Equiv | Median Min-Equiv | Pass Rate (≥0.80) |
|---|---|---|---|---|---|---|
| Tinker Qwen3-8B tightened equiv | 0.80 | On | 1,753 / 2,497 | 0.6791 | 0.7102 | 21.11% |
| Evaluator Model | Combined Avg | Combined Min | Judge-Only Avg | Judge-Only Min |
|---|---|---|---|---|
claude-sonnet-4-20250514 | 0.7868 | 0.1842 | 0.7784 | 0.2500 |
gpt-4o-mini | 0.7911 | 0.1538 | 0.7777 | 0.2500 |
gemini-2.0-flash | 0.7092 | 0.1682 | 0.6968 | 0.2562 |
Notice why the strict ≥0.80 pass rate sits at 21.11% while median worst-model equivalence is 0.7102 (and Claude/GPT individually average ~0.79): taking the minimum across three models pulls the combined score down whenever one model (gemini-2.0-flash at 0.7092) lags on shorthand formatting. Being conservative in scoring keeps optimization honest.
Going Forward
- Push worst-model equivalence higher while tightening token ratios (especially on multi-hop reasoning).
- Fold equivalence directly into the training objective (reward/preference optimization).
- Benchmark end-to-end agent memory middleware integrations on live multi-turn workflows.
Repository: github.com/Sudhendra/compression-layer · Dataset: huggingface.co/datasets/Sudhendra/semantic-compression-sft
Originally published on X (@wthagi).