← All postsWhat actually happens when you ask ChatGPT a question

What actually happens when you ask ChatGPT a question

November 4, 2026·21 min read
#generative ai#ai engineering#chatgpt#how chatgpt works#large language models#llm#transformers#self-attention#tokenization#embeddings#kv cache#llm inference#gpu inference#vllm

You type a question. Press Enter. A few seconds later, an answer appears.

It feels simple.

But what if I told you that your sentence first becomes a sequence of numerical IDs, passes through dozens of neural network operations, gets transformed through attention mechanisms, and eventually becomes a probability distribution over thousands of possible tokens?

And that's only the beginning. Behind that familiar chat interface is an entire computational pipeline involving tokenization, vector representations, matrix multiplication, transformer layers, autoregressive decoding, GPU memory management, and inference infrastructure.

Let's open the hood.


01 . The Illusion

Does ChatGPT actually understand your question?

Imagine this scenario. Swarup, an engineering manager, opens ChatGPT and asks:

Why does our support team keep missing its response-time target?

Within seconds, ChatGPT responds:

Assistant

Start by comparing the time requests arrive with the time agents first respond. Look for staffing gaps, queue assignment problems, and differences in response-time definitions.

It sounds like the system understood his operational problem. But what actually happened?

Did it search through a database of previously written answers? Did it look up a document containing the exact response? Did it reason like a human? Not necessarily.

A language model performs computations over numerical representations of its input and generates output based on learned parameters and the context available to it. At its core, a standard autoregressive language model estimates what token should come next, given the preceding context.

That doesn't mean the entire ChatGPT product is just a next-token prediction loop. Production systems can also include tools, retrieval, safety mechanisms, multimodal processing, and other infrastructure. But understanding this fundamental mechanism gives us a powerful starting point.


Context goes in. Numerical computation happens. Tokens come out.


Let's follow Swarup's question through the system.

02 . The journey begins

What happens after you press Send?

Before discussing neural networks, let's understand the overall journey. A simplified text-generation pipeline has eight stages, and there are important engineering details behind every one of them. The Text-Generation Pipeline

Figure 1. From chat bubble to response. Each stage is covered in the sections that follow.

03 . Tokenization

Your sentence becomes numbers

Let's start with something surprisingly important. Neural networks don't directly process the English sentence Swarup typed. They operate on numerical data.

Before the model can process his question, a tokenizer divides the text into smaller units called tokens. Consider:

"Artificial intelligence is transforming engineering."

A tokenizer might split this into units resembling ["Artificial", " intelligence", " is", " transforming", " engineering", "."]. This is illustrative. Actual token boundaries depend on the model's tokenizer and encoding.

A token can represent an entire word, part of a word, punctuation, or a sequence of characters. A less common word may be divided into multiple tokens, while a common word may occupy just one. This is why one word does not necessarily equal one token.

From Question to Tokens

Figure 2. Words become token chips, chips become IDs. A dot marks a leading space, which is usually part of the token. Long, rare words split into pieces, and code tends to cost more tokens per character than prose.

But why do we need tokenization?

Computers work efficiently with numerical representations. A tokenizer provides a mapping between text fragments and numerical identifiers:

TokenIllustrative token ID
Artificial1842
intelligence5921
is374
transforming8421
engineering10932
.13

These IDs are hypothetical, not actual IDs from a particular model.

The original sentence is now represented as the sequence:

[1842, 5921, 374, 8421, 10932, 13]

Notice something important. These numbers are not semantic representations by themselves. Token IDs are identifiers that allow the model to look up corresponding learned representations.

Engineering insight

Tokenization affects context-window usage, inference cost, latency, and how efficiently a model handles different languages and code. A longer prompt generally means more input tokens to process.

You can experiment with tokenization using OpenAI's token concepts and tokenizer documentation.


04 . Embeddings

Turning token IDs into vectors

We now have numerical token IDs. But an integer such as 1842 doesn't tell a neural network that a token relates to artificial intelligence, programming, or engineering. This is where embeddings enter the picture.

An embedding is a vector: a collection of numerical values representing a token in a learned mathematical space. For illustration:

Artificial   → [0.21, -0.42, 0.87, 0.15, …]
intelligence → [0.34, -0.18, 0.72, 0.29, …]

