Skip to main content
Tutorial: Testing Context Cascade Compression (C3)
This article explores whether Context Cascade Compression can turn long documents into compact latent representations that remain useful for real tasks like summarization, rather than just reconstruction.
Last updated: February 3, 2026
Already familiar with C3? Click to jump to the tutorial!





Long context is one of the hardest problems facing modern language models. While performance on short prompts has improved rapidly, most real-world tasks involve inputs that are far larger. Research papers, large codebases, legal documents, and internal knowledge bases routinely exceed a few thousand tokens. As context grows, inference costs increase, latency rises, and model behavior becomes harder to predict. Simply extending context windows alleviates some pressure, but it does not address the underlying inefficiencies of token-based processing.
At the core of the problem is representation. Language models operate over long sequences of discrete text tokens, each carrying very little information on its own. Capturing meaning requires extensive attention over the entire sequence, which scales poorly with length. As a result, long context workloads are expensive and fragile, even with modern attention optimizations.
Context Cascade Compression (C3) proposes a different approach. Instead of passing the full text to a large model, a smaller model first reads the entire document and compresses it into a fixed set of learned latent vectors. A larger model then performs downstream tasks using only these latents as context. The raw text never reaches the decoder. The context budget is explicit, fixed in size, and learned through training rather than managed through heuristics.
This reframes long context handling as a representation problem rather than a window management problem. Rather than deciding what to retrieve or drop, the model learns how to pack information into a compact internal representation. Prior work shows that this compression can be extreme while still supporting accurate reconstruction, suggesting that long documents do not inherently require long token sequences.
The rest of this article examines what this means beyond reconstruction. We first review how C3 works and what the original results demonstrate. We then ask whether these compressed representations remain useful when the task changes, focusing on long document summarization as a concrete and demanding test case.

Table of contents
Table of contentsThe challenge of long contextHow Context Cascade Compression worksResults from the Context Cascade Compression paperThe question: Is reconstruction ability proof of utility? Tutorial Overview: Attempting to train C3 for summarizationStep 1: Generating Our DataStep 2: Training our model Step 3: Evaluating our fine-tuned modelResults Conclusion
The challenge of long context
Long context is the real pressure point for large language models. Most problems that actually matter live far beyond a few thousand tokens. Research papers, large codebases, contracts, internal documentation, and long conversations. As context grows, costs and latencies increase, and model behavior becomes harder to predict. Even with larger context windows, the core issue remains. We are still pushing massive sequences of discrete tokens through systems that scale poorly with length.
Text tokens are an inefficient representation. Each token is a symbolic unit that carries very little information on its own. Meaning only appears after the model expands computation to relate tokens across the sequence. Longer context means more attention operations, more memory pressure, and more room for error. Attention optimizations improve throughput, but they do not change the underlying economics of token-by-token processing.
Retrieval-based systems became the default workaround for this. They reduce input size by selecting text chunks in advance. This works when relevance is local and easy to predict. It breaks when information is distributed across a document, when dependencies span long ranges, or when the task itself depends on details you cannot know in advance. In those cases, retrieval quietly discards information and hopes the loss does not matter.
DeepSeek-OCR made this limitation concrete. Their work showed that long text could be rendered as images, passed through a vision encoder, and reconstructed with far fewer tokens. At around ten times compression, reconstruction accuracy stayed high. This result mattered because it demonstrated that long context does not inherently require long token sequences.
The important takeaway from DeepSeek-OCR was not about images. It was about representation. The vision encoder produced dense latent vectors that carried far more information per unit than text tokens. The optical pipeline worked, but it also introduced layout constraints, resolution issues, and unnecessary complexity for a purely textual problem.
Context Cascade Compression takes that insight and applies it directly to language. A smaller language model reads a long document and compresses it into a fixed number of learned latent vectors. A larger language model then performs downstream tasks using only those latents as context. The raw text never reaches the decoder. The bottleneck is explicit, fixed in size, and learned through training.
This reframes long-context handling as a representation problem rather than a window management problem. Instead of deciding what to drop or stretching context limits, the model learns how to pack information into a compact internal form. The original C3 results show that this compression can be extreme while still preserving nearly all recoverable information.
The rest of this article explores what that means in practice. We first break down how Context Cascade Compression works and what the original results actually show. Then we ask the more important question. Reconstruction is a useful probe, but real workloads are not about copying text. The question is whether these compressed representations remain useful when the task changes. To answer that, we walk through training C3-style summarization models, from data generation through model modification, fine-tuning, and evaluation against strong baseline summaries.
How Context Cascade Compression works
At its core, Context Cascade Compression is a learned text compression system built entirely out of language models. There is no retrieval step and no auxiliary modality. The system consists of two models that play different roles: a compressor and a decoder.
The compressor is a smaller language model. It reads the full input document, which can be thousands of tokens long. This document includes a fixed set of special tokens, called latent query tokens. These tokens are not part of the text. They exist solely to act as information sinks.
During the forward pass, the compressor processes the text and the latent query tokens together using standard self-attention. Nothing about the transformer architecture changes. The latent query tokens attend to the entire document and learn to pull useful information into their hidden states. After the forward pass, all hidden states except those corresponding to the latent query tokens are discarded.
What remains is a small matrix of vectors. If there are N latent tokens and the model hidden size is D, the compressed representation has shape N×D. This is the entire document, compressed into a fixed-size latent buffer.
The decoder is a larger language model. It never sees the original text. Instead, it receives the latent vectors produced by the compressor, along with a task prompt. These latent vectors are treated as if they were ordinary context tokens, even though they do not correspond to any text. The decoder then generates output autoregressively, conditioned only on the latent representation and the prompt.

