惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

B
Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Microsoft Security Blog
Microsoft Security Blog
B
Blog RSS Feed
云风的 BLOG
云风的 BLOG
G
Google Developers Blog
Recent Announcements
Recent Announcements
A
About on SuperTechFans
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Google Online Security Blog
Google Online Security Blog
Google DeepMind News
Google DeepMind News
S
Schneier on Security
S
Secure Thoughts
T
The Exploit Database - CXSecurity.com
Martin Fowler
Martin Fowler
P
Proofpoint News Feed
Security Latest
Security Latest
Jina AI
Jina AI
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Recorded Future
Recorded Future
T
Tor Project blog
有赞技术团队
有赞技术团队
H
Hackread – Cybersecurity News, Data Breaches, AI and More
N
News | PayPal Newsroom
博客园 - 三生石上(FineUI控件)
MyScale Blog
MyScale Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Last Week in AI
Last Week in AI
F
Full Disclosure
Hacker News: Ask HN
Hacker News: Ask HN
Forbes - Security
Forbes - Security
D
DataBreaches.Net
人人都是产品经理
人人都是产品经理
NISL@THU
NISL@THU
C
Cisco Blogs
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Google DeepMind News
Google DeepMind News
Project Zero
Project Zero
IT之家
IT之家
T
Threatpost
Cyberwarzone
Cyberwarzone
O
OpenAI News
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
J
Java Code Geeks
P
Proofpoint News Feed
The Last Watchdog
The Last Watchdog
月光博客
月光博客
Latest news
Latest news
MongoDB | Blog
MongoDB | Blog
Apple Machine Learning Research
Apple Machine Learning Research

MarkTechPost

