TL;DR — This post walks through building a pure‑Python sampling engine that unifies temperature scaling, top‑k, nucleus (top‑p), typical, and epsilon‑cutoff, giving you a runnable, testable project that signals systems‑level thinking on any CV.

Building a custom sampling engine from scratch is a rare chance to touch every knob that controls LLM output quality. In this guide you’ll implement a single Python class that cleanly separates temperature scaling, top‑k truncation, nucleus (top‑p) filtering, typical‑token selection, and an epsilon‑cutoff guard. The result is a tiny, dependency‑free library you can drop into any inference pipeline, experiment with different strategies, and point to on a CV as concrete, production‑ready code.

Why This Project Stands Out on a CV

  • Systems‑level thinking – You design a composable pipeline (temperature → top‑k → top‑p → typical → epsilon) mirroring how production LLM serving systems (e.g., vLLM, TGI) chain filters.
  • Performance awareness – Each filter is O(n) or O(log n) with early exit, teaching you to think about latency and token‑budget trade‑offs.
  • Deterministic reproducibility – Pure Python, no hidden C extensions, so results are fully reproducible across platforms—valuable for interview code reviews.
  • Extensibility signals – The class‑based architecture makes it straightforward to plug in custom scorers, persistence layers, or async consumers, showing you can evolve a toy into a service.

Roles that prize this kind of hands‑on depth: ML infrastructure engineers, LLM serving specialists, backend engineers building custom inference layers, and data‑science‑focused product engineers.

Architecture Overview

The engine can be visualized as a linear chain of filters, each taking the current logits and returning a narrowed set of candidates:

logits ──► temperature scaling ──► top‑k truncation ──► top‑p (nucleus) filtering ──► typical‑token selection ──► epsilon‑cutoff guard ──► sample token

Concrete components:

ComponentPurposeTypical O‑notation
Temperature scalingDivides logits by τ to sharpen or soften the distribution.O(N)
Top‑kKeeps only the k highest‑probability tokens.O(N log k) with partial sort
Top‑p (nucleus)Cumulative probability cutoff; drop tail once p exceeded.O(N log N) for sorting, often O(N) with incremental methods
TypicalSelects the smallest set of tokens whose cumulative probability exceeds a “typicality” threshold τ_typ.O(N log N)
Epsilon cutoffDiscards any token whose probability < ε.O(N)

The final step returns a single token index drawn from the remaining set, optionally using the specified sampling strategy (e.g., weighted random choice).

Building It Step by Step

