Skip to content
AI Foundations

How Large Language Models Actually Work

What happens between asking an AI assistant a question and receiving an answer?

Share this article

LinkedInXWhatsApp
On this page

Key Takeaways

  • LLMs process tokens, not words in the human sense. Text is broken into tokens and converted into numerical representations that the model can process.
  • Transformers use attention to process context. Attention mechanisms allow token positions to incorporate information from other permitted positions, helping the model represent relationships across a sequence.
  • Training and inference are different activities. Training establishes learned parameters; inference uses those parameters to generate responses to new inputs.
  • Fluent output is not proof of understanding or accuracy. Organisations still need evaluation, reliable data, appropriate controls and human accountability when deploying LLM applications.

Imagine a procurement manager preparing for a difficult supplier negotiation. The supplier has requested a price increase, deliveries have been delayed, and the agreement contains clauses that could affect the company's options. The manager opens an AI assistant, attaches the agreement and asks: "What are the main risks in this agreement, and which clauses should I examine before negotiating?"

A few seconds later, the assistant produces a structured response. It identifies provisions about price adjustments, delivery obligations, liability and termination, then suggests questions to raise with the supplier. It appears to have read a contract, understood a commercial problem and offered advice.

What happens inside the language model is rather different from the work of a procurement specialist. The model processes numerical representations of text through a neural network whose parameters were learned during training. Its calculations produce a sequence of tokens that can form a coherent, useful answer. Yet fluency alone cannot establish whether its reading of the contract is correct.

To understand both the achievement and the limitation, we can follow the manager's question through a typical modern, decoder-only Transformer language model. The surrounding application matters too: the model can analyse the agreement only if relevant content is supplied to it, perhaps directly or through an authorised retrieval system.

1. Before the model sees a word

The application first assembles the context for the request. That might include system instructions, the user's question, the text extracted from the attached agreement and relevant information retrieved from other permitted sources. A document attachment is not automatically the same thing as text available to the model. The application has to process it and decide what information to include.

A tokeniser then divides the text into units called tokens. A token can represent a word, part of a word, punctuation or another character sequence. The boundaries depend on the model's particular tokeniser, so one word does not necessarily equal one token. Each token is assigned an identifier that the model can use to look up a numerical representation.

User question, supplier agreement and system instructions are assembled into context, then tokenised.

From the user's question and documents to model input

Figure 1. From the user's question and documents to model input The application assembles permitted context before tokenisation. The displayed token boundaries are illustrative, not a trace of a particular tokeniser.

Model numbers and weights are illustrative.

Tokenisation has a practical consequence for enterprise applications. Context limits and many commercial usage charges are measured in tokens, not pages. Long contracts, supporting policies and the model's response all compete for available capacity, subject to the service's specific limits. Preparing documents and selecting relevant information are therefore part of the system design, not minor implementation details.

The token IDs are still only labels. A model cannot infer the meaning of supplier from whether its ID happens to be numerically larger than the ID for agreement. For that, it needs learned numerical representations.

2. How language becomes numbers

An embedding layer maps each token ID to a vector, an ordered collection of numbers. The numbers are learned parameters, adjusted during training so that the network can perform useful calculations on sequences of language. A simplified vector might look like [0.21, -0.47, 0.83, 0.16]. Real models use many more dimensions, and these particular numbers are invented for illustration.

An initial embedding is not a complete account of a token's meaning. Consider the word charge. In a contract it might refer to a fee, in a technical document to an electrical property, and in another setting to an accusation. The model needs information from the surrounding text to produce a representation appropriate to the context.

Word order also matters. "The supplier delayed the manufacturer" is different from "The manufacturer delayed the supplier". Transformer models incorporate positional information, although the exact method varies by architecture. As the sequence passes through successive layers, token representations are transformed in relation to their context. These later contextual representations differ from the initial embeddings looked up at the beginning.

Illustrative text tokens map to token IDs and vectors, with position and contextual processing.

Tokens, IDs, embeddings and contextual representations

Figure 2. Tokens, IDs, embeddings and contextual representations Token IDs map to learned vectors. Positional information and processing through model layers contribute to context-dependent representations. All numbers are illustrative.

