Skip to main content

mini-infer banner

mini-infer 🚀

PyPI version Sigstore Provenance Documentation 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

Direct from PyPI (Standard pip):

pip install mini-infer

With uv (Fastest):

uv pip install mini-infer

Run Immediately Without Installing (uvx):

uvx mini-infer --help

From source with uv (Recommended for development):

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)

🧑‍💻 Coding on Your Own Codebase with mini-infer

You can use mini-infer as a local, private copilot on any of your existing repositories without running out of memory:

1. Index Any Project into a Dense AST Skeleton

In your project directory, generate a token-budgeted prompt skeleton (classes, typed signatures, exports) while stripping away implementation boilerplate:

# Print to console
mini-infer repomap ./src --max-tokens 1000

# Or write to a markdown context file
mini-infer repomap ./src --max-tokens 1000 -o repo_context.md

Option A: Fastest Zero-Config Way (mini-infer chat)

If you want to immediately ask questions about your code without configuring VS Code or API keys:

# In any project directory (with repo context and persistent Agent Memory active):
mini-infer chat -c ./src --memory

It extracts the AST skeleton, starts the model with INT8 KV-cache, dynamically retrieves relevant persistent memories, and lets you chat directly in your terminal!

  • Use /remember <fact> to instantly store permanent developer preferences or constraints.
  • Use /memory to inspect all stored facts.
  • Toggle with --memory / --no-memory.

Option B: Connect Your Editor or Agent (Cursor / VS Code Continue / Aider)

