VISUAL LESSON · 9 PICTURES

On-Device Capstone: Speculative Heads, Unified Memory & Edge RAG

How do multiple speculative decoding heads (Medusa), Apple Silicon unified zero-copy memory, on-device voice streaming, and private local RAG unite into a complete edge AI application?

Progress stays on this device · no login
BEFORE THE FIRST PICTURE

How this lesson unfolds.

Begin with How do Medusa speculative drafting, Apple Silicon zero-copy memory, and private local RAG deliver instantaneous on-device AI experiences?. Follow the visual diagrams to build an intuitive, mathematically grounded mental model of edge capstone: speculative tree drafting, unified memory & local rag.

Picture 1 of 9 · tap to inspect in full resolution
01

How does medusa multi head speculative tree drafting operate mathematically within the overall Edge Capstone: Speculative Tree Drafting, Unified Memory & Local RAG?

INTUITION

Instead of needing a second separate draft model, Medusa sprouts multiple extra output heads directly from the single model's forehead! Head 1 predicts token +1, Head 2 predicts token +2, and Head 3 predicts token +3. They generate a tree of candidate sentences, and the model verifies the best branch in one forward glance.

MATHEMATICAL STATEMENT
  1. $$\mathbf{y} = f(\mathbf{X} \mathbf{W} + \mathbf{b})$$
✦ More context & mechanics
Conceptual Mechanics & Logic

Medusa adds K lightweight single-layer MLP heads on top of the final transformer hidden state h_t:

z_(t+k)^((k)) = MedusaHeadₖ(h_t) ∈ R^V for k ∈ [1, K]

Candidates from the top predictions are arranged into a tree structure. A specialized tree attention mask verifies all branches simultaneously in a single forward pass, accepting 2 to 3 tokens per step without any separate draft model.

Real-World Usage

Integrated into high-speed inference runtimes (SGLang, vLLM, TensorRT-LLM) for 2x to 3x throughput gains.

History & Origin Story

Invented by Tianle Cai et al. (Together AI & Princeton, 2024) in 'Medusa: Simple LLM Inference Acceleration Framework with Multiple Decoding Heads'.

How to Memorize & Golden Words

Sprout extra heads on the same trunk: Medusa accelerates generation without a second model.

Picture 2 of 9 · tap to inspect in full resolution
02

How does apple silicon unified memory zero copy architecture operate mathematically within the overall Edge Capstone: Speculative Tree Drafting, Unified Memory & Local RAG?

INTUITION

On traditional PCs, the CPU and GPU live in different houses and mail data back and forth across a slow bridge (PCIe bus). On Apple Silicon (M-series), the CPU, GPU, and Neural Engine sit at the exact same dining table, sharing the exact same unified pool of memory. The GPU reads the weights instantly with zero copy!

MATHEMATICAL STATEMENT
  1. $$\mathbf{y} = f(\mathbf{X} \mathbf{W} + \mathbf{b})$$
✦ More context & mechanics
Conceptual Mechanics & Logic

Unified Memory Architecture (UMA) connects CPU and GPU cores to a single contiguous LPDDR5 memory pool with bandwidth exceeding 400 - 800 GB/s:

Pointer_(GPU) ≡ Pointer_(CPU) ⟹ Copy Overhead = 0

Apple MLX framework exploits this via `mlx.core.array`, creating arrays in host memory that are immediately executable by Metal GPU shader pipelines with zero IPC transfer.

Real-World Usage

The standard architecture for running massive models (e.g. 70B models in 4-bit on a 64 GB MacBook Pro) that would otherwise require multiple server GPUs.

History & Origin Story

Introduced with Apple M1 in 2020, revolutionizing consumer hardware capabilities for large-scale AI research and local inference.

How to Memorize & Golden Words

Unified memory eliminates the PCIe bus: zero copy means instant model loading and massive parameter headroom.

Picture 3 of 9 · tap to inspect in full resolution
03

How does on device voice multimodal edge streaming pipeline operate mathematically within the overall Edge Capstone: Speculative Tree Drafting, Unified Memory & Local RAG?

INTUITION

A conversation that feels completely natural, like talking on the phone with a friend. The system doesn't wait for you to stop speaking, think for 5 seconds, and then play a recorded message; it processes your voice syllables as they arrive and streams back spoken words with under 300 milliseconds of total latency.

MATHEMATICAL STATEMENT
  1. $$\mathbf{y} = f(\mathbf{X} \mathbf{W} + \mathbf{b})$$
✦ More context & mechanics
Conceptual Mechanics & Logic

