MapFlow – An Open-Source Cross-Model LLM Inference Acceleration System from Peking University
Executive Summary:
MapFlow is a cross-model LLM inference acceleration system developed by the PKU-DAIR team at Peking University, aimed at addressing the pain points of repeated prefill computation when sharing long co...
1. What is MapFlow
MapFlow is a cross-model LLM inference acceleration system developed by the PKU-DAIR team at Peking University, aimed at addressing the pain points of repeated prefill computation when sharing long contexts across multiple models in Agent workflows. Unlike traditional KV Cache reuse approaches, MapFlow reuses the more transferable "attention map" across models. Under the premise of a shared tokenizer, the receiving model only recomputes the first few layers, while subsequent layers reuse the token dependencies of the sending model through lightweight layer/head linear mapping. The system employs block-sparse top-p compression, prefix hash caching, and fused GPU kernel control to manage memory and latency. In experiments, TTFT was reduced by 15%–20%, and throughput in multi-turn routing scenarios was increased by as much as 25%.
Technical Positioning and Domain: MapFlow belongs to the domain of large language model inference optimization, focusing on inference acceleration in scenarios involving multiple model collaboration. Its core innovation lies in using "attention maps" as reusable states that can be transferred across models, breaking through the limitations of traditional prefix caching (Prefix Cache), which can only be reused within the same model. This provides a new optimization path for multi-model routing, cascaded inference, and multi-Agent workflows.
Development Background: The motivation for developing this system stems from the practical needs of multi-model routing and Agent workflows. When switching between large and small models, long conversation histories often require repeated prefill operations, leading to significant computational waste. The PKU-DAIR team observed that attention maps capture the dependency structure between tokens, and when the tokenizer is shared and the context is the same, this structure exhibits stronger cross-model similarity than model-specific KV representations. Based on this insight, they designed a complete cross-model reuse mechanism.
Core Value: MapFlow addresses the core issue of unshared context computation in multi-model systems. In traditional approaches, KV Cache is tightly coupled with hidden dimensions, layers, and parameters, making it impossible to directly reuse across different models. MapFlow replaces KV Cache with attention maps as the reusable state, combined with partial recomputation and linear mapping, enabling models of different scales and architectures to share the computed token dependencies. This significantly reduces prefill latency and TTFT in multi-turn routing scenarios.
Technical Features: The system achieves cross-model reuse through a three-tier mechanism: the receiving model recomputes the first r layers to establish its own hidden states, layer mapping adopts a suffix alignment strategy, and head mapping uses a linear combination constrained by simplex. Mapping weights are trained offline, with the added parameters being less than 0.001% of the receiving model's parameters. Both large models remain frozen throughout the process, and calibration is performed once, spreading the cost across all subsequent online requests, resulting in minimal engineering overhead.
2. Key Features
Cross-model Attention Reuse: Transfer and reuse attention maps between models of different scales and architectures, replacing the difficult-to-migrate KV Cache. This feature breaks the traditional limitation of prefix caching being confined to the same model, allowing the attention states of large models such as Qwen3-8B to be directly utilized by smaller models like Qwen3-1.7B, achieving shared context computation across models.
Partial Recomputation Mechanism: The receiving model first fully computes the initial several layers to establish its own hidden states before entering the reuse path. This design is based on empirical observations: the attention maps of the first few layers of the receiving model have higher fitting errors, while the middle and later layers can be linearly approximated by the attention maps of the sending model. Thus, recomputing the first r layers balances accuracy and speed.
Layer Mapping and Head Mapping: Layer mapping uses a suffix alignment strategy, m(j) = j + L_S − L_R, mapping receiving layers to deeper, more stable layers in the sending model based on experience. Head mapping employs a linear combination under simplex constraints, combining the attention maps from each head of the sending model to approximate each head of the receiving model, preserving the basic structure of attention distribution. Mapping weights are trained offline using end-to-end response loss, with parameters of both large models kept frozen throughout.
Attention Map Sparse Compression: Leveraging the heavy-tailed nature of attention distributions, perform top-p filtering on a per-64×64 2D block basis. First, compute block-level importance scores using LogSumExp for each pair of query block and key block. Retain blocks that reach a cumulative probability threshold p row-wise to obtain a sparse mask, then precisely calculate attention scores only for the retained blocks. Store the results in contiguous memory in BSR (Block Sparse Row) format, avoiding materializing the full dense matrix.
Cache Management and Retrieval: Use prefix hashing to index sparse blocks, overlapping cache retrieval with the recomputation of the first few layers of the receiving model, thereby hiding transmission latency. Compressed attention map states can be shared among multiple downstream receiving models, requiring the sending model to compress only once, after which multiple receiving models can reuse the same cache.
Fused GPU Kernel Execution: Perform cross-head linear transformations and value multiply-accumulate operations within a single GPU kernel, avoiding the materialization of dense intermediate tensors and reducing memory usage and kernel launch overhead. This design further shortens the end-to-end latency of cross-model attention reuse.
Online Inference Acceleration: Reduce prefill latency and TTFT (Time to First Token) while maintaining generation quality, improving system throughput in multi-turn routing scenarios. In experiments, prefill latency was reduced by 15%–20%, and multi-turn routing throughput was increased by up to 25% under the same P90 latency constraints. The primary reduction was in the long-tail TTFT, leading to a more stable online experience.
3. Application Scenarios
Multi-model Routing Assistant: In systems that route complex queries to large models and simple queries to small models, the small model can reuse the attention map computed by the large model when taking over long conversation histories, avoiding redundant prefill operations. For example, in a customer service system, after a large model handles a complex issue, the small model can follow up by directly reusing the precomputed context dependencies.
Cascaded Inference (Cascade): In a cascaded architecture where a large model handles the initial processing and, if unsatisfied, escalates to a smaller model or where a small model first attempts to process and then escalates, the models share the same context computation results during handover. In this scenario, MapFlow's cross-model reuse mechanism prevents each level in the cascade from recalculating the full context from scratch.
Multi-Agent Workflow: In a pipeline such as "14B planning → 8B refinement → 3B summarization," multiple downstream models share the attention states generated by the upstream large model, saving 0.48–0.73 seconds per round. For complex tasks involving multiple rounds of agent interactions, the cumulative latency savings can be substantial.
Database and Text-to-SQL Assistant: In scenarios with long prefixes that repeatedly include the same database schema and system constraints, MapFlow enables the model to avoid recomputation upon switching by directly hitting the cache and reusing the stored attention states. These types of workloads have highly repetitive prefixes, and MapFlow can significantly improve response speed and system throughput.
4. How to Use
Environment Setup: Create a Python 3.11 conda environment, compile and install the vLLM branch included in the repository in editable mode, and then install dependency packages such as nvtx, sacrebleu, and rouge_score. It is recommended to run this on a Linux server equipped with an NVIDIA GPU.
Start MPS Service: Run
nvidia-cuda-mps-control -dto start the NVIDIA MPS (Multi-Process Service), preparing for GPU resource sharing among the sender, receiver, and caching server. MPS allows multiple processes to concurrently utilize GPU resources and forms the foundation of MapFlow's multi-process architecture.Start Caching Server: Execute the server script located in the
examples/bash/directory (e.g.,server_top_p.shfor specifying the model and top-p parameter). This service is responsible for compressing attention maps, building prefix hash indexes, and managing block pools, serving as the central component of the entire reuse system.Start Sender: Run the sender script in a separate terminal (e.g.,
sender_top_p.sh Qwen3-8B 0.7 0), allowing the large model to perform prefill operations on shared context and generate attention maps that are stored in the cache. The sender only needs to process the context once, and subsequent receivers can reuse the output.Start Receiver: Run the receiver script in another terminal (e.g.,
receiver_top_p.sh Qwen3-1.7B 0.7 1 ./examples/weights/Qwen3-8B_to_Qwen3-1.7B/hotpotqa), loading pre-calibrated mapping weights. After matching the prefix hash, the receiver will take the reuse path, avoiding a full re-calculation of prefill.Run Evaluation and Verification: Run accuracy (
accuracy/hotpotqa.sh), TTFT (ttft/hotpotqa.sh), end-to-end throughput (e2e/multi_rounds_window_correct_log.sh), three-model workflow, or RULER-20K long context scripts as needed. Use tools likeextract_ttft.pyto parse the log results.Adjust Parameters by Scenario: For short context scenarios, use the default top-p=0.7. For long context scenarios, increase it to 0.85~0.92 according to the parameter table in the README. When changing the routing threshold, simply modify the trace file path in the e2e script. Proper parameter tuning can balance compression ratio and accuracy.
5. Pros and Cons Analysis
| Pros |
|---|
| Cross-model Reusability Breakthrough: Breaks the traditional limitation where prefix caching can only be used within the same model, enabling different scales and architectures of models to share computed token dependencies. This provides a new optimization path for multi-model routing and Agent workflows. |
| Smarter State Selection: Replaces KV Cache, which is tightly coupled with model weights, with attention maps. The attention structure is more transferable across models than hidden representations, fundamentally solving the core challenge of cross-model state reuse. |
| Minimal Overhead: Only trains simplex-constrained linear mapping weights, while both large models remain frozen throughout. Once calibrated, the benefits last long, with the added weights being less than 0.001% of the receiving model, keeping engineering costs under control. |
| Balances Quality and Speed: Partial recomputation ensures precision, while linear mapping preserves structure. In experiments, prefill latency was reduced by 15%–20% without compromising generation quality, achieving a balance between inference speed and output quality. |
| Solid Engineering Implementation: Combines GPU kernel to perform cross-head weighting and value multiplication and addition on-chip, without materializing dense intermediate tensors. Cache retrieval overlaps with recomputation of the earlier layers, hiding transmission latency, with thorough engineering optimization. |
6. Comparative Analysis with Similar Tools
| Comparison Dimension | MapFlow (PKU-DAIR, Peking University) | RedKnot (Xiaohongshu / Peking University / Huawei Cloud) |
|---|---|---|
| Problem Addressed | Repeated prefill in long context during model switching in multi-model routing/Agent workflows | Repeated prefill when the same document fragment appears across requests and non-prefix positions in long context RAG |
| Reuse Scope | Cross-model (model pairs with different layers, heads, or dimensions) | Within the same model, cross-requests (position-agnostic caching, PIC) |
| Reuse State | Attention map (token dependency structure) | KV Cache (decoupled management by head dimension) |
| Core Mechanism | Partial recomputation + layer/head linear mapping + block sparse top-p compression + integrated retrieval kernel | Offline head classification (global head recomputation/local head reuse) + RoPE position alignment + SegPagedAttention per-head paging + sparse FFN/MoE |
| Training Requirement | Required: offline calibration of linear mapping weights (<0.001% of model parameters, two LLMs are frozen) | No training required: needle-in-a-haystack offline classification of attention heads, zero overhead online |
| Quality Assurance | Recompute first r layers to maintain accuracy; attention map structure is transferable across models | Head-level recovery is better than token-level recovery; EM metric outperforms CacheBlend/ProphetKV (e.g., EM 0.60→0.80 on Llama-3.3-70B HotpotQA) |
| Latency/Computational Gain | TTFT reduced by 15%–20%, multi-round routing throughput increased by up to 25% | Prefill computation reduced by 3.9–4.3× (16K–24K), QPS/GPU at 64K is about 4× that of full recomputation |
| Inference Framework | Integrated with vLLM (Triton fusion kernel) | Initially built on SGLang, now default branch shifted to DeepInfer; vLLM integration is ongoing |
| Open Source Status | Open-sourced on GitHub, with four pre-calibrated model pairs included | Open-sourced on GitHub (Apache-2.0), DeepSeek-V4-Flash has one-click reproduction configuration |
| Applicable Scenarios | Multi-model routing, cascaded inference, multi-Agent workflows (e.g., database assistant, text-to-SQL with prefix-intensive workloads) | RAG services with repeated queries on the same long document, or high-concurrency scenarios with ultra-long context (128K+) |
| Main Limitations | Requires shared tokenizer; benefits are limited by the proportion of prefill latency in end-to-end latency | Only effective for the same model, does not address cross-model handoffs; limited benefits for short contexts, some model integrations are still experimental |
Selection Recommendations: For scenarios involving frequent cross-model handoffs, such as multi-model routing, cascaded inference, and multi-Agent workflows, MapFlow is currently the preferred open-source solution. Its cross-model attention map reuse mechanism fills a gap not covered by traditional Prefix Cache, especially for prefix-intensive workloads like database assistants and text-to-SQL. However, note the prerequisite of a shared tokenizer, and ensure that the model combinations meet this requirement before deployment.
For RAG services that repeatedly query the same long document or ultra-long context high-concurrency scenarios, RedKnot's position-agnostic caching (PIC) mechanism is more suitable. Its no-training, zero-overhead online characteristics make it more cost-effective to deploy, and it can achieve up to 4× QPS/GPU compared to full recomputation in contexts of 64K or more. If the scenario involves prefix reuse in single-model services, traditional Prefix Cache is sufficient, and there is no need to introduce additional mapping training and cache management complexity.
7. Editor's Summary
MapFlow introduces a novel, theoretically profound direction in the field of LLM inference optimization—treating "attention maps" as reusable states that can be transferred across models. The clever insight behind this approach lies in its departure from the traditional framework of strong coupling between KV Cache and model parameters, instead leveraging the generality of attention maps in capturing the dependency structure between tokens. Experimental data validates the effectiveness of this idea: prefill latency is reduced by 15%–20%, multi-round routing throughput can be increased by as much as 25%, all without compromising generation quality. From an engineering perspective, MapFlow's design is also highly practical: the addition of parameters is less than 0.001% of the receiving model's size, calibration is performed once for long-term benefits, and integration with GPU kernels avoids materializing dense intermediate tensors. These details ensure the practical usability of the solution.
The practical value of MapFlow is particularly evident in scenarios such as multi-model routing, cascaded inference, and multi-Agent workflows. As Agent applications become more widespread, interactions between models will become increasingly frequent, and the problem of redundant prefill that MapFlow addresses will become more prominent. Its open-source strategy includes pre-calibrated weights for four model pairs, reducing the barrier to entry for community adoption. However, the limitation of requiring a shared tokenizer and the need for offline calibration of mapping weights remain major obstacles to its broad application.
This system is suitable for the following users: first, system engineers building multi-model routing or Agent workflows, who can directly reduce inference costs using MapFlow; second, researchers exploring inference optimization techniques, as the concept of cross-model migration of attention maps holds significant academic value for further exploration; third, online service developers sensitive to inference latency, who can improve the long-tail TTFT and enhance user experience with MapFlow. In the future, if MapFlow can offer integration with more inference frameworks and support additional model pair combinations, it has the potential to become a key component of the infrastructure for multi-model inference.
8. FAQ
Q: What is the fundamental difference between MapFlow and traditional Prefix Cache?
A: Traditional Prefix Cache requires the request prefix to be exactly the same and the models to be identical. Due to strong coupling with hidden dimensions, layers, and parameters, KV Cache cannot be reused across different models. MapFlow reuses attention maps—i.e., the dependency structure between tokens—which exhibits cross-model similarity when the tokenizer and context are shared. This enables context computation sharing between models of different scales and architectures.
Q: Does using MapFlow require training the model? What is the training cost?
A: It requires offline calibration of the linear mapping weights, but the training cost is extremely low. The parameters of the two large models are fully frozen, and only a lightweight linear mapping under simplex constraints is trained. The added weights are less than 0.001% of the receiving model's parameters. Once calibrated, it can be used long-term, with the cost amortized across all subsequent online requests.
Q: What are the requirements for model combinations when using MapFlow?
A: The core requirement is that the sending model and the receiving model must share a tokenizer. Under this premise, the models can have different numbers of layers, heads, and hidden dimensions. MapFlow addresses structural differences between models through layer mapping (suffix alignment) and head mapping (simplex-constrained linear combination).
Q: How much performance improvement can MapFlow bring?
A: In experiments, prefill latency was reduced by 15%–20%, and in multi-turn routing scenarios, throughput increased by up to 25% under the same P90 latency constraints, primarily reducing the long-tail TTFT. However, the benefits are limited by the proportion of prefill latency in the end-to-end latency. If the inference phase dominates or the context is short, the overall acceleration effect may not be significant.
Q: How is memory usage controlled in long-context scenarios with MapFlow?
A: MapFlow employs block-level top-p sparse compression, selecting important attention blocks in units of 64×64 two-dimensional blocks. This compresses the dense attention matrix into a block-sparse (BSR) format, avoiding the materialization of the full dense matrix. After 12K tokens, memory usage stabilizes, making it feasible for practical use in long-context scenarios.
Q: Which inference frameworks does MapFlow currently support?
A: MapFlow is currently primarily integrated with the vLLM framework, using Triton's fused kernel to achieve efficient cross-head linear transformations and Value multiply-add fusion. Support for other mainstream inference frameworks such as SGLang and TensorRT-LLM still requires expansion.
9. Project Links
- GitHub Repository: https://github.com/PKU-DAIR/MapFlow
- arXiv Technical Paper: https://arxiv.org/pdf/2610.14688
© All Rights Reserved. Some content on this site is partially generated by AI with human review.


