concept / research-specializations--formal-verification
Next task →
University/Specializations/Core/Formal verification
Alignment and safety · Core · Reasoning

Formal verification

Formal verification in Alignment and safety → Core → Reasoning. Autoregressive decoding is memory-bandwidth bound: one token per full model forward pass wastes the parallel compute of a GPU. Speculative decoding uses a cheap draft model to propose several tokens, then verifies them all in one target-model pass.

39 template sectionsintermediate90 mingenerated template · not reviewed
Generated template — not a reviewed lesson. This page shares boilerplate with other generated pages, so its prose may not be specific to Formal verification. The structural heuristic reports 18/100, but that number is not an accuracy score and should not be read as one.Generated template: prose is not specific to this concept · Prerequisite chain incomplete · No interactive visualStudy a hand-authored reference lesson instead →
Mastery requires: derivation reproduced, from-scratch implementation committed, failure case explained, and assessment score ≥ 80%. Current state: not_started.

1. Concept overview

Formal verification is a concept in Alignment and safety → Core → Reasoning. Autoregressive decoding is memory-bandwidth bound: one token per full model forward pass wastes the parallel compute of a GPU. Speculative decoding uses a cheap draft model to propose several tokens, then verifies them all in one target-model pass. The central question of this page is not what is it called but what problem forces it to exist, which assumptions make it valid, and how it fails. The compact statement is:

q(xt+1:t+k∣x≤t)  proposes k tokens;αi=min⁡ ⁣(1,pi(xi)qi(xi)).q(x_{t+1:t+k}\mid x_{\le t})\ \text{ proposes } k \text{ tokens};\qquad \alpha_i=\min\!\left(1,\frac{p_i(x_i)}{q_i(x_i)}\right). On rejection at ii, sample from norm(pi−qi)+\mathrm{norm}(p_i-q_i)_+. Expected accepted tokens: N=∑i=1k∏j≤iαjN=\sum_{i=1}^{k}\prod_{j\le i}\alpha_j.

Everything below derives that statement, implements it, measures it and identifies the cases where it breaks.

2. Why this concept exists

Greedy and beam search reuse no work across tokens; model parallelism and batching help throughput but not single-stream latency. Earlier speculative execution ideas existed in processors, but exact sampling from the target distribution required a rejection rule.

Before Formal verification, practitioners either solved a restricted version by hand or accepted an unjustified heuristic. Formal verification appears because it buys a real guarantee — a bound, an invariance, a tighter approximation or a tractable computation — under assumptions you can state and test. In research specializations the pressure is usually scale: larger data, higher dimensions, longer contexts or larger models.

3. Historical background

Speculative execution originates in computer architecture; exact speculative sampling for language models was introduced in 2023 and is now standard in inference servers.

The idea did not appear fully formed. Earlier work supplied the notation and the motivating failure; later work supplied the derivation and the implementation. When reading the original literature, separate the theorem from the author's heuristic justification — the two are often presented together but have different status.

4. Fundamental problem

Autoregressive decoding is memory-bandwidth bound: one token per full model forward pass wastes the parallel compute of a GPU. Speculative decoding uses a cheap draft model to propose several tokens, then verifies them all in one target-model pass.

Formally, the difficulty is that the object of interest is defined by a global property (an optimum, a distribution, an invariant, a limit) while we can only compute local quantities. Assumptions bridge that gap: The draft and target tokenize identically; probabilities are computed in the same precision; every draft token has q_i>0 wherever p_i>0 (otherwise acceptance is undefined). If any of them fails, the result may still be useful empirically, but the guarantee no longer applies.

5. First-principles explanation

Propose with q, accept with probability min(1, p/q) so the accepted tokens are distributed exactly as the target p; on rejection, resample from the corrected residual distribution. The output distribution is unchanged, only the number of target forward passes falls.

Derivation starts from the simplest possible model rather than from a definition. Draft k tokens sequentially with the small model q, recording q_i for each position. Run the large model p once on the prefix plus all k drafted tokens; obtain p_i for every position in parallel. Only after the local model is justified do we add the machinery specific to Formal verification.

6. Prerequisite concepts

You should be comfortable with: research-specializations--constitutional-ai. In particular, you must be able to manipulate the notation in section 8 and understand why each assumption in section 7 is needed. If a prerequisite is still listed as outlined in the curriculum, use the linked papers and the 11-step practical chain on its task page first.

7. Complete mathematical formulation

