LLM & AI agents

How Do LLMs Work? Tokenization, Attention and Transformer Architecture

The article follows text from token IDs to contextual representations, explaining the main components of a Transformer. Attention, positional information and causal masking lead into the inference costs of prefill, decoding and KV caching. A bilingual manual-assistant example connects these mechanisms to token budgets, long-context testing and verification against source material.

On this page

What is a token, and why is it not a word?

Language models operate on token IDs rather than words as humans define them. A token may represent an entire word, part of a word, punctuation, or a unit including whitespace. Subword and byte-level strategies handle unfamiliar words differently. In morphologically rich languages such as Turkish, a single surface word can become several tokens. A “thousand-word document” therefore says little about inference cost. Count using the tokenizer associated with the actual model. The same paragraph can produce different token counts across models; context budgets should follow the deployed model's encoding rather than a universal word-to-token rule.

How do embeddings represent text?

Tokenizer IDs index learned continuous embedding vectors. It is misleading to interpret each vector as a complete dictionary definition; the representation becomes context-dependent as it moves through the network. The same word can play different roles in different sentences. Token embeddings inside a generative model are also distinct from sentence embeddings optimized for document retrieval. The latter are usually trained to place semantically related passages near each other in a comparison space. Confusing these roles can lead to unsuitable retrieval designs and unreliable similarity scores.

From text to the next tokenText documentsTokenizerEmbedding + positionAttention layersToken generation
Figure 1. Text enters Transformer layers through token IDs and positional information; the output is a distribution over subsequent tokens.

What does self-attention compute?

Self-attention creates query (Q), key (K), and value (V) representations and combines them through a computation often written as softmax(QKᵀ/√dₖ)V. The resulting weights determine how positions contribute to a new representation. Multi-head attention allows several relation patterns to be modeled in parallel subspaces. In decoder-only generation, a causal mask prevents each position from attending to future tokens. A high attention weight is not automatically a causal explanation of a model's behavior; interpretation requires controlled interventions and evaluation beyond a heatmap.

Why do position information and context windows matter?

Attention needs positional information to distinguish sequences. Positional encoding and rotary position embeddings provide ways to represent position while the context window limits the number of tokens exposed during a request. A longer window does not guarantee equal use of every detail. Real applications may struggle with evidence buried in the middle of a document, conflicting sections, or increased costs from irrelevant context. Retrieval of a few relevant passages can outperform indiscriminate context expansion in some tasks. The choice should be based on long-document evaluations with representative questions.

How do prefill, decode and the KV cache affect latency?

A request starts with prefill, where input tokens are processed. Decode then generates new tokens step by step. The key/value cache avoids repeatedly recomputing earlier keys and values, trading memory for speed. Time to first token (TTFT) and steady-state generation speed capture different bottlenecks. A long prompt with a short answer can still spend substantial time in prefill; a short prompt with a long answer can be decode-bound. Report input/output token counts, p50/p95 latency, concurrency and memory usage rather than presenting a single tokens-per-second number.

Distinctions that matter in designToken count ≠ word countContext length ≠ evidence useFluency ≠ factual accuracySpeed ≠ total system latency
Figure 2. Token counts, evidence use, answer correctness and end-to-end latency are separate evaluation dimensions.

Pretraining, instruction alignment and inference

Pretraining learns broad statistical structure through objectives such as next-token prediction. Instruction tuning and preference optimization shape responses toward useful interaction patterns. During ordinary inference, model weights remain fixed; the prompt and supplied context influence behavior for that request. A model appearing to “learn” within a conversation does not mean its weights are being updated. Product engineers should distinguish problems requiring better training data from problems better handled by retrieval, prompt construction or deterministic business rules. Access to frequently changing facts generally demands a different solution than another training run.

Why do temperature and sampling settings change outputs?

At each generation step, the model produces scores for candidate tokens. Temperature, top-p and related sampling methods determine how a next token is selected. Lower temperature usually produces more stable outputs, but does not convert incorrect knowledge into correct facts. Variation across repeated runs remains possible. For structured extraction tasks, schema constraints, type validation and automated checks are more important than temperature tuning alone. Record model version, sampling configuration and prompt template during evaluation. When any of these changes, the relevant quality tests should run again.

How should a model be selected for a real application?

Select a model from task requirements rather than a leaderboard position alone. Define target languages, privacy constraints, citation needs, context size, expected traffic and the cost of mistakes. Evaluate a small group of candidates on the same held-out task set. Turkish technical text requires deliberate coverage of suffixes, abbreviations, punctuation and numerical expressions. A larger model is not automatically better or more economical: latency, total cost and structured-output validity matter together. A simple baseline provides a reference for the additional value of more complex or expensive options.

What a context budget can miss

A request contains more context than its user message. System instructions, tool definitions, conversation history and retrieved documents share the same budget, so a short question can produce a long input. A model migration also changes more than an API key: the tokenizer, tool-calling format, output schema and latency can differ. A numerical question or long Turkish document that worked with one model may expose a different weakness in another. Fluency alone does not reveal those differences.

Looking up torque in a product manual

Illustrative scenario; not a measured project result.

Consider a bilingual technical-manual assistant. A question about gasket torque tolerances may appear in several forms in English and Turkish. Token counts can differ by language, affecting both cost and context capacity. Even a fluent answer is hard to trust when the model has not retrieved the relevant manual section. Tokenization, context management and evidence retrieval therefore belong to the same system design. This is an illustrative scenario, not a deployed product benchmark.

What token counts change in an application

In the manual example, asking the same question in Turkish and English can change token cost without changing the technical evidence needed for the answer. This separates language capability from information access. Context limits, time to first token and answer length describe different aspects of the same request. Model selection becomes meaningful when these mechanisms are considered together in the application.

Frequently asked questions

Is a token the same as a word?

No. Tokenizers can split one word into multiple pieces. Measure with the tokenizer used by your model.

Does a larger context window always improve accuracy?

No. More context can introduce irrelevant or conflicting evidence; test long-document tasks directly.

Is attention an explainability method?

Not on its own. Attention weights can be useful visualizations but should not be taken as causal explanations.

References and further reading

  1. Attention Is All You Need
  2. Hugging Face — Transformers documentation
  3. Hugging Face — Tokenizers
  4. HELM: Holistic Evaluation of Language Models