Greedy (Top-1)
Always pick the most probable token.
From Text to Prediction
Understand how Large Language Models
turn text into intelligent responses.
Understand the fundamental principles behind LLMs – from text input to next-token prediction.
Build the mental model you need to work effectively with LLMs in real applications.
LLM Fundamentals II – Inside the Model: Transformer, Attention, Context and Limits.
Your input
Text is split
into tokens
Tokens become
numerical vectors
Predicts the
next token
Generated text
An LLM generates text by repeatedly predicting the next token.
Understand how Large Language Models turn text into responses. Text is split into tokens, token IDs become vectors, and the model predicts a distribution for the next token. Select one token, append it to the context and repeat. This module builds the mental model developers need to work effectively with LLMs. Part II explores Transformers, attention, context and limits.
An LLM (Large Language Model) is a neural network trained on large amounts of text to process and generate language.
Given a context, it predicts a probability distribution for the next token. A decoding strategy selects one token, which is added to the context. Repeating this process produces answers, summaries, translations, code, and other content.
An LLM does not normally retrieve an answer as an exact database record. It generates a response from learned patterns, although it may sometimes reproduce memorized training content.
Text is split into
tokens.
The model outputs a probability distribution for the next token.
A decoding strategy
selects one token.
The token is added to the context and the process repeats.
Generates from learned patterns and the provided context. It may sometimes reproduce memorized content.
Returns stored information
that matches a query.
In one sentence:
An LLM generates language by repeatedly predicting a probability distribution for the next token and selecting one token from it.
An LLM is a neural network trained on large amounts of text to process and generate language. Given context, it predicts a probability distribution for the next token. A decoding strategy selects one token; that token is appended and the process repeats. Example: “Explain how solar energy works.” Tokenization → neural network → token selection → append and repeat. Unlike a database query that retrieves a stored record, generation uses learned patterns and the supplied context; memorized training content may sometimes be reproduced.
An LLM is the language engine.
A complete AI application combines the model with data, tools, workflows, security, and a user experience to solve real problems.
Processes context and predicts a
probability distribution for the next token.
Combines the model with other
components to deliver value to users.
Documents, databases, APIs, and domain knowledge.
Find relevant information using search, indexing, or RAG.
Coordinate instructions, workflows, and model calls.
Connect APIs, business systems, calculators, and services.
Manage privacy, permissions, validation, and compliance.
Create a useful experience across web, mobile, and chat.
Measure quality, cost, latency, usage, and feedback.
Key takeaway:
An LLM is one component. Real value comes from combining it with data, tools, processes, security, and user experience to solve real problems.
The model is the language engine. A complete AI application combines it with data and knowledge (documents, databases and APIs), retrieval and search, prompting and orchestration, tools and integrations, guardrails and security, a UI or UX, and evaluation and monitoring. The value comes from combining the model with your data, tools, processes and user experience to solve real problems.
At the heart of every LLM is a simple idea:
given some text, predict what comes next.
The model doesn’t know the full answer in advance.
It generates text one token at a time.
The model outputs a probability distribution over the entire vocabulary.
It is not choosing the “right” answer – it is predicting what is most likely.
Probability distribution
over all tokens
Chosen based on
probabilities (e.g., sampling)
Repeat until a stop
condition is met
(e.g., end of sentence)
Key takeaway:
LLMs generate text by repeatedly predicting the next token and extending the context.
Given some text, predict what comes next. The model generates one token at a time. Example context: “The future of renewable energy is”. Illustrative next-token probabilities: bright 0.68, important 0.17, exciting 0.06 and uncertain 0.03, with the remaining probability mass on other vocabulary tokens. Choose a token based on the distribution, append it to context, and repeat until a stop condition. The model predicts likely continuations, not a guaranteed right answer.
LLMs process text by breaking it into tokens. Depending on the tokenizer, tokens may represent whole words, parts of words, punctuation, whitespace, or other byte sequences.
LLMs do not process text like humans.
They process sequences of tokens.
Some common words may form a single token.
Rare or complex words may be split into subword tokens.
Punctuation may form separate tokens or be combined with nearby text.
Spaces and line breaks may be separate tokens or encoded as part of another token.
(illustrative)
Raw text from a user or document.
The tokenizer splits or groups the text according to its vocabulary and rules.
Each token maps to an ID within that tokenizer’s vocabulary.
Illustrative IDs
Token IDs are converted to learned vectors before entering the Transformer.
The Transformer processes the vectors and predicts what may come next.
Next-token probabilities
Key takeaway:
Text → Tokens → Token IDs → Embeddings → Transformer. Tokenization converts text into units that an LLM can process and generate.
Tokens may be whole words, word parts, punctuation, whitespace or other byte sequences. Text is split into tokens, which map to token IDs in the tokenizer vocabulary. A learned embedding lookup maps IDs to vectors, and the Transformer processes them to predict the next-token distribution. The sentence “The future of renewable energy is bright.” and all splits, IDs and probabilities on this slide are illustrative and depend on the tokenizer.
The same sentence may be tokenized differently by different models and tokenizer versions.
There is no universal “correct” tokenization.
It depends on the tokenizer’s vocabulary and rules.
“The future of renewable energy is bright.”
Word-oriented vocabulary
Different vocabulary
Smaller subword units
These examples show the principle only. Exact tokens and IDs must be obtained from the actual tokenizer version.
Different vocabularies produce different token splits.
The same sentence may use a different number of tokens.
Token count affects context usage, cost, and latency.
Always test with the exact model and tokenizer version you deploy.
Determines which text units are available.
BPE, Unigram, WordPiece, and related methods split text differently.
Languages and writing systems may tokenize differently.
Spaces, punctuation, capitalization, and special tokens matter.
Tokenization may change across model families or versions.
Use the tokenizer provided for your selected model.
tokenizer = load_tokenizer(model)
tokens = tokenizer.encode(text)
print(tokens)
print(len(tokens))Key takeaway: Tokenization is model-dependent. Test the exact tokenizer you deploy to manage context limits, estimate costs, and avoid unexpected behavior.
The same sentence may produce different token splits and counts with different tokenizers. These illustrative examples show 8, 9 and 13 tokens, not measured outputs from named models. The third count matches the 13 units displayed. Vocabulary, algorithm, language, whitespace, rules, model and version affect tokenization. Always test the exact tokenizer you deploy. The code uses a conceptual load_tokenizer(model) helper to encode text and inspect token IDs and token count.
Tokens are not just a technical detail.
They directly impact the behavior, performance, and cost of your AI applications.
Every token you send or receive has an impact.
Understand tokens. Build better.
Tokens determine how much the model can “see” at once.
Used: 7,500 tokens
Limit: 8,192 tokensIllustrative context budget
Exceeding the limit may reject a request or truncate context.
LLM API usage is commonly priced by input and output tokens.
More tokens can mean higher cost. Optimize what you send and generate.
More tokens usually mean more computation and longer responses.
Longer prompts and outputs can increase response time for your users.
Split your data into token-aware chunks for retrieval.
Chunk size (in tokens) affects retrieval quality and relevance.
Tokens you send in your prompt (system + user + context).
Tokens generated by the model in its response.
Input + Output = total usage. Check model-specific limits.
Prompt: 2,000 tokens
Response: 1,000 tokens
Total: 3,000 tokens
Cost = 2 × input rate
+ 1 × output rateRates per 1K tokens
Remove unnecessary words, repetition, and verbose context.
Summarize long content before sending it.
Only include relevant information in the prompt.
Limit maximum output tokens when possible.
Track token usage, costs, and latency in production.
Key takeaway:
Tokens are a limited and valuable resource. Designing with tokens in mind leads to faster, cheaper, and more reliable AI applications.
Tokens affect context limits, API costs, latency and retrieval chunking. The 7,500 / 8,192 context budget is illustrative. Budget input and output according to the model. Excess context may cause rejection or truncation depending on the system. For 2,000 input and 1,000 output tokens, total usage is 3,000 tokens; cost is 2 times the input rate plus 1 times the output rate when rates are quoted per 1,000 tokens. Be concise, summarize, filter, control output and monitor usage, costs and latency.
LLMs work with numbers, not text.
Every token is mapped to a unique token ID (a number).
The model never sees words – it sees sequences of numbers.
Numbers in, numbers out.
Human writes
or provides text
Text is split into tokens
(words, parts, punctuation)
Each token is mapped
to a unique number (ID)
Illustrative tokens and IDs; special tokens depend on the tokenizer.
You provide text
(prompt).
Text is split into
tokens.
| Token | ID |
|---|---|
| The | 1996 |
| future | 1237 |
| of | 286 |
| … | … |
Each token is mapped
to a number.
The model processes
numerical representations.
Output IDs are converted
back to tokens and text.
Numbers are fast for computers to process.
Token IDs are used to look up learned vector representations.
The model predicts the next token ID, which is converted back to text.
The same token maps to the same ID for a given tokenizer vocabulary.
Key takeaway:
Tokens are the building blocks of language, but LLMs operate on numbers. Understanding this bridge is key to building efficient and reliable AI applications.
Text becomes tokens and then integer token IDs. Each token ID indexes the tokenizer vocabulary. The IDs shown are illustrative, including the end-token ID. Token IDs are not meanings or semantic distances. Input text is tokenized, IDs map to learned vectors and are processed by the model; generated IDs are decoded to tokens and text. The output fragment renewable energy is corresponds to the displayed IDs 54321, 12589 and 318.
Token IDs are symbolic indices. Before the Transformer can process them, each ID is mapped to a learned vector called a token embedding.
Token embeddings provide the starting representation.
Context-dependent representations emerge inside the Transformer.
Each ID identifies a token within one tokenizer’s vocabulary.
Each ID represents
a token.
Each ID selects one row from the learned embedding matrix.
…
Embedding matrix
Vocabulary size × vector dimension
Each token starts
as a dense vector.
[ 0.21 −0.47 0.18 … 0.73 ][ −0.11 0.62 −0.33 … 0.08 ][ 0.74 0.05 −0.19 … −0.41 ][ 0.33 −0.22 0.91 … −0.12 ]…
Learned during training.
Attention and other operations combine information across token positions.
Information mixes across
tokens and layers.
The vector for each position now depends on the surrounding context.
[ 0.91 −0.13 0.67 … 0.22 ][ −0.43 0.81 −0.26 … 0.12 ][ 0.11 0.64 −0.72 … −0.36 ][ 0.57 −0.08 0.31 … −0.63 ]…
Context influences each
position’s representation.
3D projection · illustrative
A learned point in a high-dimensional numerical space.
[ 0.82 −0.31 … 0.19 ][ −0.22 0.73 … 0.64 ]Same token ID and initial embedding.
The contextual representation changes.
Token ID — symbolic index
Token embedding — learned starting vector
Contextual representation — output of Transformer layers
Internal computation — numerical vector operations
Key takeaway:
Token IDs are mapped to learned embeddings. Transformer layers then turn them into context-dependent representations.
Token IDs select rows in a learned embedding matrix. These embeddings are starting vectors. Transformer layers combine information across token positions to produce contextual representations. The three-dimensional illustration is only a projection of a high-dimensional space, with arbitrary learned dimensions. In river bank and bank account, the same token ID and initial embedding are used for bank, but its contextual representation differs. All IDs and vector values shown are illustrative.
Before generation, messages and relevant context are serialized, tokenized, and processed by the model.
Generation parameters control how the output is selected.
The model can use only information represented in its learned parameters or provided in the current context.
Define behavior, constraints, and priorities.
Answer clearly and concisely.
The current request or question.
Explain how solar panels work.
Relevant documents, records, or tool results supplied for this request.
Selected content from a technical document.
Previous messages included to maintain continuity.
Earlier discussion about installation costs.
Control decoding — not part of
the tokenized prompt
Temperature
Reshapes token probabilities.
Top-p / Top-k
Restrict candidate tokens.
Max output tokens
Limits response length.
Stop conditions
End generation.
Serialized
Messages
Tokens
Transformer
Only included content consumes context-window tokens.
Next Token
Selection
Messages &
Context
Serialization
Tokenization
Transformer
Token
Probabilities
Decoding
Response
Relevance — Include information needed for the task.
Priority — Instruction roles influence behavior.
Reliability — Relevant context can reduce unsupported answers, but does not guarantee correctness.
Efficiency — Unnecessary context increases tokens, latency, and cost.
Key takeaway:
Messages and supplied data form the model context. Generation parameters separately control how the next token is selected.
Messages and supplied data form the context: system or developer instructions, user prompt, retrieved context or tool results, and included conversation history. Serialization and tokenization precede Transformer processing. Generation parameters such as temperature, top-p or top-k, output limits and stop conditions separately control decoding. Relevant context can improve reliability without guaranteeing correctness. Only content included in the request consumes context-window tokens.
After processing the input, the model predicts what tokens are most likely to come next. It outputs a probability distribution over the entire vocabulary.
The model assigns a probability to every possible token. Decoding selects the next token.
Tokenized input is converted to embeddings and passed through the model.
The model processes the sequence using attention and layers.
Embeddings
(from input tokens)
The final hidden state is projected to vocabulary scores for the next token.
Final hidden
state
Logits
One per vocabulary token
Logits are converted to probabilities using Softmax.
Converts logits
to probabilities
pᵢ = exp(zᵢ) / Σⱼ exp(zⱼ)A probability for every token in the vocabulary. Only a few have high probability.
| Token | ID | Probability |
|---|---|---|
| bright | 5022 | 0.327 |
| promising | 8121 | 0.128 |
| clean | 3416 | 0.097 |
| exciting | 9910 | 0.056 |
| the | 1996 | 0.031 |
| … | … | … |
| zzzzzzz | 250111 | 0.000001 |
Illustrative subset of a
250,112-token vocabulary.
Keep the five most likely tokens:
| 1. | bright | 0.327 |
| 2. | promising | 0.128 |
| 3. | clean | 0.097 |
| 4. | exciting | 0.056 |
| 5. | the | 0.031 |
Divide by 0.639 to renormalize, then sample.
The model predicts, it doesn’t know.
Probabilities reflect learned patterns.
Generation is a choice.
Decoding selects or samples a token.
Developers control the behavior.
Temperature, top-k and top-p shape selection.
Probabilities power generation.
Used in chat, summaries and code completion.
Key takeaway:
The model turns your input into a probability distribution over all possible next tokens. These probabilities are the foundation of every generation step.
The final hidden state is projected to vocabulary logits. Softmax turns logits into a categorical distribution summing to one. The illustrative top five probabilities are 0.327, 0.128, 0.097, 0.056 and 0.031. Top-k keeps these candidates, whose total mass is 0.639, and renormalizes before sampling. The rare-token probability 0.000001 equals 0.0001 percent. Next-token likelihood is not factual confidence.
LLMs generate text autoregressively:
They predict one token, add it to the sequence, and repeat until a stopping condition is met.
The model builds the response step by step, one token at a time.
The sequence so far is the model’s current input.
The model converts tokens to embeddings and processes them.
The model predicts a probability distribution over the vocabulary.
Choose a token using greedy decoding, top-k, or another strategy.
Selected token
(end of sentence)
Add the selected token to the sequence.
Repeat with the new sequence until a stopping condition is met.
Continue generating
the next token.
“The future of renewable energy is”
Process the current input.
Predict token probabilities.
Choose the next token.
Append the selected token.
The future of renewable energy is bright.
• End-of-sequence token (EOS)
• Output limit reached · Stop sequence encountered
Always pick the most probable token.
Sample from the k most likely tokens.
Sample from the smallest set with total probability ≥ p.
Higher: more diverse.
Lower: more focused.
Restrict the candidate
tokens considered.
Limit the generated
response length.
Tokens or strings
that stop generation.
Key takeaway:
Generation is a loop: process → predict → select → append → repeat. Each selected token becomes part of the input for the next step.
LLMs generate autoregressively, one token at a time. Current input is processed into a next-token distribution. Decoding selects a token, which is appended before the next iteration. Greedy decoding selects the highest probability; top-k and nucleus sampling restrict the candidate set before sampling. Temperature, candidate filters, output limits and stop sequences control generation. A sentence-ending period is not necessarily an end-of-sequence token; generation may continue.
The model assigns probabilities to tokens. A decoding strategy turns this distribution into a single next token.
Different strategies can produce different results.
The model produces a probability distribution over the vocabulary.
| Token | Probability |
|---|---|
| bright | 0.327 |
| promising | 0.128 |
| clean | 0.097 |
| exciting | 0.056 |
| the | 0.031 |
| … | … |
| zzzzzzz | 0.000001 |
The strategy turns probabilities into a token choice.
Adjust probabilities or filter candidates using the chosen parameters.
Example: Top-k keeps only the top 5 tokens.
Select one token from the candidate distribution.
Deterministic with greedy decoding, or random with sampling.
Use the selected token as the next token in the sequence.
Append this token and continue generating.
| Strategy | How It Works | Parameters | Behavior | Useful For |
|---|---|---|---|---|
| Greedy (Top-1) | Pick the token with the highest probability. | — | Deterministic; can be repetitive. | Focused output and consistency. |
| Top-k Sampling | Sample from the k most likely tokens. | k: 10, 20, 50 | Controlled randomness; limits the tail. | Balanced diversity and coherence. |
| Nucleus (Top-p) | Sample from the smallest set with total probability ≥ p. | p: 0.8, 0.9, 0.95 | Adaptive candidate-set size. | Open-ended text, chat and stories. |
| Temperature | Scale logits before Softmax. | T: 0.2–2.0 | Lower: more focused. Higher: more varied. | Tune output diversity. |
| Repetition Penalty | Adjust scores of tokens already generated. | e.g. 1.1–2.0 | Discourages repetition and loops. | Longer text; implementation varies. |
More focused
More creative,
more varied
More focused,
less diverse
More diverse,
more random
More focused,
smaller set
More diverse,
larger set
More repetition
possible
Fewer repeats
Key takeaway:
The model gives probabilities; decoding turns them into a decision. Tune consistency, diversity and creativity — and evaluate factual accuracy separately.
Greedy decoding selects the token with highest probability. Top-k and top-p sampling filter candidates and renormalize before sampling. Temperature rescales logits; repetition penalties adjust scores and vary by implementation. Parameter values and text examples are illustrative, not guarantees. Higher temperature or wider candidate sets do not guarantee creativity or factual accuracy.
An LLM is not a verified knowledge database.
Its responses come from learned parameters, the current context, and — when connected — external tools or retrieval.
Fluent output can still be incomplete, outdated, or wrong.
Patterns learned during training.
Information included in this request.
Optional sources accessed via tools.
Combines learned patterns and supplied context to predict tokens.
Truth — Plausible answers may be wrong.
Completeness — Relevant information may be missing.
Freshness — Learned parameters are not continuously updated.
Source fidelity — The model may misread or ignore supplied evidence.
Consistency — Outputs may vary across runs.
Retrieve relevant and authorized information.
Use tools for calculations and live data.
Ask for citations or evidence where appropriate.
Validate important claims and outputs.
Apply permissions, monitoring and evaluation.
RAG supplies evidence to the context. It does not automatically make an answer correct or up to date.
Key takeaway:
An LLM contains learned statistical representations, not a verified fact store. Add relevant context and tools — and verify important results.
Responses are shaped by learned parameters, current context and external systems called through tools. Learned patterns are not a verified knowledge database. Truth, completeness, freshness, source fidelity and consistency are not guaranteed. RAG retrieves relevant material into the model context; it does not automatically make a response correct or current. Provide relevant evidence, use tools for calculations and live data, ask for citations or abstention where appropriate, validate important outputs, and apply permissions, monitoring and evaluation.
From your text to the model’s response — every step explained.
LLMs turn text into tokens, process them as vectors, predict the next token, and generate text autoregressively.
Provide text as input.
Split the text into tokens.
Map each token to an ID.
Convert token IDs into vectors.
Process the sequence.
× N Layers
Output a distribution over the vocabulary.
Select using a decoding strategy.
(chosen token)
Add the token and repeat.
…
Stop when a stopping condition is met.
Tokens: Small pieces of text.
Embeddings: Vectors representing tokens.
Transformer: Neural network that processes context.
Autoregressive: One token at a time.
Understand model behavior.
Use parameters more effectively
(temperature, top-k, etc.).
Debug and evaluate responses.
Build reliable, efficient AI applications.
LLMs predict the next token from learned patterns and the current context — one step at a time.
This simple loop powers highly capable systems.
Key takeaway:
The complete flow is a loop: tokenize → embed → process → predict → select → append → repeat. One token at a time builds the full response.
The complete flow is input text → tokenization → token IDs → token embeddings → Transformer processing → next-token probabilities → selection → append and repeat → generated output. Token IDs and vector values are illustrative and tokenizer dependent. Training taught statistical patterns; inference processes the current context without normally updating the model's learned weights. The schematic loop reuses an expanding context; practical implementations can cache earlier computations. Use this mental model to understand behavior, evaluate outputs, debug problems and build reliable applications.
You’ve learned how LLMs turn text into tokens, process them, and generate text one token at a time.
Remember: Next-token predictions depend on learned patterns and the current context.
Your input is split into small pieces called tokens.
Each token maps to an ID in the vocabulary.
Token IDs map to learned embeddings the model can process.
A Transformer uses attention and layers to process context.
The model outputs a distribution over the entire vocabulary.
A decoding strategy chooses one token as the next output.
Add the token and repeat until a stopping condition is met.
The sequence of selected tokens forms the generated response.
Attention, positional encoding, context windows, training vs. inference, and model limitations.
Focus: Architecture & Internals
Text embeddings, vector similarity, semantic search and RAG.
Focus: Meaning & Retrieval
Prompt engineering, tool use, function calling and reliable LLM applications.
Focus: Practical Skills
Evaluation, safety, observability, cost optimization and deployment at scale.
Focus: Reliability & Scale
Keep Building:
The more you build with LLMs, the better you’ll understand their strengths and limitations. Experiment, iterate, and keep learning!
Text becomes tokens; token IDs map to learned embeddings; layers build context; the model predicts probabilities; decoding selects the next token; append and repeat; the generated output emerges one token at a time. Predictions depend on both learned parameters and the current context. Outputs are not guaranteed to be correct or coherent. The tutorial series continues with LLM Fundamentals II, embeddings and semantic search, building with LLMs, and production and best practices. Continue to Part II via its linked module title or the presentation toolbar.
Arrow keys / Page Up / Page Down: navigate · Home / End: first / last slide · Escape: exit fullscreen. On small screens, use landscape orientation or read the text below. · Download PDF: all 16 slides as a saved edition, without a print dialog.
Understand how Large Language Models turn text into responses. The fundamental loop is text → tokens → vectors → model → next token → append to context → repeat. This module builds the mental model developers need to work effectively with LLMs. Part II opens the model and explores Transformers, attention, context and limits.
Essential cookies are required for the website to work. Optional cookies help us improve content and reach. Learn more in our privacy policy.