Retrieved article excerpt
Open article Β· Retrieved 2026-11-08T06:21:45.572052+00:00
[VindexLLM](https://github.com/tinyBigGAMES/VindexLLM/blob/main/media/logo.png)
[Discord](https://discord.gg/Wb6z8Wam7p) [Follow on Bluesky](https://bsky.app/profile/tinybiggames.com)
## What is VindexLLM?
**VindexLLM** is a GPU-accelerated LLM inference engine written entirely in Delphi, using Vulkan compute shaders for all heavy computation. It loads standard GGUF model files, runs the full transformer forward pass on the GPU, and produces text β no Python, no CUDA toolkit, no external runtimes. The only dependency is `vulkan-1.dll`, which already ships with every modern GPU driver.
Feed it a prompt, get tokens back. Everything between β embedding lookup, 34 layers of attention and FFN, normalization, sampling β happens on the GPU via GLSL 450 compute shaders compiled to SPIR-V and embedded as Windows resources into the binary.
### Single-shot inference
```
var
LInference: TVdxInference;
LConfig: TVdxSamplerConfig;
begin
LInference := TVdxInference.Create();
try
// Stream tokens to console as they're generated
LInference.SetTokenCallback(
procedure(const AToken: string; const AUserData: Pointer)
begin
Write(AToken);
end, nil);
// Load model β memory-maps GGUF, initializes Vulkan, uploads weights to GPU
if LInference.LoadModel('path\to\gemma-3-4b-it-q4_0.gguf') then
try
// Configure sampler (Google-recommended settings for Gemma 3 4B IT)
LConfig := TVdxSampler.DefaultConfig();
LConfig.Temperature := 1.0;
LConfig.TopK := 64;
LConfig.TopP := 0.95;
LInference.SetSamplerConfig(LConfig);
// Generate up to 1024 tokens
LInference.Generate('Explain how a CPU works', 1024);
finally
LInference.UnloadModel();
end;
finally
LInference.Free();
end;
end;
```
### Interactive chat with persistent memory
```
var
LChat: TVdxConsoleChat;
LConfig: TVdxSamplerConfig;
begin
LChat := TVdxConsoleChat.Create();
try
LChat.ModelPath := 'path\to\gemma-3-4b-it-q4_0.gguf';
LChat.EmbedderPath := 'path\to\embeddinggemma-300M-qat-Q4_0.gguf';
LChat.MemoryDbPath := 'session.db';
LChat.SystemPrompt := 'You are a helpful assistant.';
LChat.MaxTokens := 1024;
LConfig := TVdxSampler.DefaultConfig();
LConfig.Temperature := 1.0;
LConfig.TopK := 64;
LConfig.TopP := 0.95;
LChat.SamplerConfig := LConfig;
// Enter interactive chat loop β loads model, opens memory DB,
// retrieves context via RAG each turn, streams responses
LChat.Run();
finally
LChat.Free();
end;
end;
```
Load a model, generate text, done. The chat example adds multi-turn conversation with SQLite-backed persistent memory and RAG retrieval across sessions. For the full implementations including status callbacks, cancel support, event hooks, error handling, and performance stats, see `testbed\UTest.Demo.pas`.
## Why VindexLLM?
Most LLM inference stacks depend on CUDA (NVIDIA-only, ~3GB toolkit install), Python environments, or large runtime libraries. VindexLLM takes a different approach:
- **Zero install** β Vulkan ships with every NVIDIA, AMD, and Intel GPU driver. No separate toolkit download, no PATH configuration, no DLL hell. The app calls `LoadLibrary('vulkan-1.dll')` and talks directly to the GPU.
- **No vendor lock-in** β Vulkan runs on any modern GPU. Not tied to NVIDIA hardware.
- **Self-contained binary** β All 37 compute shaders are compiled to SPIR-V at build time and embedded into the executable as Windows resources. No loose shader files, no runtime compilation.
- **No Python, no runtime** β Pure compiled Delphi. Starts instantly, no interpreter warmup, no dependency resolution.
- **Memory-mapped model loading** β GGUF files are mapped directly via `CreateFileMapping` / `MapViewOfFile`. Weights are accessed at their file offsets and uploaded to VRAM through staging buffers. No intermediate copies, no parsing into custom formats.
- **Everything on GPU** β The residual stream never leaves VRAM between layers. The only PCIe transfers are the initial token embedding (~10KB) and the final logits download for sampling. Everything else β attention, FFN, norms, activations, residual additions β runs as GPU compute dispatches.
## How It Works
VindexLLM implements the standard dense transformer forward pass. For each token, the engine runs 34 layers of attention and FFN computation on the GPU, then samples the next token from the output logits.
```
ββββββββββββββββ
β GGUF File β
β (mmap'd) β
ββββββββ¬ββββββββ
β weights uploaded to VRAM at startup
βΌ
ββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββ
β "prompt" ββββββΊβ Tokenize (BPE) βββΊ Embed (GPU lookup) β
ββββββββββββββ ββββββββββββββββββββ¬ββββββββββββββββββββββββββββ
β
βΌ Γ 34 layers
ββββββββββββββββββββββββββββββββββββββββββββββββ
β PreAttnNorm βββΊ Attention (GQA + RoPE + β
β QK-norm + TQ3 KV cache) βββΊ PostAttnNorm β
β βββΊ residual += attn_out β
β β
β PreFFNNorm βββΊ gate(x), up(x) βββΊ β
β GELU(gate) * up βββΊ down(hidden) β
β βββΊ PostFFNNorm βββΊ residual += ffn_out β
ββββββββββββββββββββ¬ββββββββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββ
β Final RMSNorm βββΊ Unembed (tied weights) β
β βββΊ Sample (temp, top-K/P, min-P, repeat) β
ββββββββββββββββββββββββββββββββββββββββββββββββ
```
Prefill processes all prompt tokens in parallel using batched matmul shaders. Autoregressive generation runs one token at a time using matvec shaders. Both paths share the same KV cache, which uses TQ3 compression to reduce VRAM usage by ~9Γ compared to F32.
## Current Status
Dense inference is working end-to-end. The engine loads a Gemma 3 4B GGUF, tokenizes a prompt with chat template formatting, runs the full forward pass on the GPU, and generates coherent text with configurable sampling. A complete interactive chat system with persistent memory and RAG is built on top of the inference engine.
**What works today:**
- Full Gemma 3 4B forward pass (34 layers, all on GPU, no CPU fallbacks)
- Batched prefill (all prompt tokens processed in parallel via matmul shaders)
- Autoregressive generation with streaming token callback
- F16, Q8\_0, and Q4\_0 weight format support (detected automatically from GGUF metadata)
- TurboQuant TQ3 KV cache compression with fused attention scoring (no separate dequant step)
- Pure Delphi BPE tokenizer loaded directly from GGUF vocabulary (no external SentencePiece library)
- Token sampling: temperature, top-K, top-P, min-P, repetition penalty, deterministic seeding (xoshiro256\*\* PRNG)
- Gemma 3 chat template formatting
- Interactive multi-turn console chat (`TVdxConsoleChat`) with streaming output, ESC cancel, slash commands
- SQLite-backed persistent conversation memory (`TVdxMemory`) with SHA-256 dedup and semantic dedup (cosine similarity threshold)
- RAG retrieval: cosine-similarity vector search over stored turns using EmbeddingGemma 300M, merged and injected as reference context each turn
- Embedding model support (`TVdxEmbeddings`) β loads a second GGUF for vector search independently of the inference model
- Session management (`TVdxSession`) wrapping inference + memory + embeddings into a single lifecycle
- Model abstraction layer with architecture registry β graceful error for unsupported models
- Architecture validation and configurable context length with model-max clamping
- VRAM usage reporting (weights, cache, buffers breakdown)
- Context overflow detection (`srContextFull` stop reason)
- Inference event callbacks (load/unload/prefill/generate start/end)
- Cancel callback (poll per-layer, ESC to abort in testbed)
- Memory-mapped file access (`TVdxVirtualFile`) for zero-copy GGUF weight reads
- Page-file-backed virtual buffers (`TVdxVirtualBuffer<T>`) for CPU workspace β allocates address space without committing physical RAM until touched
- 37 GLSL 450 compute shaders compiled to SPIR-V and embedded as Windows resources
## TurboQuant (TQ3)
TurboQuant is VindexLLM's custom 3-bit quantization format, designed specifically for KV cache compression. It uses a Walsh-Hadamard Transform (WHT) to decorrelate values within each 32-element block before quantizing to 3 bits using Lloyd-Max optimal centroids fitted to a standard normal distribution.
The result is ~9Γ compression versus F32 with quality that significantly outperforms naive 3-bit rounding because the WHT spreads information across all elements before quantization.
**TQ3 pipeline (per block of 32 values):**
1. Apply fixed sign-flip pattern (improves WHT energy distribution)
2. 5-stage butterfly WHT (in-place, no temporary buffers)
3. Normalize by 1/β32
4. Find absolute max, compute FP16 scale factor (gamma)
5. Quantize each value to nearest Lloyd-Max centroid (8 levels, 3 bits)
6. Pack: 2 low bits into `qs` words, 1 high bit into `qr` word, gamma into FP16
All four TQ3 phases run as GPU compute shaders: general quantize/dequantize (`tq3_quantize.comp`, `tq3_dequantize.comp`), KV-cache-specific quantize/dequantize (`tq3_kv_quantize.comp`, `tq3_kv_dequantize.comp`), fused batch KV store + quantize (`kv_cache_store_batch_tq3.comp`), and fused attention scores directly on TQ3-compressed keys (`attn_scores_mh_tq3.comp`) β eliminating the separate K dequantization step entirely.
CPU reference implementations exist in `VindexLLM.TurboQuant.pas` for validation.
## Supported Models
VindexLLM currently implements the Gemma 3 4B architecture. The following GGUF files have been vetted and confirmed to produce correct output. All vetted models are collected in the [tinyBigGAMES Hugging Face collection](https://huggingface.co/collections/tinybiggames/gemma-3).
| Model | Purpose | Format | Size | Download |
| --- | --- | --- | --- | --- |
| gemma-3-4b-it-qat-q4\_0 | Inference (chat/generation) | Q4\_0 | ~2.5 GB | [Download](https://huggingface.co/tinybiggames/gemma-3-4b-it-qat-q4_0-gguf/resolve/main/gemma-3-4b-it-q4_0.gguf?download=true) |
| embeddinggemma-300M-qat-Q4\_0 | Embeddings (memory/RAG) | Q4\_0 | ~278 MB | [Download](https://huggingface.co/tinybiggames/embeddinggemma-300m-qat-Q8_0/resolve/main/embeddinggemma-300m-qat-Q8_0.gguf?download=true) |
Both vetted models use **QAT (Quantization-Aware Training)** Q4\_0 rather than post-training quantized Q4\_0. With QAT, the quantization error is accounted for during training β the model learns to compensate for reduced precision, producing significantly better output quality at the same 4-bit size. This gives the smallest practical VRAM footprint while preserving quality, making it possible to run the full stack (inference + embeddings + memory/RAG) comfortably on most consumer GPUs with 4β6 GB of VRAM.
Other Gemma 3 4B GGUF files may work but have not been tested. Non-Gemma architectures are not supported at this time β the engine will report a clear error message if you attempt to load an unsupported model.
## Performance
Measured on an NVIDIA RTX 3060 12GB with Gemma 3 4B Q8\_0:
| Metric | Value |
| --- | --- |
| Prefill throughput | 35.0 tok/s |
| Generation throughput | 24.4 tok/s |
| Time to first token | 457 ms |
All computation runs on the GPU. The only PCIe transfers per token are the embedding lookup input and the logits download for sampling.
## Getting Started
1. Download