Macalinao StudioLearnAll lessons ↗

TAKE THE LONGER ROUTE

Open the complete college lesson →

Worked explanations, full local narration, and connected Signal Room, Workbench and Field Notes.

SIGNAL ROOM

Local InferenceUnderstand the moving parts.

Ollama, llama.cpp, vLLM, SGLang.

Suggested preparation: 08

WORKBENCH / CHANGE ONE THING

Quantize a small weight

Change bit width and inspect reconstruction error.

Computed teaching example · fixed assumptions shown below

LISTEN & FOLLOW / GUIDED RECAP

Audio starts only when you choose.

FIELD NOTES / THE COMPLETE READING

Take the longer way.

The full lesson narrative, equations and code. Switch views without losing your place.

A slower starting point

Round a measurement to a coarse ruler and calculate what was lost.

Where this deserves more time

Signed ranges, scale and zero point; cache and workspace memory; quality evaluation.

Open the complete high-school reading

Moment 01 / 11

Course Introduction and Overview

Welcome to the course on offline inference engines. We will study how large language models are served locally: the systems, memory hierarchies, and scheduling decisions that determine latency and throughput.

Offline inference means executing the forward pass on local hardware rather than calling a remote API. The motivation is not only cost and privacy; it is control over quantization, batching, and the key value cache, which govern memory footprint and tokens per second.

We will compare four stacks: Ollama for usability, llama.cpp for quantized CPU and edge execution, vLLM for PagedAttention and continuous batching, and SGLang for RadixAttention and structured generation. Same model, very different systems tradeoffs.

Objectives: read a serving stack end to end, from tokenizer to logits; reason about memory bandwidth, arithmetic intensity, and batch size; and deploy a reproducible local inference workflow.

By the end, you should choose a framework deliberately: estimate throughput from model size and hardware, quantify the quality cost of quantization, and ablate serving choices rather than trusting benchmarks.

With that roadmap, we begin with first principles: why local inference is a memory-bound workload, and what that implies for every engine we will study.

Equations, code and original cards

Offline Inference Engines: Course Overview

• Offline inference: local forward passes, no cloud API dependency

• Motivation: privacy, cost, and control over latency and memory

• Ollama, llama.cpp, vLLM, SGLang: distinct serving tradeoffs

• Objectives: throughput, memory bandwidth, quantization, deployment

Moment 02 / 11

Mathematical Foundations of Inference Engines

Today we examine the mathematical foundations of inference engines: the linear algebra of forward passes, gradient flow through the computation graph, and the loss functions that shape optimization.

First, matrix operations. Every forward pass reduces to tensor contractions: activations are multiplied by weight matrices layer by layer, and end-to-end throughput is governed by how efficiently the hardware executes these multiplications.

The core equation is Y equals X W plus b: the input matrix X is projected by the weight matrix W and shifted by a bias b, yielding the pre-activation output Y.

Next, gradients. Strictly speaking, gradients are a training-time quantity, not an inference one: they measure the sensitivity of the loss to each parameter and drive backpropagation during learning.

This expression is the gradient of the loss L with respect to W: the partial derivatives computed by applying the chain rule backward through every operation in the computation graph.

Finally, the loss function. It quantifies the discrepancy between predictions and targets, and its gradient defines the descent direction for every parameter update in stochastic optimization.

Here L is the empirical risk: one over N times the sum of per-sample losses, typically cross-entropy for classification or mean squared error for regression.

Together, linear algebra, the chain rule, and loss geometry underpin every inference engine; mastering them is prerequisite to reasoning about latency, throughput, and numerical stability.

Equations, code and original cards

Mathematical Foundations of Inference Engines

• Forward Passes as Tensor Contractions

• Y = XW + b: Pre-activation Projections

• Batched GEMMs Govern Throughput

• PyTorch: torch.mm(input, weight)

\mathbf{Y} = \mathbf{X} \times \mathbf{W} + \mathbf{b}

• Gradients: Training-Time, Not Inference

• Chain Rule over the Computation Graph

• Reverse-Mode Autodiff (Backpropagation)

• PyTorch Autograd: loss.backward()

\nabla_{\mathbf{W}} L = \frac{\partial L}{\partial \mathbf{Y}} \cdot \frac{\partial \mathbf{Y}}{\partial \mathbf{W}}

• Loss Defines the Optimization Landscape

• Empirical Risk: Cross-Entropy or MSE

• Gradient Direction Drives Updates

L = \frac{1}{N} \sum_{i=1}^N (\hat{y}_i - y_i)^2

Moment 03 / 11

Model Compression and Quantization Techniques

Welcome to today's session on model compression and quantization. These techniques let a model like Llama-3-8B run on offline devices, where memory and bandwidth are hard constraints rather than inconveniences.