A Coding Implementation of End-to-End Brain Decoding from MEG Signals Using NeuralSet and Deep Learning for Predicting Linguistic Features Meta Introduces Autodata: An Agentic Framework That Turns AI Models into Autonomous Data Scientists for High-Quality Training Data Creation A Coding Guide on LLM Post Training with TRL from Supervised Fine Tuning to DPO and GRPO Reasoning Qwen AI Releases Qwen-Scope: An Open-Source Sparse AutoEncoders (SAE) Suite That Turns LLM Internal Features into Practical Development Tools A Coding Deep Dive into Agentic UI, Generative UI, State Synchronization, and Interrupt-Driven Approval Flows Moonshot AI Open-Sources FlashKDA: CUTLASS Kernels for Kimi Delta Attention with Variable-Length Batching and H20 Benchmarks Microsoft Research’s World-R1 Uses Flow-GRPO and 3D-Aware Rewards to Inject Geometric Consistency Into Wan 2.1 Without Architectural Changes A Coding Implementation on Pyright Type Checking Covering Generics, Protocols, Strict Mode, Type Narrowing, and Modern Python Typing IBM Releases Two Granite Speech 4.1 2B Models: Autoregressive ASR with Translation and Non-Autoregressive Editing for Fast Inference Top 10 KV Cache Compression Techniques for LLM Inference: Reducing Memory Overhead Across Eviction, Quantization, and Low-Rank Methods Qwen Team Releases FlashQLA: a High-Performance Linear Attention Kernel Library That Achieves Up to 3× Speedup on NVIDIA Hopper GPUs Step by Step Guide to Build a Complete PII Detection and Redaction Pipeline with OpenAI Privacy Filter Meta FAIR Releases NeuralSet: A Python Package for Neuro-AI That Supports fMRI, M/EEG, Spikes, and HuggingFace Embeddings smol-audio: A Colab-Friendly Notebook Collection for Fine-Tuning Whisper, Parakeet, Voxtral, Granite Speech, and Audio Flamingo 3 A Coding Implementation on Document Parsing Benchmarking with LlamaIndex ParseBench Using Python, Hugging Face, and Evaluation Metrics Poolside AI Introduces Laguna XS.2 and M.1: Agentic Coding Models Reaching 68.2% and 72.5% on SWE-bench Verified How to Build Traceable and Evaluated LLM Workflows Using Promptflow, Prompty, and OpenAI OpenAI Releases Privacy Filter: A 1.5B-Parameter Open-Source PII Redaction Model with 50M Active Parameters Top 10 Physical AI Models Powering Real-World Robots in 2026 How to Build a Lightweight Vision-Language-Action-Inspired Embodied Agent with Latent World Modeling and Model Predictive Control Meet Talkie-1930: A 13B Open-Weight LLM Trained on Pre-1931 English Text for Historical Reasoning and Generalization Research Build a Reinforcement Learning Powered Agent that Learns to Retrieve Relevant Long-Term Memories for Accurate LLM Question Answering OpenMOSS Releases MOSS-Audio: An Open-Source Foundation Model for Speech, Sound, Music, and Time-Aware Audio Reasoning Meta AI Releases Sapiens2: A High-Resolution Human-Centric Vision Model for Pose, Segmentation, Normals, Pointmap, and Albedo The LoRA Assumption That Breaks in Production How to Build a Fully Searchable AI Knowledge Base with OpenKB, OpenRouter, and Llama How to Build Smarter Multilingual Text Wrapping with BudouX Through Parsing, HTML Rendering, Model Introspection, and Toy Training Top 7 Benchmarks That Actually Matter for Agentic Reasoning in Large Language Models RAG Without Vectors: How PageIndex Retrieves by Reasoning A Coding Tutorial on Datashader on Rendering Massive Datasets with High-Performance Python Visual Analytics xAI Launches grok-voice-think-fast-1.0: Topping τ-voice Bench at 67.3%, Outperforming Gemini, GPT Realtime, and More Google DeepMind Introduces Vision Banana: An Instruction-Tuned Image Generator That Beats SAM 3 on Segmentation and Depth Anything V3 on Metric Depth Estimation Meet GitNexus: An Open-Source MCP-Native Knowledge Graph Engine That Gives Claude Code and Cursor Full Codebase Structural Awareness A Coding Implementation on Deepgram Python SDK for Transcription, Text-to-Speech, Async Audio Processing, and Text Intelligence A Coding Implementation on Microsoft’s OpenMementos with Trace Structure Analysis, Context Compression, and Fine-Tuning Data Preparation DeepSeek AI Releases DeepSeek-V4: Compressed Sparse Attention and Heavily Compressed Attention Enable One-Million-Token Contexts Google DeepMind Introduces Decoupled DiLoCo: An Asynchronous Training Architecture Achieving 88% Goodput Under High Hardware Failure Rates Mend Releases AI Security Governance Framework: Covering Asset Inventory, Risk Tiering, AI Supply Chain Security, and Maturity Model Mend.io Releases AI Security Governance Framework Covering Asset Inventory, Risk Tiering, AI Supply Chain Security, and Maturity Model OpenAI Releases GPT-5.5, a Fully Retrained Agentic Model That Scores 82.7% on Terminal-Bench 2.0 and 84.9% on GDPval A Coding Tutorial on OpenMythos on Recurrent-Depth Transformers with Depth Extrapolation, Adaptive Computation, and Mixture-of-Experts Routing Google Cloud AI Research Introduces ReasoningBank: A Memory Framework that Distills Reasoning Strategies from Agent Successes and Failures Xiaomi Releases MiMo-V2.5-Pro and MiMo-V2.5: Matching Frontier Model Benchmarks at Significantly Lower Token Cost How to Design a Production-Grade CAMEL Multi-Agent System with Planning, Tool Use, Self-Consistency, and Critique-Driven Refinement Alibaba Qwen Team Releases Qwen3.6-27B: A Dense Open-Weight Model Outperforming 397B MoE on Agentic Coding Benchmarks A Detailed Implementation on Equinox with JAX Native Modules, Filtered Transforms, Stateful Layers, and End-to-End Training Workflows Next Leap to Harness Engineering: JiuwenClaw Pioneers ‘Coordination Engineering’ Photon Releases Spectrum: An Open-Source TypeScript Framework that Deploys AI Agents Directly to iMessage, WhatsApp, and Telegram OpenAI Open-Sources Euphony: A Browser-Based Visualization Tool for Harmony Chat Data and Codex Session Logs Hugging Face Releases ml-intern: An Open-Source AI Agent that Automates the LLM Post-Training Workflow A Coding Implementation to Build a Conditional Bayesian Hyperparameter Optimization Pipeline with Hyperopt, TPE, and Early Stopping Google Introduces Simula: A Reasoning-First Framework for Generating Controllable, Scalable Synthetic Datasets Across Specialized AI Domains A Coding Implementation on Qwen 3.6-35B-A3B Covering Multimodal Inference, Thinking Control, Tool Calling, MoE Routing, RAG, and Session Persistence Moonshot AI Releases Kimi K2.6 with Long-Horizon Coding, Agent Swarm Scaling to 300 Sub-Agents and 4,000 Coordinated Steps A Coding Implementation on Microsoft’s Phi-4-Mini for Quantized Inference Reasoning Tool Use RAG and LoRA Fine-Tuning OpenAI Scales Trusted Access for Cyber Defense With GPT-5.4-Cyber: a Fine-Tuned Model Built for Verified Security Defenders Moonshot AI and Tsinghua Researchers Propose PrfaaS: A Cross-Datacenter KVCache Architecture that Rethinks How LLMs are Served at Scale Meet OpenMythos: An Open-Source PyTorch Reconstruction of Claude Mythos Where 770M Parameters Match a 1.3B Transformer How TabPFN Leverages In-Context Learning to Achieve Superior Accuracy on Tabular Datasets Compared to Random Forest and CatBoost A Coding Implementation to Build an AI-Powered File Type Detection and Security Analysis Pipeline with Magika and OpenAI NVIDIA Releases Ising: the First Open Quantum AI Model Family for Hybrid Quantum-Classical Systems xAI Launches Standalone Grok Speech-to-Text and Text-to-Speech APIs, Targeting Enterprise Voice Developers A Coding Tutorial for Running PrismML Bonsai 1-Bit LLM on CUDA with GGUF, Benchmarking, Chat, JSON, and RAG A Coding Guide for Property-Based Testing Using Hypothesis with Stateful, Differential, and Metamorphic Test Design Anthropic Releases Claude Opus 4.7: A Major Upgrade for Agentic Coding, High-Resolution Vision, and Long-Horizon Autonomous Tasks Google AI Releases Auto-Diagnose: An Large Language Model LLM-Based System to Diagnose Integration Test Failures at Scale A End-to-End Coding Guide to Running OpenAI GPT-OSS Open-Weight Models with Advanced Inference Workflows Top 19 AI Red Teaming Tools (2026): Secure Your ML Models A Coding Guide to Build a Production-Grade Background Task Processing System Using Huey with SQLite, Scheduling, Retries, Pipelines, and Concurrency Control Qwen Team Open-Sources Qwen3.6-35B-A3B: A Sparse MoE Vision-Language Model with 3B Active Parameters and Agentic Coding Capabilities OpenAI Launches GPT-Rosalind: Its First Life Sciences AI Model Built to Accelerate Drug Discovery and Genomics Research Building Transformer-Based NQS for Frustrated Spin Systems with NetKet UCSD and Together AI Research Introduces Parcae: A Stable Architecture for Looped Language Models That Achieves the Quality of a Transformer Twice the Size How to Build a Universal Long-Term Memory Layer for AI Agents Using Mem0 and OpenAI A Coding Implementation to Build Multi-Agent AI Systems with SmolAgents Using Code Execution, Tool Calling, and Dynamic Orchestration A Technical Deep Dive into the Essential Stages of Modern Large Language Model Training, Alignment, and Deployment Google AI Launches Gemini 3.1 Flash TTS: A New Benchmark in Expressive and Controllable AI Voice Google DeepMind Releases Gemini Robotics-ER 1.6: Bringing Enhanced Embodied Reasoning and Instrument Reading to Physical AI Google Launches ‘Skills’ in Chrome: Turning Reusable AI Prompts into One-Click Browser Workflows A Coding Implementation of Crawl4AI for Web Crawling, Markdown Generation, JavaScript Execution, and LLM-Based Structured Extraction TinyFish AI Releases Full Web Infrastructure Platform for AI Agents: Search, Fetch, Browser, and Agent Under One API Key NVIDIA and the University of Maryland Researchers Released Audio Flamingo Next (AF-Next): A Super Powerful and Open Large Audio-Language Model A Hands-On Coding Tutorial for Microsoft VibeVoice Covering Speaker-Aware ASR, Real-Time TTS, and Speech-to-Speech Pipelines Meta AI and KAUST Researchers Propose Neural Computers That Fold Computation, Memory, and I/O Into One Learned Model A Coding Implementation of MolmoAct for Depth-Aware Spatial Reasoning, Visual Trajectory Tracing, and Robotic Action Prediction MiniMax Just Open Sourced MiniMax M2.7: A Self-Evolving Agent Model that Scores 56.22% on SWE-Pro and 57.0% on Terminal Bench 2 Liquid AI Releases LFM2.5-VL-450M: a 450M-Parameter Vision-Language Model with Bounding Box Prediction, Multilingual Support, and Sub-250ms Edge Inference Researchers from MIT, NVIDIA, and Zhejiang University Propose TriAttention: A KV Cache Compression Method That Matches Full Attention at 2.5× Higher Throughput How to Build a Secure Local-First Agent Runtime with OpenClaw Gateway, Skills, and Controlled Tool Execution How Knowledge Distillation Compresses Ensemble Intelligence into a Single Deployable AI Model Alibaba’s Tongyi Lab Releases VimRAG: a Multimodal RAG Framework that Uses a Memory Graph to Navigate Massive Visual Contexts A Coding Guide to Markerless 3D Human Kinematics with Pose2Sim, RTMPose, and OpenSim NVIDIA Releases AITune: An Open-Source Inference Toolkit That Automatically Finds the Fastest Inference Backend for Any PyTorch Model Five AI Compute Architectures Every Engineer Should Know: CPUs, GPUs, TPUs, NPUs, and LPUs Compared An End-to-End Coding Guide to NVIDIA KVPress for Long-Context LLM Inference, KV Cache Compression, and Memory-Efficient Generation Meta Superintelligence Lab Releases Muse Spark: A Multimodal Reasoning Model With Thought Compression and Parallel Agents Sigmoid vs ReLU Activation Functions: The Inference Cost of Losing Geometric Context A Coding Guide to Build Advanced Document Intelligence Pipelines with Google LangExtract, OpenAI Models, Structured Extraction, and Interactive Visualization Google AI Research Introduces PaperOrchestra: A Multi-Agent Framework for Automated AI Research Paper Writing A Comprehensive Implementation Guide to ModelScope for Model Search, Inference, Fine-Tuning, Evaluation, and Export
A Coding Implementation on kvcached for Elastic KV Cache Memory, Bursty LLM Serving, and Multi-Model GPU Sharing
Sana Hassan · 2026-04-26 · via MarkTechPost

