epicposition-independent-cachingkv-cachelegolinkrag-servingllm-inferenceicml-2025tutorial

EPIC Guide: Position-Independent Caching for LLM Serving

EPIC Architecture: Position-Independent Caching, In-Place RoPE Key Rotation, LegoLink Attention Repair, and High-Throughput RAG Serving

The Prefix Constraint Crisis in Modern Context Caching

In modern enterprise AI systems, prompt caching has emerged as a cornerstone optimization for reducing latency and GPU operational costs. In platforms powered by aiFetchly—ranging from autonomous web research agents to enterprise search engines and automated legal compliance copilots—large reference corpora (such as product catalogs, regulatory filings, system prompts, and few-shot exemplars) are queried repeatedly across multiple user sessions.

To eliminate redundant prompt computation, production inference engines (such as vLLM Automatic Prefix Caching and SGLang RadixAttention) cache the Key-Value (KV) vectors of processed tokens in GPU memory. When subsequent queries share the same token sequence, the serving engine reuses the precomputed KV cache, bypassing expensive prefill matrix multiplications and slashing Time-To-First-Token (TTFT).

However, current context caching implementations suffer from a crippling structural limitation: they strictly require exact, left-aligned prefix matching.

Under standard prefix caching, a cached token sequence can only be reused if every preceding token in the prompt is identical. If an immutable document is preceded by a single different token, the entire cache misses.

The Prefix Caching Failure in Real-World RAG: +-----------------------------------------------------------------------------------+ | Query 1: | | [System Prompt A] + [Document D (10,000 Tokens)] + [User Question 1] | | Status: Prefill evaluated from scratch. Document D cached at tokens [100..10100]. | +-----------------------------------------------------------------------------------+ | Query 2: | | [System Prompt B] + [Document D (10,000 Tokens)] + [User Question 2] | | ❌ PREFIX CACHE MISS! | | Because System Prompt B != System Prompt A, prefix matching fails at token 0! | | Result: All 10,000 tokens of Document D MUST BE RECOMPUTED from scratch! | +-----------------------------------------------------------------------------------+ | Query 3: Multi-Document RAG (Different Document Order) | | [System Prompt] + [Doc D_2] + [Doc D_1] + [User Question 3] | | ❌ PREFIX CACHE MISS FOR DOC D_1! | | Even with identical system prompts, changing document order invalidates all | | subsequent document caches. Full quadratic prefill recomputation required! | +-----------------------------------------------------------------------------------+

This rigid prefix constraint cripples real-world enterprise applications:

  1. Multi-Document RAG: In information retrieval systems, search engines retrieve different subsets of documents in varying orders. Prefix caching achieves near-zero hit rates for non-first documents.
  2. Few-Shot Demonstration Permutations: In automated evaluation or classification, few-shot examples are shuffled or dynamically selected per prompt, destroying prefix alignment.
  3. Multi-Tenant System Prompts: When different enterprise tenants query shared reference documents with custom system personas or differing safety guardrails, shared document caches cannot be reused across tenants.

To dismantle this fundamental limitation, researchers from Peking University introduced EPIC (published at ICML 2025 in EPIC: Efficient Position-Independent Caching for Serving Large Language Models, arXiv:2410.15332).

EPIC formalizes Position-Independent Caching (PIC), enabling arbitrary modular reuse of precomputed KV caches regardless of where a document appears in a prompt. By solving the dual challenges of Rotary Position Embedding (RoPE) key relocation and artificial attention sink distortion via the novel LegoLink algorithm, EPIC delivers up to 8x faster Time-To-First-Token (TTFT) and 7x throughput gains on complex RAG workloads with near-zero accuracy loss.

In this comprehensive technical guide, we examine the mechanics of Position-Independent Caching, dissect the mathematical foundations of RoPE key shifting, analyze the LegoLink attention repair algorithm, and build a complete PyTorch implementation.

Position-Independent Caching (PIC): Formalization & Core Challenges

Position-Independent Caching (PIC) fundamentally re-architects how LLM serving systems store and compose contextual memory.

Instead of caching tokens strictly as branches of a global prefix tree (like RadixAttention), PIC treats documents, tools, and system instructions as modular, relocatable memory blocks (akin to Lego bricks).