For reconstruction, the prompt is something like “Repeat the text.” The training objective is straightforward: next-token prediction against the original document. Gradients flow from the decoder through the latent vectors back into the compressor. This forces the compressor to learn how to store everything the decoder might need inside the fixed latent budget.
A key detail is that the bottleneck is strict. The decoder never has access to the raw tokens. There is no cross-attention over the original text, no residual connections, and no retrieval fallback. If information is not captured by the latent tokens, it is gone.
This is what separates C3 from summarization or abstraction. The goal is not to keep meaning while discarding details. The goal is to preserve as much information as possible under a hard capacity constraint. The model is effectively learning to zip and unzip text using continuous vectors rather than symbols.
Another important property is that compression quality degrades predictably. As the number of latent tokens decreases, errors tend to appear first near the end of the document. Earlier sections remain accurate. This behavior reflects the sequential nature of decoding and makes failure modes easier to reason about than uniform corruption.
From a systems perspective, the appeal is obvious. Once a long document is compressed, downstream computation scales with the number of latent tokens rather than the original context length. A document that was tens of thousands of tokens long can be reduced to a few dozen vectors and reused across tasks.
This mechanism is simple, but the implications are large. It suggests that long-context handling does not require ever-expanding windows, only better representations. In the next section, we look at what the original C3 paper actually achieves with this setup and where the limits start to appear.
Results from the Context Cascade Compression paper
The C3 paper evaluates compression using a strict reconstruction task. The decoder is prompted to reproduce the original input text exactly, using only the compressed latent representation. This provides a direct measure of how much information survives the compression bottleneck.
On the Fox benchmark, C3 significantly outperforms optical compression methods such as DeepSeek-OCR across all tested settings. At moderate compression levels, where DeepSeek-OCR peaks at around ten times compression, C3 achieves near-perfect reconstruction. As compression increases, the gap widens sharply. At compression ratios approaching twenty times, DeepSeek-OCR’s precision drops to around sixty percent, while C3 maintains reconstruction accuracy above ninety-eight percent. Even at extreme settings approaching 40x compression, C3 retains over 93% precision.
These results establish that direct text-to-latent compression preserves substantially more information per token than optical pipelines. By avoiding the image rendering step, C3 eliminates resolution limits, layout artifacts, and visual encoder bottlenecks that constrain OCR-based approaches.
Beyond benchmark numbers, the paper also qualitatively probes failure modes. In Figure 4, the authors test C3 on unconventional inputs, including text containing random, non-semantic characters and structurally disordered passages in both English and Chinese. Even under these conditions, the model can reconstruct the input nearly verbatim at extreme compression levels. This suggests that C3 is learning a general-purpose compression mechanism rather than relying purely on linguistic regularities.