In this tutorial, we explore kvcached, a dynamic KV-cache implementation on top of vLLM, to understand how dynamic KV-cache allocation transforms GPU memory usage for large language models. We begin by setting up the environment and deploying lightweight Qwen2.5 models through an OpenAI-compatible API, ensuring a realistic inference workflow. We then design controlled experiments where we simulate bursty workloads to observe how memory behaves under both elastic and static allocation strategies. Through systematic measurement and visualization, we directly compare VRAM utilization and latency, and extend the setup to a multi-model scenario where we observe how memory flexibly shifts across active workloads in real time.

import os, sys, time, json, subprocess, threading, signal, shutil
from pathlib import Path


def sh(cmd, check=True):
   return subprocess.run(cmd, check=check, shell=isinstance(cmd, str))


try:
   import torch
except ImportError:
   sh([sys.executable, "-m", "pip", "install", "-q", "torch"])
   import torch


assert torch.cuda.is_available(), \
   "No GPU detected. In Colab: Runtime > Change runtime type > GPU."
props = torch.cuda.get_device_properties(0)
print(f"[GPU] {torch.cuda.get_device_name(0)}  "
     f"({props.total_memory / 1e9:.1f} GB, "
     f"compute capability {props.major}.{props.minor})")


def pip_install(*pkgs, extra=()):
   subprocess.run([sys.executable, "-m", "pip", "install", "-q", *pkgs, *extra],
                  check=True)


