Large Language Models for Developers: Tokens, Context and Sampling
Large Language Models for Developers: Tokens, Context and Sampling
Search
Ask the AI

Large Language Models for Developers: Tokens, Context and Sampling

Applications such as ChatGPT and Claude use Large Language Models (LLMs) to process and generate language. Foundation Models is a broader category that also includes models for vision and other modalities.

I use LLMs in personal projects, including automated code auditing tools and script generators. Drawing on that work and on running open-source models locally, this article explains how large language models operate.

1. Next-token prediction in autoregressive LLMs

This article focuses on autoregressive language models: given a prefix, the model predicts the next token, then extends the context with the selected token. Next-token prediction is a common pretraining and generation mechanism; chat models can also undergo instruction tuning and preference training.

Example: After “The quick brown fox jumps over the lazy,” the model scores possible next tokens and the decoder selects one. A familiar continuation may rank highly, but its tokenization, rank and probability depend on the model and context. Inference normally uses learned parameters, rather than searching training documents one by one.

An autoregressive model generates dialogue, code and translations by repeatedly computing conditional distributions for subsequent tokens. Applications such as ChatGPT can also use retrieval, computation and other tools; those system operations are distinct from the model’s text generation.

2. The Architectural Foundation: The Transformer Workflow

The Transformer, introduced in the 2017 paper “Attention Is All You Need,” is a common language-model architecture. The diagram shows a conceptual autoregressive loop and omits residual connections and normalization. Cached inference normally reuses prefix keys and values rather than recomputing every historical token at each step.


graph TD
    A["User Input Text (Prompt)"] --> B["Tokenization"]
    B --> C["Embedding (Map to high-dimensional vectors)"]
    C --> D["Positional Encoding (Inject position data)"]
    D --> E["Transformer Architecture (N layers)"]
    
    subgraph Transformer Architecture
        E1["Self-Attention (Calculate relationships between words)"]
        E2["Feed Forward Network"]
        E1 --> E2
    end
    
    E --> Transformer Architecture
    Transformer Architecture --> F["Softmax (Calculate probability distribution of next token)"]
    F --> G["Sampling (Output the next token)"]
    G --> H{Is it an EOS token?}
    H -- No, add new token to input --> B
    H -- Yes --> I["Output complete response"]

Self-Attention computes query–key weights and combines values from visible positions so that a position can use context. Attention weights do not guarantee correct coreference: understanding whether profit is higher than last year requires the learned model and context, not a direct proof from one weight.

3. Hands-on: Running an 8B Model Locally with Python

The local example below calls llama.cpp through llama-cpp-python. It requires a compatible installation, the specified GGUF file, sufficient memory and the Llama-3 chat template expected by that file.


from llama_cpp import Llama

# 1. Load the quantized local model file (e.g., Llama-3-8B-Instruct-Q4_K_M.gguf)
# n_gpu_layers=-1 means offloading as many layers to the GPU as possible
llm = Llama(
    model_path="./models/Llama-3-8B-Instruct-Q4_K_M.gguf",
    n_gpu_layers=-1, 
    n_ctx=4096,      # Set the context window to 4K
    verbose=False
)

# 2. Construct the prompt matching the model's specific chat template
prompt = "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\nPlease write a quicksort algorithm in Python<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n"

# 3. Generate the response (Next-Token Prediction)
output = llm(
    prompt,
    max_tokens=256,
    temperature=0.3, # A lower temperature makes code output more stable
    stop=["<|eot_id|>"]
)

print(output["choices"][0]["text"])

Here n_gpu_layers=-1 requests all-layer offload. It requires a supported GPU backend and can fail when memory is insufficient; it does not promise to choose a fitting layer count automatically. n_ctx=4096 configures this context budget, shared by the input, template and generated output under the runtime’s rules. temperature=0.3 changes sampling, not code correctness; max_tokens=256 can truncate unfinished code. The original program is preserved, and this review did not load the model or benchmark a GPU.

4. Memory and backend conditions for local runs

Before a local run, estimate weights, KV cache, compute buffers and system headroom, then check memory under the actual configuration.

Break down VRAM (Video RAM) requirements and keep GB and GiB units explicit:

  • Base Parameter VRAM Footprint: Ideal 4-bit weights use 0.5 GB per 1 Billion (1B) parameters, before scales, mixed-precision tensors and runtime overhead. The old 0.7 GB of VRAM rule and Llama-3-8B estimate of 8 * 0.7 = 5.6 GB of VRAM are rough heuristics; check the actual quantized file and loading layout.
  • KV Cache Footprint: A typical autoregressive Transformer caches historical keys and values, not full attention matrices. Payload depends on layers, tokens, batch, KV heads, head dimension and cache dtype; 8B parameters alone do not imply an extra 1~2 GB at 8K context. For an illustrative 32-layer, batch-1 configuration with 8192 tokens, 8 KV heads, head dimension 128 and 2-byte elements, raw K/V payload is 1 GiB, before allocation and compute overhead.
  • Bottom Line Recommendation: Whether 8GB of VRAM (like an RTX 4060) can run a quantized 7B~8B model depends on quantization, context, offload and headroom; capacity alone does not establish speed. 16GB of VRAM (like an RTX 4080 16G or a Mac with unified memory) is not a universal threshold for 14B~32B models: ideal 32B 4-bit weights already require 16 GB of raw payload. Mac unified memory is also shared with the system and other processes rather than reserved entirely for the model. For a term-by-term breakdown at a given context length and concurrency, see the site’s VRAM calculator (it currently covers the Gemma 4 variants).