When reconstruction does fail, the errors follow a consistent pattern. Fidelity is preserved at the beginning of the document, with mistakes accumulating toward the end. This sequential degradation contrasts with optical compression methods, which exhibit more uniform corruption as compression increases. The authors draw an analogy to human memory, where information decays progressively rather than all at once.
Together, these results show that C3 is not just an incremental improvement over optical compression. It demonstrates a fundamentally more efficient representation for long texts, while also exhibiting predictable, interpretable failure behavior under extreme compression pressure.
The question: Is reconstruction ability proof of utility?
Reconstructing the input text is a useful stress test, but it is not a real workload. It tells us whether information survives compression, not whether that information is usable. A system that can perfectly repeat text may still fail when asked to reason, summarize, or transform that text in meaningful ways.
The C3 paper explicitly addresses this limitation. The decoder is only evaluated on reconstruction, using a fixed prompt and a single objective. This makes sense for establishing an upper bound on information preservation, but it leaves an open question. What happens when the task changes?
In practical settings, compressed context is rarely consumed for verbatim reproduction. The goal is usually to extract structure, synthesize ideas, answer questions, or produce summaries. These tasks place different pressures on the latent representation. Some details become irrelevant, while others become more important. The model must decide what to emphasize without access to the original text.
This raises a deeper concern. A latent space trained only for lossless reconstruction may encode information optimally for copying but be brittle for downstream use. If the latent tokens act like a compressed archive, the decoder might rely on patterns that only work when the goal is exact reproduction. There is no guarantee that the same representation supports abstraction or reasoning.
At the same time, reconstruction gives us a strong starting point. If information is not present in the latent tokens, no downstream task can recover it. The question is whether the representation learned for reconstruction can be adapted, or extended, to support other objectives without collapsing.
This is the gap this article focuses on. Rather than proposing a new compression architecture, we take C3 as a foundation and ask whether it can be trained to do something useful beyond repeating its input. In the sections that follow, we treat summarization as a concrete test case and walk through how to generate data, modify the latent setup, fine-tune the model, and evaluate whether compressed context remains effective when the task changes.
Tutorial Overview: Attempting to train C3 for summarization
This tutorial focuses on a single downstream task: document summarization. Summarization is a strong stress test for compressed context because it is explicitly lossy, global, and sensitive to structure. A good summary depends on information distributed across an entire document, not just the opening sections or a small set of retrieved chunks.
The objective is straightforward. A long document is compressed into a fixed number of latent tokens using a C3-style encoder. A decoder then generates a summary using only those latent tokens as context. The original text is never provided to the decoder.
This setup forces the latent representation to carry meaningful structure. Definitions, claims, and conclusions must survive compression in a form that remains usable for generation. If the latent space only supports verbatim reconstruction, summarization quality should degrade quickly.
The tutorial is organized into four parts. The first part covers data generation. Long-form documents are paired with high-quality summaries. Context length matters here. Short inputs allow the model to rely on superficial patterns rather than learning to compress global structure. The second part covers model adaptation. The latent token embedding is expanded to increase capacity, and the training loop is modified to support multiple objectives. The core C3 architecture stays intact, but the latent space is trained under different pressures.
The third part covers fine-tuning. Reconstruction and summarization objectives are combined so that information retention and task relevance are learned jointly rather than in isolation. The final part covers evaluation. Summaries generated from compressed context are compared against summaries produced by a base model operating on the full text. The discussion focuses on which metrics are informative in this setting and where automated scores fall short.
The following sections walk through each step in detail, keeping the focus on how compressed latent representations behave under real downstream tasks.
Step 1: Generating Our Data
💡
Before training a C3-style model for summarization, the first requirement is a dataset that actually stresses long-context compression. The model needs to see full documents that are long enough to exceed what a normal decoder can comfortably handle, paired with summaries that depend on information spread across the entire text.
This step is split into two simple scripts. The first script collects raw long-form documents. The second script turns those documents into summary pairs that can be used for training. Keeping these responsibilities separate makes the pipeline easier to inspect, rerun, and modify later.
The raw data script downloads research papers and extracts clean text from them. Each paper is stored as a standalone document with minimal preprocessing. The goal at this stage is not to optimize formatting or remove every artifact, but to preserve as much of the original structure and content as possible. Length and coverage matter more than polish.
Once the raw papers are collected, the second script generates summaries. It loads each document, feeds it to a strong reference language model (Qwen-3 3B, which is the same LLM used as the decoder model in C3), and prompts the model to produce a concise summary. These summaries serve as supervision for the decoder. They are consistent, reasonably high quality, and cheap to generate at scale.
Below is the script that fetches and processes the raw papers.
"""Build training dataset from AI arxiv papers for context compression training.Downloads papers, extracts text (~10 pages per sample), creates JSON dataset.Also creates a validation set of recent papers (last 2 months).Optimized for speed with parallel downloads and exponential backoff."""import osimport jsonimport timeimport arxivimport fitz # PyMuPDFimport tempfileimport randomimport threadingfrom pathlib import Pathfrom datetime import datetime, timedeltafrom concurrent.futures import ThreadPoolExecutor, as_completedfrom dataclasses import dataclassfrom typing import Optional, List, Tuple, Set# ConfigNUM_TRAIN_SAMPLES = 5000NUM_VAL_SAMPLES = 50PAGES_PER_SAMPLE = 10TRAIN_OUTPUT_PATH = "/home/cloud/c3/C3-Context-Cascade-Compression/dataset/arxiv_ai_papers.json"VAL_OUTPUT_PATH = "/home/cloud/c3/C3-Context-Cascade-Compression/dataset/arxiv_ai_papers_val.json"# Parallel processing configMAX_WORKERS = 10 # Number of parallel download threadsMAX_RETRIES = 3 # Retries per paperBASE_DELAY = 0.5 # Base delay between requests (seconds)MAX_DELAY = 30 # Max backoff delay (seconds)# AI/ML arxiv categoriesAI_CATEGORIES = ["cs.LG", # Machine Learning"cs.CL", # Computation and Language (NLP)"cs.CV", # Computer Vision"cs.AI", # Artificial Intelligence"stat.ML", # Machine Learning (stats)]# Thread-safe rate limiterclass RateLimiter:"""Token bucket rate limiter with exponential backoff"""def __init__(self, requests_per_second: float = 3.0):self.min_interval = 1.0 / requests_per_secondself.lock = threading.Lock()self.last_request = 0.0self.backoff_until = 0.0self.consecutive_errors = 0def wait(self):"""Wait for rate limit, respecting backoff"""with self.lock:now = time.time()# Check backoffif now < self.backoff_until:sleep_time = self.backoff_until - nowtime.sleep(sleep_time)now = time.time()# Check rate limitelapsed = now - self.last_requestif elapsed < self.min_interval:time.sleep(self.min_interval - elapsed)self.last_request = time.time()def report_success(self):"""Reset backoff on success"""with self.lock:self.consecutive_errors = 0def report_error(self):"""Increase backoff on error"""with self.lock:self.consecutive_errors += 1# Exponential backoff with jitterdelay = min(BASE_DELAY * (2 ** self.consecutive_errors), MAX_DELAY)jitter = random.uniform(0, delay * 0.1)self.backoff_until = time.time() + delay + jitterreturn delay + jitter# Global rate limiterrate_limiter = RateLimiter(requests_per_second=3.0)def search_arxiv_papers(num_papers=150, recent_only=False, days_back=60):"""Search for AI papers on arxivArgs:num_papers: Number of papers to fetchrecent_only: If True, only fetch papers from last `days_back` daysdays_back: Number of days to look back for recent papers"""print(f"Searching arxiv for AI papers...")# Build query for AI categoriescat_query = " OR ".join([f"cat:{cat}" for cat in AI_CATEGORIES])# Add date filter for recent papersif recent_only:cutoff_date = datetime.now() - timedelta(days=days_back)date_str = cutoff_date.strftime("%Y%m%d")query = f"({cat_query}) AND submittedDate:[{date_str} TO 99991231]"print(f" Filtering for papers after {cutoff_date.strftime('%Y-%m-%d')}")else:query = cat_queryclient = arxiv.Client()search = arxiv.Search(query=query,max_results=num_papers,sort_by=arxiv.SortCriterion.SubmittedDate,sort_order=arxiv.SortOrder.Descending,)papers = list(client.results(search))print(f"Found {len(papers)} papers")return papersdef download_and_extract_pdf(paper, max_pages=PAGES_PER_SAMPLE) -> Optional[str]:"""Download paper PDF and extract text from first N pages with retries"""tmp_path = Nonefor attempt in range(MAX_RETRIES):try:# Wait for rate limitrate_limiter.wait()with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as tmp:tmp_path = tmp.name# Download PDFpaper.download_pdf(filename=tmp_path)# Extract textdoc = fitz.open(tmp_path)text_parts = []pages_to_read = min(max_pages, len(doc))for page_num in range(pages_to_read):page = doc[page_num]text = page.get_text()if text.strip():text_parts.append(text)doc.close()# Cleanupif tmp_path and os.path.exists(tmp_path):os.unlink(tmp_path)rate_limiter.report_success()return "\n\n".join(text_parts)except Exception as e:backoff = rate_limiter.report_error()error_msg = str(e).lower()# Check if rate limitedis_rate_limit = "429" in error_msg or "rate" in error_msg or "too many" in error_msgif attempt < MAX_RETRIES - 1:if is_rate_limit:print(f" Rate limited, backing off {backoff:.1f}s (attempt {attempt + 1}/{MAX_RETRIES})")time.sleep(backoff)else:print(f" Error processing {paper.title[:50]}...: {e}")# Cleanup on errorif tmp_path and os.path.exists(tmp_path):try:os.unlink(tmp_path)except:passtmp_path = Nonereturn Nonedef clean_text(text):"""Clean extracted text"""if not text:return None# Remove excessive whitespacelines = text.split("\n")cleaned_lines = []for line in lines:line = line.strip()if line:cleaned_lines.append(line)text = "\n".join(cleaned_lines)# Skip if too short (probably extraction failed)if len(text) < 5000:return None# Truncate if too long (keep ~10 pages worth, roughly 30k chars)if len(text) > 35000:text = text[:35000]# Try to end at a sentencelast_period = text.rfind(".")if last_period > 30000:text = text[:last_period + 1]return textdef create_sample(text):"""Create a training sample in C3 format"""return {"image": "","conversations": [{"from": "context","value": text},{"from": "human","value": "<image>\nRepeat the text: "},{"from": "gpt","value": text}]}def process_single_paper(args: Tuple[int, any, str]) -> Tuple[Optional[dict], str, int]:"""Process a single paper - designed for parallel execution"""idx, paper, dataset_name = argstry:text = download_and_extract_pdf(paper)text = clean_text(text)if text:sample = create_sample(text)return (sample, paper.entry_id, idx)return (None, paper.entry_id, idx)except Exception as e:print(f" [{dataset_name}] Error on paper {idx}: {e}")return (None, paper.entry_id, idx)def process_papers(papers, num_samples, dataset_name):"""Process papers in parallel and return samples"""samples = []paper_ids = set()lock = threading.Lock()completed = [0] # Use list for mutability in closuresuccess = [0]print(f"[{dataset_name}] Processing {len(papers)} papers with {MAX_WORKERS} workers...")start_time = time.time()# Prepare work itemswork_items = [(i, paper, dataset_name) for i, paper in enumerate(papers)]with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:# Submit all tasksfutures = {executor.submit(process_single_paper, item): item for item in work_items}for future in as_completed(futures):# Check if we have enough sampleswith lock:if len(samples) >= num_samples:# Cancel remaining futuresfor f in futures:f.cancel()breaktry:sample, paper_id, idx = future.result()with lock:completed[0] += 1paper_ids.add(paper_id)if sample and len(samples) < num_samples:samples.append(sample)success[0] += 1text_len = len(sample["conversations"][0]["value"])elapsed = time.time() - start_timerate = success[0] / elapsed if elapsed > 0 else 0print(f"[{dataset_name}] {success[0]}/{num_samples} samples "f"({completed[0]} processed, {rate:.1f}/sec, {text_len} chars)")except Exception as e:with lock:completed[0] += 1print(f" [{dataset_name}] Future error: {e}")elapsed = time.time() - start_timeprint(f"[{dataset_name}] Completed: {len(samples)} samples from {completed[0]} papers in {elapsed:.1f}s")print(f"[{dataset_name}] Rate: {len(samples)/elapsed:.2f} samples/sec")return samples, paper_idsdef save_dataset(samples, output_path, name):"""Save dataset and print stats"""print(f"\nSaving {len(samples)} {name} samples to {output_path}")os.makedirs(os.path.dirname(output_path), exist_ok=True)with open(output_path, "w", encoding="utf-8") as f:json.dump(samples, f, indent=2, ensure_ascii=False)total_chars = sum(len(s["conversations"][0]["value"]) for s in samples)avg_chars = total_chars / len(samples) if samples else 0print(f" {name} samples: {len(samples)}")print(f" Total chars: {total_chars:,}")print(f" Avg chars/sample: {avg_chars:,.0f}")def main():print("=" * 60)print("Building Arxiv AI Papers Dataset (Parallelized)")print(f"Training set: {NUM_TRAIN_SAMPLES} samples")print(f"Validation set: {NUM_VAL_SAMPLES} samples (recent papers, last 2 months)")print(f"Pages per sample: ~{PAGES_PER_SAMPLE}")print(f"Parallel workers: {MAX_WORKERS}")print(f"Max retries: {MAX_RETRIES}")print("=" * 60)total_start = time.time()# ===== VALIDATION SET (recent papers from last 2 months) =====print("\n" + "=" * 60)print("STEP 1: Building VALIDATION set (recent papers)")print("=" * 60)val_papers = search_arxiv_papers(num_papers=NUM_VAL_SAMPLES + 30, recent_only=True, days_back=60)val_samples, val_paper_ids = process_papers(val_papers, NUM_VAL_SAMPLES, "VAL")save_dataset(val_samples, VAL_OUTPUT_PATH, "Validation")# ===== TRAINING SET (older papers, excluding validation papers) =====print("\n" + "=" * 60)print("STEP 2: Building TRAINING set (excluding validation papers)")print("=" * 60)# Get more papers for training (older ones)train_papers = search_arxiv_papers(num_papers=NUM_TRAIN_SAMPLES + 500, recent_only=False)# Filter out papers that are in validation settrain_papers = [p for p in train_papers if p.entry_id not in val_paper_ids]print(f"Filtered to {len(train_papers)} papers (excluded {len(val_paper_ids)} validation papers)")random.shuffle(train_papers)train_samples, _ = process_papers(train_papers, NUM_TRAIN_SAMPLES, "TRAIN")save_dataset(train_samples, TRAIN_OUTPUT_PATH, "Training")# ===== FINAL SUMMARY =====total_elapsed = time.time() - total_starttotal_samples = len(train_samples) + len(val_samples)print("\n" + "=" * 60)print("DONE!")print("=" * 60)print(f" Training set: {len(train_samples)} samples -> {TRAIN_OUTPUT_PATH}")print(f" Validation set: {len(val_samples)} samples -> {VAL_OUTPUT_PATH}")print(f" Total time: {total_elapsed:.1f}s ({total_elapsed/60:.1f} min)")print(f" Overall rate: {total_samples/total_elapsed:.2f} samples/sec")print("=" * 60)if __name__ == "__main__":main()
After the papers are downloaded and converted to text, the summarization script is run to create the training pairs.
#!/usr/bin/env python3"""Generate paper summaries using Ollama's qwen2.5:3b model.Takes first 28k tokens from each paper and generates a summary."""import jsonimport asyncioimport aiohttpimport tiktokenimport timefrom pathlib import Pathfrom typing import Optional# ConfigDATASET_DIR = Path("/home/cloud/c3/C3-Context-Cascade-Compression/dataset")DATASETS = [("arxiv_ai_papers_val.json", "arxiv_summaries_val.json", "VAL"),("arxiv_ai_papers.json", "arxiv_summaries.json", "TRAIN"),]OLLAMA_URL = "http://localhost:11434/api/generate"MODEL = "qwen2.5:3b"MAX_TOKENS = 28000MAX_CONCURRENT = 4 # Ollama default OLLAMA_NUM_PARALLEL is 1, increase if you set it higherSAVE_EVERY = 10enc = tiktoken.get_encoding("cl100k_base")def truncate_to_tokens(text: str, max_tokens: int) -> str:"""Truncate text to max_tokens."""tokens = enc.encode(text, disallowed_special=())if len(tokens) <= max_tokens:return textreturn enc.decode(tokens[:max_tokens])async def get_summary(session: aiohttp.ClientSession,semaphore: asyncio.Semaphore,paper_text: str,idx: int,total: int,results: dict,counter: dict,start_time: float,name: str,) -> None:"""Get summary with semaphore limiting concurrency."""print(f"[{name}] {idx}: waiting for semaphore...", flush=True)async with semaphore:print(f"[{name}] {idx}: got semaphore, sending request...", flush=True)prompt = f"""Summarize the paper:{paper_text}Summary:"""payload = {"model": MODEL,"prompt": prompt,"stream": False,"options": {"num_ctx": 32768,"temperature": 0.3,}}try:print(f"[{name}] {idx}: posting to {OLLAMA_URL}...", flush=True)async with session.post(OLLAMA_URL, json=payload) as resp:print(f"[{name}] {idx}: got response status {resp.status}", flush=True)if resp.status == 200:print(f"[{name}] {idx}: reading json...", flush=True)data = await resp.json()print(f"[{name}] {idx}: got json, extracting response...", flush=True)summary = data.get("response", "").strip()if summary:results[idx] = (paper_text, summary)counter["done"] += 1elapsed = time.time() - start_timerate = counter["done"] / elapsed if elapsed > 0 else 0print(f"[{name}] {counter['done']}/{total} done ({rate:.2f}/sec) - {len(summary)} chars", flush=True)else:print(f"[{name}] {idx}: empty response, keys: {list(data.keys())}", flush=True)else:text = await resp.text()print(f"[{name}] {idx}: HTTP {resp.status}: {text[:200]}", flush=True)except Exception as e:import tracebackprint(f"[{name}] {idx}: Error {e}", flush=True)traceback.print_exc()def extract_context(paper: dict) -> str:"""Extract context from paper dict."""for conv in paper.get("conversations", []):if conv.get("from") == "context":return conv.get("value", "")return ""def create_result(context: str, summary: str) -> dict:"""Create output in training format."""return {"image": "","conversations": [{"from": "context", "value": context},{"from": "human", "value": "<image>\nSummarize the paper: "},{"from": "gpt", "value": summary}]}async def process_dataset(input_path: Path,output_path: Path,name: str,session: aiohttp.ClientSession) -> tuple[int, int]:"""Process a single dataset."""print(f"\n{'='*60}", flush=True)print(f"[{name}] Processing {input_path.name}", flush=True)print(f"{'='*60}", flush=True)if not input_path.exists():print(f"[{name}] Input file not found, skipping")return 0, 0with open(input_path, "r") as f:papers = json.load(f)print(f"[{name}] Found {len(papers)} papers", flush=True)# Prepare all contextswork_items = []for i, paper in enumerate(papers):context = extract_context(paper)if context:truncated = truncate_to_tokens(context, MAX_TOKENS)work_items.append((i, truncated))print(f"[{name}] Prepared {len(work_items)} papers, max {MAX_CONCURRENT} concurrent", flush=True)print(f"[{name}] Creating tasks...", flush=True)results = {}counter = {"done": 0}start_time = time.time()semaphore = asyncio.Semaphore(MAX_CONCURRENT)# Create all taskstasks = [get_summary(session, semaphore, text, idx, len(work_items), results, counter, start_time, name)for idx, text in work_items]# Run with periodic savessave_task = asyncio.create_task(periodic_save(results, output_path, name))await asyncio.gather(*tasks)save_task.cancel()# Final savefinal_results = [create_result(ctx, summ) for idx, (ctx, summ) in sorted(results.items())]with open(output_path, "w") as f:json.dump(final_results, f, indent=2)elapsed = time.time() - start_timeprint(f"[{name}] Done: {len(results)}/{len(work_items)} in {elapsed:.1f}s")return len(results), len(work_items)async def periodic_save(results: dict, output_path: Path, name: str):"""Save results periodically."""while True:await asyncio.sleep(30)if results:final_results = [create_result(ctx, summ) for idx, (ctx, summ) in sorted(results.items())]with open(output_path, "w") as f:json.dump(final_results, f, indent=2)print(f"[{name}] Saved {len(results)} results")async def main():print("=" * 60)print("Generate Summaries")print(f"Model: {MODEL}, Max concurrent: {MAX_CONCURRENT}")print("=" * 60)total_start = time.time()total_success = 0total_attempted = 0timeout = aiohttp.ClientTimeout(total=600)async with aiohttp.ClientSession(timeout=timeout) as session:for input_file, output_file, name in DATASETS:input_path = DATASET_DIR / input_fileoutput_path = DATASET_DIR / output_filesuccess, attempted = await process_dataset(input_path, output_path, name, session)total_success += successtotal_attempted += attemptedtotal_time = time.time() - total_startprint(f"\nDone! {total_success}/{total_attempted} in {total_time:.1f}s")if __name__ == "__main__":asyncio.run(main())
The output of these scripts is a dataset in which each example consists of a long document and its corresponding summary. No task-specific formatting is applied yet. That happens later, closer to the training loop. At this stage, the focus is on building a clean, reproducible source of long-context supervision.
With raw documents and summaries in place, the next step is to adapt the C3 training setup so the latent tokens are trained to support summarization rather than pure reconstruction.
Step 2: Training our model
With the dataset prepared, the next step is training the model. This stage builds directly on top of the original C3 setup rather than starting from scratch. The encoder and decoder are initialized from the authors’ released pre-trained checkpoints, which were already trained on simple reconstruction tasks. This provides a strong starting point where the latent tokens are known to preserve information, even before any summarization objective is introduced.
The model uses two pre-trained Qwen 2.5 checkpoints exactly as provided. A Qwen 2.5 1.5B model serves as the encoder, and a Qwen 2.5 3B model serves as the decoder. These checkpoints have already learned to compress and reconstruct text through a small latent bottleneck. Training in this tutorial continues from that point rather than relearning compression from raw language modeling.
One key change from the original configuration is the size of the latent space. The number of latent tokens is expanded from 32 to 160. These increases representational capacity while keeping the overall context length fixed. The expanded latent space gives the model more room to store structure that is useful for summarization rather than just verbatim reconstruction.
Training runs on a single NVIDIA H100 GPU using DeepSpeed with ZeRO Stage 3 enabled. This enables handling long input sequences, larger latent capacity, and mixed objectives within a single training run. All experiments use Weights & Biases for logging, which provides visibility into loss curves, objective balance, and overall training stability.
To keep the tutorial focused, implementation details are omitted. Reproducing the setup only requires cloning the repository and running a single training command. The command configures the encoder and decoder checkpoints, latent capacity, objective mixing, and logging.
deepspeed /home/cloud/c3/C3-Context-Cascade-Compression/C3-master/C3/train/train_160.py \--deepspeed /home/cloud/c3/C3-Context-Cascade-Compression/C3-master/zero_config/zero3.json \--model_name_or_path liufanfanlff/C3-Context-Cascade-Compression \--use_im_start_end True \--bf16 True \--gradient_accumulation_steps 64 \--save_strategy steps \--save_steps 10 \--save_total_limit 1 \--weight_decay 0. \--warmup_ratio 0.01 \--lr_scheduler_type cosine \--tf32 True \--model_max_length 30000 \--gradient_checkpointing True \--dataloader_num_workers 8 \--report_to none \--per_device_train_batch_size 1 \--num_train_epochs 1 \--learning_rate 1e-5 \--output_dir /home/cloud/c3/C3-Context-Cascade-Compression/output_dir \--run_name context_32 \--logging_steps 10
Because training starts from models that already know how to reconstruct from compressed context, fine-tuning can focus on reshaping the latent representation for summarization rather than teaching compression from scratch.
The next step evaluates how well this compressed representation supports summarization compared to a baseline model with access to the full document text.
Step 3: Evaluating our fine-tuned model
After training, the final step is to evaluate how well the fine-tuned model performs summarization when operating solely on compressed context. The key question at this stage is not just whether the model can generate fluent summaries, but whether the latent tokens actually preserve and organize the important information from the original document.
Evaluation is done using a standalone script that loads a trained checkpoint and runs it over a held-out validation set. Each example consists of a long document, a summarization prompt, and a ground truth summary. During inference, the model only sees the compressed latent representation produced by the encoder. The full document text is never passed directly to the decoder.
The evaluation script is designed to support multiple complementary metrics. Standard automated metrics like ROUGE capture surface-level overlap with the reference summaries. BERTScore provides a more semantic comparison, measuring similarity in embedding space rather than exact wording. In addition to these, simple compression and coverage metrics track length ratios and word overlap, which help identify degenerate behaviors like overly short or overly verbose outputs.
To supplement automated metrics, the script also supports LLM based evaluation using LiteLLM. In this mode, a separate language model scores each generated summary on how well it captures the key information from the ground truth. While this type of evaluation is slower and more expensive, it provides a useful signal for judging global coherence and factual coverage that is difficult to capture with n-gram metrics alone.
All evaluation results are logged using the Weave evaluation framework. This makes it easy to inspect individual examples, compare runs, and view aggregate statistics in a single interface. Each example records the input context, prompt, generated output, and all computed scores, which is especially helpful for qualitative analysis.
Running evaluation only requires pointing the script at a trained model checkpoint and a validation dataset. Optional flags control how many samples are evaluated and which scorers are enabled. This makes it easy to trade off evaluation cost against depth of analysis, depending on the stage of experimentation.
At this point, the pipeline is complete. Long documents are compressed into latent tokens, summaries are generated from that compressed representation, and evaluation provides both quantitative and qualitative insight into how well the latent space supports downstream summarization.
Here's the code:
#!/usr/bin/env python3"""Evaluate trained C3 model on validation set using weave evaluation framework.Supports multiple scorers: ROUGE, BERTScore, Claude, compression, coverage."""import jsonimport argparseimport torchfrom time import sleepfrom typing import Dictfrom transformers import AutoModel, AutoTokenizerfrom litellm import completionimport weavefrom weave import EvaluationLogger# Optional imports - graceful fallbacktry:import bert_scoreBERT_SCORE_AVAILABLE = Trueexcept ImportError:BERT_SCORE_AVAILABLE = Falseprint("Warning: bert_score not installed, skipping BERTScore")try:from rouge_score.rouge_scorer import RougeScorerROUGE_AVAILABLE = Trueexcept ImportError:ROUGE_AVAILABLE = Falseprint("Warning: rouge_score not installed, skipping ROUGE")# ========== SCORERS ==========def bert_scorer(gt_text: str, model_output: str) -> Dict[str, float]:"""Calculate BERTScore."""if not BERT_SCORE_AVAILABLE or not model_output:return {'bert_score': 0.0}try:P, R, F1 = bert_score.score([model_output],[gt_text],lang='en',model_type='microsoft/deberta-xlarge-mnli')return {'bert_score': float(F1.mean())}except Exception as e:print(f"Error calculating BERTScore: {e}")return {'bert_score': 0.0}def llm_scorer(gt_text: str, model_output: str) -> Dict[str, float]:"""Evaluate using LLM via LiteLLM."""if not model_output:return {'llm_score': 0.0}prompt = f'''Rate how well this generated text captures the key information from the ground truth on a scale from 1-5:1: Poor - Missing most key information or seriously misrepresenting the content2: Fair - Captures some information but misses crucial elements3: Good - Captures most key points but has some gaps or inaccuracies4: Very Good - Accurately captures nearly all key information with minor omissions5: Excellent - Perfectly captures all key information and maintains accuracyGround Truth:{gt_text}Generated:{model_output}Provide your rating as a JSON object: {{"score": <integer 1-5>}}'''try:response = completion(model="gpt-5",messages=[{"role": "user", "content": prompt}],)result = response["choices"][0]["message"]["content"].strip()score = json.loads(result)["score"]sleep(1) # Rate limitingreturn {'llm_score': float(score)}except Exception as e:print(f"Error in LLM evaluation: {e}")return {'llm_score': 0.0}def rouge_scorer_fn(gt_text: str, model_output: str) -> Dict[str, float]:"""Calculate ROUGE scores."""if not ROUGE_AVAILABLE or not model_output:return {'rouge1_f': 0.0, 'rouge2_f': 0.0, 'rougeL_f': 0.0}try:scorer = RougeScorer(['rouge1', 'rouge2', 'rougeL'], use_stemmer=True)scores = scorer.score(gt_text, model_output)return {'rouge1_f': float(scores['rouge1'].fmeasure),'rouge2_f': float(scores['rouge2'].fmeasure),'rougeL_f': float(scores['rougeL'].fmeasure)}except Exception as e:print(f"Error calculating ROUGE: {e}")return {'rouge1_f': 0.0, 'rouge2_f': 0.0, 'rougeL_f': 0.0}def compression_scorer(gt_text: str, model_output: str) -> Dict[str, float]:"""Calculate compression/length ratio."""if not model_output:return {'compression_ratio': 0.0, 'length_ratio': 0.0}gt_words = len(gt_text.split())gen_words = len(model_output.split())compression_ratio = min(gt_words, gen_words) / max(gt_words, gen_words) if max(gt_words, gen_words) > 0 else 0length_ratio = gen_words / gt_words if gt_words > 0 else 0return {'compression_ratio': float(compression_ratio),'length_ratio': float(length_ratio)}def coverage_scorer(gt_text: str, model_output: str) -> Dict[str, float]:"""Calculate word overlap (Jaccard similarity)."""if not model_output:return {'coverage_score': 0.0}gt_words = set(gt_text.lower().split())gen_words = set(model_output.lower().split())intersection = len(gt_words.intersection(gen_words))union = len(gt_words.union(gen_words))return {'coverage_score': float(intersection / union) if union > 0 else 0.0}# ========== MODEL INFERENCE ==========class C3Model:"""Wrapper for C3 model inference."""def __init__(self, model_path: str):print(f"Loading model from: {model_path}")self.tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)self.model = AutoModel.from_pretrained(model_path,trust_remote_code=True,torch_dtype=torch.bfloat16,).eval().cuda()print(f"Model loaded. Latent tokens: {self.model.config.latent_token_len}")def generate(self, context: str, prompt: str) -> str:"""Generate output from context and prompt."""try:output = self.model.chat(self.tokenizer, context, prompt)return outputexcept Exception as e:print(f"Error during generation: {e}")return ""# ========== DATASET LOADING ==========def load_val_dataset(path: str, max_samples: int = None):"""Load validation dataset."""with open(path, 'r') as f:data = json.load(f)if max_samples:data = data[:max_samples]samples = []for item in data:context = ""prompt = ""gt_output = ""for conv in item.get("conversations", []):if conv["from"] == "context":context = conv["value"]elif conv["from"] == "human":# Extract just the prompt part (after <image>\n)prompt = conv["value"].replace("<image>\n", "").strip()elif conv["from"] == "gpt":gt_output = conv["value"]if context and gt_output:samples.append({"context": context,"prompt": prompt or "Summarize the paper: ","ground_truth": gt_output})return samples# ========== MAIN EVALUATION ==========def main():parser = argparse.ArgumentParser(description="Evaluate C3 model on validation set")parser.add_argument("--model_path", type=str, required=True,help="Path to trained model checkpoint")parser.add_argument("--val_path", type=str, default=None,help="Path to validation dataset (auto-selected based on task if not specified)")parser.add_argument("--task", type=str, default="summarize", choices=["summarize", "repeat"],help="Task to evaluate: 'summarize' or 'repeat'")parser.add_argument("--max_samples", type=int, default=None,help="Max samples to evaluate (default: all)")parser.add_argument("--max_context_chars", type=int, default=50000,help="Max context characters to use")parser.add_argument("--pct", type=int, default=100,help="Percentage of original context to use (1-100)")parser.add_argument("--weave_project", type=str, default="c3-evaluation",help="Weave project name")parser.add_argument("--use_llm", action="store_true", default=True,help="Use LLM scorer via LiteLLM (gpt-5)")parser.add_argument("--use_bert", action="store_true", default=True,help="Use BERTScore (slow)")args = parser.parse_args()# Auto-select validation path based on task if not specifiedif args.val_path is None:if args.task == "repeat":args.val_path = "/home/cloud/c3/C3-Context-Cascade-Compression/dataset/arxiv_ai_papers_val.json"else:args.val_path = "/home/cloud/c3/C3-Context-Cascade-Compression/dataset/arxiv_summaries_val.json"# Initialize weaveweave.init(args.weave_project)# Load modelmodel = C3Model(args.model_path)# Load datasetprint(f"\nLoading validation data from: {args.val_path}")samples = load_val_dataset(args.val_path, args.max_samples)print(f"Loaded {len(samples)} samples")# Create evaluation loggermodel_name = args.model_path.split("/")[-1]ev = EvaluationLogger(name=f"c3-{args.task}-eval", model=model_name)print(f"\n{'='*60}")print(f"Starting evaluation: {len(samples)} samples")print(f"Task: {args.task}")print(f"Context percentage: {args.pct}%")print(f"{'='*60}\n")for i, sample in enumerate(samples):context = sample["context"][:args.max_context_chars]# Apply percentage truncation if specifiedif args.pct < 100:truncate_len = int(len(context) * args.pct / 100)context = context[:truncate_len]# Set prompt and ground truth based on taskif args.task == "repeat":prompt = "Repeat the text: "gt = context # For repeat task, ground truth is the input contextelse:prompt = sample["prompt"]gt = sample["ground_truth"]print(f"[{i+1}/{len(samples)}] Running inference (context: {len(context)} chars, {args.pct}%)...")# Generate outputoutput = model.generate(context, prompt)# Calculate scoresscores = {}# Always run these (fast)scores.update(rouge_scorer_fn(gt, output))scores.update(coverage_scorer(gt, output))# Task-specific scorersif args.task == "repeat":# For repeat task, just use basic metrics (ROUGE + coverage)passelse:# For summarization, add more scorersscores.update(compression_scorer(gt, output))if args.use_bert and BERT_SCORE_AVAILABLE:scores.update(bert_scorer(gt, output))if args.use_llm:scores.update(llm_scorer(gt, output))print(f" ROUGE-L: {scores.get('rougeL_f', 0):.3f}, Coverage: {scores.get('coverage_score', 0):.3f}")# Log to weaveev.log_example(inputs={"context": context,"prompt": prompt,"grount_truth": gt},output=output,scores=scores,)# Finish and summarizeev.log_summary()print(f"\n{'='*60}")print(f"Evaluation complete!")print(f"Results: {ev.ui_url}")print(f"{'='*60}")if __name__ == "__main__":main()
After running the eval, we can see the results inside Weave:

Results
In practice, the summarization quality fell short of what I had hoped for. This does not imply that C3 style context compression is fundamentally incompatible with summarization or other downstream tasks. Instead, the results point to a familiar bottleneck. Insufficient scale.
Analysis of the evaluation traces in Weave shows that the model has learned the form of a good paper summary. Generated outputs closely mirror the structure and style of the ground truth summaries. They often introduce a named method or benchmark and organize contributions in a clear and conventional way. This is a positive signal. It indicates that the latent space is learning abstraction and discourse level structure rather than collapsing into generic text.


At the same time, the model frequently hallucinates details. It may attribute the wrong method, benchmark, or technical contribution to a paper, even while remaining fluent and well-structured. A particularly revealing failure mode is acronym drift. In this case, the model uses plausible but incorrect acronyms that are closely related to the true ones. These errors suggest that the latent representation captures that a specific concept exists, but not which one.
This behavior is consistent with an overly tight information bottleneck. With only 160 latent tokens and relatively small encoder and decoder models, fine-grained factual details such as exact method names, identifiers, and subtle technical distinctions are often lost during compression. When that happens, the decoder relies on strong learned priors to fill in the gaps, producing summaries that are coherent but incorrect.
There are several clear avenues for improvement. Increasing the number of latent tokens would directly raise the information capacity of the compressed representation and should reduce the loss of symbolic detail. Scaling up the encoder and decoder models would allow both better compression and more faithful reconstruction from the latent space. More training data, especially longer documents paired with high-quality summaries, would help the model learn stronger associations between compressed representations and factual content. Diversity in that data also matters. Exposure to a wider range of domains, writing styles, and summary formats could reduce overfitting to a narrow template and improve generalization.
Beyond raw scale, stronger supervision could also help. Objectives that explicitly penalize factual errors or reward correct entity and acronym preservation may encourage the latent space to retain precise identifiers rather than only high level structure. Longer training runs and more careful objective balancing between reconstruction and summarization could further stabilize this behavior.
Overall, the results suggest that the hardest part of the problem is already being addressed. Learning to abstract long documents under a fixed context budget. The remaining challenge is preserving enough detail to ground that abstraction in the correct facts. With more capacity, more data, and larger models, C3-style context compression remains a promising foundation for summarization and for a wide range of long context reasoning tasks that exceed the limits of standard language models.
Conclusion
We explored how C3-style context compression can be extended beyond pure reconstruction to support long document summarization. Starting from the authors’ released pre-trained checkpoints, we built a simple yet scalable pipeline that collects long papers, automatically generates summaries, and fine-tunes the latent space to encourage abstraction rather than verbatim copying. This setup allowed us to probe how much useful information can be retained when documents are aggressively compressed into a small set of latent tokens.
From a systems perspective, these experiments show that long context compression is practical even on modest hardware. Training and evaluation on a single H100 GPU using ZeRO Stage 3 enabled processing very long documents without ever passing the full text to the decoder. This keeps inference costs predictable and highlights one of the architecture's most appealing aspects. The same compressed representation can, in principle, be reused across multiple downstream tasks.
At the same time, the evaluation results make it clear that there is still significant work to be done. While summaries generated from compressed context often capture the overall structure and intent of the original document, they also reveal failure modes such as hallucinated details and confusion around specific identifiers.
Taken together, these results paint a cautiously optimistic picture. The model appears to be learning meaningful abstractions despite a severe information bottleneck, a strong signal that the approach is viable. However, fully understanding how information is stored, lost, and transformed in this latent space will require further experimentation. Scaling the models, increasing latent capacity, improving data quality and diversity, and developing better supervision signals are all likely necessary to unlock the full potential of this architecture.
Overall, this work demonstrates a concrete and promising step toward scalable long context reasoning. By separating information ingestion from task-specific generation, C3-style models offer a compelling foundation for working with documents that would otherwise exceed the limits of standard language models, while also highlighting how much remains to be learned about this new and still evolving design space
Add a comment