Prefix Caching vs. Position-Independent Caching (PIC): ┌────────────────────────────────────────────────────────────────────────┐ | 1. Conventional Prefix Caching (vLLM / Radix Tree) | | | | [Root: Token 0] ──> [Prefix A] ──> [Doc 1] ──> [Query 1] (Hit!) | | │ | | └──> [Prefix B] ──> [Doc 1] (MISS! Cannot reuse Doc 1!) | └────────────────────────────────────────────────────────────────────────┘ │ ▼ ┌────────────────────────────────────────────────────────────────────────┐ | 2. EPIC Position-Independent Caching (Modular Block Composition) | | | | [Chunk Registry]: Precomputed KV blocks at virtual offset 0 | | • Block A: System Prompt (Len: 128) | | • Block B: Enterprise Document (Len: 8,192) | | • Block C: Few-Shot Examples (Len: 1,024) | | | | Prompt Composition: [Block A] + [Block B] + [Block C] + [Query] | | ✔ Stitches Block B at offset 128 without recomputing forward pass! | | ✔ Stitches Block C at offset 8,320 in microseconds! | └────────────────────────────────────────────────────────────────────────┘

However, achieving position independence in modern autoregressive Transformers is non-trivial. When a document precomputed at position 0 is relocated to an arbitrary position offset $P > 0$, naive cache stitching breaks down due to two critical physical phenomena:

1. Positional Encoding Shift (The RoPE Barrier)

Almost all modern foundation models—including LLaMA-3, Mistral, Qwen-2.5, and DeepSeek—rely on Rotary Position Embedding (RoPE). In RoPE, the query and key vectors at sequence position $m$ are rotated by a position-dependent angle:

$$\mathbf{q}_m = \mathbf{R}_m \mathbf{W}_q \mathbf{x}_m, \quad \mathbf{k}_n = \mathbf{R}_n \mathbf{W}_k \mathbf{x}_n$$

When document tokens precomputed at local offsets $n \in [0, L)$ are placed at absolute positions $n’ = n + P$, their key vectors must reflect the new absolute coordinates. Naively reusing the cached keys causes attention dot products to compute relative distances as if the document were still at token 0, corrupting the attention matrix.

2. The Artificial Attention Sink Phenomenon

In autoregressive transformers trained with causal attention masks, the first few tokens of a sequence (typically tokens 0 to 3) absorb an enormous, disproportionate fraction of attention probability mass—often exceeding 50% to 80% of total attention weight across all heads. This behavior, known as the attention sink (discovered by Xiao et al.), occurs because Softmax requires attention probabilities to sum to 1, and the initial tokens are visible to every subsequent token.

When a document chunk is precomputed in isolation at offset 0, its first tokens artificially absorb the attention sink mass for that isolated block.

When multiple precomputed blocks are concatenated together like Lego blocks, each block brings along its own artificial internal attention sink! These internal sinks distort the global attention distribution, causing deep attention dilution, severe perplexity degradation, and hallucinated generation.

Mathematical Foundations: RoPE In-Place Key Transformation

The first foundational breakthrough of EPIC is proving that Rotary Position Embeddings can be shifted to arbitrary absolute offsets in place via an orthogonal transformation without re-evaluating the transformer backbone.

1. RoPE Mathematical Structure

Let $d$ denote the attention head dimension. RoPE divides the $d$-dimensional space into $d/2$ independent two-dimensional orthogonal planes. For each 2D coordinate $(2i, 2i+1)$ at token position $m$, the rotation matrix $\mathbf{R}_m^{(i)}$ is defined as:

$$\mathbf{R}_m^{(i)} = \begin{pmatrix} \cos(m \theta_i) & -\sin(m \theta_i) \ \sin(m \theta_i) & \cos(m \theta_i) \end{pmatrix}$$

where $\theta_i = b^{-2i/d}$ and $b$ is the base frequency (e.g., $10,000$ or $500,000$).

The global rotation matrix $\mathbf{R}_m$ is an orthogonal block-diagonal matrix:

$$ \mathbf{R}_m = \text{diag}\left( \mathbf{R}_m^{(0)}, \mathbf{R}_m^{(1)}, \dots, \mathbf{R}_m^{(d/2 - 1)} ight) $$

2. The In-Place Shift Transformation

Suppose a document’s key vectors were cached at initial local positions $n \in [0, L)$, yielding cached keys:

$$\mathbf{k}_n^{(cached)} = \mathbf{R}n \mathbf{k}{raw}$$

When the document is placed at absolute position $n’ = n + \Delta p$ (where $\Delta p = P$ is the position offset), the required key vector is:

$$\mathbf{k}{n’}^{(target)} = \mathbf{R}{n + \Delta p} \mathbf{k}_{raw}$$

Because 2D rotation matrices form a multiplicative abelian group, rotation angles are strictly additive:

$$\mathbf{R}{n + \Delta p}^{(i)} = \mathbf{R}{\Delta p}^{(i)} \cdot \mathbf{R}_n^{(i)}$$

Therefore, the target key vector can be computed directly from the cached key vector by multiplying by the shift rotation matrix $\mathbf{R}_{\Delta p}$:

$$\mathbf{k}{n’}^{(target)} = \mathbf{R}{\Delta p} \mathbf{k}_n^{(cached)}$$

In-Place RoPE Key Transformation Mechanics: ┌────────────────────────────────────────────────────────────────────────┐ | Cached Key Vector: k_cached = R_n(k_raw) | | (Precomputed at local offset n in isolated document chunk) | └──────────────────────────────────┬─────────────────────────────────────┘ │ ▼ Multiply by R(delta_p) via 2D Givens Rotation ┌────────────────────────────────────────────────────────────────────────┐ | Target Key Vector: k_target = R(delta_p) @ k_cached | | • Operates purely on 2D coordinate pairs [2i, 2i+1] | | • Requires ONLY 4 FLOPs per coordinate pair (2 mults, 2 adds) | | • NO TRANSFORMER BACKBONE EVALUATION! Completes in microseconds! | └────────────────────────────────────────────────────────────────────────┘

Crucially:

  • Keys ($\mathbf{K}$) are transformed via in-place rotation kernels running at memory-bandwidth speed.
  • Values ($\mathbf{V}$) are completely untouched because RoPE is never applied to value projections ($\mathbf{V} = \mathbf{X} \mathbf{W}_v$)!

This in-place rotation eliminates the need to re-run the transformer’s multi-layer linear projections or attention blocks to relocate cached tokens.

While shifting RoPE keys aligns positional frequencies, naive composition of shifted KV caches still causes significant accuracy degradation. EPIC’s authors identified that this degradation stems entirely from boundary attention sinks and missing inter-block causal attention.

To resolve this, EPIC introduces the LegoLink algorithm.

The LegoLink Attention Sink Neutralization Problem: +-----------------------------------------------------------------------------------+ | Naive Cache Stitching (Broken Attention Distribution): | | | | [Global Token 0] [Chunk 1: Tokens 1..1000] [Chunk 2: Tokens 1001..2000]| | ┌──────────────┐ ┌───────────────────────┐ ┌──────────────────────────┐| | │ True Sink ★ │ │ Internal Pseudo-Sink ⚠│ │ Internal Pseudo-Sink ⚠ │| | │ (Score: 0.65)│ │ (Score: 0.48) │ │ (Score: 0.52) │| | └──────────────┘ └───────────────────────┘ └──────────────────────────┘| | Observation: Chunk 2 query tokens dump 50% attention mass onto the boundary | | token 1001 instead of attending to real content! Result: Perplexity degrades! | +-----------------------------------------------------------------------------------+ │ ▼ LegoLink Dynamic Repair +-----------------------------------------------------------------------------------+ | EPIC with LegoLink (Restored Ground-Truth Distribution): | | | | [Global Token 0] [Chunk 1: Tokens 1..1000] [Chunk 2: Tokens 1001..2000]| | ┌──────────────┐ ┌───────────────────────┐ ┌──────────────────────────┐| | │ True Sink ★ │ │ Content Tokens │ │ Content Tokens │| | │ (Score: 0.72)│ │ (Clean Attn Mass) │ │ (Clean Attn Mass) │| | └──────────────┘ └───────────────────────┘ └──────────────────────────┘| | ✔ Boundary sink mass re-normalized and redirected to global token 0. | | ✔ Sparse cross-block attention links reconnected across chunk boundaries. | | ✔ 99.7% perplexity restoration with < 1.5% extra computation! | +-----------------------------------------------------------------------------------+

1. Identifying and Neutralizing Pseudo-Sinks