The important distinction is between giving the model numerical input and allowing the network to construct representations that depend on the other tokens in the sequence. Attention is one of the mechanisms that makes the latter possible.

3. What attention actually does

Consider a sentence from the agreement: "The supplier informed the manufacturer that it would delay the shipment." A reader will probably associate it with the supplier, but the reference is not established simply by looking at the word in isolation.

In a Transformer, self-attention lets a token position combine information from other permitted positions. It does this using three learned projections of the representations, conventionally called queries, keys and values.

A query is compared with keys to calculate how strongly one position should draw information from another. Those comparison scores are scaled and converted into weights. The model then uses the weights to combine the value vectors. Queries, keys and values are mathematical representations, not literal questions, index entries or facts stored in separate boxes.

For one attention head, the operation is commonly expressed as:

Attention(Q,K,V) = softmax(QKᵀ / √dₖ) V

The equation is less intimidating than it first appears. The query-key calculation produces scores, softmax turns those scores into weights, and the weights determine how the values are combined. Multiple attention heads allow the network to learn different patterns of relationships in parallel.

Self-attention compares a token query with keys, combines values using weights, and masks future tokens.

How masked self-attention combines information

Figure 3. How masked self-attention combines information A conceptual illustration of attention weights and a weighted combination of values. Weights are invented examples. In a causal model, each position can attend only to permitted earlier positions and itself.

Model numbers are illustrative.

A decoder-only autoregressive model uses causal masking. While processing a sequence, a position cannot access tokens that come after it. During generation, the model must not use words it has not yet produced. This restriction is built into the attention calculation.

Attention provides a way for the representation at one position to use information from other positions. It is not the same as human attention or comprehension, and high attention weight does not automatically explain a model's answer. A model can attend to the contract and still interpret a clause incorrectly.

The mechanism also helps explain why a larger context window is not a promise of better analysis. More material may be available to the model, but the system still needs to select relevant documents and evaluate whether the answer reflects them accurately.

4. Inside a Transformer block

Attention is only part of the architecture. A typical decoder-only Transformer has a stack of processing blocks, each transforming the representations it receives from the preceding block.

Within a simplified block, masked multi-head self-attention mixes information across token positions. A feed-forward network then applies learned transformations at each position. The feed-forward component does not perform the same cross-position exchange as attention; it transforms the information already represented at that position. Residual connections help information flow around the components, and normalisation supports stable numerical computation.

A simplified decoder Transformer block with masked attention, feed-forward processing, residual paths and normalisation.

A simplified Transformer processing block

Figure 4. A simplified Transformer processing block A representative Transformer block with attention, feed-forward processing, residual pathways and normalisation. The precise order and implementation vary across architectures.

Model numbers and weights are illustrative.

Repeating these operations across many layers allows the network to construct complex representations. That does not mean each layer corresponds neatly to a human concept such as grammar, legal meaning or commercial risk. What the network learns is distributed across many parameters and operations. Some patterns can be studied, but we should resist presenting the internal layers as a sequence of human reasoning steps.

The original 2017 Transformer was an encoder-decoder design. The decoder-only architecture described here is a particularly useful reference for modern autoregressive text generation, not a description of every language model. Encoder-based models, encoder-decoder models and other architectures also exist.

After processing the supplied context, the model has representations it can use to produce an output. The next stage is generation.

5. How a response appears one token at a time

For many deployed autoregressive LLMs, generation begins with an initial processing stage often called prefill. The model processes the supplied prompt and builds the internal state needed for generation. It then predicts the next token and continues producing tokens sequentially, typically reusing cached information from earlier positions rather than recomputing everything from scratch.

Suppose the response begins, "The agreement contains several ...". The model produces scores, called logits, for possible next tokens. These can be converted into probabilities. Imagine an illustrative distribution in which risks has a probability of 48%, clauses 27%, provisions 15%, obligations 7%, and all remaining tokens together 3%.

These figures are invented. They show the form of the decision, not the output of an actual model.

A decoding strategy chooses a token. Some strategies favour the highest-scoring option; sampling strategies can introduce controlled variation. The selected token becomes part of the growing response, and the process repeats until a stopping condition is reached.

Prompt prefill followed by illustrative next-token probabilities, token selection and repeated generation.

Prefill, next-token selection and repeated generation