Real embedding dimensions can be much larger than this example. The embedding layer typically uses a learned matrix. Let V be the vocabulary size, d the embedding dimension, and E the embedding matrix. Then:

E∈RV×dE \in \mathbb{R}^{V \times d}

For a token with ID i, its initial token embedding is simply row i of that matrix:

x=E[i]x = E[i]

The result is a vector that can be processed by subsequent neural network layers.

Does an embedding contain the complete meaning of a word?

No. This is an important distinction. The initial token embedding is a learned representation. As the token passes through transformer layers, its representation is repeatedly updated using contextual information, so it can become sensitive to the surrounding sequence. Consider:

"The bank approved my loan."

"We sat beside the river bank."

The same word appears in two different contexts. The model must process the surrounding information to distinguish their usage. This brings us to one of the most important ideas in modern language models.


Meaning is not determined by an isolated token alone. Context matters.


05 . Transformers

The architecture that changed everything

In 2017, researchers introduced a neural network architecture in a paper titled Attention Is All You Need.

The Transformer changed how sequence-processing models could be designed. Instead of relying on recurrent processing as the central mechanism, it introduced attention-based processing that allowed relationships between sequence elements to be calculated efficiently.

You will find Transformers at the heart of many modern language models. What makes them so powerful? The answer is attention. Before understanding attention, we need to understand one limitation.

Why can't we process every token independently?

"The developer placed the laptop on the table because it was unstable."

What does "it" refer to? Understanding this sentence requires considering relationships between different words. A model processing only isolated tokens would lose important contextual information.

A Transformer uses attention mechanisms to calculate how different positions in a sequence should contribute to one another's representations. Let's look inside.


06 . Self-attention

Query, Key, and Value

Self-attention allows each token position to calculate relationships with other positions in the sequence. The mechanism uses three learned projections:

  • Query (Q): what information is this position looking for?
  • Key (K): what information does another position offer for matching?
  • Value (V): what information should be contributed?

Think of it as a mathematical information-retrieval mechanism operating within a sequence. For an input representation matrix X:

Q=XWQK=XWKV=XWVQ = XW_Q \qquad K = XW_K \qquad V = XW_V

Here, WQ, WK, and WV are learned projection matrices. The model calculates attention using:

Attention(Q,K,V)=softmax(QK⊤dk)V\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}\right) V

Inside One Attention Head_ Four-Step Pipeline

Figure 3. Queries are compared against keys, the scores are scaled and normalized, and the resulting weights decide how much each value contributes.

Step 1, similarity scores. QKᵀ compares each query against the keys from the sequence.

Step 2, scale. Dividing by √dₖ helps control the magnitude of attention scores.

Step 3, softmax. Softmax converts the scores into normalized attention weights.

Step 4, combine values. The attention weights determine how much information each value contributes. The output is a contextualized representation of the sequence.

What is the practical benefit?

A token can incorporate information from other relevant tokens instead of relying only on its own initial embedding. This is one reason Transformers can model long-range relationships in text.

Pronoun Attention Weights Dashboard

Figure 4. Each bar is the share of attention "it" gives to that token, and each head's weights sum to 100%. Different heads can pick up different patterns. The labels here are interpretations for teaching, not fixed roles inside a real model.

Multi-head attention: why one attention mechanism isn't enough

Transformers commonly use multiple attention heads. Each head has its own learned projections and can capture different patterns in the sequence. Conceptually, one head might emphasize syntactic relationships, while another might respond to positional or semantic patterns. These are illustrative interpretations, not fixed roles assigned to individual heads.

The outputs of multiple heads are combined through another learned projection. This is called multi-head attention.

Remember

Attention is not simply a search operation. It is a differentiable mathematical computation over learned representations.


07 . Positional information

How does a model know word order?

"Dog bites man."

"Man bites dog."

Both contain the same words, but their meanings differ. If a model only received an unordered collection of token representations, it would lose important information about sequence order. Transformers therefore need a mechanism for incorporating positional information. Different architectures use different approaches, including:

  • Learned positional embeddings.
  • Sinusoidal positional encodings.
  • Rotary positional embeddings (RoPE).

The exact choice depends on the architecture. The important principle is that token identity alone is insufficient. Position and sequence structure also matter.


08 . Inside a Transformer block

Attention is only half the story

A typical Transformer block also includes a feed-forward network and normalization operations. A model stacks many of these blocks to build increasingly sophisticated representations.