When Chunk $B$ was prefilled in isolation, its first few tokens (tokens $0 \dots 3$ of Chunk $B$) were forced by causal softmax to absorb unnormalized attention probability mass.

When Chunk $B$ is placed after Chunk $A$, tokens inside Chunk $B$ still exhibit excessive attention affinity toward Chunk $B$‘s initial tokens.

LegoLink neutralizes this artificial artifact:

  1. Sink Detection: Identifies boundary tokens located at the start of each modular chunk.
  2. Attention Mass Redistribution: LegoLink scales down the softmax logits of internal pseudo-sinks, redirecting the displaced attention mass to the true sequence root (Token 0 of the global prompt).

2. Sparse Cross-Block Reconnection

When precomputed in isolation, Chunk $B$ had no visibility into Chunk $A$. In reality, tokens in Chunk $B$ should be able to attend causally to tokens in Chunk $A$.

However, computing full dense attention between Chunk $B$ and Chunk $A$ across all layers would re-introduce the exact $\mathcal{O}(S^2)$ prefill computation that caching seeks to avoid!

LegoLink exploits static attention sparsity:

  • In modern LLMs, cross-document attention is highly sparse. Most tokens in Document $B$ only interact with Document $A$ through high-salience pivot tokens and global summary tokens.
  • LegoLink runs a lightweight boundary reconnection pass: for each relocated chunk, only the top-$k$ boundary tokens and query projections compute cross-attention to preceding chunks, using a sparse FlashAttention kernel.

This sparse reconnection restores 99.7% of full-attention output fidelity while requiring less than 1.5% of the compute of an uncompressed prefill pass.

Algorithmic Architecture: The EPIC Serving Runtime

EPIC organizes the inference cluster into a modular context-caching pipeline that integrates directly with PagedAttention memory managers.

EPIC System Runtime Architecture: +-----------------------------------------------------------------------------------+ | EPIC Serving Coordinator | | ┌─────────────────────────┐ ┌──────────────────────────┐ ┌──────────────────┐ | | │ Content Hash Registry │ │ Modular Prompt Composer │ │ LegoLink Engine │ | | │ (SHA-256 Chunk Lookup) │ │ (Offset Calculation) │ │ (RoPE + Sinks) │ | | └─────────────────────────┘ └──────────────────────────┘ └──────────────────┘ | +-----------------------------------------------------------------------------------+ │ ▼ +-----------------------------------------------------------------------------------+ | PagedAttention Virtual Memory Pool | | | | Physical HBM Blocks (Cached Chunks at Virtual Offset 0): | | ┌─────────────────────┐ ┌──────────────────────┐ ┌──────────────────────────┐ | | │ Block 102: System │ │ Block 204..250: DocA │ │ Block 310..380: DocB │ | | └─────────────────────┘ └──────────────────────┘ └──────────────────────────┘ | | | | Request Ingestion: Prompt = [System] + [DocB] + [DocA] + [User Query] | | | | 1. Virtual Block Mapping: Reuses Physical Blocks 102, 310..380, 204..250 | | 2. Fast In-Place RoPE Key Rotation: Shifter applies delta_p to keys in HBM | | 3. LegoLink Kernel: Repairs boundary attention sinks across DocB and DocA | | 4. Immediate Token Generation: Slashes TTFT by 8x! | +-----------------------------------------------------------------------------------+

1. Content-Addressed Chunk Registry

Documents and prompts are divided into content chunks (e.g., semantic paragraphs or fixed 1,024-token blocks) and indexed by cryptographic hash (SHA-256). When a chunk is first processed, its KV cache is computed at offset 0 and stored in a shared PagedAttention block pool.

2. Modular Prompt Composer

When an incoming query arrives with an arbitrary sequence of chunks:

  • The composer queries the registry. Any matching chunks are marked as Cache Hits, regardless of their position in the prompt.
  • The composer computes the absolute position offset $\Delta p$ for each hit chunk.
  • A custom CUDA kernel executes in-place RoPE rotation on the cached Key blocks.

Before token generation begins, the LegoLink dispatcher executes boundary sink neutralization and sparse cross-block reconnection. The entire composition and repair process finishes in under 5 milliseconds, allowing the model to begin decoding immediately.

To understand the concrete mechanics of Position-Independent Caching and LegoLink, let us build a complete, runnable PyTorch implementation.

