In this tutorial, we take a detailed, practical approach to exploring NVIDIA’s KVPress and understanding how it can make long-context language model inference more efficient. We begin by setting up the full environment, installing the required libraries, loading a compact Instruct model, and preparing a simple workflow that runs in Colab while still demonstrating the real value of KV cache compression. As we move through implementation, we create a synthetic long-context corpus, define targeted extraction questions, and run multiple inference experiments to directly compare standard generation with different KVPress strategies. At the end of the tutorial, we will have built a stronger intuition for how long-context optimization works in practice, how different press methods affect performance, and how this kind of workflow can be adapted for real-world retrieval, document analysis, and memory-sensitive LLM applications.
warnings.filterwarnings(“ignore”)
def run(cmd):
print(“\n[RUN]”, ” “.join(cmd))
subprocess.check_call(cmd)
run([sys.executable, “-m”, “pip”, “install”, “-q”, “–upgrade”, “pip”])
run([sys.executable, “-m”, “pip”, “install”, “-q”, “torch”, “transformers”, “accelerate”, “bitsandbytes”, “sentencepiece”, “kvpress==0.4.0”])
try:
from google.colab import userdata
hf_token = userdata.get(“HF_TOKEN”)
except Exception:
hf_token = os.environ.get(“HF_TOKEN”, “”)
if not hf_token:
try:
import getpass
hf_token = getpass.getpass(“Enter your Hugging Face token (leave empty if model is public and accessible): “).strip()
except Exception:
hf_token = “”
if hf_token:
os.environ[“HF_TOKEN”] = hf_token
os.environ[“HUGGINGFACEHUB_API_TOKEN”] = hf_token
import torch
import transformers
import kvpress
from transformers import pipeline, BitsAndBytesConfig
from kvpress import ExpectedAttentionPress, KnormPress
print(“Python:”, sys.version.split()[0])
print(“Torch:”, torch.__version__)
print(“Transformers:”, transformers.__version__)
print(“CUDA available:”, torch.cuda.is_available())
if torch.cuda.is_available():
print(“GPU:”, torch.cuda.get_device_name(0))
MODEL_ID = “Qwen/Qwen2.5-1.5B-Instruct”
MAX_NEW_TOKENS = 96
SEED = 42
random.seed(SEED)
torch.manual_seed(SEED)
We set up the Colab environment and install all required libraries to run the KVPress workflow successfully. We securely collect the Hugging Face token, set environment variables, and import the core modules needed for model loading, pipeline execution, and compression experiments. We also print the runtime and hardware details so we clearly understand the setup in which we perform the tutorial.
torch.cuda.empty_cache()
quantization_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_compute_dtype=torch.float16,
bnb_4bit_quant_type=”nf4″,
bnb_4bit_use_double_quant=True,
)
pipe = pipeline(
“kv-press-text-generation”,
model=MODEL_ID,
device_map=”auto”,
token=hf_token if hf_token else None,
model_kwargs={
“quantization_config”: quantization_config,
“attn_implementation”: “sdpa”,
},
)
else:
pipe = pipeline(
“kv-press-text-generation”,
model=MODEL_ID,
device_map=”auto”,
torch_dtype=torch.float32,
token=hf_token if hf_token else None,
model_kwargs={
“attn_implementation”: “sdpa”,
},
)
def cuda_mem():
if not torch.cuda.is_available():
return {“allocated_gb”: None, “reserved_gb”: None, “peak_gb”: None}
return {
“allocated_gb”: round(torch.cuda.memory_allocated() / 1024**3, 3),
“reserved_gb”: round(torch.cuda.memory_reserved() / 1024**3, 3),
“peak_gb”: round(torch.cuda.max_memory_allocated() / 1024**3, 3),
}
def reset_peak():
if torch.cuda.is_available():
torch.cuda.reset_peak_memory_stats()
def extract_answer(x):
if isinstance(x, list) and len(x) > 0:
x = x[0]
if isinstance(x, dict):
for k in [“answer”, “generated_text”, “text”, “output_text”]:
if k in x:
return x[k]
return json.dumps(x, indent=2, ensure_ascii=False)
return str(x)
def generate_once(context, question, press=None, label=”run”):
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
reset_peak()
start = time.time()
out = pipe(
context,
question=question,
press=press,
max_new_tokens=MAX_NEW_TOKENS,
do_sample=False,
temperature=None,
return_full_text=False,
)
elapsed = time.time() – start
answer = extract_answer(out)
stats = cuda_mem()
result = {
“label”: label,
“elapsed_sec”: round(elapsed, 2),
“allocated_gb”: stats[“allocated_gb”],
“reserved_gb”: stats[“reserved_gb”],
“peak_gb”: stats[“peak_gb”],
“answer”: answer.strip(),
}
return result
We initialize the kv-press-text-generation pipeline and configure it differently depending on whether GPU support is available. We define the helper functions that measure CUDA memory usage, reset peak memory, extract answers from model outputs, and run a single generation pass cleanly. This part provides the reusable execution logic that powers the rest of the tutorial and enables us to compare baseline inference with KV cache compression.
{“company”: “Arcturus Dynamics”, “hq”: “Bengaluru”, “founded”: 2017, “focus”: “warehouse robotics”},
{“company”: “BlueMesa Energy”, “hq”: “Muscat”, “founded”: 2014, “focus”: “grid analytics”},
{“company”: “CinderPeak Health”, “hq”: “Pune”, “founded”: 2019, “focus”: “clinical imaging AI”},
{“company”: “DeltaForge Marine”, “hq”: “Kochi”, “founded”: 2012, “focus”: “autonomous vessel telemetry”},
{“company”: “EonCircuit Labs”, “hq”: “Hyderabad”, “founded”: 2020, “focus”: “edge silicon tooling”},
{“company”: “Frostline Aero”, “hq”: “Jaipur”, “founded”: 2016, “focus”: “drone inspection”},
]
needle_facts = [
“PROJECT NEEDLE 1: The internal codename for the confidential pilot program is SAFFRON-17.”,
“PROJECT NEEDLE 2: The audit escalation owner is Meera Vashisht.”,
“PROJECT NEEDLE 3: The approved deployment region for the first production rollout is Oman North.”,
“PROJECT NEEDLE 4: The emergency rollback phrase is amber lantern.”,
“PROJECT NEEDLE 5: The signed commercial start date is 17 September 2026.”,
]
background_block = “””
Long-context systems often contain repeated operational notes, historical records, policy sections, and noisy retrieval artifacts.
The goal of this demo is to create a realistically long prompt where only a few details matter for downstream answering.
KV cache compression reduces memory usage by pruning cached key-value pairs while preserving answer quality.
“””
policy_block = “””
Operational policy summary:
1. Safety overrides throughput when sensor confidence falls below threshold.
2. Logs should preserve region, timestamp, device class, and operator approval state.
3. Field trials may contain duplicated annexes, OCR-style artifacts, and repeated compliance summaries.
4. A good long-context model must ignore irrelevant repetition and retrieve the specific details that matter.
“””
records_text = []
for i in range(120):
rec = company_records[i % len(company_records)]
records_text.append(
f”Record {i+1}: {rec[‘company’]} is headquartered in {rec[‘hq’]}, founded in {rec[‘founded’]}, and focuses on {rec[‘focus’]}. ”
f”Quarterly memo {i+1}: retention remained stable, operator training progressed, and the compliance appendix was reattached for review.”
)
needle_insert_positions = {18, 41, 73, 96, 111}
full_corpus = []
for i, para in enumerate(records_text):
full_corpus.append(background_block.strip())
full_corpus.append(policy_block.strip())
full_corpus.append(para)
if i in needle_insert_positions:
full_corpus.append(needle_facts[len([x for x in needle_insert_positions if x <= i]) – 1])
We create a synthetic long-context dataset to test the KVPress system in a controlled yet realistic way. We define company records, insert important hidden facts at different positions, and mix them with repeated background and policy blocks, making the prompt long and noisy. This helps us simulate the context in which memory-efficient inference matters and the model must retrieve only the truly relevant details.
question = textwrap.dedent(“””
Answer using only the provided context.
Give a compact JSON object with exactly these keys:
commercial_start_date
deployment_region
audit_owner
rollback_phrase
pilot_codename
“””).strip()
print(“\nContext characters:”, len(context))
print(“Approx words:”, len(context.split()))
experiments = []
baseline = generate_once(context, question, press=None, label=”baseline_no_compression”)
experiments.append(baseline)
presses = [
(“expected_attention_0.7”, ExpectedAttentionPress(compression_ratio=0.7)),
(“expected_attention_0.5”, ExpectedAttentionPress(compression_ratio=0.5)),
(“knorm_0.5”, KnormPress(compression_ratio=0.5)),
]
for label, press in presses:
try:
result = generate_once(context, question, press=press, label=label)
experiments.append(result)
except Exception as e:
experiments.append({
“label”: label,
“elapsed_sec”: None,
“allocated_gb”: None,
“reserved_gb”: None,
“peak_gb”: None,
“answer”: f”FAILED: {type(e).__name__}: {e}”
})
try:
from kvpress import DecodingPress
sig = inspect.signature(DecodingPress)
kwargs = {“base_press”: KnormPress()}
if “compression_interval” in sig.parameters:
kwargs[“compression_interval”] = 10
elif “compression_steps” in sig.parameters:
kwargs[“compression_steps”] = 10
if “target_size” in sig.parameters:
kwargs[“target_size”] = 512
elif “token_buffer_size” in sig.parameters:
kwargs[“token_buffer_size”] = 512
if “hidden_states_buffer_size” in sig.parameters:
kwargs[“hidden_states_buffer_size”] = 0
decoding_press = DecodingPress(**kwargs)
decoding_result = generate_once(context, question, press=decoding_press, label=”decoding_knorm”)
experiments.append(decoding_result)
except Exception as e:
experiments.append({
“label”: “decoding_knorm”,
“elapsed_sec”: None,
“allocated_gb”: None,
“reserved_gb”: None,
“peak_gb”: None,
“answer”: f”SKIPPED_OR_FAILED: {type(e).__name__}: {e}”
})
We assemble the final context, define the structured extraction question, and launch the core set of inference experiments. We first run the baseline without compression, then apply multiple press strategies to observe how different compression ratios affect the results. We also conduct a decoding-oriented compression experiment, which extends the tutorial beyond prefilling and provides a broader view of the KVPress framework.
print(“RESULTS”)
print(“=” * 120)
for r in experiments:
print(f”\n[{r[‘label’]}]”)
print(“elapsed_sec:”, r[“elapsed_sec”])
print(“allocated_gb:”, r[“allocated_gb”])
print(“reserved_gb:”, r[“reserved_gb”])
print(“peak_gb:”, r[“peak_gb”])
print(“answer:”)
print(r[“answer”])
print(“\n” + “=” * 120)
print(“SIMPLE SUMMARY”)
print(“=” * 120)
def safe_float(x):
try:
return float(x)
except Exception:
return None
base_peak = safe_float(baseline[“peak_gb”]) if baseline.get(“peak_gb”) is not None else None
base_time = safe_float(baseline[“elapsed_sec”]) if baseline.get(“elapsed_sec”) is not None else None
for r in experiments[1:]:
peak = safe_float(r[“peak_gb”])
t = safe_float(r[“elapsed_sec”])
peak_delta = None if base_peak is None or peak is None else round(base_peak – peak, 3)
time_delta = None if base_time is None or t is None else round(base_time – t, 2)
print({
“label”: r[“label”],
“peak_gb_saved_vs_baseline”: peak_delta,
“time_sec_saved_vs_baseline”: time_delta,
“answer_preview”: r[“answer”][:180].replace(“\n”, ” “)
})
print(“\n” + “=” * 120)
print(“OPTIONAL NEXT STEPS”)
print(“=” * 120)
print(“1. Swap MODEL_ID to a stronger long-context instruct model that fits your GPU.”)
print(“2. Increase context length by duplicating records_text more times.”)
print(“3. Try other presses from kvpress, such as SnapKVPress, StreamingLLMPress, QFilterPress, or ChunkKVPress.”)
print(“4. Replace the synthetic corpus with your own long PDF/text chunks and keep the same evaluation loop.”)
We print all experiment outputs in a readable format and summarize the runtime and memory differences relative to the baseline. We calculate simple comparison metrics to quickly see how much memory or time each compression strategy saves. We then conclude with suggested next steps to extend the tutorial to stronger models, longer contexts, additional press methods, and real-world document workloads.
In conclusion, we developed a strong practical understanding of how NVIDIA’s KVPress can be used to optimize long-context inference in a realistic Colab-based setting. We did more than simply run a model: we built an end-to-end workflow that installs the framework, loads the pipeline correctly, constructs a meaningful long-context input, applies multiple compression presses, and evaluates the results in terms of answer quality, runtime, and memory behavior. By comparing baseline generation with compressed KV-cache generation, we clearly saw the trade-offs involved. We gained useful intuition about when these methods can help reduce resource pressure without severely harming output fidelity. We also explored the framework’s flexibility by testing different press configurations and including an optional decoding-oriented compression path, providing a broader view of how KVPress can be used beyond a single static example.
Check out the Codes and Notebook here. Also, feel free to follow us on Twitter and don’t forget to join our 120k+ ML SubReddit and Subscribe to our Newsletter. Wait! are you on telegram? now you can join us on telegram as well.
Need to partner with us for promoting your GitHub Repo OR Hugging Face Page OR Product Release OR Webinar etc.? Connect with us

