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

  1. Wrapper architecture: Retrieved context → local compressor (Qwen3-8B LoRA trained on bootstrapped synthetic pairs) → compressed sequence → frontier LLM.
  2. Cross-model validation: Evaluated across Claude Sonnet, GPT-4o-mini, and Gemini 2.0 Flash so the compressor cannot exploit single-model quirks.
  3. 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).
  4. Training: LoRA on Qwen3-4B (local MLX) and Qwen3-8B (cloud Tinker), reaching 0.2845 validation 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)

CR=TcompressedTverbose

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:

Equiv=minm∈ℳ(1|𝒯|∑t∈𝒯sm,t)

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:

sm,t(judge)=0.6sjudge+0.4cos(ev,ec)
SymbolMeaning
i ∈ {1, …, n}Example index in dataset of size n
m ∈ MEvaluator model (Claude Sonnet, GPT-4o-mini, Gemini 2.0 Flash)
t ∈ TTask (QA, reasoning, summarization, code)
CR_iToken compression ratio N_c / N_v for example i
Equiv_iWorst-case equivalence score across all evaluator models
s_ASTAST structural similarity for generated code
s_judgeLLM-judge semantic equivalence score

Results (8B Model, Full Test Set)

RunSplit SizeEvaluatedAvg Compression RatioAvg Token ReductionMedian CR
Tinker Qwen3-8B tightened eval2,4972,4970.520747.93%0.5847
RunThresholdJudgeEvaluatedAvg Min-EquivMedian Min-EquivPass Rate (≥0.80)
Tinker Qwen3-8B tightened equiv0.80On1,753 / 2,4970.67910.710221.11%
Evaluator ModelCombined AvgCombined MinJudge-Only AvgJudge-Only Min
claude-sonnet-4-202505140.78680.18420.77840.2500
gpt-4o-mini0.79110.15380.77770.2500
gemini-2.0-flash0.70920.16820.69680.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

  1. Push worst-model equivalence higher while tightening token ratios (especially on multi-hop reasoning).
  2. Fold equivalence directly into the training objective (reward/preference optimization).
  3. 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).