Transformer Block Architecture Infographic

Figure 5. Attention mixes information across token positions. Feed-forward layers transform information within each position. Residual connections carry the input forward around each sublayer.

The feed-forward network typically applies learned linear transformations with a nonlinear activation function σ:

FFN(x)=W2⋅σ(W1x+b1)+b2\text{FFN}(x) = W_2 \cdot \sigma(W_1 x + b_1) + b_2

Together, attention and feed-forward layers form the computational foundation of many Transformer-based language models.


09 . The prediction engine

Logits, softmax, and probabilities

Now comes the exciting part. Swarup's question has passed through the model's Transformer layers, and the model has produced a final representation for the position used to predict the next token.

That representation is projected into a vector of scores over the model's vocabulary. These scores are called logits. If the vocabulary contains 50,000 token IDs, the output projection produces roughly 50,000 scores, one per candidate token.

Candidate tokenLogit (hypothetical)
The5.2
Your4.1
Start3.8
Because1.2
Banana−2.4

The model transforms logits into a probability distribution using softmax, where zᵢ is the logit for candidate i, the numerator exponentiates it, and the denominator normalizes so the values sum to one:

P(xi)=ezi∑jezjP(x_i) = \frac{e^{z_i}}{\sum_j e^{z_j}}

Does a higher probability mean the answer is true?

Absolutely not. This is a critical distinction for AI engineers.

A probability distribution over possible next tokens represents the model's relative preferences under its learned parameters and current context. It is not a fact-checking mechanism. A highly probable continuation can still be factually incorrect, which is one reason language models can produce convincing but inaccurate statements.


10 . Decoding

How does the model choose the next token?

The model now has a probability distribution. Selecting a token from it is the job of decoding. Common approaches include:

Greedy decoding selects the token with the highest probability. It is straightforward but can produce repetitive or less varied output.

xnext=arg⁡max⁡i P(xi)x_{\text{next}} = \arg\max_i \, P(x_i)

Temperature modifies the distribution before sampling. Lower temperature generally sharpens the distribution; higher temperature generally flattens it. Temperature does not add knowledge or guarantee creativity.

Pi=softmax(ziT)P_i = \text{softmax}\left(\frac{z_i}{T}\right)

Top-k sampling restricts candidate selection to the k highest-scoring tokens. Top-p sampling selects from a dynamic candidate set whose cumulative probability reaches a specified threshold.

Neon Decoding Playground Dashboard

Figure 6. Drag the temperature down and "The" takes almost all the probability, which is how greedy decoding behaves. Drag it up and the tail grows. Top-k and top-p remove candidates (struck through) before sampling, then the rest are renormalized.

Different models and inference systems can use different decoding configurations.

Here's the interesting part

After selecting a token, the model adds it to the existing context. Then it predicts another token. And another. And another.

This is autoregressive generation. The model is not necessarily retrieving a complete paragraph from a database. It is incrementally generating a sequence conditioned on the context available at each step.


11 . Autoregressive generation

One token becomes an answer

Let's return to Swarup and his question about response-time targets. Imagine the model begins generating "Start", then "Start by", then "Start by comparing", and so on. Each newly generated token becomes part of the context used for the next prediction.

Neon Token Decoding Dashboard

Figure 7. Grey chips are the prompt; colored chips are generated. Each new token joins the context before the next prediction runs. At step 1 the sampler chose "Start" even though "The" scored higher, which is what sampling allows.

Mathematically, the probability of the whole sequence factors into one next-token prediction per step, where C is the available preceding context:

P(x1,x2,…,xn)=∏t=1nP(xt∣x1,…,xt−1,C)P(x_1, x_2, \ldots, x_n) = \prod_{t=1}^{n} P(x_t \mid x_1, \ldots, x_{t-1}, C)

This factorization is the foundation of autoregressive language generation.

Why does the response appear gradually?

Because generation happens incrementally. An application can stream generated output as it becomes available instead of waiting for the entire response to finish, so you can start reading while the model is still generating. There is an important performance distinction here:

MetricWhat it measures
Time to first tokenHow long before the first generated token becomes available.
Inter-token latencyHow much time passes between subsequent generated tokens.
ThroughputHow many tokens can be generated per unit of time.

These metrics matter enormously when building production AI applications.


12 . KV cache

The optimization that makes generation practical

