Ankit KanojiyaBeginner
Evergreen guide by Ankit Kanojiya · Beginner · AI / ML
How Large Language Models Work: Tokens, Transformers, and Inference
A practical tour of what happens inside a large language model, from splitting text into tokens to generating one word at a time. Written for application developers who call these models through an API.
- LLM
- Transformers
- Tokens
- Inference
- Fundamentals
Large language models (LLMs) look like magic from the outside: text goes in, fluent text comes out. Underneath, the behavior is mechanical and predictable enough that developers can reason about cost, latency, and failure modes. This article explains the three pieces that matter most in practice: tokens, the transformer architecture, and the inference loop.
Tokens: the real unit of work
Models do not read characters or words. They read tokens, which are chunks of text produced by a tokenizer. A token is often a word fragment. Common English words are usually one token, while rare words, code, and non-English text split into several.
As a rough rule of thumb, one token is about four characters of English, so 1,000 tokens is roughly 750 words. This matters because billing, context limits, and latency are all measured in tokens, not words.
- Input tokens are the prompt you send.
- Output tokens are what the model generates.
- Most providers charge more per output token than per input token.
A short prompt that asks for a long answer can cost more than a long prompt that asks for a short one. When estimating cost, count both directions.
The context window
Every model has a maximum number of tokens it can consider at once, called the context window. Prompt plus generated output must fit inside it. If a conversation grows past the limit, the earliest messages must be dropped or summarized.
Two practical consequences:
- Long documents may need to be chunked and processed in pieces.
- Information buried in the middle of a very long context is sometimes used less reliably than information at the start or end, so placement matters.
Transformers and attention
The transformer is the neural network architecture behind modern LLMs. Its central mechanism is attention, which lets the model weigh how relevant every earlier token is to the token it is currently processing. This is why a pronoun can be linked to a noun mentioned paragraphs earlier.
The model is trained to do one narrow thing: given a sequence of tokens, predict a probability distribution over the next token. Fluency, reasoning, and style are all emergent effects of doing that prediction well across enormous training data. The model has no built-in database of facts and no live access to the world; it has learned statistical patterns, which is why it can state false things confidently.
The inference loop
Generation is autoregressive, meaning the model produces one token, appends it to the input, and runs again. The loop looks like this:
tokens = tokenize(prompt)
while not done:
logits = model(tokens) # scores for every possible next token
probs = softmax(logits[-1]) # turn scores into probabilities
next_token = sample(probs) # pick one
tokens.append(next_token)
done = next_token == END or len(tokens) >= max_tokens
Because each new token depends on all previous ones, output time grows with output length. This is also why streaming works: the API can send each token as soon as it is produced.
Sampling knobs developers control
The sample step is where temperature and related settings act.
- Temperature scales randomness. Near 0 the model almost always picks the highest-probability token, giving stable, repeatable output. Higher values spread probability out and produce more varied, creative text.
- Top-p (nucleus sampling) restricts choices to the smallest set of tokens whose combined probability crosses a threshold.
- Max tokens caps output length and protects against runaway cost.
For extraction, classification, and anything requiring consistency, use a low temperature. For brainstorming or varied copy, raise it.
What this means in practice
A few operational takeaways follow directly from the mechanics:
- Latency has two parts: time to first token (processing the prompt) and time per output token. Long prompts raise the first; long answers raise the second.
- To cut cost, shorten outputs before shortening inputs, since output tokens usually cost more.
- Determinism is limited. Even at temperature 0, hardware and batching can introduce small variations, so do not assume byte-identical responses.
- The model predicts plausible text, not verified truth. Treat factual claims as drafts to check, especially names, numbers, and citations.
Understanding tokens, attention, and the generation loop turns an LLM from a black box into a component with knowable costs and limits, which is exactly what you need to build reliable features on top of it.