Start with the baseline: Llama-3-8B in Float16. Eight billion parameters at two bytes each is roughly 15 gigabytes of weights, demanding high VRAM and memory bandwidth — a poor fit for offline deployment.

GGUF int4 quantization cuts that footprint roughly fourfold, from two bytes to half a byte per weight. The architecture is untouched; only the weight representation changes, which is what makes this so practical.

The cost is precision. Lower bit-widths shrink the footprint but perturb the weights, degrading perplexity and downstream accuracy. Choosing a bit-width is choosing a point on that trade-off curve.

The mechanism is straightforward: each floating-point weight x is scaled and rounded to the nearest quantized level q, then reconstructed at inference by multiplying by the scale. Continuous values become a small discrete codebook.

In summary, quantization compresses Llama-3-8B enough for offline inference while trading away some representational fidelity. Keep this precision-versus-size trade-off in mind as we move to hands-on implementations.

Equations, code and original cards

Model Compression and Quantization Techniques

Post-training quantization for efficient offline inference

• Float16 Llama-3-8B: 8B params × 2 bytes ≈ 15GB

• High VRAM & memory bandwidth required

• Weight loading dominates offline inference latency

• GGUF int4 quantization
– 2 bytes → 0.5 byte per weight, ~4× smaller

• Architecture unchanged; only weight representation

• Near-baseline perplexity at 4-bit precision

• Precision vs. footprint trade-off:

– Lower bit-width = smaller, faster model

– Weight perturbation degrades perplexity

– Bit-width choice is application-dependent

q=\mathrm{round}\left(\frac{x - x_{\min}}{s}\right), \quad s = \frac{x_{\max} - x_{\min}}{2^b - 1}

Moment 04 / 11

Inference Execution Pipeline Visualization

Trace the inference pipeline: weight loading, graph capture, quantization, kernel selection, and execution across CPU or GPU backends.

Quantization compresses weights and accelerates memory-bound decode; GPTQ is post-training, layerwise second-order rounding that holds perplexity near baseline at four bits.

llama.cpp executes those packed tensors with vectorized AVX2 or AVX512 kernels, cache-aware blocking, and memory-mapped weights for local CPU decoding.

The scheduler then targets CPU or GPU, while Ollama or LM Studio manages request routing, continuous batching, key value cache reuse, and streaming responses.

Equations, code and original cards

Moment 05 / 11

Ollama and llama.cpp Implementation Details

Ollama and llama.cpp occupy different layers: one is a local model server and package manager, the other is the inference engine that turns quantized weights into logits.

Ollama runs as a daemon on localhost, not as a model. It pulls and versions weight blobs, builds prompts from templates, keeps sessions warm, and exposes generate and chat endpoints over HTTP.

llama.cpp is the C plus plus runtime underneath: it loads G G U F tensors, applies quantization kernels, allocates the key value cache, decodes batches, and hands back logits for sampling.

The Python binding is inference only, despite the torch-like feel. There is no autograd graph; you get prompt tokenization, context state, logits, temperature and nucleus sampling, then text.

LangChain should stay an orchestration layer. Wrap the local model behind one interface, then keep retrieval, tools, and prompt composition separate from quantization, context length, and decoding policy.

The stack is therefore explicit: server lifecycle above, native engine below, adapters at the edges. That separation is what makes local inference debuggable, portable, and fast enough to matter.

Equations, code and original cards

Ollama and llama.cpp: Local Inference Internals

• Ollama: local daemon, model manifests, REST generate and chat endpoints

• llama.cpp: C plus plus inference over G G U F quantized weights

• Key value cache, context window, batch decode, C U D A and Metal backends

• Python and LangChain adapters: inference only, no autograd

# Ollama generate endpointimport requestsresp = requests.post('http://localhost:11434/api/generate',                json={'model': 'llama2', 'prompt': 'Hello, world', 'stream': False})print(resp.json()['response'])
// llama.cpp: explicit model, context, key value cachellama_model * model = llama_load_model_from_file(path, mparams);llama_context * ctx = llama_new_context_with_model(model, cparams);// tokenize prompt, llama_decode batches, sample logits, llama_free(ctx)
# llama-cpp-python: local inference, no training graphfrom llama_cpp import Llamamodel = Llama(model_path='models/llama.gguf', n_ctx=4096, n_gpu_layers=-1)out = model.create_completion(prompt='Explain causal masking', max_tokens=128, temperature=0.2)print(out['choices'][0]['text'])

• LangChain wraps the local server or llama-cpp-python behind one LLM interface

• Chains, retrieval, and tools see the same prompt in, text out contract

