You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
"source": "# Compress the KV Cache with TurboQuant and Haystack\n\n- **Level**: Advanced\n- **Time to complete**: 20 min\n- **Nodes Used**: [`HuggingFaceLocalChatGenerator`](https://docs.haystack.deepset.ai/docs/huggingfacelocalchatgenerator)\n- **Goal**: Apply TurboQuant KV cache compression to a local LLM and measure its memory and throughput impact with Haystack."
7
+
},
8
+
{
9
+
"cell_type": "markdown",
10
+
"metadata": {},
11
+
"source": "## Overview\n\nEvery time an LLM generates a token, it reads and writes a **key-value (KV) cache** - a growing table of intermediate activations that lets the model attend to previous tokens without recomputing them. On long contexts or large models, this cache becomes the dominant consumer of GPU memory.\n\n[TurboQuant](https://research.google/blog/turboquant-redefining-ai-efficiency-with-extreme-compression/) is a KV cache compression algorithm from Google Research (ICLR 2026) that shrinks those vectors to 3–4 bits per coordinate without any retraining. It works in two stages:\n\n1. **PolarQuant** - a random orthogonal rotation maps cache vectors to a more uniform distribution, then quantizes them in polar coordinates using Lloyd-Max optimal centroids.\n2. **QJL** (Quantized Johnson-Lindenstrauss) - a single extra bit per vector corrects residual errors in attention score computation, preserving accuracy at extreme compression ratios.\n\nThe result: KV memory can drop from 1,639 MiB to 435 MiB (3.76x) on an RTX 4090, with ≥6x reduction validated on server hardware, and near-identical output quality.\n\nIn this tutorial you will wire TurboQuant's `CompressedDynamicCache` into Haystack's [`HuggingFaceLocalChatGenerator`](https://docs.haystack.deepset.ai/docs/huggingfacelocalchatgenerator), run a generation, and measure time-to-first-token, throughput, and live VRAM usage."
12
+
},
13
+
{
14
+
"cell_type": "markdown",
15
+
"metadata": {},
16
+
"source": "## Installing Haystack and TurboQuant\n\nFirst, let's install `haystack-ai` and `turboquant-vllm`, which provides the `CompressedDynamicCache` wrapper."
17
+
},
18
+
{
19
+
"cell_type": "code",
20
+
"execution_count": null,
21
+
"metadata": {},
22
+
"outputs": [],
23
+
"source": [
24
+
"%%bash\n",
25
+
"\n",
26
+
"pip install -q haystack-ai turboquant-vllm"
27
+
]
28
+
},
29
+
{
30
+
"cell_type": "markdown",
31
+
"metadata": {},
32
+
"source": "## Setting Up a Streaming Callback\n\nTo measure **time-to-first-token (TTFT)** and throughput, we pass a streaming callback that timestamps each arriving token. The first call marks TTFT; the last marks the end of generation."
33
+
},
34
+
{
35
+
"cell_type": "code",
36
+
"execution_count": null,
37
+
"metadata": {},
38
+
"outputs": [],
39
+
"source": [
40
+
"import time\n",
41
+
"\n",
42
+
"first_token_time = None\n",
43
+
"last_token_time = None\n",
44
+
"\n",
45
+
"def timing_callback(chunk):\n",
46
+
" global first_token_time, last_token_time\n",
47
+
" now = time.perf_counter()\n",
48
+
" if first_token_time is None:\n",
49
+
" first_token_time = now\n",
50
+
" last_token_time = now"
51
+
]
52
+
},
53
+
{
54
+
"cell_type": "markdown",
55
+
"metadata": {},
56
+
"source": [
57
+
"## Compressing the KV Cache\n",
58
+
"\n",
59
+
"Next, let's create the compressed cache. We start with HuggingFace's standard `DynamicCache` and wrap it with `CompressedDynamicCache`, which intercepts cache writes and applies TurboQuant compression in place.\n",
60
+
"\n",
61
+
"Two parameters control the compression:\n",
62
+
"- `head_dim` - the dimensionality of each attention head's key/value vectors\n",
63
+
"- `bits` - the target bit-width per coordinate\n",
64
+
"\n",
65
+
"> **Note**: Pass the original `cache` object to the generator - not `compressed`. `CompressedDynamicCache` modifies `cache` internally, so both variables point to the same compressed state."
"source": "## Initializing the Generator\n\nNow let's set up [`HuggingFaceLocalChatGenerator`](https://docs.haystack.deepset.ai/docs/huggingfacelocalchatgenerator) with a selected model, like `Qwen/Qwen3-4B-Thinking-2507`. We pass the compressed `cache` via `generation_kwargs` so that every decoding step writes through TurboQuant."
"Let's run a generation and record the total wall time."
117
+
]
118
+
},
119
+
{
120
+
"cell_type": "code",
121
+
"execution_count": null,
122
+
"metadata": {},
123
+
"outputs": [],
124
+
"source": [
125
+
"from haystack.dataclasses import ChatMessage\n",
126
+
"\n",
127
+
"start = time.perf_counter()\n",
128
+
"output = generator.run(messages=[\n",
129
+
" ChatMessage.from_user(\"What is the capital of France?\"),\n",
130
+
"])\n",
131
+
"total_time = time.perf_counter() - start"
132
+
]
133
+
},
134
+
{
135
+
"cell_type": "code",
136
+
"execution_count": null,
137
+
"metadata": {},
138
+
"outputs": [],
139
+
"source": [
140
+
"reply = output[\"replies\"][0]\n",
141
+
"print(reply.text)"
142
+
]
143
+
},
144
+
{
145
+
"cell_type": "markdown",
146
+
"metadata": {},
147
+
"source": "## Reading the Metrics\n\nThree metrics to check:\n\n- **TTFT** (time-to-first-token) - latency to the first output token; a proxy for perceived responsiveness.\n- **Throughput** (tok/s) - tokens decoded per second. TurboQuant's memory savings reduce cache read pressure, which can improve this on memory-bandwidth-bound hardware.\n- **Total time** - end-to-end wall time including model loading overhead."
"source": "## Checking VRAM Usage\n\n`vram_bytes()` returns the byte footprint of all compressed KV tensors. Compare it against an uncompressed `DynamicCache` to verify the reduction reported in the TurboQuant paper."
168
+
},
169
+
{
170
+
"cell_type": "code",
171
+
"execution_count": null,
172
+
"metadata": {},
173
+
"outputs": [],
174
+
"source": [
175
+
"compressed.vram_bytes()"
176
+
]
177
+
},
178
+
{
179
+
"cell_type": "markdown",
180
+
"metadata": {},
181
+
"source": [
182
+
"🎉 Congratulations! You've successfully run a local LLM with TurboQuant KV cache compression through Haystack and measured its real-world memory and throughput impact."
0 commit comments