The edge streaming voice pipeline cascades three streaming stages:

  1. Streaming ASR: Neural acoustic model (Whisper/Zipformer) converts microphone audio chunks into text tokens in 50ms intervals.
  2. Streaming SLM: Text tokens stream into our edge transformer, yielding response tokens at 40 tokens/sec.
  3. Streaming TTS: Neural vocoder (StyleTTS2, Kokoro) synthesizes text tokens into audio waveforms chunk-by-chunk directly to the speaker buffer.

End-to-end conversational turnaround time is ≤ 250 ms, crossing the human natural conversation threshold.

Real-World Usage

Deployed in smart wearables, voice assistants, and smart home edge devices (Ray-Ban Meta glasses, Rabbit, Apple Siri).

History & Origin Story

Pioneered in duplex conversational systems (Google Gemini Live, OpenAI Advanced Voice Mode) and adapted to local edge silicon in 2024.

How to Memorize & Golden Words

Stream audio in → stream tokens out → stream audio back: pipelined concurrency crushes conversational latency.

Picture 4 of 9 · tap to inspect in full resolution
04

How does battery and thermal throttling curves mobile npu operate mathematically within the overall Edge Capstone: Speculative Tree Drafting, Unified Memory & Local RAG?

INTUITION

Your smartphone has no cooling fan. When an AI model pushes the processor to 100%, the metal chassis heats up. When it hits 42 degrees Celsius, the phone's thermal protection kicks in, cutting processor speed in half to keep your battery from swelling and your fingers from burning.

MATHEMATICAL STATEMENT
  1. $$\mathbf{y} = f(\mathbf{X} \mathbf{W} + \mathbf{b})$$
✦ More context & mechanics
Conceptual Mechanics & Logic

Thermal dynamics on fanless mobile SoCs are governed by Newton's law of cooling:

dT/dt = -k(T - T_(amb)) + (P_(dissipated)) / (C_(thermal))

When skin temperature reaches T_(throttle) ≈ 43^(∘)C, the Dynamic Voltage and Frequency Scaling (DVFS) governor drops clock frequencies from 3.2 GHz to 1.8 GHz, causing inference throughput to drop by 40 - 50\%. Edge models must operate below the sustained thermal envelope (3 - 5 Watts).

Real-World Usage

Critical in mobile app development to prevent app store rejections and maintain smooth sustained frame rates.

History & Origin Story

Standardized in mobile processor engineering across Apple, Qualcomm, and Arm to guarantee safety and battery longevity.

How to Memorize & Golden Words

Peak performance is a sprint; thermal envelope is a marathon: design for sustained wattage, not burst benchmarks.

Picture 5 of 9 · tap to inspect in full resolution
05

How does local function calling constrained json schemas operate mathematically within the overall Edge Capstone: Speculative Tree Drafting, Unified Memory & Local RAG?

INTUITION

Giving the AI model a template stencil: if the model is outputting a flight booking, it is physically impossible for it to output invalid syntax, extra text, or broken quotes. The token generator's keyboard only lights up keys that form valid JSON.

MATHEMATICAL STATEMENT
  1. $$\mathbf{y} = f(\mathbf{X} \mathbf{W} + \mathbf{b})$$
✦ More context & mechanics
Conceptual Mechanics & Logic

Grammar-constrained decoding uses a Context-Free Grammar (CFG) or JSON Schema compiled into a finite state machine (FSM). At every step t, the FSM determines valid next tokens:

z'ᵢ = zᵢ & if wᵢ ∈ ValidTokens(FSM_(state)) \ -∞ & otherwise

This guarantees that output strings adhere strictly to schemas with 100% syntactic validity.

Real-World Usage

The standard engine powering tool calling and local function calling in Outlines, LM Format Enforcer, and llama.cpp grammar mode (`--grammar`).

History & Origin Story

Formulated by Willard and Louf (2023) in 'Efficient Guided Generation for Large Language Models', solving the chronic problem of malformed JSON in API integrations.

How to Memorize & Golden Words

Constrain the logits with an FSM: eliminate parse errors at the source of generation.

Picture 6 of 9 · tap to inspect in full resolution
06

How does private local edge rag architecture operate mathematically within the overall Edge Capstone: Speculative Tree Drafting, Unified Memory & Local RAG?

INTUITION

Your own private digital butler who has read all your personal tax returns, medical records, and private journals. The butler never uploads your documents to the cloud, never leaks your data, and runs 100% locally on your laptop or phone.

MATHEMATICAL STATEMENT
  1. $$\mathbf{y} = f(\mathbf{X} \mathbf{W} + \mathbf{b})$$
✦ More context & mechanics
Conceptual Mechanics & Logic