• Keep quantization, context length, and sampling outside the orchestration layer

Moment 06 / 11

LM Studio Features and VRAM Management

Let's start by exploring the LM Studio desktop GUI and how it simplifies managing large language models. This slide highlights the core features with a special focus on VRAM management during inference.

First, LM Studio downloads quantized GGUF models directly from HuggingFace. Quantization compresses weights to lower bit-widths, shrinking file size while retaining most of the original model quality.

Thanks to quantized GGUF downloads, the models take up less disk space and load faster into memory, which speeds up your workflow and lowers hardware demands.

One of the standout features is the real-time VRAM visualization. You can monitor memory usage dynamically during inference, which helps prevent out-of-memory errors and optimizes resource allocation.

On the practical side, LM Studio integrates Python code snippets, such as PyTorch imports and model loading commands, to facilitate local inference setups. This puts powerful tools directly into your hands.

By combining efficient model quantization, an intuitive interface, and insightful VRAM tracking, LM Studio empowers you to maximize performance during local AI inference tasks.

Equations, code and original cards

LM Studio Features and VRAM Management

• Download quantized GGUF models from HuggingFace efficiently

• Use intuitive desktop GUI for model search & query

• Monitor VRAM usage in real-time during inference

• Practical strategies to optimize local inference performance

Quantized GGUF Downloads

Lower bit-width weights shrink files, speed transfers, cut storage

Real-Time VRAM Visualization

Track memory load dynamically to prevent bottlenecks

import torch
from transformers import AutoModel

# Load quantized GGUF model
model = AutoModel.from_pretrained('gguf/quantized-model')
# Monitor VRAM during inference
print(torch.cuda.memory_allocated())

Moment 07 / 11

Advanced Techniques and Optimizations (2024-2026)

Here are the advanced techniques driving offline inference engines from 2024 through 2026. This period delivers concrete gains in model efficiency and output quality, grounded in scaling theory and systems co-design.

First, scaling laws constrain model compression. Chinchilla-style compute-optimal ratios tell us how many parameters a given token budget justifies, so we can prune or distill aggressively while holding perplexity flat, which is what makes deployment on memory-limited hardware viable.

Second, quantization and execution strategies have matured. Weight-only formats at four bits, KV-cache compression, and fused kernels cut memory bandwidth and latency together, often halving serving cost with negligible degradation in downstream benchmarks.

Third, alignment techniques now target inference-time quality directly. Methods like direct preference optimization and best-of-n reranking reshape the output distribution without retraining the base model, reducing reward hacking and off-policy drift.

Finally, open research questions remain. Adaptive compute allocation, speculative decoding with learned drafters, and compression below three bits are active fronts where the tradeoffs are not yet settled.

Together these points map the frontier of inference optimization. As we cover each, ask which constraints dominate your own deployment target, because the right technique depends entirely on whether you are bandwidth-bound, compute-bound, or latency-bound.

Equations, code and original cards

Advanced Techniques and Optimizations (2024-2026)

State-of-the-art optimization techniques and research trends in offline inference engines.

Key Points (2024-2026)

• Scaling laws constraining model compression

• Quantization and execution efficiency gains

• Alignment techniques for output quality

• Open research questions in offline inference

Moment 08 / 11

Cutting-Edge Variations and Future Directions

We close with frontier directions in inference engines: hybrid execution, runtime sparsity, low-bit quantization, and the systems work behind them, from FlexGen to GPTQ and speculative decoding.

Hybrid CPU-GPU inference, exemplified by FlexGen and PowerInfer, offloads cold weights or inactive neurons to host memory while the GPU handles hot computation, trading interconnect bandwidth for model capacity on consumer hardware.

Dynamic pruning and adaptive quantization strip redundant computation at runtime: magnitude masks zero out small weights, while eight-bit dynamic quantization cuts weight bandwidth fourfold with negligible perplexity loss on constrained devices.

The snippet thresholds weights at one percent magnitude to build an unstructured sparsity mask, then runs the prepare, calibrate, convert pipeline with the fbgemm backend, mapping linear layers to eight-bit integers.

Framework integration through ONNX Runtime, TensorRT, GGUF, and ExecuTorch keeps engines current with new kernels and operators, enabling deployment from datacenter GPUs down to mobile neural accelerators.

The open problems are concrete: as Dettmers and colleagues showed, emergent outlier features destabilize quantization below eight bits; unstructured sparsity rarely outperforms dense kernels; and numerics diverge across hardware.

Summary: hybrid offloading, runtime sparsity, low-bit quantization, and framework portability define the near-term frontier, with speculative decoding and structured pruning as the next levers for local inference.

Equations, code and original cards

Cutting-Edge Variations and Future Directions