print("[install] vLLM ...")
pip_install("vllm==0.10.2")
print("[install] kvcached (compiles a small CUDA extension) ...")
pip_install("kvcached", extra=["--no-build-isolation"])
print("[install] misc (matplotlib, requests, pynvml) ...")
pip_install("matplotlib", "requests", "pynvml", "numpy")


MODEL_A = "Qwen/Qwen2.5-0.5B-Instruct"
MODEL_B = "Qwen/Qwen2.5-1.5B-Instruct"
PORT_A, PORT_B = 8001, 8002
MAX_MODEL_LEN = 2048

We start by setting up the environment and verifying that a GPU is available for our experiments. We install all required dependencies including vLLM and kvcached along with supporting libraries. We then define our model configurations and ports to prepare for launching the inference servers.

def launch_vllm(model, port, kvcached=True, gpu_mem_util=0.55, log_path=None):
   """Start a vLLM OpenAI-compatible server as a subprocess. With kvcached=True
   the autopatch hooks replace vLLM's KV-cache allocator with the elastic one."""
   env = os.environ.copy()
   env["VLLM_USE_V1"] = "1"
   if kvcached:
       env["ENABLE_KVCACHED"]    = "true"
       env["KVCACHED_AUTOPATCH"] = "1"
       env["KVCACHED_IPC_NAME"]  = f"kvc_{port}"
   cmd = [
       sys.executable, "-m", "vllm.entrypoints.openai.api_server",
       "--model", model, "--port", str(port),
       "--max-model-len", str(MAX_MODEL_LEN),
       "--disable-log-requests",
       "--no-enable-prefix-caching",
       "--enforce-eager",
   ]
   if not kvcached:
       cmd += ["--gpu-memory-utilization", str(gpu_mem_util)]
   log = open(log_path or os.devnull, "w")
   proc = subprocess.Popen(cmd, env=env, stdout=log, stderr=subprocess.STDOUT,
                           preexec_fn=os.setsid)
   return proc, log