How tokens relate to characters and words

The model receives token IDs. Depending on the tokenizer, a token may represent a character, subword, word or byte fragment; tokens do not have a one-to-one relationship with characters or words.

The preserved splits below are schematic, not measurements from a specified tokenizer. Verify each segmentation and token count with the target model’s tokenizer:

"hello world"      ->  ["hello", " world"]           2 tokens
"你好世界"           ->  ["你好", "世界"]               about 2-4
"antidisestablish" ->  ["anti", "dis", "establish"]   3
"3.14159"          ->  ["3", ".", "141", "59"]        4

Token counts depend on vocabulary, tokenization rules, language and the particular text. A Chinese character may use one or several tokens, while frequent spans may merge. The old 1-to-2 estimate is not universal. Compare actual passages to estimate language-specific costs; information density alone does not determine the ratio.

Knowing this explains several otherwise puzzling behaviours:

  • If a model is explicitly configured for 8192 tokens, that budget counts tokens, not 8192 characters. Check whether “8K” means 8192 and how the runtime accounts for system prompts, history and output. Four to five thousand Chinese characters is only a rough estimate to verify.
  • Character counting requires recovering characters from token representations. “strawberry” may occupy two or three tokens, but reversible byte-level BPE does not discard its letters. Tokenization can affect task difficulty; it does not make letter counting impossible or guarantee an error.
  • Exact arithmetic is unreliable. Tokenization and training affect arithmetic, but whether “141” and “59” are separate tokens depends on the tokenizer. Splitting does not imply that the model cannot represent the value 3.14159. Use a verifiable computation tool when exact results matter.

Practical advice: never estimate context usage from character counts — run the tokeniser and count. And when exact computation matters, hand it to an external tool rather than asking the model to do it mentally.

What temperature and top_p actually adjust

Temperature and top_p control the decoding distribution and candidate set. Fix the model, prompt, sampler order and evaluation task before comparing settings:

The model usually computes logits for the vocabulary, which are converted to a probability distribution over the entire vocabulary. Sampling parameters modify scores, probabilities or candidate sets in a backend-specific order.

Temperature is commonly defined by softmax(logits/T) for T >0. The simplified notes below are preserved; interfaces commonly handle T=0 as a separate greedy-selection rule rather than dividing by zero:

T = 1.0   original distribution unchanged
T < 1.0   score gaps widen, high-probability items dominate  -> more deterministic
T > 1.0   score gaps compress, distribution flattens          -> more random, more drift
T -> 0    degenerates to always taking the top item (greedy)

top_p (nucleus sampling) retains the shortest probability-sorted prefix whose cumulative mass reaches at least p, then renormalizes within it. With top_p = 0.9, retained mass can exceed 90% because the last token cannot be split. Minimum candidate counts and other samplers can also affect the implementation.

Temperature changes relative probabilities; top_p truncates the candidate pool. Candidate count depends on the distribution, not simply on whether temperature is high and top_p is small. With tied maxima, the mathematical limit as T approaches 0 does not choose one token; a greedy implementation needs a tie rule.

Use T = 0 to request an interface’s greedy decoding; T = 0.7, top_p = 0.9 is one conversational comparison setting. Neither guarantees factual, code or format correctness, or bitwise agreement across backends. Hold the other settings fixed and vary one at a time, checking task results and output format.

5. Takeaways for Developers

Token prediction and hardware limits have several consequences for development:

  1. Fighting “Hallucinations”: A generative model can produce wrong or unsupported answers. RAG (Retrieval-Augmented Generation) supplies external evidence, whose sources, retrieval and citations still need checking. It is neither mandatory for every task nor a database access-control mechanism. Production database operations require external authorization and parameter validation.
  2. Prompt Engineering is not magic: Provide the Context needed for the task, explicit input/output conventions and examples where useful. Evaluate their effect on the task; longer or more detailed prompts do not guarantee a monotonic increase in correct-answer probability.

Start with a fixed task: choose a model and runtime, record inputs, versions, sampling settings, resources and verifiable outputs, then decide between an API and local deployment.

Leave a Reply

Scroll down