Skip to main content

mini-infer 🚀

CI License Python PyTorch Hardware

A minimal, educational, and high-performance continuous-batching LLM inference engine with Paged KV-cache, radix prefix caching, and speculative decoding built from scratch in pure Python and PyTorch.

Most developers only know how to call an inference engine (ollama run or vllm serve). The actual systems algorithms—how tensors are paged in VRAM to eliminate fragmentation, how continuous batching schedules requests at the iteration level, how prefix caching avoids redundant prefills, and how speculative decoding generates multiple tokens per forward pass—are locked behind tens of thousands of lines of complex C++/CUDA.

mini-infer implements these exact production algorithms in pure, readable, testable Python/PyTorch designed to run on a single consumer GPU (such as an entry-level 6 GB laptop GPU or a free Kaggle T4), with zero C++ compiler or CMake toolchain required.


⚡ Core Architecture

                                 Client / servebench
                                          │
                                          ▼
┌──────────────────────────────────────────────────────────────────────────────────┐
│ mini-infer Engine                                                                │
│                                                                                  │
│  ┌───────────────────────┐         ┌──────────────────────────────────────────┐  │
│  │   HTTP Server (SSE)   │         │       Continuous Batching Scheduler      │  │
│  │  /v1/chat/completions ├────────►│  - Iteration-level token scheduler       │  │
│  └───────────────────────┘         │  - Dynamic prefill/decode interleaving   │  │
│                                    └────────────────────┬─────────────────────┘  │
│                                                         │                        │
│                                                         ▼                        │
│  ┌────────────────────────────────────────────────────────────────────────────┐  │
│  │                        Paged KV-Cache Memory Manager                       │  │
│  │  - Fixed Physical Block Pool (16 tokens/block in pre-allocated GPU VRAM)   │  │
│  │  - Virtual-to-Physical Block Table per request (zero fragmentation)        │  │
│  │  - Radix / Prefix Cache (zero recompute for shared system prompts)         │  │
│  └──────────────────────────────────────────────┬─────────────────────────────┘  │
│                                                 │                                │
│                                                 ▼                                │
│  ┌────────────────────────────────────────────────────────────────────────────┐  │
│  │                       Qwen2.5 Model Executor & Kernels                     │  │
│  │  - Pure safetensors streaming loader (RMSNorm, RoPE, SwiGLU, SDPA)         │  │
│  │  - Speculative Decoding (0.5B draft proposes → 1.5B target verifies)       │  │
│  └────────────────────────────────────────────────────────────────────────────┘  │
└──────────────────────────────────────────────────────────────────────────────────┘

⏱️ Quickstart: Up and Running in 60 Seconds

Step 1: Install Dependencies

With uv (Recommended & fastest):

git clone https://github.com/Prajwal7-2002/mini-infer.git
cd mini-infer
uv sync

With standard pip & virtualenv:

git clone https://github.com/Prajwal7-2002/mini-infer.git
cd mini-infer
python -m venv .venv

# Windows
.venv\Scripts\activate
# Linux / macOS
source .venv/bin/activate

pip install -e .

Step 2: Check Hardware Diagnostics

Verify your GPU and memory allocation plan:

uv run mini-infer info
mini-infer System Diagnostics
PyTorch version: 2.6.0+cu124
CUDA available: True
GPU Device: NVIDIA GeForce RTX 3050 6GB Laptop GPU
Total VRAM: 6.00 GB

Memory Allocation Plan (RTX 3050 6 GB):
  • Qwen2.5-1.5B (Target Model): ~3.0 GB VRAM
  • Qwen2.5-0.5B (Draft Model):  ~1.0 GB VRAM
  • Paged KV-Cache Memory Pool:  ~1.5 GB VRAM (~2000 blocks)
  • Safety Buffer:               ~0.5 GB

Step 3: Launch the Streaming Server

Start serving Qwen2.5-0.5B-Instruct (model weights will download automatically from Hugging Face on the first run):