def wait_ready(port, timeout=420):
   import requests
   url = f"http://localhost:{port}/v1/models"
   t0 = time.time()
   while time.time() - t0 < timeout:
       try:
           if requests.get(url, timeout=2).status_code == 200:
               return True
       except Exception:
           pass
       time.sleep(3)
   raise TimeoutError(f"vLLM on port {port} didn't come up within {timeout}s")


def shutdown(proc, log):
   if proc and proc.poll() is None:
       try:
           os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
           proc.wait(timeout=45)
       except Exception:
           os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
   if log and not log.closed:
       log.close()
   time.sleep(3)

We implement helper functions to launch and manage the vLLM server with and without kvcached enabled. We configure environment variables to activate dynamic KV-cache behavior and ensure proper server initialization. We also define utilities to wait for server readiness and safely shut down processes after execution.

import pynvml
pynvml.nvmlInit()
NV_HANDLE = pynvml.nvmlDeviceGetHandleByIndex(0)


def vram_used_mb():
   info = pynvml.nvmlDeviceGetMemoryInfo(NV_HANDLE)
   return info.used / (1024 ** 2)


class MemorySampler(threading.Thread):
   def __init__(self, interval=0.2):
       super().__init__(daemon=True)
       self.interval = interval
       self.samples  = []
       self._stop    = threading.Event()
   def run(self):
       t0 = time.time()
       while not self._stop.is_set():
           self.samples.append((time.time() - t0, vram_used_mb()))
           time.sleep(self.interval)
   def stop(self):
       self._stop.set(); self.join()


import requests
from concurrent.futures import ThreadPoolExecutor


PROMPTS = [
   "Explain quantum entanglement to a curious 10-year-old.",
   "Write a Python function that detects cycles in a linked list.",
   "Summarize the plot of Hamlet in one paragraph.",
   "List 5 surprising household uses for baking soda with explanations.",
   "Compose a vivid haiku about rainy Monday mornings.",
   "Describe the Fermi paradox and three plausible resolutions.",
   "Translate 'knowledge is power' into French, German, and Japanese.",
   "Explain the difference between TCP and UDP with real examples.",
]