Private local Retrieval-Augmented Generation (RAG) executes in four offline steps:

  1. Document Chunking: Splits local files into 500-token chunks with 50-token overlap.
  2. Local Embedding: Small embedding model (e.g. `bge-small-en-v1.5`, 33M params) encodes chunks into 384-dimensional vectors.
  3. Local Vector Search: HNSW vector index (sqlite-vec, FAISS) retrieves top-k chunks via cosine similarity:

sim(q, d) = (q · d) / (\|q\| \|d\|)

  1. Local Generation: Edge SLM synthesizes the final answer using retrieved context inside a secure sandboxed memory space.
Real-World Usage

The premier architecture for privacy-sensitive deployments: healthcare apps, legal compliance tools, and confidential on-device search.

History & Origin Story

Pioneered by Lewis et al. (2020) at Meta AI and miniaturized into local embedded runtimes in 2023–2024.

How to Memorize & Golden Words

Private embeddings, private search, private generation: edge RAG delivers intelligence with zero cloud leakage.

Picture 7 of 9 · tap to inspect in full resolution
07

How do tokenization, KV-cache quantization, speculative decoding, and unified on-device memory orchestrate into an end-to-end production edge inference engine?

INTUITION

Think of a Formula 1 pit stop crew. If the tire changers, fuel pumpers, and windshield wipers work independently without choreography, the stop takes 30 seconds. When perfectly synchronized, the car is serviced and accelerating in 1.9 seconds. Similarly, edge SLM deployment is not just a model; it is a synchronized assembly line: audio enters via on-device Whisper, flows directly through zero-copy unified memory to the quantized transformer, drafts 3 candidate tokens simultaneously with Medusa heads, and outputs streaming voice synthesis without ever round-tripping to cloud servers.

MATHEMATICAL STATEMENT
  1. $$\text{Throughput} = \frac{\text{Memory Bandwidth (GB/s)}}{\text{Quantized Model Size (GB)}} \times \mathbb{E}[\alpha_{spec}]$$
✦ More context & mechanics
Conceptual Mechanics & Logic

The complete edge execution lifecycle operates across four tightly coupled stages:

  1. Memory Budget & Footprint:

RAM_(total) = Model_(INT4) + KV_(INT8)(B, L, H, dₖ) + Runtime Overhead

  1. Speculative Generation Step:

y_(t+1:t+k) = Verify(MedusaHeads(h_t), M_(tree))

  1. Zero-Copy Memory Bandwidth:

Eliminates PCIe serialization by sharing RAM directly between CPU cores, GPU metal compute units, and the Apple Neural Engine (ANE).

Concrete Numeric Walkthrough

Consider deploying a 3-Billion parameter Small Language Model on an iPhone 16 Pro (8 GB Unified RAM):

  • FP16 Base Size: 3 × 10⁹ × 2 bytes = 6.0 GB (Violates 4 GB app memory limit; crashes the OS).
  • INT4 Quantized Size (AWQ): 3 × 10⁹ × 0.55 bytes ≈ 1.65 GB (Comfortably fits with 60% memory headroom).
  • KV Cache for 2048 Context: 2 × 28 layers × 4 heads × 128 dim × 2048 × 1 byte (INT8) ≈ 117 MB.
  • Throughput Calculation: With unified memory bandwidth of 60 GB/s, raw memory-bound generation achieves:

Speed = (60 GB/s) / (1.65 GB/token) × α_(spec) ≈ 36.3 × 1.8 ≈ 65.3 tokens/second

Real-World Usage

Powers Apple Intelligence (on-device 3B foundation model), Google Gemini Nano on Android Pixel Tensor G4, and private local assistants running on MLX and llama.cpp.

History & Origin Story

Synthesized from quantization breakthroughs (SmoothQuant, Xiao et al. 2022; AWQ, Lin et al. 2023) and multi-head speculative decoding (Cai et al. 2024), shifting AI from centralized cloud servers to autonomous edge devices.

How to Memorize & Golden Words

Quantize the weights, share the memory, draft with speculative trees: the fastest cloud query is the one that never leaves your pocket.

Picture 8 of 9 · tap to inspect in full resolution
08

How do tree-structured candidate projections allow parallel verification of multiple speculative tokens in a single forward pass?

INTUITION

