Metadata-Version: 2.4
Name: dag-kv
Version: 0.7.1
Summary: Universal Position-Decoupled Graph KV Cache with Query-Side Adjoint RoPE & LSE-Bounded Sparse Bridge Repair
Author: Kaushal Dineshbhai Nandaniya
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/kaushalnandaniya/dag-kv
Project-URL: Documentation, https://kaushalnandaniya.github.io/dag-kv/
Project-URL: Repository, https://github.com/kaushalnandaniya/dag-kv
Project-URL: Issues, https://github.com/kaushalnandaniya/dag-kv/issues
Project-URL: Changelog, https://github.com/kaushalnandaniya/dag-kv/blob/main/CHANGELOG.md
Keywords: kv-cache,llm,llm-inference,paged-attention,rope,triton,vllm,deepseek,mla,rag,rdma,pytorch
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: System :: Distributed Computing
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: torch>=2.2.0
Requires-Dist: transformers>=4.44.0
Requires-Dist: accelerate>=0.33.0
Requires-Dist: numpy>=1.26.0
Requires-Dist: safetensors>=0.4.0
Requires-Dist: pyyaml>=5.3.0
Requires-Dist: triton>=3.0.0; sys_platform == "linux"
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pytest-cov; extra == "dev"
Requires-Dist: ruff>=0.8.0; extra == "dev"
Provides-Extra: vllm
Requires-Dist: vllm>=0.6.0; extra == "vllm"
Provides-Extra: cluster
Requires-Dist: redis>=5.0.0; extra == "cluster"
Requires-Dist: boto3>=1.34.0; extra == "cluster"
Provides-Extra: ast
Requires-Dist: tree-sitter-language-pack>=0.7.0; extra == "ast"
Provides-Extra: observability
Requires-Dist: opentelemetry-api>=1.20.0; extra == "observability"
Requires-Dist: opentelemetry-sdk>=1.20.0; extra == "observability"
Dynamic: license-file

<div align="center">

# DAG-KV

**Position-Decoupled Graph KV Cache for Fast, Order-Invariant LLM Serving**