def bursty_workload(port, model, n_bursts=3, burst_size=6, pause=6.0,
                   max_tokens=180):
   """Fire n_bursts waves of burst_size concurrent requests with an idle
   gap between waves. The idle gap is where kvcached releases physical
   VRAM -- a static-allocation engine simply cannot."""
   url = f"http://localhost:{port}/v1/chat/completions"
   def one(i):
       body = {
           "model": model,
           "messages": [{"role": "user", "content": PROMPTS[i % len(PROMPTS)]}],
           "max_tokens": max_tokens, "temperature": 0.7,
       }
       t0 = time.time()
       r = requests.post(url, json=body, timeout=180)
       r.raise_for_status()
       return time.time() - t0
   latencies = []
   with ThreadPoolExecutor(max_workers=burst_size) as ex:
       for b in range(n_bursts):
           print(f"    burst {b+1}/{n_bursts}  ({burst_size} concurrent)")
           latencies += list(ex.map(one, range(burst_size)))
           if b < n_bursts - 1:
               time.sleep(pause)
   return latencies

We initialize GPU memory tracking using pynvml to monitor VRAM usage in real time. We create a background sampling thread that continuously records memory consumption during experiments. We then define a bursty workload generator that sends concurrent requests to simulate realistic LLM usage patterns.

print("\n=== Experiment 1: vLLM + kvcached ===")
proc, log = launch_vllm(MODEL_A, PORT_A, kvcached=True,
                       log_path="/tmp/vllm_kvc.log")
try:
   wait_ready(PORT_A)
   idle_kvc = vram_used_mb()
   print(f"  Idle VRAM after load (weights only): {idle_kvc:.0f} MB")
   sampler = MemorySampler(); sampler.start()
   lat_kvc = bursty_workload(PORT_A, MODEL_A)
   time.sleep(6)
   sampler.stop()
   mem_kvc = sampler.samples
finally:
   shutdown(proc, log)


print("\n=== Experiment 2: vLLM baseline (static KV allocation) ===")
proc, log = launch_vllm(MODEL_A, PORT_A, kvcached=False,
                       log_path="/tmp/vllm_base.log")
try:
   wait_ready(PORT_A)
   idle_base = vram_used_mb()
   print(f"  Idle VRAM (weights + pre-reserved KV pool): {idle_base:.0f} MB")
   sampler = MemorySampler(); sampler.start()
   lat_base = bursty_workload(PORT_A, MODEL_A)
   time.sleep(6)
   sampler.stop()
   mem_base = sampler.samples
finally:
   shutdown(proc, log)

We run the first experiment with kvcached enabled and capture both memory usage and latency metrics. We then execute the same workload under a baseline static allocation setup for comparison. We collect and store all results to enable a clear side-by-side evaluation of both approaches.

import numpy as np
import matplotlib.pyplot as plt


fig, axes = plt.subplots(1, 2, figsize=(14, 4.5))


tk, mk = zip(*mem_kvc); tb, mb = zip(*mem_base)
axes[0].plot(tk, mk, label="with kvcached", linewidth=2, color="#1f77b4")
axes[0].plot(tb, mb, label="baseline (static)", linewidth=2,
            linestyle="--", color="#d62728")
axes[0].axhline(idle_kvc,  color="#1f77b4", alpha=.3, linestyle=":")
axes[0].axhline(idle_base, color="#d62728", alpha=.3, linestyle=":")
axes[0].set_xlabel("time (s)"); axes[0].set_ylabel("GPU memory used (MB)")
axes[0].set_title("VRAM under a bursty workload\n(dotted = idle-baseline VRAM)")
axes[0].grid(alpha=.3); axes[0].legend()


axes[1].boxplot([lat_kvc, lat_base], labels=["kvcached", "baseline"])
axes[1].set_ylabel("request latency (s)")
axes[1].set_title(f"Latency across {len(lat_kvc)} requests")
axes[1].grid(alpha=.3)