q(xt+1:t+k∣x≤t)  proposes k tokens;αi=min⁡ ⁣(1,pi(xi)qi(xi)).q(x_{t+1:t+k}\mid x_{\le t})\ \text{ proposes } k \text{ tokens};\qquad \alpha_i=\min\!\left(1,\frac{p_i(x_i)}{q_i(x_i)}\right). On rejection at ii, sample from norm(pi−qi)+\mathrm{norm}(p_i-q_i)_+. Expected accepted tokens: N=∑i=1k∏j≤iαjN=\sum_{i=1}^{k}\prod_{j\le i}\alpha_j.

Assumptions. The draft and target tokenize identically; probabilities are computed in the same precision; every draft token has q_i>0 wherever p_i>0 (otherwise acceptance is undefined).

Domain of validity. The statement is made for the setting described above. Extending it to research specializations / Core requires new assumptions and a new proof; do not assume the formula transfers automatically.

8. Notation dictionary

| Symbol | Meaning | Type | |---|---|---| | xx | input / state / observation | vector | | θ\theta | parameters being learned or solved for | vector | | ff | objective, map or density under study | function | | ∇,∂\nabla,\partial | gradient / partial derivative | differential operator | | E\mathbb{E} | expectation under an implied distribution | operator | | ε,δ\varepsilon,\delta | tolerance and the radius it forces | positive scalar | | α,η,γ\alpha,\eta,\gamma | step size, learning rate, discount | scalar | | X\mathcal{X} | domain / feasible set | set | | TT | number of steps, samples or trials | integer |

Every symbol above is used with the same meaning throughout this page. The concept-specific symbols appear in section 7.

9. Step-by-step derivation

Steps

  1. Draft k tokens sequentially with the small model q, recording q_i for each position.
  2. Run the large model p once on the prefix plus all k drafted tokens; obtain p_i for every position in parallel.
  3. Accept token i with probability min(1,p_i/q_i); on first rejection sample a replacement from the positive part of p_i-q_i and stop.
  4. Append one bonus token sampled from p at the verified prefix, so accepted length is at least one.
  5. Show by the rejection-sampling identity that the marginal distribution of every emitted token equals p.

At each step, pause and check which assumption is doing the work. A step that seems obvious is usually hiding one: for Formal verification the hidden assumption is typically about regularity, independence or finite precision.

10. Proofs and proof intuition

Proof / proof intuition. For one step, the probability of emitting token x equals q(x)·min(1,p(x)/q(x)) plus the rejection branch mass, which sums to p(x). By induction over positions, the joint distribution of the emitted sequence equals the target autoregressive distribution — the method is lossless.

The standard proof is constructive: it exhibits the quantity that must shrink and shows it does. If you remove an assumption, locate the exact line of the proof that fails — that line is the boundary of the result.

11. Geometric interpretation

Think of a line of k proposed arrows. Each arrow is accepted if it lies under the target density; rejected mass p−q is the leftover region from which a corrected arrow is sampled.

Draw the objects before trusting the algebra. In two dimensions the statement usually reduces to angles, distances, projections or contour shapes; the same geometry survives in high dimensions even when you cannot plot it.

12. Visual explanation

Use the interactive visualizers in Practical Labs to see Formal verification change as its controlling parameters move. For this topic, plot the governing expression from section 7 against one variable at a time. Label axes with units, overlay the assumption boundary, and annotate the point where the conclusion stops holding. A visual that does not let you predict the outcome before changing a parameter is decorative, not explanatory.

13. Numerical worked example

Worked numerical example. Let p=(0.7,0.2,0.1), q=(0.5,0.3,0.2) for a token position. For drafted token 1: α=min(1,0.7/0.5)=1, always accepted. For token 2 drafted from q: α=0.2/0.3=0.667. Over 100 trials about 67 are accepted; rejected cases sample from norm((0.7−0.5)+,(0−0)+,(0)_+)=(1,0,0), i.e. token 1.

Redo this calculation by hand, then reproduce it in code. If your computed numbers disagree with the text, either the arithmetic or the implementation is wrong — find out which.

14. Real-world analogy

A junior assistant drafts an email and the senior reviewer checks all paragraphs at once, accepting the good ones and rewriting only the first bad paragraph.

Analogies are scaffolding: they make the first step intuitive, but they break where the formal assumptions are stronger than the analogy. Always return to the equation after using one.

15. Algorithm pseudocode