uv run mini-infer serve --port 8000
mini-infer serving Qwen/Qwen2.5-0.5B-Instruct on 127.0.0.1:8000 (cuda)
Loading tokenizer...
Loading model weights...
Streaming weights from 1 safetensors file(s) into cuda (torch.bfloat16)...
Initializing Paged KV-Cache (256 blocks of size 16)...
Server ready! Connect any OpenAI-compatible client or run servebench quick against http://127.0.0.1:8000/v1
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

Step 4: Stream Tokens (Choose your client)

Option A: Quick curl terminal command

curl -N http://127.0.0.1:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen2.5-0.5b",
    "messages": [{"role": "user", "content": "Explain Paged KV-Cache in 1 sentence."}],
    "stream": true
  }'

Option B: Standard Python Streaming

import urllib.request, json

data = json.dumps({
    "model": "qwen2.5-0.5b",
    "messages": [{"role": "user", "content": "Explain continuous batching in 1 sentence."}],
    "stream": True,
}).encode("utf-8")

req = urllib.request.Request(
    "http://127.0.0.1:8000/v1/chat/completions",
    data=data,
    headers={"Content-Type": "application/json"}
)

for line in urllib.request.urlopen(req):
    text = line.decode("utf-8")
    if text.startswith("data: ") and not text.startswith("data: [DONE]"):
        chunk = json.loads(text[6:])
        print(chunk["choices"][0]["delta"].get("content", ""), end="", flush=True)
print()

Option C: Official OpenAI Python SDK

Because mini-infer implements standard OpenAI streaming protocols, it works out of the box with openai-python, LangChain, and Open-WebUI:

from openai import OpenAI

client = OpenAI(base_url="http://127.0.0.1:8000/v1", api_key="none")

response = client.chat.completions.create(
    model="qwen2.5-0.5b",
    messages=[{"role": "user", "content": "Hello mini-infer!"}],
    stream=True,
)

for chunk in response:
    print(chunk.choices[0].delta.content or "", end="", flush=True)

⚡ The Four Systems Breakthroughs Explained

1. Paged KV-Cache (Virtual Memory Management)

Standard PyTorch caches allocate contiguous tensors for each sequence up to max_seq_len. This causes over 60% memory waste due to internal and external VRAM fragmentation.

  • mini-infer divides KV-cache memory into a fixed pool of 16-token physical blocks (BlockAllocator).
  • Each request maintains a dynamic BlockTable mapping logical token positions to non-contiguous physical blocks on the GPU.
  • Allows dynamically growing and shrinking memory with zero reallocation bubbles.

2. True Continuous Batching (Iteration-Level Scheduling)

Traditional batching evaluates all requests together until the longest one completes, leaving GPU compute units idle during short completions.

  • mini-infer steps at the iteration level: every decode forward pass processes exactly one token across all active requests.
  • When a request generates <|im_end|>, its physical blocks are immediately recycled to the pool.
  • Incoming requests enter the engine on the very next token iteration without waiting for current batches to finish.

3. Hash-Based Radix Prefix Caching

Repeated system prompts (e.g., "You are a helpful coding assistant...") waste significant compute in redundant prefill passes.

  • Completed 16-token blocks are cryptographically hashed and indexed in a prefix cache table.
  • Incoming requests sharing common prefixes match these block hashes and bypass prefill entirely, reducing Time-to-First-Token (TTFT) by up to 80%.

4. Speculative Decoding with Zero Distribution Drift

Autoregressive decoding is memory-bandwidth bound on single tokens.

  • mini-infer runs a lightweight 0.5B draft model proposing $K=3$ candidate tokens.
  • A larger 1.5B target model verifies all $K$ candidates in a single parallel forward pass.
  • Uses Leviathan rejection sampling to accept or correct candidates, mathematically guaranteeing that outputs match the exact distribution of the 1.5B model alone.

⚡ Real-World Benchmarks on Real Hardware

Measured live using Flagship #1 servebench on an NVIDIA GeForce RTX 3050 6GB Laptop GPU running Qwen2.5-0.5B-Instruct in pure PyTorch CUDA:

servebench run --url http://127.0.0.1:8000/v1 --model qwen2.5-0.5b --concurrency 1,2,4
Concurrency Requests (OK / Fail) Throughput (tok/s) TTFT p50 (ms) TTFT p99 (ms) TPOT p50 (ms) VRAM Peak (MB) Power Avg (W) Tok/Joule
c = 1 6 / 0 9.6 112 ms 171 ms 102 ms 1,482 MB 12.7 W 0.76
c = 2 6 / 0 12.0 203 ms 380 ms 157 ms 1,482 MB 13.1 W 0.92
c = 4 6 / 0 11.7 496 ms 1,037 ms 297 ms 1,734 MB 13.8 W 0.85

🏎️ Speculative Decoding Benchmark (0.5B Draft Proposer → 1.5B Target Verifier)

Evaluated live on NVIDIA GeForce RTX 3050 6GB Laptop GPU using zero-overhead in-place streaming bfloat16 weights with PyTorch SDPA:

Pipeline Model(s) Total VRAM Acceptance Rate $\alpha$ Verify Mode Distribution Match
Standalone Target Qwen2.5-1.5B 2.88 GB N/A Autoregressive (1 tok/step) Reference ground truth
Speculative Pair 0.5B (Draft) + 1.5B (Target) 3.81 GB 43.6% – 77.8% Leviathan Parallel Rejection ($K=3$) 100% Exact (Zero drift)
  • Zero Distribution Drift: Target rejection sampling mathematically guarantees exact equivalence to sampling from the 1.5B target distribution alone.
  • Dual-Model VRAM Fit: Both models load simultaneously into just 3.81 GB VRAM via zero-overhead in-place file streaming, running effortlessly within consumer 6 GB limits.

🛠️ Comparison: mini-infer vs Production Engines

Feature mini-infer vLLM llama.cpp HuggingFace Transformers
Core Language Pure Python / PyTorch C++ / CUDA / Python Pure C / C++ Python / PyTorch
Paged Attention ✅ (16-tok blocks) ✅ (CUDA kernel) ❌ ❌
Continuous Batching ✅ (Iteration-level) ✅ (Iteration-level) ⚠️ (Slot-based) ❌ (Static padding)
Prefix Caching ✅ (Hash matching) ✅ (Radix tree) ✅ (Prompt cache) ❌
Speculative Decoding ✅ (Rejection sampling) ✅ (Draft worker) ✅ (Draft model) ⚠️ (Experimental)
Hardware Barrier None (Runs on Laptop GPU) High (Requires full CUDA toolkit) Low (Runs on CPU/GPU) None
Code Readability ⭐⭐⭐⭐⭐ (Clean & Modular) ⭐⭐ (Deep C++ macros) ⭐⭐ (Low-level C) ⭐⭐⭐ (Heavy abstraction)

💻 Python Programmatic API

Want to experiment with the engine directly inside Python scripts or Jupyter Notebooks without launching the HTTP server?

import torch
from mini_infer.engine import InferenceEngine
from mini_infer.models.loader import load_model_from_safetensors

# 1. Load weights directly from safetensors with zero host memory duplication
model, config = load_model_from_safetensors("Qwen/Qwen2.5-0.5B-Instruct", device="cuda")

# 2. Initialize the Paged KV engine
engine = InferenceEngine(
    model=model,
    config=config,
    num_blocks=256,
    block_size=16,
    device=torch.device("cuda"),
)

# 3. Submit a prompt and step the continuous batching scheduler
prompt_ids = [785, 6722, 315, 9625, 374]  # "The capital of France is"
req_id = engine.add_request(prompt_tokens=prompt_ids, max_tokens=10)

# 4. Iterate scheduler until request finishes
while not engine.is_finished(req_id):
    outputs = engine.step()
    for seq_id, new_token in outputs:
        if seq_id == req_id:
            print(f"Generated token ID: {new_token}")

❓ Frequently Asked Questions (FAQ)

1. Do I need an expensive GPU to run mini-infer?

No. mini-infer is specifically engineered to run within the memory constraints of consumer laptop GPUs (like an NVIDIA RTX 3050 6GB) and free cloud tiers (Kaggle or Google Colab T4). It also features automatic CPU fallback via --device cpu.

2. How are model weights downloaded?

