-
Notifications
You must be signed in to change notification settings - Fork 118
Add tutorial for KV cache compression with TurboQuant #438
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kacperlukawski
wants to merge
4
commits into
main
Choose a base branch
from
turboquant-tutorial
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+255
−0
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
65416cd
Add tutorial for KV cache compression with TurboQuant
kacperlukawski 0b86083
Make it clear that we use unofficial turboquant implementation
kacperlukawski abc01d4
Sspecify Python version in tutorial configuration
kacperlukawski 47a33b0
Remove HF_TOKEN ref
kacperlukawski File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
242 changes: 242 additions & 0 deletions
242
tutorials/49_TurboQuant_Quantization_with_HuggingFace.ipynb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,242 @@ | ||
| { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can you leave the outputs, especially when we print a result? I find these very useful Reply via ReviewNB |
||
| "cells": [ | ||
| { | ||
| "cell_type": "markdown", | ||
| "metadata": {}, | ||
| "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." | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "markdown", | ||
| "metadata": {}, | ||
| "source": [ | ||
| "## Overview\n", | ||
| "\n", | ||
| "Every 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", | ||
| "\n", | ||
| "1. **PolarQuant** - a random orthogonal rotation maps cache vectors to a more uniform distribution, then quantizes them in polar coordinates using Lloyd-Max optimal centroids.\n", | ||
| "2. **QJL** (Quantized Johnson-Lindenstrauss) - a single extra bit per vector corrects residual errors in attention score computation, preserving accuracy at extreme compression ratios.\n", | ||
| "\n", | ||
| "The 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", | ||
| "\n", | ||
| "In this tutorial you will use [`turboquant-vllm`](https://github.com/Alberto-Codes/turboquant-vllm), a community implementation of the TurboQuant algorithm, to wire `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." | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "markdown", | ||
| "metadata": {}, | ||
| "source": [ | ||
| "## Installing Haystack and TurboQuant\n", | ||
| "\n", | ||
| "First, let's install `haystack-ai` and [`turboquant-vllm`](https://github.com/Alberto-Codes/turboquant-vllm), a community implementation of the TurboQuant algorithm that provides the `CompressedDynamicCache` wrapper." | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "code", | ||
| "execution_count": null, | ||
| "metadata": {}, | ||
| "outputs": [], | ||
| "source": [ | ||
| "%%bash\n", | ||
| "\n", | ||
| "pip install -q haystack-ai turboquant-vllm" | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "markdown", | ||
| "metadata": {}, | ||
| "source": [ | ||
| "## Setting Up a Streaming Callback\n", | ||
| "\n", | ||
| "To measure **time-to-first-token (TTFT)** and throughput, we pass a streaming callback that timestamps each arriving token. The first call marks TTFT, while the last marks the end of generation." | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "code", | ||
| "execution_count": null, | ||
| "metadata": {}, | ||
| "outputs": [], | ||
| "source": [ | ||
| "import time\n", | ||
| "\n", | ||
| "first_token_time = None\n", | ||
| "last_token_time = None\n", | ||
| "\n", | ||
| "def timing_callback(chunk):\n", | ||
| " global first_token_time, last_token_time\n", | ||
| " now = time.perf_counter()\n", | ||
| " if first_token_time is None:\n", | ||
| " first_token_time = now\n", | ||
| " last_token_time = now" | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "markdown", | ||
| "metadata": {}, | ||
| "source": [ | ||
| "## Compressing the KV Cache\n", | ||
| "\n", | ||
| "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", | ||
| "\n", | ||
| "Two parameters control the compression:\n", | ||
| "- `head_dim` - the dimensionality of each attention head's key/value vectors\n", | ||
| "- `bits` - the target bit-width per coordinate\n", | ||
| "\n", | ||
| "> **Note**: Pass the original `cache` object to the generator - not `compressed`. `CompressedDynamicCache` modifies `cache` internally, so both variables point to the same compressed state." | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "code", | ||
| "execution_count": 10, | ||
| "metadata": {}, | ||
| "outputs": [], | ||
| "source": [ | ||
| "from transformers import DynamicCache\n", | ||
| "from turboquant_vllm import CompressedDynamicCache\n", | ||
| "\n", | ||
| "# The CompressedDynamicCache modifies the DynamicCache internally,\n", | ||
| "# so we pass the same `cache` instance to both the generator,\n", | ||
| "# and not `compressed` directly.\n", | ||
| "cache = DynamicCache()\n", | ||
| "compressed = CompressedDynamicCache(cache, head_dim=128, bits=4)" | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "markdown", | ||
| "metadata": {}, | ||
| "source": [ | ||
| "## Initializing the Generator\n", | ||
| "\n", | ||
| "Now 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." | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "code", | ||
| "execution_count": null, | ||
| "metadata": {}, | ||
| "outputs": [], | ||
| "source": [ | ||
| "from haystack.components.generators.chat import HuggingFaceLocalChatGenerator\n", | ||
| "from haystack.utils import Secret\n", | ||
| "\n", | ||
| "generator = HuggingFaceLocalChatGenerator(\n", | ||
| " model=\"Qwen/Qwen3-4B-Thinking-2507\",\n", | ||
| " task=\"text-generation\",\n", | ||
| " generation_kwargs={\n", | ||
| " \"past_key_values\": cache,\n", | ||
| " \"use_cache\": True,\n", | ||
| " },\n", | ||
| " streaming_callback=timing_callback,\n", | ||
| ")" | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "markdown", | ||
| "metadata": {}, | ||
| "source": [ | ||
| "## Running the Generator\n", | ||
| "\n", | ||
| "Let's run a generation and record the total wall time." | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "code", | ||
| "execution_count": null, | ||
| "metadata": {}, | ||
| "outputs": [], | ||
| "source": [ | ||
| "from haystack.dataclasses import ChatMessage\n", | ||
| "\n", | ||
| "start = time.perf_counter()\n", | ||
| "output = generator.run(messages=[\n", | ||
| " ChatMessage.from_user(\"What is the capital of France?\"),\n", | ||
| "])\n", | ||
| "total_time = time.perf_counter() - start" | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "code", | ||
| "execution_count": null, | ||
| "metadata": {}, | ||
| "outputs": [], | ||
| "source": [ | ||
| "reply = output[\"replies\"][0]\n", | ||
| "print(reply.text)" | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "markdown", | ||
| "metadata": {}, | ||
| "source": [ | ||
| "## Reading the Metrics\n", | ||
| "\n", | ||
| "Three 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." | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "code", | ||
| "execution_count": null, | ||
| "metadata": {}, | ||
| "outputs": [], | ||
| "source": [ | ||
| "tokens = reply.meta[\"usage\"][\"completion_tokens\"]\n", | ||
| "if first_token_time is not None and last_token_time is not None:\n", | ||
| " generation_time = last_token_time - first_token_time\n", | ||
| " print(f\"TTFT: {first_token_time - start:.3f}s\")\n", | ||
| " print(f\"Tokens: {tokens}\")\n", | ||
| " print(f\"Speed: {tokens / generation_time:.1f} tok/s\")\n", | ||
| "print(f\"Total time: {total_time:.3f}s\")" | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "markdown", | ||
| "metadata": {}, | ||
| "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." | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "code", | ||
| "execution_count": null, | ||
| "metadata": {}, | ||
| "outputs": [], | ||
| "source": [ | ||
| "compressed.vram_bytes()" | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "markdown", | ||
| "metadata": {}, | ||
| "source": [ | ||
| "🎉 Congratulations! You've successfully run a local LLM with TurboQuant KV cache compression through Haystack and measured its real-world memory and throughput impact." | ||
| ] | ||
| } | ||
| ], | ||
| "metadata": { | ||
| "kernelspec": { | ||
| "display_name": "Python 3", | ||
| "language": "python", | ||
| "name": "python3" | ||
| }, | ||
| "language_info": { | ||
| "name": "python", | ||
| "version": "3.10.0" | ||
| } | ||
| }, | ||
| "nbformat": 4, | ||
| "nbformat_minor": 4 | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Components Used:..
Goal: After completing this tutorial, you will have learned how to apply TurboQuant KV cache compression to a local LLM and measure its memory and throughput impact with Haystack.
Reply via ReviewNB