Because mini-infer serve exposes standard OpenAI endpoints (http://127.0.0.1:8000/v1):

  1. Start the server:
    mini-infer serve --model Qwen/Qwen2.5-Coder-1.5B-Instruct --kv-cache-dtype int8 --port 8000
    
  2. Connect:
    • Cursor: Set OpenAI Base URL to http://127.0.0.1:8000/v1, API Key to dummy, and model to Qwen/Qwen2.5-Coder-1.5B-Instruct.
    • VS Code (Continue): Set provider to openai, apiBase to http://127.0.0.1:8000/v1.
    • Aider (Autonomous Terminal Pair Programmer):
      # Windows (PowerShell):
      $env:OPENAI_API_BASE = "http://127.0.0.1:8000/v1"
      $env:OPENAI_API_KEY = "dummy"
      aider --model openai/Qwen/Qwen2.5-Coder-1.5B-Instruct
      
      # Linux / macOS (bash/zsh):
      export OPENAI_API_BASE=http://127.0.0.1:8000/v1
      export OPENAI_API_KEY=dummy
      aider --model openai/Qwen/Qwen2.5-Coder-1.5B-Instruct
      

💡 Zero-File-Selection Prompting (Direct Natural Language)

You do not need to manually copy-paste file contents or type @filename.py:

  • In mini-infer chat -c ./src: Because -c injects the whole AST skeleton, just type: > Add a GET /metrics endpoint returning server uptime The engine locates api/app.py from the AST and writes the code automatically!
  • In Aider: Aider reads the repo-map automatically. Just type: > Add a /metrics endpoint returning server uptime Aider identifies api/app.py, edits the file on disk, and creates a git commit.
  • In VS Code (Continue): Use @Codebase instead of individual files: @Codebase Add a /metrics endpoint returning server uptime

Why This Works on a Laptop GPU:

  • INT8 KV Cache: Drops memory for 8,192 tokens from 96 MB down to 49.5 MB (-48.4%).
  • Radix Prefix Caching: The 1,000-token repository skeleton stays resident in GPU memory across turns. Follow-up prompts reuse the cached prefix, so only the new question is prefilled (see measured numbers below).

🔬 Real-World Empirical Proof: Synthesizing Code for EdgeSLM

Evaluated on an NVIDIA GeForce RTX 3050 6GB Laptop GPU running against EdgeSLM/src (15 subdirectories):

  • AST Parsing: Parsed entire repository in 82.38 ms into a 961-token typed skeleton.

  • KV-Cache Footprint: 8,192 token pool compressed from 96.00 MB down to 49.50 MB (-48.4%).

  • Prefix-cache TTFT (measured, warmed up, median of 5, Qwen2.5-0.5B bf16):

    Prompt No prefix cache Prefix-cache hit Speedup
    ~935 tokens 143 ms 66 ms 2.2×
    ~3,040 tokens 480 ms 68 ms 7.0×

    The gain grows with the length of the shared prefix. In float32, cached and uncached runs produce identical greedy tokens (5/5); in bfloat16 they can differ after a few tokens because the attention is split differently and rounding changes near-ties.

    Earlier versions of this README claimed "29.7× faster TTFT". That number compared an un-warmed first request (CUDA start-up included) with a warm second one, and the prefix cache in those versions produced wrong output on a hit. Both were fixed in v0.2.8.

# Reproduce the prefix-cache numbers:
uv run python scripts/bench_prefix_cache.py --prefix-tokens 900
uv run python scripts/bench_prefix_cache.py --prefix-tokens 3000
uv run python scripts/bench_prefix_cache.py --dtype float32   # exact-output check
# Run the live real-world verification script yourself:
uv run python scripts/test_real_repo.py path/to/any/repo/src

⚡ 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 skip prefill for those blocks; only the uncached suffix is computed. Measured TTFT drops 2.2× for a ~935-token prompt and 7× for a ~3,000-token prompt on an RTX 3050 (see above).

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.

5. Sub-Byte Weight Quantization with quantbench-engine

Autoregressive decode is strictly memory-bandwidth bound: each generated token must stream the entire weight matrix through the memory bus ($I = 2 / \text{bytes_per_param}$ FLOPs/byte).

  • mini-infer integrates directly with quantbench-engine for on-the-fly sub-byte layer replacement.
  • Vectorized INT4 Nibble Packing: Packs weights into uint8 byte buffers (2 weights/byte) with blockwise scaling (group_size=64). Compresses Qwen2.5-1.5B linear projections from 3.08 GB down to 0.84 GB (~3.7× compression).
  • INT8 Absmax: 8-bit signed integer representation with per-channel scales, cutting VRAM by ~50% with near-zero perplexity loss.
  • BitNet 1.58b Ternary: 2-bit offset-binary packed buffers for ternary weights ${-1, 0, +1}$ with mean absolute scaling $\gamma = \text{mean}(|W|)$, dropping Qwen2.5-1.5B down to 0.48 GB.
  • Ampere 2:4 Structured Sparsity: Enforces 50% sparsity with 2-bit index metadata nibbles, unlocking massive VRAM headroom for larger Paged KV-cache block pools on consumer GPUs.
# Serve Qwen2.5-1.5B in INT4 precision on an entry-level 6 GB GPU:
mini-infer serve --model Qwen/Qwen2.5-1.5B-Instruct --quant int4 --group-size 64

# Interactive terminal coding chat in INT4 precision:
mini-infer chat -c ./src --quant int4

6. Unified Batched Paged Decoding & Slot Mapping (v0.2.1)

Standard naive continuous batching runs a serial Python loop over each active sequence, transferring weights from DRAM $B$ times.

  • mini-infer v0.2.1 combines all active decodes into a single unified [batch_size, 1] forward pass.
  • Physical KV blocks are gathered directly from the pre-allocated BlockPool into sequence-masked tensor slots, achieving up to 4× reduction in GPU DRAM memory bandwidth.

7. Chunked Prefill & Memory Pressure Preemption (v0.2.1)

Burst prompt arrivals can starve active decode sequences and cause high Inter-Token Latency (ITL) spikes or physical block exhaustion.

  • Chunked Prefill: Bounded prompt prefill slices (chunked_prefill_size=512) interleave long prompt ingestion with active token generation.
  • Preemption Recovery: When the physical block pool exhausts under burst concurrency, the scheduler preempts lowest-priority sequences back to WAITING instead of crashing with OOM.

8. INT8 Dynamic KV-Cache Quantization (v0.2.2)

To double available context token capacity on consumer GPUs without losing precision, mini-infer supports dynamic INT8 KV caching:

  • Per-Token Dynamic Scaling: Quantizes cached Key and Value tensors to 1-byte torch.int8 with per-token scale factors.
  • 50% KV Footprint Reduction: Drops KV DRAM storage from 12.3 KB/tok down to ~6.2 KB/tok.
  • Zero Compiler Dependencies: Runs purely in PyTorch SDPA on CUDA, Apple MPS, and CPU.

9. AST Repo-Map Generator for Large Codebases (v0.2.2)

To code on large repositories without exceeding context limits or losing context, use mini-infer repomap to extract an AST outline (classes, typed signatures, exports) into a token-budgeted prompt skeleton:

# Index repository structure into a 1500-token prompt skeleton
mini-infer repomap . --max-tokens 1500 --output repomap.md

Combined with mini-infer's radix prefix caching, this skeleton stays warm in GPU memory across queries, so follow-up questions only pay prefill for the new text.

10. Embedded Agent Cognitive Memory Engine (v0.2.7)

Prevent context window bloat and eliminate external vector DB dependencies with zero-dependency long-term cognitive storage:

  • Embedded SQLite WAL: Pure Python standard library SQLite with Write-Ahead Logging (.mini_infer/memory.db) ensures ACID safety with zero background daemon overhead.
  • Hybrid Semantic + Lexical Retrieval: Combines deterministic 256-dimensional subword character-trigram feature embeddings ($<0.2\text{ ms}$ on CPU) with Okapi BM25 keyword ranking for exact code identifiers.
  • 4-Tier Cognitive Hierarchy: Differentiates CORE rules (permanent, never decayed) from PROJECT, DECISION, and EPISODIC context with frequency-reinforced exponential half-life decay ($t_{1/2} = 14$ days).
  • CLI Memory Management: Full terminal CRUD suite via mini-infer memory add/list/search/stats/consolidate/clear.
  • Full architecture and mathematical formulation: see Agent Cognitive Memory Documentation.
# Store a permanent core preference
mini-infer memory add "RTX 3050 has 6GB VRAM; use INT4 quantization" --category core

# Search memories across semantic & keyword boundaries
mini-infer memory search "quantization setup"

# Prune decayed episodic items while preserving core rules
mini-infer memory consolidate

⚡ Real-World Benchmarks on Real Hardware (v0.2.9)

Measured with servebench on an NVIDIA GeForce RTX 3050 6GB Laptop GPU, Qwen2.5-0.5B-Instruct (bf16), ~286-token prompts, 128 output tokens, 24 requests per level:

servebench run --url http://127.0.0.1:8000/v1 --model Qwen/Qwen2.5-0.5B-Instruct   --concurrency 1,2,4 --num-requests 24 --input-len 256 --output-len 128 --ignore-eos --warmup 2 --seed 1
Concurrency Requests (OK / Fail) Throughput TTFT p50 TPOT p50 Power avg Tok/Joule GPU clock avg
c = 1 24 / 0 8.5 tok/s 118 ms 117 ms 14.1 W 0.60 811 MHz
c = 2 24 / 0 15.3 tok/s 255 ms 146 ms 14.2 W 1.07 814 MHz
c = 4 24 / 0 26.4 tok/s 756 ms 151 ms 14.9 W 1.77 891 MHz
  • Batching works: 4 users get 3.1× the total throughput of 1 user, while each user's TPOT rises only 29%.
  • mini-infer is CPU-bound: the GPU is ~32% busy and clocks down to ~810 MHz. Each decode step runs many small PyTorch operations from Python (per-layer paged-KV gathers), so CPU speed and the laptop's power state change the result run to run; an earlier run on the same laptop measured 14.9 tok/s at c=1. For comparison, Ollama (llama.cpp) serves the 4-bit version of this model at ~190 tok/s on the same GPU. mini-infer is built to show how the algorithms work, not to compete on speed.
  • Versions before 0.2.9 failed requests with MemoryError once enough distinct prompts had been served (14 of 24 failed at c=4 in this sweep), because cached prefixes were never evicted. The v0.2.1 numbers previously shown here were measured before that and before the prefix-cache correctness fix in 0.2.8.

🏎️ 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)
Chunked Prefill ✅ (Bounded slicing) ✅ (Chunked prefill) ⚠️ (Partial) ❌
Memory Preemption ✅ (Graceful re-queue) ✅ (Recompute/Swap) ❌ (Drop) ❌
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)