plt.tight_layout()
plt.savefig("/content/kvcached_single_model.png", dpi=120, bbox_inches="tight")
plt.show()


print("\n--- Single-model summary --------------------------------------------")
print(f"  Idle VRAM    kvcached: {idle_kvc:>6.0f} MB   "
     f"baseline: {idle_base:>6.0f} MB  "
     f"(savings: {idle_base - idle_kvc:>5.0f} MB)")
print(f"  Peak VRAM    kvcached: {max(mk):>6.0f} MB   "
     f"baseline: {max(mb):>6.0f} MB")
print(f"  Median lat.  kvcached: {np.median(lat_kvc):>6.2f} s   "
     f"baseline: {np.median(lat_base):>6.2f} s")
print(f"  VRAM flex    kvcached: peak-idle = {max(mk)-min(mk):>5.0f} MB  "
     f"(baseline can't release -- static pool)")


print("\n=== Experiment 3: Two LLMs sharing one GPU (kvcached on both) ===")
pA, lA = launch_vllm(MODEL_A, PORT_A, kvcached=True, log_path="/tmp/mA.log")
try:
   wait_ready(PORT_A)
   pB, lB = launch_vllm(MODEL_B, PORT_B, kvcached=True, log_path="/tmp/mB.log")
   try:
       wait_ready(PORT_B)
       print(f"  Both models loaded. Idle VRAM: {vram_used_mb():.0f} MB")


       sampler = MemorySampler(); sampler.start()
       for i in range(4):
           port, model = ((PORT_A, MODEL_A) if i % 2 == 0
                          else (PORT_B, MODEL_B))
           print(f"  round {i+1}: driving {model}")
           bursty_workload(port, model, n_bursts=1, burst_size=4, pause=0)
           time.sleep(5)
       sampler.stop()
       t, m = zip(*sampler.samples)


       plt.figure(figsize=(11, 4.2))
       plt.plot(t, m, color="#c2410c", linewidth=2)
       plt.xlabel("time (s)"); plt.ylabel("GPU memory used (MB)")
       plt.title("Two LLMs on one T4 via kvcached — memory flexes per active model")
       plt.grid(alpha=.3); plt.tight_layout()
       plt.savefig("/content/kvcached_multillm.png", dpi=120,
                   bbox_inches="tight")
       plt.show()
   finally:
       shutdown(pB, lB)
finally:
   shutdown(pA, lA)


print("\n=== Bonus: kvcached ships CLI tools ===")
print("  kvtop  — live per-instance KV memory monitor (like nvtop for kvcached)")
print("  kvctl  — set/limit per-instance memory budgets in shared memory")
for tool in ("kvtop", "kvctl"):
   path = shutil.which(tool)
   print(f"    {tool}: {path or 'not on PATH'}")
print("\nAll plots saved to /content/. Done.")

We visualize the collected data by plotting VRAM usage trends and latency distributions across both setups. We compute summary statistics to quantify improvements in memory efficiency and performance. We finally extend the experiment to a multi-model scenario, observe how memory dynamically adapts across active models, and conclude with additional insights into tooling.

In conclusion, we demonstrated how dynamic KV-cache management fundamentally improves GPU efficiency compared to traditional static allocation approaches. We observed that kvcached enables significant VRAM savings during idle periods while maintaining competitive latency under load, making it especially effective for bursty or multi-tenant inference environments. By running multiple models on a single GPU and alternating traffic, we clearly saw how memory is allocated only when needed and released when idle, validating the core premise of demand-driven caching. Overall, we established a practical and reproducible framework for evaluating memory optimization techniques in LLM serving and highlighted how this approach can scale to more complex, production-grade deployments.


Check out the Full Codes with Notebook. Also, feel free to follow us on Twitter and don’t forget to join our 130k+ 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

Sana Hassan, a consulting intern at Marktechpost and dual-degree student at IIT Madras, is passionate about applying technology and AI to address real-world challenges. With a keen interest in solving practical problems, he brings a fresh perspective to the intersection of AI and real-life solutions.