algorithm SpeculativeDecode(p, q, prefix, k):
    y, qprobs <- q.sample_k(prefix, k)
    pprobs <- p.forward_all(prefix + y)
    for i = 1..k:
        u <- Uniform(0,1)
        if u < min(1, pprobs[i][y[i]] / qprobs[i][y[i]]):
            emit y[i]
        else:
            emit sample(norm(pprobs[i] - qprobs[i])_+); stop
    emit sample(p at verified prefix)

The pseudocode intentionally omits engineering details. Add input validation, numerical guards and logging in the real implementation.

16. Implementation from scratch

import numpy as np

def speculative_step(p, q, drafted, rng):
    """One verification step. p,q: arrays (k, V) of probabilities; drafted: (k,) token ids."""
    p = np.asarray(p, float); q = np.asarray(q, float); drafted = np.asarray(drafted, int)
    assert p.shape == q.shape and len(drafted) == p.shape[0]
    accepted = []
    for i in range(len(drafted)):
        tok = drafted[i]
        pi = p[i, tok]; qi = q[i, tok]
        alpha = min(1.0, pi / qi) if qi > 0 else 0.0
        if rng.random() < alpha:
            accepted.append(tok)
        else:
            residual = np.maximum(p[i] - q[i], 0.0)
            if residual.sum() > 0:
                accepted.append(int(rng.choice(len(residual), p=residual / residual.sum())))
            else:
                accepted.append(int(np.argmax(p[i])))
            return accepted, i + 1
    accepted.append(int(rng.choice(len(p[-1]), p=p[-1] / p[-1].sum())))
    return accepted, len(drafted)

rng = np.random.default_rng(0)
p = np.array([[.7,.2,.1],[.1,.8,.1]])
q = np.array([[.5,.3,.2],[.1,.4,.5]])
out, n = speculative_step(p, q, [0,1], rng)
assert n >= 1 and len(out) == n + 1
print(out, n)

This implementation is deliberately small and dependency-light. Run it, then extend it to the concrete dataset named in the experimental section.

17. Professional library implementation

# Production stacks: vLLM and SGLang expose speculative decoding via
# --speculative-model <draft> and related flags; Hugging Face Transformers has
# `assistant_model` in generate(). The rejection rule above is what they implement.
from transformers import AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained("gpt2")
assistant = AutoModelForCausalLM.from_pretrained("distilgpt2")
# out = model.generate(**batch, assistant_model=assistant, max_new_tokens=64)

The library version uses a battle-tested kernel. Compare it to your from-scratch version on a tiny input before trusting either on real data.

18. Code walkthrough

Scratch code. The function first validates its inputs, then performs the core computation and asserts a known answer. The assertion is the point: without a hand-computed reference, a wrong implementation looks identical to a right one.

Library code. The library call hides numerical safeguards (stable softmax, fused kernels, dtype handling). Know which safeguards it provides so you can reproduce them when writing your own Formal verification kernel.

19. Tensor and memory analysis

For a batch of shape (b,d)(b,d) in fp32, the input occupies 4bd4bd bytes and each same-sized buffer another 4bd4bd. A quantity of shape (b,n,n)(b,n,n) costs 4bn24bn^2 bytes, which becomes the dominant term once nn grows. Stores k draft distributions of shape (k,V) and one target distribution per position; KV cache grows with accepted tokens. On a GPU, also budget for allocator fragmentation, CUDA context and communication buffers; a theoretical fit is not the same as a successful allocation.

20. Time complexity

Draft cost k·c_q plus one target pass c_p; with acceptance length N, speedup ≈ N·c_p/(k·c_q+c_p). Large k hurts if acceptance falls. Express the bound in terms of the problem dimensions you actually measured — sample count n, feature dimension d, sequence length L or vocabulary size V — and state whether it is per update or over the full training run. Report both asymptotic growth and measured wall-clock time, because constants and memory movement decide real performance.

21. Space complexity

Stores k draft distributions of shape (k,V) and one target distribution per position; KV cache grows with accepted tokens. Separate persistent state (parameters, buffers, caches) from transient working memory (activations, temporaries, communication buffers). The peak allocation, not the average, determines whether a job fits on the device. When you change batch size or precision, recompute this estimate rather than extrapolating from a small run.

22. Experimental demonstration

Sweep draft length k∈{2,4,8} and draft size; measure accepted-token count and tokens/s on one prompt at fixed temperature.

Pre-register the hypothesis, fix the seed before running, and keep a record of every failed attempt. Report at least three seeds so a reader can tell signal from noise.

23. Benchmark results