🤖 Powering Autonomous Coding Agents ($0 Cost, 100% Private)

Because mini-infer implements an OpenAI-compatible /v1/chat/completions streaming API, it serves as a high-throughput, zero-cost backend for local AI and coding agents:

1. Terminal Pair-Programming Agent (Aider)

Run a full-featured terminal coding agent on your local git repository without paying OpenAI API tokens or exposing proprietary code:

# Terminal 1: Launch mini-infer with Qwen2.5-Coder
mini-infer serve --model Qwen/Qwen2.5-Coder-0.5B-Instruct --port 8000

# Terminal 2: Run Aider connected to your local mini-infer
aider --openai-api-base http://127.0.0.1:8000/v1 --openai-api-key none --model openai/Qwen/Qwen2.5-Coder-0.5B-Instruct

2. In-Editor Copilot in VS Code (Continue.dev)

Connect mini-infer to Continue for free in-editor autocomplete, inline code refactoring (Ctrl+I), and workspace chat (Ctrl+L):

{
  "models": [
    {
      "title": "Local Qwen Coder (mini-infer)",
      "provider": "openai",
      "model": "Qwen/Qwen2.5-Coder-0.5B-Instruct",
      "apiBase": "http://127.0.0.1:8000/v1",
      "apiKey": "none"
    }
  ]
}