During autoregressive generation, the model repeatedly needs attention information from previously processed tokens. Would it make sense to recalculate everything from scratch after every new token? That would be extremely inefficient.

This is where the Key-Value cache comes in. During inference, Transformers can cache previously computed attention keys and values. When a new token arrives, the model reuses that cached information rather than recomputing the previous tokens' key and value projections.

KV Cache_ Decoding Steps Compared

Figure 8. Without a cache, the work grows with every step because the whole sequence is reprocessed. With a cache, each step computes keys and values for one new token and reads the rest from memory. The cost moves from compute to GPU memory.

This substantially reduces repeated computation during autoregressive decoding. However, there is a trade-off. The cache consumes GPU memory, and its size grows with the sequence length, number of layers, attention heads, and other architecture-specific factors. For an engineer, this creates an important optimization problem:

How do you manage GPU memory efficiently while serving many concurrent requests?

This is where inference engines such as vLLM become interesting. The PagedAttention research introduced a memory-management approach inspired by operating-system paging, allowing KV cache blocks to be allocated more flexibly. See Efficient Memory Management for Large Language Model Serving with PagedAttention.


13 . GPU inference

Where does all this computation happen?

So far, we've discussed the mathematical side. But neural networks require hardware. Modern LLM inference commonly uses GPUs because they are designed to execute large numbers of parallel mathematical operations efficiently.

A Transformer performs substantial matrix multiplications involving input representations, attention projections, attention score calculations, feed-forward transformations, and output vocabulary projections. These operations involve large tensors and substantial memory movement.

KV Cache_ Decoding Steps Compared

Figure 9. A request moves through ordinary web infrastructure until the scheduler hands it to GPU workers, where the model and its KV cache live. Tokens stream back as they are produced.

Prefill versus decode

LLM inference is commonly understood as having two major phases, and they have different performance bottlenecks.

PhaseTypical bottleneckWhat happens
PrefillOften compute-boundThe model processes the input prompt, computes representations, and populates the KV cache. Work can often run in parallel across input positions.
DecodeOften memory-bandwidth-boundThe model generates output tokens one at a time. Each depends on the preceding context and reuses cached keys and values.

Why do inference engineers care?

Because a model that performs well in an isolated benchmark may behave very differently under thousands of concurrent requests. Production serving requires balancing latency, throughput, GPU memory, batch size, context length, concurrent requests, and cost per generated token.

These are not merely machine-learning concerns. They are distributed systems and infrastructure engineering concerns.


14 . Continuous batching & PagedAttention

Serving thousands of requests

Imagine 500 users asking questions simultaneously. A naive serving system might process requests in rigid batches. But requests do not finish at the same time. Some users ask short questions; others submit enormous documents and request lengthy answers. A fixed batch can leave GPU capacity underutilized while some requests finish earlier than others.

Continuous batching addresses this by allowing new requests to enter execution as existing requests complete.

Then there is the KV cache memory problem. PagedAttention addresses inefficient KV cache allocation by dividing cache storage into blocks rather than requiring every request to occupy one large contiguous allocation. Think of it like virtual memory in an operating system: instead of reserving one enormous continuous space for every request, memory is managed in smaller blocks. This can reduce fragmentation and increase the number of requests that fit in GPU memory.

KV Cache Memory_ Two Allocation Ways

Figure 10. Contiguous allocation reserves space for each request's maximum length, so much of it sits empty. Paged allocation hands out small blocks as tokens arrive, leaving room for more requests.

The original vLLM research reported substantial throughput improvements in its evaluated workloads. Those results are workload- and configuration-dependent, not a universal performance guarantee. For AI infrastructure engineers, this is an important lesson:


Making an LLM faster is not only about making the neural network faster. It is also about managing computation, memory, and scheduling more intelligently.


15 . Beyond the model

ChatGPT is more than a language model

At this point, you might think we've explained everything. Not quite. A production AI assistant can be much more than a model receiving text and generating text.

Tool calling

Suppose Swarup asks: "Check our support database and tell me why the response-time target is being missed." A language model alone cannot inspect a private database it has not been given access to. But an application can provide tools that allow the model to request an operation:

  1. User asks a question.
  2. App provides the model with relevant tool descriptions.
  3. Model generates a structured tool request.
  4. App validates and executes the request.
  5. Tool returns its result.
  6. Model uses that result to generate a response.