Weights are automatically fetched on the first run via huggingface_hub and cached locally in ~/.cache/huggingface/. You do not need to convert or manually download .bin or .gguf files.

3. How do I run the automated test suite?

Run the test suite using pytest:

uv run pytest -v

All 13 unit tests cover block allocation, continuous scheduling, prefix hash matching, and speculative rejection verification.

4. How does mini-infer pair with servebench?

servebench was built as Flagship #1 of our portfolio to rigorously measure local LLM engines. When mini-infer is running, servebench automatically detects it at GET /health (status: ok, engine: mini-infer) and provides instant TTFT, TPOT, and throughput cards.


📂 Codebase Tour

mini-infer/
├── src/mini_infer/
│   ├── models/
│   │   ├── config.py         # Architecture specs (hidden size, heads, RoPE theta)
│   │   ├── qwen2.py          # Pure PyTorch Qwen2 model with SDPA attention
│   │   ├── loader.py         # Zero-overhead in-place safetensors streaming loader
│   │   └── sampler.py        # Temperature, top-p, and greedy token sampling
│   ├── cache/
│   │   ├── block.py          # Physical memory blocks & BlockAllocator pool
│   │   ├── table.py          # Virtual-to-physical block translation table
│   │   └── prefix_cache.py   # Radix hash matching for shared prompt prefixes
│   ├── scheduler/
│   │   ├── sequence.py       # Sequence lifecycle & state machine (WAITING, RUNNING)
│   │   └── continuous.py     # Iteration-level continuous batching scheduler
│   ├── speculative/
│   │   └── verifier.py       # Leviathan rejection sampling draft/target verifier
│   ├── api/
│   │   └── server.py         # FastAPI OpenAI-compatible SSE streaming endpoints
│   ├── engine.py             # Unified InferenceEngine coordinator
│   └── cli.py                # Typer CLI (serve, info)
└── tests/                    # Comprehensive unit tests (cache, scheduler, models)

📋 Roadmap & Completed Milestones

  • M1: Self-Contained Model & Weights Loader: Clean Qwen2.5 in PyTorch, direct .safetensors loader without transformers.AutoModel, logits verified against reference within $10^{-4}$.
  • M2: Paged KV-Cache: Block allocator, virtual-to-physical block table, zero VRAM waste.
  • M3: Continuous Batching Engine: Iteration-level dynamic batching scheduler.
  • M4: Prefix Caching: Radix block matching for shared prompt prefixes.
  • M5: Speculative Decoding: 0.5B draft proposer + 1.5B target parallel verifier.
  • M6: HTTP Streaming Server & Benchmark Battle: OpenAI SSE streaming API benchmarked live against real hardware with servebench.

📄 License

Apache 2.0 — free for commercial, research, and educational use.

Metadata

Release files for mini-infer 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mini-infer 0.1.0
File Size Uploaded Provenance
mini_infer-0.1.0.tar.gz 195.5 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for mini-infer 0.1.0
File Interpreter ABI Platform
mini_infer-0.1.0-py3-none-any.whl Python 3 none any Details

Total release size: 227.0 kB

Release files / mini_infer-0.1.0.tar.gz

Download URL mini_infer-0.1.0.tar.gz
Size 195.5 kB
Tags Source
SHA-256 checksum
How to use checksums
ea553089274a9072b4d3e65e80e54d147f3e56a7bce4ff69c02b549659a992d4
BLAKE2b-256 checksum
How to use checksums
6e522832c2a4bac71a2f0facdd0219bc3b7ada5f0bd0fcd14ef9d62eef975182
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.23 {"installer":{"name":"uv","version":"0.12.23","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / mini_infer-0.1.0-py3-none-any.whl

Download URL mini_infer-0.1.0-py3-none-any.whl
Size 31.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f51dd3af5c2e8f1e605ae42120aa0c8778a6e0f09fe6dfb287683028527592c5
BLAKE2b-256 checksum
How to use checksums
b1360ab27c9eaefadb911cec6b8dd9b50356ce6aa9fdbe6202fee724a8e41f25
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.23 {"installer":{"name":"uv","version":"0.12.23","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for mini-infer 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page