Imagine playing chess against a grandmaster. A fast amateur assistant suggests: 'If you move Knight to F3, they will respond Pawn to E5, then you can play Bishop to C4.' The grandmaster doesn't think about these moves one by one: in a single glance at the board, the grandmaster verifies all three moves at once and agrees. Speculative decoding uses a tiny draft model (the amateur) to guess 4 tokens ahead in a branching tree, and a giant LLM (the grandmaster) verifies the whole tree in one single parallel forward pass, accelerating text generation by 3x.

  • Learning goalConstruct tree attention masks for speculative decoding candidate branches and compute token acceptance probabilities.
  • Helpful foundationsCausal masking · Fast Inference from Transformers via Speculative Decoding (Leviathan et al., 2023)
  • Common trapThinking speculative decoding produces approximate or degraded outputs; mathematical rejection sampling guarantees that the output distribution is mathematically identical to sampling directly from the large target model.
  • Next connectionBefore understanding complex neural layers, how does a basic matrix-vector multiplication transform Euclidean coordinates? We look at basis coordinate transformations.
✦ More context & mechanics
Conceptual Mechanics & Logic

In speculative decoding:

  1. A small draft model generates a tree of K candidate tokens with branching paths.
  2. The tree is flattened into a single sequence accompanied by a custom 2D Tree Attention Mask M_(tree) ∈ 0, -∞^(K × K):

M_(i, j) = 0 & if token j is an ancestor of token i \ -∞ & otherwise

  1. The large target model evaluates all K candidates in a single parallel GEMM forward pass.
  2. Speculative tokens are accepted or rejected sequentially using modified rejection sampling:

P(accept x_(t)) = min(1, (P_(target)(x_t | x_(<t))) / (P_(draft)(x_t | x_(<t))))

If a branch is rejected, the draft tree is pruned and generation resumes from the verified prefix.

Real-World Usage

Speculative decoding is integrated into inference engines like vLLM, TensorRT-LLM, and Apple MLX, delivering 2.5x to 3.5x wall-clock speedups for LLaMA-3 and Mistral without any loss in output distribution quality.

History & Origin Story

Charlie Chen et al. (Google Research) and Yaniv Leviathan et al. published speculative decoding independently in 2022/2023, revolutionizing memory-bound LLM serving.

How to Memorize & Golden Words
  • Draft quickly in trees; verify in parallel with one big forward pass.
  • Tree masks prevent cross-branch cheating during verification.
Picture 9 of 9 · tap to inspect in full resolution
09

How do multiple speculative decoding heads predict subsequent tokens concurrently, verified in a single forward pass?

INTUITION

In Greek mythology, Medusa had multiple serpent heads looking in every direction. Standard LLMs have only one head predicting token 1. Medusa attaches 4 lightweight heads to the top of the frozen LLM: Head 1 predicts token t+1, Head 2 predicts t+2, Head 3 predicts t+3, and Head 4 predicts t+4. Instead of requiring an entire separate draft model, the base model itself generates a branching tree of speculative guesses. In the next step, a single forward pass with a tree mask verifies the guesses, sprinting through text 3x faster.

  • Learning goalArchitect Medusa speculative decoding heads and construct the 2D tree-attention verification mask.
  • Helpful foundationsSpeculative decoding basics · Medusa: Simple Framework for Accelerated LLM Generation (Cai et al., 2024)
  • Common trapThinking Medusa requires fine-tuning the entire backbone; the base model backbone weights are completely frozen—only the small multi-head MLPs are trained.
  • Next connectionWe now transition to the neural network foundations: writing neurons and layers from scratch in pure Python and NumPy.
✦ More context & mechanics
Conceptual Mechanics & Logic

Medusa architecture:

  1. Medusa Heads: Given the final hidden state h_t from the base model backbone:

p_t^((k)) = softmax( W_(head)^((k)) · SiLU( W_(proj)^((k)) h_t ) ), k ∈ 1, 2, ṡ, K

Each head k predicts the probability of the token at future offset t + k.

  1. Tree Generation:

Top-scoring candidates from each head form a speculative prefix tree (e.g. 64 candidate paths).

  1. Tree-Attention Single-Pass Verification:

All candidate paths are flattened into a single sequence and fed to the backbone model using a custom 2D Tree Attention Mask M:

M_(i, j) = 0 & if node j is an ancestor of node i \ -∞ & otherwise

  1. Longest Accepted Path:

The verification pass evaluates ground truth predictions for all candidates. The longest valid prefix is accepted, advancing generation by multiple tokens per forward pass.

Real-World Usage

Medusa is implemented in open-source serving systems like vLLM and Together AI, delivering 2.2x to 3.0x speedups without needing to host a secondary draft model in VRAM.

History & Origin Story

Tianle Cai et al. (Princeton, Together AI) published Medusa in 2024 ('Medusa: Simple LLM Inference Acceleration Framework with Multiple Decoding Heads').

How to Memorize & Golden Words
  • Multiple heads sprout from the backbone; tree mask verifies all paths at once.
  • No secondary draft model needed; generate multiple tokens per tick.