The important distinction is that the model can request an action, but the surrounding application executes it. Tool execution requires appropriate permissions and validation.

Retrieval-Augmented Generation (RAG)

What if Swarup's company has thousands of internal support reports? Instead of placing every report into the prompt, an application can retrieve the relevant ones.

Retrieval-Augmented Generation Explained

Figure 11. Documents are embedded once and stored. At question time the query is embedded the same way, the closest chunks are found, and they become extra context for generation.

RAG does not automatically guarantee correctness. Retrieval quality, document freshness, source relevance, and answer verification still matter.

Multimodal processing

Modern AI systems can also work with images, audio, and other modalities. A user might upload a screenshot, speak a question, or provide a document. The application and model architecture must process those inputs using appropriate modality-specific representations and pathways. The text-only pipeline we've followed is a foundation, not a complete description of every multimodal system.


16 . Hallucination

Why can ChatGPT still be wrong?

We've followed the entire journey: tokens, embeddings, attention, probabilities, decoding, and powerful GPUs. So why can the model still give incorrect answers?

Because generating a plausible continuation is not equivalent to verifying a fact. The model can produce a grammatically perfect answer without having access to the information required to establish whether it is true.

Suppose Swarup asks, "Which specific agent caused our response-time failure yesterday?" If the model has not received the relevant operational records or accessed an authorized tool, it cannot reliably identify that agent. It might generate a plausible explanation, but that doesn't make it an evidence-based conclusion. This is why production AI systems often need:

  • Grounded retrieval
  • Reliable data sources
  • Tool validation
  • Structured output validation
  • Evaluation datasets
  • Human review for consequential decisions
  • Monitoring and observability

A fluent answer is not necessarily a verified answer.


That distinction is fundamental to responsible AI engineering.


17 . The complete mental model

Bringing it all together

When Swarup presses Send, a simplified text-generation journey looks like this:

LLM Token Generation Loop Infographic Figure 12. Everything between the transformer layers and the next token runs once per generated token. Production systems add routing, retrieval, tool execution, safety, scheduling, caching, and multimodal handling around this core.

The central mathematical idea can be summarized in one line, where xₜ is the next token, the previous tokens form the available context, and θ represents the learned model parameters:

P(xt∣x1,x2,…,xt−1,θ)P(x_t \mid x_1, x_2, \ldots, x_{t-1}, \theta)

The model estimates a distribution over possible next tokens and generates a sequence from that distribution. That is the foundation of autoregressive language generation.


18 . What to learn next

Where to go as an AI engineer

Understanding the journey is only the beginning. If you want to build AI-powered products and production-grade LLM systems, these are the concepts worth exploring next:

AreaTopics to master
MathematicsLinear algebra, vectors, matrices, dot products, softmax
Deep learningBackpropagation, gradient descent, activation functions
NLPTokenization, embeddings, positional encoding
TransformersSelf-attention, multi-head attention, causal masking
LLM internalsLogits, sampling, autoregressive generation
OptimizationKV cache, quantization, FlashAttention
InfrastructureGPU memory, batching, inference scheduling
AI applicationsRAG, agents, tool calling, evaluation
Production engineeringObservability, latency, throughput, reliability

You don't need to master everything at once. Build the mental model first, then investigate each layer through mathematics, experiments, and implementation.


Final thoughts

The next time you press Send

Remember what's happening behind that simple interface.

  • → Your sentence becomes tokens.
  • → Those tokens become numerical representations.
  • → Transformer layers process contextual relationships.
  • → The model calculates possible continuations.
  • → A decoding process selects tokens.
  • ↻ The process repeats, and the sequence becomes the response you read.

Behind production AI systems, there is an entire engineering discipline dedicated to making this process accurate, fast, scalable, and reliable.

The fascinating part isn't simply that an AI can generate a paragraph. It's that a sequence of mathematical operations, learned parameters, and carefully engineered infrastructure can transform a human question into a useful response.

That's the machinery behind modern generative AI. Understanding it is where becoming an AI engineer really begins.


References and further reading

Technical note: This article explains a generalized Transformer-based autoregressive text-generation and inference pipeline. It is not a disclosure of ChatGPT's proprietary architecture. Actual model architectures, decoding strategies, infrastructure, and product workflows can differ. All token IDs, logits, probabilities, and attention weights shown are illustrative.