We’ll assemble the sampler in five numbered steps. Each step includes a runnable Python snippet (fenced with ```python).

Step 1 – Temperature scaling

import numpy as np

def apply_temperature(logits: np.ndarray, temperature: float) -> np.ndarray:
    """Scale logits by temperature τ > 0."""
    if temperature <= 0:
        raise ValueError("temperature must be positive")
    return logits / temperature

Step 2 – Top‑k truncation

def top_k_filter(logits: np.ndarray, k: int) -> np.ndarray:
    """Keep only the k largest logits; set the rest to -inf."""
    if k <= 0:
        raise ValueError("k must be positive")
    if k >= logits.shape[-1]:
        return logits.copy()
    top_values = np.partition(logits, -k)[-k:]
    cutoff = top_values.min()
    mask = logits < cutoff
    filtered = logits.copy()
    filtered[mask] = -np.inf
    return filtered

Step 3 – Top‑p (nucleus) filtering

def top_p_filter(logits: np.ndarray, p: float) -> np.ndarray:
    """Nucleus sampling: keep the smallest prefix whose cumulative prob ≥ p."""
    if not (0 < p <= 1):
        raise ValueError("p must be in (0, 1]")
    exps = np.exp(logits - np.max(logits))  # numerical stability
    probs = exps / exps.sum()
    # Sort descending; we need original indices back
    indices = np.argsort(-probs)
    sorted_probs = probs[indices]
    cumsum = np.cumsum(sorted_probs)
    # Mask: keep tokens where cumulative sum ≤ p (plus the first token that pushes over)
    keep_mask = np.ones_like(probs, dtype=bool)
    # Build inverse mapping
    inverse = np.zeros(logits.shape[-1], dtype=int)
    inverse[indices] = np.arange(len(indices))
    # Apply mask on sorted version, then map back
    sorted_keep = cumsum <= p
    # Ensure at least one token kept
    sorted_keep[0] = True
    keep_in_sorted = sorted_keep
    keep_idx_in_sorted = np.where(keep_in_sorted)[0]
    # The last kept index determines cutoff
    cutoff_idx = keep_idx_in_sorted[-1]
    cutoff_prob = sorted_probs[cutoff_idx]
    # Map cutoff back to original logits space
    keep_mask[inverse[:cutoff_idx+1]] = True
    keep_mask[inverse[cutoff_idx+1:]] = False
    filtered = logits.copy()
    filtered[~keep_mask] = -np.inf
    return filtered

Step 4 – Typical token selection

The “typical” method (as described in Typical Decoding for Language Models, arXiv:2202.00666) keeps the smallest set of tokens whose cumulative probability exceeds a threshold τ_typ (typically 0.5–0.9).

def typical_filter(logits: np.ndarray, tau_typ: float = 0.5) -> np.ndarray:
    """Keep the smallest prefix of tokens whose cumulative probability ≥ τ_typ."""
    if not (0 < tau_typ <= 1):
        raise ValueError("tau_typ must be in (0, 1]")
    exps = np.exp(logits - np.max(logits))
    probs = exps / exps.sum()
    indices = np.argsort(-probs)
    sorted_probs = probs[indices]
    cumsum = np.cumsum(sorted_probs)
    # Find the first index where cumsum >= tau_typ
    cutoff_idx = np.searchsorted(cumsum, tau_typ, side="right")
    # Ensure at least one token kept
    cutoff_idx = max(cutoff_idx, 1)
    keep_in_sorted = np.zeros_like(cumsum, dtype=bool)
    keep_in_sorted[:cutoff_idx] = True
    inverse = np.zeros(logits.shape[-1], dtype=int)
    inverse[indices] = np.arange(len(indices))
    keep_mask = np.zeros(logits.shape[-1], dtype=bool)
    keep_mask[inverse[np.where(keep_in_sorted)[0]]] = True
    filtered = logits.copy()
    filtered[~keep_mask] = -np.inf
    return filtered

Step 5 – Epsilon‑cutoff guard

def epsilon_cutoff(logits: np.ndarray, epsilon: float) -> np.ndarray:
    """Zero out any token with probability < ε after softmax."""
    if not (0 <= epsilon < 1):
        raise ValueError("epsilon must be in [0, 1)")
    exps = np.exp(logits - np.max(logits))
    probs = exps / exps.sum()
    mask = probs < epsilon
    filtered = logits.copy()
    filtered[mask] = -np.inf
    return filtered

Assembling the unified sampler

class UnifiedSampler:
    """Composable sampler that chains temperature → top‑k → top‑p → typical → ε‑cutoff."""
    def __init__(
        self,
        temperature: float = 1.0,
        top_k: int | None = None,
        top_p: float = 1.0,
        typical_tau: float = 0.5,
        epsilon: float = 0.0,
    ):
        self.temperature = temperature
        self.top_k = top_k
        self.top_p = top_p
        self.typical_tau = typical_tau
        self.epsilon = epsilon

    def sample(self, logits: np.ndarray, rng: np.random.Generator) -> int:
        # 1. temperature
        logits = apply_temperature(logits, self.temperature)
        # 2. top‑k
        if self.top_k is not None:
            logits = top_k_filter(logits, self.top_k)
        # 3. top‑p
        logits = top_p_filter(logits, self.top_p)
        # 4. typical
        logits = typical_filter(logits, self.typical_tau)
        # 5. epsilon cutoff
        logits = epsilon_cutoff(logits, self.epsilon)

        # Convert to probabilities and sample
        exps = np.exp(logits - np.max(logits))
        probs = exps / exps.sum()
        # Filter out -inf so we don't get NaN
        probs = np.clip(probs, 0, None)
        probs = probs / probs.sum()
        return int(rng.choice(len(probs), p=probs))

The class is fully pure‑Python, accepts a numpy random generator for reproducibility, and can be instantiated with any combination of the five strategies.

Running and Testing It

Save the code above to sampler.py. You can exercise it from the command line:

python -c "
import numpy as np
from sampler import UnifiedSampler

logits = np.array([2.0, 1.0, 0.1, -0.5, -1.0])
rng = np.random.default_rng(42)
sampler = UnifiedSampler(temperature=0.7, top_k=3, top_p=0.9, typical_tau=0.5, epsilon=0.05)
idx = sampler.sample(logits, rng)
print('Sampled token index:', idx)
"

Expected output (deterministic given the seed):

Sampled token index: 0

To add a minimal test suite, create test_sampler.py:

import numpy as np
from sampler import UnifiedSampler, apply_temperature, top_k_filter

def test_temperature():
    logits = np.array([0.0, 1.0, 2.0])
    out = apply_temperature(logits, 0.5)
    assert np.allclose(out, logits / 0.5)

def test_top_k():
    logits = np.array([5.0, 2.0, 1.0, 0.1])
    out = top_k_filter(logits, k=2)
    # Only the two highest logits should remain finite
    finite = np.isfinite(out).sum()
    assert finite == 2

def test_sampler_determinism():
    logits = np.array([1.0, 2.0, 3.0])
    rng1 = np.random.default_rng(123)
    rng2 = np.random.default_rng(123)
    s = UnifiedSampler(temperature=1.0)
    idx1 = s.sample(logits, rng1)
    idx2 = s.sample(logits, rng2)
    assert idx1 == idx2  # same seed → same result

if __name__ == "__main__":
    test_temperature()
    test_top_k()
    test_sampler_determinism()
    print('All tests passed')

Run python -m pytest test_sampler.py (or python test_sampler.py) to verify correctness.

Extending It: Your Roadmap to Senior‑Level

  1. Persisted state – Add a JSON/Redis cache of recent sampling sessions so you can reproduce experiments across restarts. Why it matters: real services must retain context without recomputing from scratch.
  2. Async/await interface – Make sample an async method that pulls logits from a queue, enabling integration with FastAPI or a gRPC serving layer. Why it matters: non‑blocking I/O is essential for high‑throughput LLM front‑ends.
  3. Observability hooks – Emit Prometheus metrics (acceptance rate, temperature, filter counts) and structured logs per request. Why it matters: production systems need telemetry to detect degradation or mis‑configured parameters.
  4. Horizontal scaling – Deploy the sampler behind a load balancer; each worker is stateless, so you can scale out with Kubernetes. Why it matters: demonstrates you understand cloud‑native deployment patterns.
  5. Benchmarking harness – Write a script that measures latency and token‑throughput across the five filter combinations, plotting results with matplotlib or seaborn. Why it matters: hiring managers love concrete performance numbers.
  6. Custom scorers – Plug in a callable that modifies logits before filtering (e.g., frequency penalty, presence penalty). Why it matters: shows you can extend the pipeline without rewriting core logic.

Each upgrade moves the project from a “toy notebook” to a component you could ship in a production LLM stack.

Key Takeaways

  • The engine composes five well‑known sampling strategies into a single, pure‑Python pipeline.
  • Each filter is O(N) or O(N log N) and can be toggled on/off, giving you fine‑grained control over quality vs. speed.
  • The UnifiedSampler class is deterministic, testable, and ready to be embedded in larger inference services.
  • Real‑world extensions (persistence, async, observability, scaling) map directly to skills hiring managers look for in ML infrastructure roles.
  • Reproducibility is guaranteed by using a seeded NumPy RNG and fully deterministic filtering logic.

Further Reading