3. Why mini-infer Excels at Agentic Workloads

  • Radix Prefix Caching: Autonomous agents repeatedly send full repository file trees, schemas, and instructions on every step. With radix prefix caching, only the new suffix is prefilled; on an RTX 3050 a ~3,000-token shared prefix goes from 480 ms to 68 ms TTFT.
  • Continuous Batching for Multi-Agent Loops: When orchestrating multi-agent loops (e.g., Planner + Critic + Coder in AutoGen, CrewAI, or LangGraph), mini-infer dynamically batches concurrent subagent streams in a unified [batch_size, 1] forward pass.
  • Graceful Preemption: Prevents out-of-memory crashes during burst multi-agent tool loops by re-queueing lowest-priority sequences back to WAITING.

💻 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.

🤝 Contributing

We welcome contributions from systems engineers, performance enthusiasts, and AI researchers! Whether you want to add support for a new model architecture (Llama-3, Gemma-2), optimize memory layouts, or implement dynamic scheduling algorithms, we would love your help.

Getting Started:

  1. Check the Contributing Guide for architectural invariants and code standards.
  2. Ensure all additions maintain the Pure PyTorch Rule (zero C++ compiler or CMake build dependencies).
  3. Run tests and lint checks before opening a pull request:
    uv run pytest
    uv run ruff check src tests scripts
    uv run ruff format src tests scripts
    

See CONTRIBUTING.md for full guidelines, pull request conventions, and high-value areas for contribution.


📄 License

Apache 2.0 — Copyright (c) 2026 Prajwal Pujari. Free for commercial, research, and educational use. See LICENSE for details.


📌 Citation

If you use mini-infer in your research, systems, or performance benchmarks, please cite it as:

@software{pujari2026miniinfer,
  author = {Prajwal Pujari},
  title = {mini-infer: Minimal Continuous-Batching LLM Inference Engine with Paged KV-Cache},
  year = {2026},
  url = {https://github.com/Prajwal7-2002/mini-infer}
}

Metadata

Release files for mini-infer 0.2.10

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.2.10
File Size Uploaded Provenance Actions
mini_infer-0.2.10.tar.gz 307.8 kB With provenance Details for mini_infer-0.2.10.tar.gz

Built distribution (wheel)

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

Total release size: 366.3 kB

Release files / mini_infer-0.2.10.tar.gz

Download URL mini_infer-0.2.10.tar.gz
Size 307.8 kB
Tags Source
SHA-256 checksum
How to use checksums
0b2ee47e7242500a0cdcd65ee513e47c623ce9267615188d227c78d29366ee05
BLAKE2b-256 checksum
How to use checksums
9d0a527c96c7daf400d2e4117800a6ec2bfc5a027f23de5e8335101598b04828
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 5, 2026.

Transparency log

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

Download URL mini_infer-0.2.10-py3-none-any.whl
Size 58.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cce1ad6edba652c8e33b47119af6cd87a16cd235d9f18052db34b17bbe60ec9b
BLAKE2b-256 checksum
How to use checksums
456c18e61eb803a2826aae1a58ffe52ea3b0301d48a98486ef3595e9f30d9a7d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 5, 2026.

Transparency log

Security for mini-infer 0.2.10

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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for mini_infer-0.2.10.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 5, 2026.

Transparency log

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