Report speedup relative to target-only decoding at matched output distribution; include draft cost and rejection overhead. Do not report speedup without verifying distributional equivalence.

There is no legitimate universal benchmark number for this concept. Any claim of state of the art must name the dataset, hardware, precision, implementation and metric. Qualitative claims in this page are theory; numbers you obtain by running the experiment are evidence.

24. Limitations

  • Little gain when draft and target disagree
  • Extra memory for the draft model
  • Sampling path depends on a correct RNG and probability normalization

Limitations are part of the result, not an appendix. A method whose assumptions you cannot check is a method whose conclusions you cannot trust when using Formal verification.

25. Failure scenarios

  • q_i=0 where p_i>0 → division by zero
  • Different tokenizers → accepted tokens decode differently
  • Using float16 probabilities can make p−q negative after rounding

For each scenario, write down which assumption is violated, the earliest observable symptom and an automatic detector. A failure you cannot detect is a failure you will eventually ship.

26. Common misconceptions

  • Speculative decoding changes the output distribution (it does not when rejection sampling is correct)
  • More draft tokens always faster (acceptance drops)

Misconceptions survive because the wrong story is often simpler than the correct one. Replace each with the precise statement from section 7.

27. Alternative approaches

  • Lookahead decoding
  • Medusa multi-head draft
  • Prompt lookup decoding
  • Quantized target model

Choose among alternatives by stating which assumption you are willing to drop and what you get in exchange. Compare them with the same budget and the same metric.

29. Research applications

  • Low-latency chat serving
  • Batch inference cost reduction
  • On-device assistants

For each application, write one sentence about what Formal verification contributes and one about what it cannot contribute. Research uses a tool well when it knows its boundary.

30. Important research papers

  • Constitutional AI: Harmlessness from AI Feedback — 2022, arXiv (library id: constitutional2022)
  • Zoom In: An Introduction to Circuits — 2020, Distill (library id: circuits2020)
  • In-context Learning and Induction Heads — 2022, arXiv (library id: inductionheads2022)
  • Towards Monosemanticity: Decomposing Language Models with Dictionary Learning — 2023, Anthropic research report (library id: sparseautoencoder2023)

31. Further reading

vLLM documentation on speculative decoding; Leviathan et al. (2023) Fast Inference from Transformers via Speculative Decoding; Chen et al. (2023) Accelerating Large Language Model Decoding with Speculative Sampling.

Prefer primary sources and official documentation over blog summaries. When a source states a result without proof, mark it as a claim until you can derive it.

32. Practical exercises

  1. Implement single-step rejection sampling and verify the emitted distribution empirically over 10,000 trials.
  2. Measure acceptance rate as a function of draft temperature.
  3. Show that greedy speculative decoding is a special case.
  4. Complete the 11-step practical chain for Formal verification in My Tasks, starting with the from-scratch implementation.
  5. Record a plot and a numerical table, not just a sentence saying it worked.

33. Debugging challenges

  • Output distribution drifts: check the residual resampling branch.
  • Speedup negative: draft too expensive relative to target.
  • NaNs: guard q=0.

For each bug, add a regression test that fails before the fix and passes after it.

34. Advanced exercises

  1. Derive the expected speedup under an i.i.d. acceptance model.
  2. Combine speculation with quantization and continuous batching.
  3. Write a one-page critique of a paper that uses Formal verification: identify which assumptions it relies on and whether it checks them.

35. Interview questions

  • Prove the output distribution is unchanged.
  • When would you choose greedy versus stochastic verification?

Also be ready to: state the assumptions out loud before deriving anything; give a concrete counterexample where Formal verification fails; explain the difference between a theorem and an empirical observation about it; and describe how you would verify your implementation in a code review.

36. Research questions

  • Can the draft be learned jointly with the target without changing p?
  • What is the optimal k under a bandwidth constraint?

A research question is useful only if an experiment could answer it. For each one above, state what observation would falsify your preferred answer.

37. Mastery assessment

No mastery rubric is shown for this page. It is a generated template, and its rubric was boilerplate that did not match the topic. Use the core path or a hand-authored lesson for assessed material.

38. Implementation submission

No mastery rubric is shown for this page. It is a generated template, and its rubric was boilerplate that did not match the topic. Use the core path or a hand-authored lesson for assessed material.

39. Completion criteria

All of: derivation reproduced on paper; code executed with passing tests; numerical example matched; one failure mode reproduced and detected; assessment passed; primary source cited; results written up with hardware, seed and metric. Only then may the task be marked mastered.

Research papers linked to this concept