• Hybrid CPU-GPU offloading: FlexGen, PowerInfer

• Dynamic pruning & adaptive low-bit quantization

• Framework integration: ONNX Runtime, TensorRT, GGUF, ExecuTorch

• Open problems: activation outliers, sparse-kernel efficiency, cross-hardware numerics

PyTorch: Magnitude Pruning & INT8 Quantization Example

import torch
import torch.nn as nn
import torch.quantization as quant

model = nn.Sequential(  
    nn.Linear(512, 256),
    nn.ReLU(),
    nn.Linear(256, 128),
    nn.ReLU())

# Unstructured magnitude pruning mask
def prune_weights(m, threshold=0.01):
    with torch.no_grad():
        mask = m.weight.abs() > threshold
        m.weight.mul_(mask)

for layer in model:
    if isinstance(layer, nn.Linear):
        prune_weights(layer)

# Post-training static quantization (INT8)
model.qconfig = quant.get_default_qconfig('fbgemm')
quant.prepare(model, inplace=True)
# Calibrate observers on sample input
model(torch.randn(1, 512))
quant.convert(model, inplace=True)

Moment 09 / 11

Code Walkthrough: Building a Local Inference Pipeline

Today we build a local inference pipeline around llama.cpp and GGUF adapters: load quantized weights, allocate the KV cache, decode logits, and measure latency rather than trusting benchmarks.

First, load GGUF models through the Python bindings, then run requests on CPU or GPU. The key constraints are memory bandwidth, context length, and where each layer resides.

The snippet imports llama cpp, constructs a Llama object from the model path, sets context and GPU offload, then samples with low temperature and prints the first choice text.

Compression stores weights at four or eight bits, cutting bytes moved per token; perplexity rises slightly, while cache pressure and prefill time usually fall.

For debugging, check tokenizer alignment, context overflow, sampling parameters, and thread pinning; tune batch size and offload layers until tokens per second stabilizes.

You leave with a reproducible recipe: quantized artifacts, explicit decoding controls, measured throughput, and ablations that expose which optimization actually buys speed.

Equations, code and original cards

Code Walkthrough: Local Inference with llama.cpp and GGUF

• Loading GGUF weights with llama-cpp-python

• Tokenization, logits, and local decoding

• Four- and eight-bit quantization tradeoffs

• Profiling latency, KV cache, and batch size

from llama_cpp import Llamallm = Llama(model_path='model.gguf', n_ctx=4096, n_gpu_layers=-1)prompt = 'Explain local inference pipeline steps.'out = llm(prompt, max_tokens=64, temperature=0.2)print(out['choices'][0]['text'])

Moment 10 / 11

Advanced Quiz on Offline Inference Engines

Now test whether the offline inference concepts have settled: continuous batching, key value cache layout, quantization, scheduling, and the throughput latency tradeoff. Answer independently.

When finished, we will interrogate errors at the mechanism level: memory footprint, kernel fusion, speculative decoding, and serving objectives.

Equations, code and original cards

Moment 11 / 11

Summary and Key Takeaways

Let us consolidate the case for local inference and model compression. Quantizing weights to four-bit GGUF and reusing the key value cache reduce memory-bandwidth demand, enabling low-latency, privacy-preserving decoding on commodity hardware.

We then examined how Ollama, llama.cpp, and LM Studio compose into a coherent offline stack: a GGML runtime, model management, and an OpenAI-compatible interface for deploying large language models locally.

We situated recent progress, from 2024 through 2026, in context: better quantization-aware training, speculative decoding, and key value cache compression have jointly raised throughput, accuracy, and hardware portability.

Finally, we framed open problems: scaling to longer contexts, robustness under distribution shift, and energy per token, alongside learning paths spanning systems, numerics, and accelerator-aware kernel design.

The takeaway is that offline engines convert foundation models into local infrastructure: deterministic latency, data sovereignty, and independence from serving providers. Apply these mechanisms to your own systems and research.

Equations, code and original cards

Summary and Key Takeaways

• Local inference: latency and privacy
• Four-bit quantization and key value cache reuse

• Ollama, llama.cpp, LM Studio as one stack
• GGML runtime plus OpenAI-compatible serving

• Research 2024 to 2026: throughput and portability

• Speculative decoding and key value cache compression

• Open problems: context, robustness, energy per token

• Learning paths: systems, numerics, kernels

MAKE IT YOURS

Explain the change.

References, scope & corrections

Research snapshots in the source material are not a claim of current state of the art. The reference review corrects identified errors; it is not exhaustive certification of every historical statement. Source code snippets are examples, not a tested production training system.

0 correction entries · expansion notes

Reset this lesson?

This removes only this lesson’s saved notes, experiments and progress.