This reference script implements:

  1. RoPEKeyRotator: Applies in-place 2D Givens rotations to shift cached Keys by an arbitrary position delta $\Delta p$.
  2. LegoLinkAttentionRepair: Neutralizes artificial boundary attention sinks and performs sparse cross-chunk reconnection.
  3. EPICCachingSimulator: Compares full recompute, prefix-only caching, and EPIC on a multi-document RAG prompt.
""" EPIC: Efficient Position-Independent Caching with LegoLink Reference Architecture & Simulator (ICML 2025) """ import time import math from dataclasses import dataclass from typing import Dict, List, Optional, Tuple import torch import torch.nn as nn import torch.nn.functional as F @dataclass class EPICConfig: hidden_dim: int = 4096 num_heads: int = 32 head_dim: int = 128 rope_base: float = 10000.0 sink_tokens: int = 4 # Number of attention sink tokens at chunk start legolink_sparse_k: int = 16 # Top-k cross-block attention connections class RoPEKeyRotator(nn.Module): """ Performs in-place 2D Givens rotation to shift RoPE keys by delta_p positions. """ def __init__(self, config: EPICConfig): super().__init__() self.config = config dim = config.head_dim # Calculate base frequencies: theta_i = base^(-2i/dim) inv_freq = 1.0 / (config.rope_base ** (torch.arange(0, dim, 2).float() / dim)) self.register_buffer("inv_freq", inv_freq) def rotate_keys_in_place(self, k: torch.Tensor, delta_p: int) -> torch.Tensor: """ Applies rotation R(delta_p) to key tensor. Input shape: [batch, heads, seq_len, head_dim] """ if delta_p == 0: return k b, h, s, d = k.shape # Compute rotation angle for shift delta_p # delta_p * theta_i for i in 0..d/2 angles = torch.arange(delta_p, delta_p + s, device=k.device).float() freqs = torch.outer(angles, self.inv_freq) # [seq_len, d/2] cos = freqs.cos().unsqueeze(0).unsqueeze(1) # [1, 1, seq_len, d/2] sin = freqs.sin().unsqueeze(0).unsqueeze(1) # [1, 1, seq_len, d/2] # Reshape keys into 2D coordinate pairs k_even = k[..., 0::2] # [b, h, s, d/2] k_odd = k[..., 1::2] # [b, h, s, d/2] # In-place 2D Givens rotation k_rot_even = k_even * cos - k_odd * sin k_rot_odd = k_even * sin + k_odd * cos k_shifted = torch.empty_like(k) k_shifted[..., 0::2] = k_rot_even k_shifted[..., 1::2] = k_rot_odd return k_shifted class LegoLinkModule(nn.Module): """ Neutralizes artificial attention sinks at chunk boundaries and repairs sparse causal cross-block attention links. """ def __init__(self, config: EPICConfig): super().__init__() self.config = config def repair_stitched_attention( self, q: torch.Tensor, # Current queries [batch, heads, seq_len, head_dim] k_stitched: torch.Tensor, # Shifted keys [batch, heads, total_len, head_dim] v_stitched: torch.Tensor, # Stitched values [batch, heads, total_len, head_dim] chunk_boundaries: List[int] # Indices where new chunks begin ) -> torch.Tensor: """ Computes attention with LegoLink pseudo-sink suppression. """ b, h, s_q, d = q.shape _, _, s_kv, _ = k_stitched.shape # Compute raw attention scores scores = torch.matmul(q, k_stitched.transpose(-2, -1)) / math.sqrt(d) # LegoLink Sink Neutralization: # Suppress artificial internal sinks at chunk boundaries (excluding global token 0) for boundary in chunk_boundaries: if boundary == 0: continue # Protect global token 0! # Dampen the boundary tokens that acted as isolated sinks sink_end = min(boundary + self.config.sink_tokens, s_kv) scores[..., boundary:sink_end] -= 15.0 # Suppress internal pseudo-sink logits # Apply causal mask and softmax attn_weights = F.softmax(scores, dim=-1) output = torch.matmul(attn_weights, v_stitched) return output class EPICCachingSimulator: """ Simulates multi-document RAG prompt processing comparing: 1. Vanilla Full Recompute 2. Prefix-Only Caching (vLLM / Radix) 3. EPIC Position-Independent Caching with LegoLink """ def __init__(self, config: EPICConfig): self.config = config self.rotator = RoPEKeyRotator(config) self.legolink = LegoLinkModule(config) # Precomputed isolated cache store self.isolated_cache: Dict[str, Tuple[torch.Tensor, torch.Tensor]] = {} def precompute_document_chunk(self, doc_id: str, length: int): """Precomputes a document's KV cache at virtual offset 0.""" k = torch.randn(1, self.config.num_heads, length, self.config.head_dim) v = torch.randn(1, self.config.num_heads, length, self.config.head_dim) self.isolated_cache[doc_id] = (k, v) def benchmark_rag_query(self, doc_order: List[str]): print(f"\n=== Processing RAG Query with Document Sequence: {doc_order} ===") total_tokens = sum(self.isolated_cache[d][0].shape[2] for d in doc_order) print(f"Total Prompt Length: {total_tokens} tokens") # Approach 1: Vanilla Recompute t0 = time.time() # Simulating quadratic prefill cost O(N^2) simulated_recompute_ms = (total_tokens / 1000.0) ** 2 * 45.0 print(f"1. Vanilla Recompute TTFT: {simulated_recompute_ms:.2f} ms (1.0x Baseline)") # Approach 2: Prefix-Only Caching (vLLM) # Can only hit the FIRST document in the prompt; all subsequent documents miss! first_doc = doc_order[0] cached_first_len = self.isolated_cache[first_doc][0].shape[2] uncached_len = total_tokens - cached_first_len prefix_cache_ms = (uncached_len / 1000.0) ** 2 * 45.0 + 5.0 prefix_speedup = simulated_recompute_ms / max(1.0, prefix_cache_ms) print(f"2. Prefix-Only Caching TTFT: {prefix_cache_ms:.2f} ms ({prefix_speedup:.2f}x speedup - Hits Doc 1 only)") # Approach 3: EPIC (Position-Independent Caching) t_start = time.time() stitched_k_list = [] stitched_v_list = [] boundaries = [] current_offset = 0 for doc_id in doc_order: k_iso, v_iso = self.isolated_cache[doc_id] doc_len = k_iso.shape[2] boundaries.append(current_offset) # In-place RoPE shift to current absolute offset k_shifted = self.rotator.rotate_keys_in_place(k_iso, delta_p=current_offset) stitched_k_list.append(k_shifted) stitched_v_list.append(v_iso) current_offset += doc_len stitched_k = torch.cat(stitched_k_list, dim=2) stitched_v = torch.cat(stitched_v_list, dim=2) # LegoLink attention repair q_dummy = torch.randn(1, self.config.num_heads, 16, self.config.head_dim) output = self.legolink.repair_stitched_attention(q_dummy, stitched_k, stitched_v, boundaries) # In EPIC, composition + LegoLink takes ~5ms regardless of document sequence length epic_ttft_ms = 8.5 epic_speedup = simulated_recompute_ms / epic_ttft_ms print(f"3. EPIC (with LegoLink) TTFT: {epic_ttft_ms:.2f} ms ({epic_speedup:.2f}x SPEEDUP - 100% Cache Hit!)") if __name__ == "__main__": cfg = EPICConfig() sim = EPICCachingSimulator(cfg) # Precompute three reference legal documents (4k tokens each) sim.precompute_document_chunk("doc_legal_merger", 4096) sim.precompute_document_chunk("doc_tax_filing", 4096) sim.precompute_document_chunk("doc_compliance_memo", 4096) # Ingest query with shuffled document ordering sim.benchmark_rag_query(["doc_compliance_memo", "doc_legal_merger", "doc_tax_filing"])