Figure 5. Prefill, next-token selection and repeated generation The model processes the prompt, selects a next token from model scores and repeats. The displayed probabilities are illustrative.

Model numbers and weights are illustrative.

This is more sophisticated than choosing from a collection of memorised phrases. The scores reflect an enormous learned function applied to the supplied context. Training can produce capabilities that extend well beyond obvious word association, including translation, coding and structured analysis. Yet next-token generation is not an independent truth-checking procedure.

The model can write a persuasive paragraph that omits a contractual qualification or incorrectly links two provisions. Post-training can improve instruction following and factual behaviour, but cannot guarantee that each answer is faithful to the agreement. In a procurement setting, source traceability and professional review remain important.

6. How the model learned, and what happens when you use it

Where did the embeddings, attention projections and other parameters come from? They were learned during training.

In a common pretraining process, an autoregressive model receives sequences of text and learns to predict subsequent tokens. Its predictions are compared with the training targets, and optimisation algorithms adjust the parameters to reduce error. This is repeated across very large datasets. Through this process, the network learns statistical regularities involving language, concepts, facts, code and many other relationships.

After pretraining, further stages can adapt the model for instruction following, dialogue, safety-related behaviour or particular tasks. Methods vary and may include supervised fine-tuning and preference-based optimisation.

Ordinary use of a deployed model is called inference. The model applies its existing parameters to the prompt and generates output. The current conversation can influence that output through the context provided, but this does not mean the underlying model is retrained every time someone asks a question. Some products also have separate memory, retrieval or adaptation mechanisms, which should not be confused with routine parameter updates during inference.

Training compares predictions with targets and updates parameters; inference uses fixed parameters to generate output.

The difference between training and inference

Figure 6. The difference between training and inference Training updates model parameters using feedback from prediction errors. Ordinary inference uses trained parameters to produce responses. Retrieval, tools and application memory are separate optional systems.

Model numbers and weights are illustrative.

This distinction is especially important when an organisation expects a model to know its latest policies or supplier agreements. Pretraining does not automatically provide current, private enterprise knowledge. The application must supply the necessary information through an appropriate, authorised mechanism. A foundation model is therefore a component of an enterprise system, not the complete system itself.

What this changes for an organisation

The procurement manager's apparently simple interaction now contains several distinct responsibilities. The application must obtain and prepare the agreement, enforce permissions and decide what context to supply. The model converts the text into numerical representations, processes them through its learned network and generates an answer token by token. The business must then decide what the answer can safely be used for.

The architecture helps explain practical trade-offs. Token limits affect document preparation and costs. Prefill and sequential generation affect latency in different ways. Model design and serving infrastructure affect speed and resource requirements. The ability to use contextual information supports useful analysis, but neither attention nor fluent output guarantees that a clause has been interpreted correctly.

It is also why model quality and application quality should be evaluated separately. A capable model may be let down by incomplete document extraction, irrelevant retrieval or poor access controls. Conversely, careful preparation of evidence, clear instructions, source references and appropriate human review can make a model much more useful in a specific workflow.

Model quality and application quality should be evaluated separately.

The manager originally wanted to understand contractual risk. An LLM can help identify provisions worth examining and organise questions for a negotiation. Whether those provisions create material legal or commercial risk still depends on the agreement, the circumstances and appropriate professional judgment.

Understanding the model's mechanism does not diminish what it can do. It makes the achievement more intelligible, and it gives organisations a better basis for deciding what the technology should be trusted to do.

Sources cited

  1. Vaswani, A. et al. (2017). Attention Is All You Need. https://arxiv.org/abs/1706.03762

  2. Devlin, J. et al. (2018). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. https://arxiv.org/abs/1810.04805

  3. Brown, T. B. et al. (2020). Language Models are Few-Shot Learners. https://arxiv.org/abs/2005.14165

  4. Kaplan, J. et al. (2020). Scaling Laws for Neural Language Models. https://arxiv.org/abs/2001.08361

  5. Hoffmann, J. et al. (2022). Training Compute-Optimal Large Language Models. https://arxiv.org/abs/2203.15556

Editorial note: The procurement scenario is fictional. Token boundaries, numerical vectors, attention weights and next-token probabilities in the illustrations are teaching examples, not measured outputs from a particular model.