[![CI](https://github.com/kaushalnandaniya/dag-kv/actions/workflows/ci.yml/badge.svg)](https://github.com/kaushalnandaniya/dag-kv/actions/workflows/ci.yml)
[![Docs](https://github.com/kaushalnandaniya/dag-kv/actions/workflows/docs.yml/badge.svg)](https://kaushalnandaniya.github.io/dag-kv/)
[![PyPI](https://img.shields.io/pypi/v/dag-kv?color=blue)](https://pypi.org/project/dag-kv/)
[![Python](https://img.shields.io/pypi/pyversions/dag-kv)](https://pypi.org/project/dag-kv/)
[![License](https://img.shields.io/badge/License-Apache%202.0-green.svg)](https://github.com/kaushalnandaniya/dag-kv/blob/main/LICENSE)
[![Paper](https://img.shields.io/badge/Paper-Preprint%20PDF-b31b1b)](https://github.com/kaushalnandaniya/dag-kv/blob/main/paper/dag_kv_arxiv_preprint.pdf)
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/kaushalnandaniya/dag-kv/blob/main/examples/dag_kv_colab_demo.ipynb)

<p>
  <a href="https://kaushalnandaniya.github.io/dag-kv/"><b>Documentation</b></a> &nbsp;·&nbsp;
  <a href="https://kaushalnandaniya.github.io/dag-kv/quickstart/"><b>Quickstart</b></a> &nbsp;·&nbsp;
  <a href="https://kaushalnandaniya.github.io/dag-kv/benchmarks/"><b>Benchmarks</b></a> &nbsp;·&nbsp;
  <a href="https://github.com/kaushalnandaniya/dag-kv/tree/main/examples"><b>Examples</b></a> &nbsp;·&nbsp;
  <a href="https://github.com/kaushalnandaniya/dag-kv/blob/main/paper/dag_kv_arxiv_preprint.pdf"><b>Paper (PDF)</b></a> &nbsp;·&nbsp;
  <a href="https://github.com/kaushalnandaniya/dag-kv/blob/main/CHANGELOG.md"><b>Changelog</b></a> &nbsp;·&nbsp;
  <a href="https://github.com/kaushalnandaniya/dag-kv/blob/main/ROADMAP.md"><b>Roadmap</b></a>
</p>

<img src="https://raw.githubusercontent.com/kaushalnandaniya/dag-kv/main/assets/dag_kv_demo.gif" alt="DAG-KV vs Standard Prefix Caching Demo" width="90%" />

</div>

---

**DAG-KV** eliminates the **0% prefix cache hit cliff** in RAG pipelines and AI coding assistants. Standard prefix caches (vLLM Automatic Prefix Caching, SGLang RadixAttention) require exact left-to-right token matches from index `0` — reordering retrieved documents (`[Doc_B, Doc_A]`) or editing one function near the top of a file invalidates the entire cached suffix.

DAG-KV stores document and AST-symbol KV blocks in a **100% read-only, zero-copy canonical graph** and applies exact **Query-Side Adjoint RoPE** ($\mathcal{R}(-\Delta_b)$) in SRAM registers alongside **LSE-bounded Submodular Bridge Repair** (`4% → 1.5%`) — achieving **100% cache reuse under arbitrary permutations** across GQA and absorbed DeepSeek MLA architectures.

## Latest News

- **`v0.7.0` Released** ([Release Notes](https://github.com/kaushalnandaniya/dag-kv/blob/main/docs/launch_post.md) · [Changelog](https://github.com/kaushalnandaniya/dag-kv/blob/main/CHANGELOG.md)):
  - **Beats live `vLLM 0.34.0` APC (`4.77×`/`4.00×`) and `SGLang 1.0.0` RadixAttention (`4.29×`/`3.42×`)** on H200 `Qwen2.5-14B` permuted prompts (`3/3 EM`), while matching SGLang within `0.47 ms` on `18.5K` prefix hits.
  - **Outperforms CacheBlend-15%** on standardized real **LongBench (`N=111`)** (`40.70` vs `40.36` macro avg) at **`2.10×` lower TTFT** (`4.65×` faster than Dense Oracle).
  - **Real `DeepSeek-V2-Lite-Chat` Absorbed MLA Engine (`DeepSeekMLADAGKVEngine`)**: `8.89×` native KV VRAM compression, `3/3 EM` via Latent-Space CoW Bridge Repair, and `8.48×` faster prefill at `32K`.
  - **Single-H200 `Qwen2.5-32B` Scaling & Live `100GbE RoCE` RDMA**: `10.03×` (`8.4K`) / `7.00×` (`33.8K`, `3/3 EM`) Native FP8, `242 tok/s` (`6.50×`) lossless speculative decoding, native `vLLM v1` plugin GPU parity (`0.0` roundtrip diff), and **`10.44 GB/s` (`83.5 Gbps`)** H200 → Blackwell RoCE KV transfer.

---

## Installation

```bash
pip install dag-kv
```

Optional extras:

```bash
pip install "dag-kv[vllm]"           # Zero-fork vLLM v0 & v1 plugin
pip install "dag-kv[ast]"            # Tree-sitter multi-language AST chunking
pip install "dag-kv[cluster]"        # Redis & S3 Tier-4 cluster KV fabric
pip install "dag-kv[observability]"  # OpenTelemetry distributed tracing
```

Verify discovered accelerators, Triton JIT availability, and recommended topology:

```bash
dag-kv info
```

---

## Quickstart

### 1. Drop-In Hugging Face Wrapper (3 Lines)

```python
from transformers import AutoModelForCausalLM, AutoTokenizer
from dag_kv import patch_hf_model

model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-3B-Instruct")
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-3B-Instruct")

# Auto-detects GPU/MPS/CPU, Triton kernels, and model adapter (GQA or DeepSeek MLA)
dag_model = patch_hf_model(model, tokenizer, quantization="k8v4", block_size=16)

# Prefill chunks once in isolation into read-only canonical memory
doc_a = dag_model.prefill_chunk("Service A: Uses PostgreSQL 16 on port 5432...")
doc_b = dag_model.prefill_chunk("Service B: JWT auth middleware validates scopes...")

# Query in ANY permutation with 100% zero-copy KV reuse
print(dag_model.generate([doc_b, doc_a], prompt_suffix="Which database does Service A use?"))
```

### 2. OpenAI-Compatible Server, Cluster KV Fabric & MCP

```bash
# Start a shared Tier-4 Cluster KV Cache Node (HTTP/Binary/RDMA/Redis/S3)
dag-kv cache-node --host 0.0.0.0 --port 9100 --cache-dir /var/lib/dagkv-cluster --max-disk-gb 128

# Launch an async OpenAI/SSE server with K8V4 quantization, CUDA Graphs & NVMe spill
dag-kv serve --host 0.0.0.0 --port 8000 \
  --model Qwen/Qwen2.5-7B-Instruct --sharded \
  --quantization k8v4 --bridge-strategy lse_hybrid --cuda-graphs \
  --disk-cache /tmp/dag_kv_cache --remote-cache-url http://127.0.0.1:9100

# Or connect directly to Claude Code / Cursor / Cline over MCP stdio
dag-kv mcp --model Qwen/Qwen2.5-3B-Instruct --quantization k8v4
```

### 3. Zero-Fork vLLM v0 & v1 Plugin

`dag-kv` auto-registers via the `vllm.general_plugins` entry point (`KVConnectorBase_V1` + `vllm.v1.attention.backend.AttentionBackend` — live-verified on `vLLM 0.34.0` H200 with `0.0` KV roundtrip diff). See [Integrations Docs](https://kaushalnandaniya.github.io/dag-kv/integrations/) and [`examples/05_vllm_kv_connector.py`](https://github.com/kaushalnandaniya/dag-kv/blob/main/examples/05_vllm_kv_connector.py) for LangChain, LlamaIndex, vLLM, and MCP recipes.

---

## Headline Benchmarks (`v0.7.0`)

<div align="center">
  <img src="https://raw.githubusercontent.com/kaushalnandaniya/dag-kv/main/assets/dag_kv_v1_flagship.png" alt="DAG-KV v0.7.0 Flagship Evaluation on NVIDIA H200 NVL and RTX PRO 6000 Blackwell" width="96%" />
</div>

### Live 3-Way H200 Head-to-Head (`vLLM 0.34.0` vs. `SGLang 1.0.0` vs. `DAG-KV`)

| Workload (NVIDIA H200 NVL 141 GB, `sm_90`) | `vLLM 0.34.0` APC | `SGLang 1.0.0` RadixAttn | **DAG-KV (`K8V4`)** | Speedup vs. vLLM / SGLang |
|---|---:|---:|---:|---|
| `Qwen2.5-3B` — `9.2K` Permuted RULER | 121.89 ms (0%) | 103.26 ms (0%) | **37.36 ms (100%)** | **3.26× / 2.76×** (`3/3 EM`) |
| `Qwen2.5-3B` — `18.5K` Permuted RULER | 298.16 ms (0%) | 263.95 ms (0%) | **99.52 ms (100%)** | **3.00× / 2.65×** (`3/3 EM`) |
| `Qwen2.5-3B` — `18.5K` Same-Order Prefix Hit | 32.28 ms | **24.57 ms** | **25.04 ms (Bypass)** | **1.29× vs vLLM** (within `0.47 ms` of SGLang) |
| `Qwen2.5-14B` — `9.2K` Permuted RULER | 487.09 ms (0%) | 437.92 ms (0%) | **102.06 ms (100%)** | **4.77× / 4.29×** (`3/3 EM`) |
| `Qwen2.5-14B` — `18.5K` Permuted RULER | 1,168.91 ms (0%) | 1,000.38 ms (0%) | **292.18 ms (100%)** | **4.00× / 3.42×** (`3/3 EM`) |
| `Qwen2.5-14B` — Live IDE Edit (`pytorch_fallbacks.py`) | 157.36 ms (miss) | **68.27 ms** | **71.15 ms (AST Delta)** | **2.21× vs vLLM** (`92.7%` AST reuse) |

### LongBench vs. CacheBlend, `Qwen2.5-32B`, Real `DeepSeek-V2-Lite` MLA & `100GbE RoCE RDMA`

| Evaluation Suite (`H200 NVL` & `RTX PRO 6000 Blackwell`) | Baseline | **DAG-KV (`v0.7.0`)** | Verified Gain / Fidelity |
|---|---:|---:|---|
| **LongBench Macro Avg (`N=111`, 4 tasks, `Qwen2.5-14B`)** | Dense `410.3 ms` (`43.69`) / CB-15% `185.7 ms` (`40.36`) | **`88.3 ms` (`40.70`)** | **Beats CB-15% @ `2.10×` faster / `4.65×` vs Dense** |
| **`Qwen2.5-32B` (64 GB) Permuted `8.4K` / `33.8K` (FP8)** | `1,199.6` / `6,741.3 ms` (Dense) | **`119.6` / `963.7 ms`** | **`10.03×` / `7.00×` faster \| `3/3 EM`** |
| **`Qwen2.5-32B` & `14B` Lossless Speculative Decode** | `37.2` / `69.9 tok/s` | **`242.0` / `352.1 tok/s`** | **`6.50×` (32B) / `5.04×` (14B) \| 100% lossless** |
| **Real `DeepSeek-V2-Lite-Chat` Absorbed MLA (6-Doc / `32K`)** | `1/3 EM` (`0%`) / `1,695.1 ms` | **`3/3 EM` / `199.8 ms`** | **`8.89×` KV compression \| `8.48×` @ `32K`** |
| **2-Node `100GbE RoCE` RDMA: H200 → Blackwell (`bnxt_re0`)** | `99.9 MB/s` (1GbE HTTP) | **`10.44 GB/s` (`83.5 Gbps`)** | **`91.8%` of `ib_write_bw` ceiling (`107×` HTTP, bit-exact)** |
| **Blackwell `sm_120` 64K GQA-SplitKV & DeepSeek MLA** | `47.9 ms` FP16 / `215 ms` PT | **`33.3 ms` K8V4 / `2.00 ms` MLA** | **`1.44×` @ 64K / `107.3×` MLA (`8.01 ms` @ 64K)** |

> See **[Full Multi-Generation Benchmarks](https://kaushalnandaniya.github.io/dag-kv/benchmarks/)** (including RTX 2080 Ti vs. `vLLM 0.6.6`, quantization Pareto, 8K concurrency ceiling, CUDA Graphs, and TP=2) and **[`benchmarks/README.md`](https://github.com/kaushalnandaniya/dag-kv/blob/main/benchmarks/README.md)** for exact reproduction commands.

---

## How It Works

```mermaid
flowchart LR
    A["Documents / AST Symbols"] --> B["Sink-Canonicalized Isolated Prefill"]
    B --> C[("Read-Only Paged Pool<br/>FP16 / FP8 / K8V4 / INT4 / MLA")]
    C --> D["Dynamic DAG Assembly<br/>(Any Permutation · Block Delta Δ_b)"]
    D --> E["Query-Side Adjoint RoPE<br/>q_adj = R(-Δ_b) q in SRAM"]
    D --> F["Layer-1 Q1 LSE + 1D NMS<br/>Bridge Repair (4% → 1.5%)"]
    F --> G["Request-Private CoW Shadow Blocks"]
    E --> H["GQA-SplitKV / MLA Decode<br/>+ Speculative / CUDA Graphs"]
    G --> H
    C <--> I["4-Tier Fabric: HBM ↔ Pinned RAM ↔ NVMe ↔ 100GbE RoCE RDMA"]
```

1. **Query-Side Adjoint RoPE in $\mathrm{SO}(2)$:** Because RoPE matrices satisfy $\mathcal{R}(p + \Delta_b) = \mathcal{R}(\Delta_b)\mathcal{R}(p)$ and $\mathcal{R}(\Delta_b)^T = \mathcal{R}(-\Delta_b)$, counter-rotating queries in Triton SRAM registers preserves exact relative positions while keeping physical KV blocks **100% immutable and globally shareable across concurrent tenants**:
   $$\big\langle \tilde{\mathbf{q}}_{\text{global}},\, \mathcal{R}(\Delta_b)\tilde{\mathbf{k}}_{\text{canon}} \big\rangle = \big\langle \mathcal{R}(-\Delta_b)\tilde{\mathbf{q}}_{\text{global}},\, \tilde{\mathbf{k}}_{\text{canon}} \big\rangle$$
2. **Canonical Attention Sink Isolation:** Every chunk is prefilled behind a shared 4-token canonical sink prefix (`[0..3]`) and sliced to payload offsets `[4..L+3]`, eliminating norm pathologies when relocated to $\Delta_b > 0$.
3. **Exact Layer-1 $Q_1$ LSE + Submodular Pyramid Repair:** Captures local Log-Sum-Exp $\ell_i^{\text{local}}$ during isolated prefill and bounds cross-chunk drift via $\alpha_i = \sigma(\ell_{i\to\text{prior}} - \ell_i^{\text{local}})$, repairing only `4.0% → 1.5%` diverse bridge tokens (or latent-space MLA bridges) into Copy-on-Write shadow blocks.

---

## Support Matrix

| Dimension | Supported Targets |
|---|---|
| **Model Families** | Qwen-2 / 2.5 / 3 (QK-Norm), Llama-2 / 3 / 3.2, DeepSeek-V2 / V3 / R1 (**Absorbed MLA** `DeepSeekMLADAGKVEngine`), Mistral / Mixtral (SWA), Gemma-2 (logit softcapping + alternating SWA) |
| **Hardware & Backends** | NVIDIA CUDA (`sm_75` Turing → `sm_90` Hopper → `sm_120` Blackwell, Triton JIT), AMD ROCm (Triton), Apple Silicon (`mlx_backend.py` + MPS), Host CPU (vectorized PyTorch fallback) |
| **KV Compression** | `none` (FP16/BF16), Native `fp8` (`sm_89+`), `int8` (`1.97×`), **`k8v4`** (`2.53×`, default), `int4` (`3.05×`), Native Absorbed MLA (`8.89×`) |
| **Parallelism & Serving** | Single-GPU, Megatron Tensor Parallelism (`TP=2`), Dual-GPU Ping-Pong Pipeline, CUDA Graph Decode, Prompt-Lookup Speculative Decoding, Batched Ragged Prefill, OpenAI SSE Server |
| **Storage & Cluster Fabric** | HBM → `PinnedCPUPool` → NVMe `DiskKVCache` (`SCHEMA_VERSION=1.0`) → `NCCLRDMAKVStore` (100GbE RoCE/IB), `BinaryStreamKVStore`, `NIXLRDMAKVStore`, `SharedHTTPKVStore`, Redis, S3 |
| **Ecosystem Integrations** | Zero-fork **vLLM v0 & v1 Plugin**, **Hugging Face**, **LangChain**, **LlamaIndex**, **MCP Server (`dag-kv mcp`)**, **Tree-sitter / Python AST**, **OpenTelemetry & Prometheus/Grafana** |

---

## Development & Testing

```bash
git clone https://github.com/kaushalnandaniya/dag-kv.git
cd dag-kv
pip install -e ".[dev]"
ruff check dag_kv tests
pytest -v tests/                     # Full GPU suite (123 tests)
CUDA_VISIBLE_DEVICES="" pytest -v    # CPU-only fallback suite (macOS / CI)
```

See [CONTRIBUTING.md](https://github.com/kaushalnandaniya/dag-kv/blob/main/CONTRIBUTING.md), [CODE_OF_CONDUCT.md](https://github.com/kaushalnandaniya/dag-kv/blob/main/CODE_OF_CONDUCT.md), and [SECURITY.md](https://github.com/kaushalnandaniya/dag-kv/blob/main/SECURITY.md) for guidelines.

---

## Citation & License

If you use DAG-KV in your research or serving stack, please cite our work (also available via GitHub's **"Cite this repository"** button from [`CITATION.cff`](https://github.com/kaushalnandaniya/dag-kv/blob/main/CITATION.cff)):

```bibtex
@software{nandaniya2026dagkv,
  title   = {{DAG-KV: Position-Decoupled Graph KV Cache with Query-Side Adjoint RoPE and LSE-Bounded Sparse Bridge Repair}},
  author  = {Nandaniya, Kaushal Dineshbhai},
  year    = {2026},
  version = {0.7.1},
  url     = {https://github.com/kaushalnandaniya/dag-kv}
}
```

Released under the [Apache License 2.0](https://github.com/kaushalnandaniya/dag-kv/blob/main/LICENSE).