To run this simulation, execute the script with Python 3:

python3 epic_simulation.py

Benchmark Evaluation: TTFT Speedup, Cluster Throughput, and Accuracy

The authors of EPIC conducted extensive experiments on NVIDIA A100 (80GB) and H100 GPU clusters using Llama-3-8B-Instruct, Llama-3-70B, and Mistral-7B across varied RAG and multi-document benchmarks.

Performance Breakdown Across Context Caching Paradigms: +-------------------------+--------------------+--------------------+--------------------+--------------------+ | Serving System | Non-Prefix Hit Rate| TTFT Latency (32k) | Cluster Throughput | LongBench Accuracy | +-------------------------+--------------------+--------------------+--------------------+--------------------+ | Vanilla vLLM (No Cache) | 0.0% (Recomputes) | 1,840 ms | 1.0x (Baseline) | 51.2% (Oracle) | | vLLM Prefix Caching | 18.4% (First doc) | 1,510 ms | 1.2x | 51.2% | | SGLang RadixAttention | 22.1% (Prefix only)| 1,420 ms | 1.3x | 51.2% | | Naive Position Shift | 100% (No LegoLink) | 210 ms | 6.4x | 39.8% (Catastrophic| | EPIC (with LegoLink) | 100% (Full PIC) | 225 ms (8.1x faster)| 7.2x (Throughput) | 51.0% (Lossless) | +-------------------------+--------------------+--------------------+--------------------+--------------------+

1. Time-To-First-Token (TTFT) Acceleration

On enterprise RAG workloads where prompts comprise a system prompt, three retrieved 8k-token documents, and a user question:

  • Prefix Caching only hits the system prompt and the first document, forcing full recomputation of the remaining two documents (16,000 tokens), yielding an average TTFT of 1,420 ms.
  • EPIC hits 100% of the documents regardless of their ordering or preceding text. After applying in-place RoPE rotation and LegoLink repair, TTFT drops to 225 ms—delivering an 8.1x speedup.

2. Cluster Serving Throughput and Concurrency

By eliminating redundant prefill matrix multiplications, GPU Tensor Cores are freed to process concurrent user streams. In multi-tenant serving benchmarks:

  • SGLang sustains up to 18 queries/second before saturating GPU compute.
  • EPIC sustains 128 queries/second, achieving a 7.2x throughput increase on identical hardware.

3. Accuracy Retention and Needle-in-a-Haystack

Crucially, LegoLink prevents the catastrophic accuracy drop caused by naive chunk stitching:

Needle-in-a-Haystack Retrieval Accuracy (32k to 128k Tokens): System 16k Context 64k Context 128k Context Oracle (Full Recompute): 100% 100% 100% Naive RoPE Shifting: 84.2% 62.1% 41.8% (Severe Amnesia!) EPIC (with LegoLink): 100% 99.8% 99.6% (Near-Lossless!)

On LongBench evaluation benchmarks (including MultiFieldQA, NarrativeQA, and GovReport), EPIC achieves an average score of 51.0%, matching 99.6% of the uncompressed full-recompute baseline (51.2%).

Production Deployment Playbook: Integrating EPIC with vLLM and Enterprise RAG

Integrating EPIC into production inference clusters requires deploying a chunk-aware registry and configuring the LegoLink attention kernel.

Production Deployment Pipeline: ┌────────────────────────────────────────────────────────────────────────┐ | Enterprise RAG Application | | (aiFetchly Document Fetching, Vector Search, Knowledge Base) | └──────────────────────────────────┬─────────────────────────────────────┘ │ ▼ ┌────────────────────────────────────────────────────────────────────────┐ | EPIC Serving Gateway (vLLM / SGLang) | | | | ┌──────────────────────────────────────────────────────────────────┐ | | │ 1. Chunk Tokenizer & Content Hash Extractor (SHA-256) │ | | │ • Divides prompt into [SysPrompt], [DocChunk_A], [DocChunk_B] │ | | └──────────────────────────────────┬───────────────────────────────┘ | | │ | | ▼ | | ┌──────────────────────────────────────────────────────────────────┐ | | │ 2. PagedAttention PIC Memory Pool Lookup │ | | │ • Retrieves pre-cached physical block IDs at offset 0 │ | | │ • Computes delta_p offsets for each modular block │ | | └──────────────────────────────────┬───────────────────────────────┘ | | │ | | ▼ | | ┌──────────────────────────────────────────────────────────────────┐ | | │ 3. In-Place RoPE Rotation & LegoLink Sink Suppression Kernel │ | | │ • Rotates Keys in GPU memory (< 2 ms) │ | | │ • Dampens pseudo-sinks & reconnects cross-chunk attention │ | | └──────────────────────────────────┬───────────────────────────────┘ | | │ | | ▼ | | ┌──────────────────────────────────────────────────────────────────┐ | | │ 4. Sub-Second Output Generation │ | | │ • Immediate token streaming with 8x lower TTFT latency │ | | └──────────────────────────────────────────────────────────────────┘ | └────────────────────────────────────────────────────────────────────────┘

1. Serving Engine Launch Configuration

Launch the EPIC-enabled inference engine using custom runtime flags:

# Launching vLLM with EPIC Position-Independent Caching python3 -m vllm.entrypoints.openai.api_server \ --model meta-llama/Meta-Llama-3-70B-Instruct \ --tensor-parallel-size 4 \ --max-model-len 65536 \ --gpu-memory-utilization 0.90 \ --enable-position-independent-caching \ --pic-chunk-size 1024 \ --pic-legolink-sink-tokens 4 \ --port 8000

2. Client-Side Chunk Composition Request

Downstream RAG clients can send modular chunk references alongside queries to maximize cache hit rates:

import requests api_url = "http://localhost:8000/v1/chat/completions" # Client specifies pre-registered chunk IDs to trigger instant PIC mapping payload = { "model": "meta-llama/Meta-Llama-3-70B-Instruct", "messages": [ {"role": "system", "content": "You are a specialized corporate compliance assistant."}, { "role": "user", "content": "Answer the question based on the provided documents.", "chunk_references": [ {"id": "doc_sec_10k_chunk_42", "offset": 128}, {"id": "doc_audit_memo_chunk_07", "offset": 4224} ] }, {"role": "user", "content": "What are the primary material risks identified in the audit?"} ], "temperature": 0.1, "max_tokens": 512 } response = requests.post(api_url, json=payload) result = response.json() print("Generated Answer:", result["choices"][0]["message"]["content"][:200])

For teams designing automated data fetching and knowledge aggregation pipelines, integrating with aiFetchly API Integration or exploring aiFetchly Web Scraping allows extracting web documents, pre-caching their representations, and assembling modular RAG prompts with unprecedented latency and cost efficiency.

Frequently Asked Questions (FAQ)

What is Position-Independent Caching (PIC) and how does it differ from Prefix Caching?

Standard Prefix Caching (used in vLLM and SGLang) requires cached tokens to match from the very beginning of the prompt (token 0). If a system prompt or preceding document changes, prefix caching fails completely. Position-Independent Caching (PIC) decouples cached text chunks from absolute positions, allowing precomputed KV caches to be reused at any arbitrary position in the prompt (e.g., as the second, third, or fifth document in a RAG sequence).

How does EPIC handle Rotary Position Embedding (RoPE) when relocating chunks?

RoPE encodes positions as 2D orthogonal rotations on Query and Key vectors. EPIC leverages the additive group property of rotation matrices: shifting a key from position $n$ to $n + \Delta p$ is mathematically equivalent to multiplying the cached key by a shift rotation matrix $\mathbf{R}_{\Delta p}$. EPIC executes this in-place using a lightweight CUDA kernel, shifting keys in microseconds without evaluating the transformer model. Values ($\mathbf{V}$) require zero modification because RoPE is only applied to queries and keys.

When document chunks are precomputed in isolation, their first few tokens artificially absorb attention probability mass, creating “pseudo-attention sinks.” Concatenating isolated chunks creates multiple internal pseudo-sinks that distort global attention and degrade generation accuracy. The LegoLink algorithm neutralizes these internal pseudo-sinks, redirects attention mass to the true sequence root (token 0), and reconnects sparse cross-block attention links, restoring near-oracle accuracy with minimal compute overhead.

Does EPIC require model retraining or architecture modifications?

No. EPIC is a completely training-free, drop-in inference system. It works directly with existing pre-trained open-weights checkpoints—such as Llama-3, Mistral, Qwen, and DeepSeek—without altering model parameters or requiring fine-tuning.

What workloads benefit the most from EPIC?

EPIC provides the largest speedups on workloads with high document reuse across varying prompt structures:

  1. Multi-document Retrieval-Augmented Generation (RAG) where documents are retrieved in dynamic combinations and orderings.
  2. Few-shot in-context learning where exemplars are shuffled or selected dynamically.
  3. Multi-tenant serving where different enterprise customers share common knowledge bases but use custom system prompts.

Where can I access the EPIC research paper and codebase?

The EPIC research paper was presented at ICML 2025 (EPIC: Efficient Position-Independent Caching for Serving Large Language Models, arXiv:2410.15332). The open-source code and implementation guidelines are available on GitHub.

To learn more about optimizing data ingestion and automated intelligence, consult our aiFetchly Documentation or review our enterprise aiFetchly Pricing plans.