Introduction
Large Language Models (LLMs) are transforming the way we interact with technology.
Models such as GPT, Claude, Gemini, and Llama can generate text, write code, summarize information, answer questions, and perform many other language-related tasks.
But have you ever wondered what actually happens inside an LLM?
How does it process our input? How does it understand relationships between words? How does it generate responses one token at a time?
To understand these questions, we need to explore the fundamentals of Large Language Models and the Transformer architecture behind them.
In this article, we will move from the basic concepts of LLMs to their internal working, including tokenization, embeddings, self-attention, next-token prediction, and model training.
The goal is to understand not just how to use an LLM, but what happens behind the API when we interact with one.
1. Understanding AI, ML, Deep Learning, and LLMs
Before exploring LLMs, let's understand how they fit into the broader field of Artificial Intelligence.
These terms are related, but they do not mean the same thing.
Artificial Intelligence (AI)
|
└── Machine Learning (ML)
|
└── Deep Learning (DL)
|
└── Large Language Models (LLMs)
Artificial Intelligence (AI): The broader field of building systems that perform tasks associated with human intelligence.
Machine Learning (ML): A subset of AI that allows systems to learn patterns from data and make predictions.
Deep Learning (DL): A subset of Machine Learning that uses multi-layer neural networks to learn complex patterns.
Large Language Models (LLMs): Deep learning models trained on large datasets to process and generate language.
Examples of LLMs include GPT, Claude, Gemini, and Llama.
An important point is that LLMs are only one part of AI. Not every AI system uses an LLM.
2. What Does GPT Stand For?
GPT stands for:
- Generative
- Pre-trained
- Transformer
Each term describes an important property of GPT models.
Generative
Generative means creating new content.
For example, a GPT model can generate:
- Text.
- Programming code.
- Explanations.
- Summaries.
- Structured content.
When you ask a model to write a JavaScript function, it generates an output based on patterns learned during training.
Pre-trained
Pre-trained means that the model has already gone through a training process before developers start using it.
During pre-training, the model learns patterns from large datasets containing text, code, and other supported data.
It learns relationships between tokens, language structures, and information.
Pre-training does not mean the model has memorized the entire internet. It learns statistical patterns from its training data.
Transformer
Transformer is the neural network architecture used by GPT-style models.
In 2017, researchers published an important paper titled:
Attention Is All You Need.
This paper introduced the Transformer architecture and its attention mechanism, which became the foundation of many modern language models.
3. What Is an LLM?
LLM stands for Large Language Model.
An LLM is a deep learning model trained to process and generate sequences of tokens.
At a high level, an LLM receives input, processes it through neural network layers, and predicts what should come next.
Input
|
v
LLM
|
v
Generated Output
For example:
Input:
Explain React Hooks.
|
v
Language Model
|
v
Output:
React Hooks are functions
that allow components to use
state and other React features.
An important distinction is that an LLM does not work like a traditional search engine.
A search engine primarily retrieves existing information.
An LLM generates output using patterns learned during training and the context provided to it.
This is also why an LLM can sometimes generate incorrect information even when its response sounds convincing.
4. Application Developer vs Machine Learning Engineer
There are different ways to work with AI.
Understanding this distinction is useful for developers entering the AI field.
Application Developer
An Application Developer integrates existing AI models into software applications.
For example:
Your Application
|
v
AI API
|
v
Language Model
|
v
Generated Response
|
v
Your Application
The developer focuses on:
- API integration.
- Backend and frontend development.
- Authentication.
- Data management.
- Error handling.
- Application architecture.
- User experience.
They do not need to build the Transformer architecture themselves.
Machine Learning Engineer
A Machine Learning Engineer works closer to the internal mechanics of AI models.
Their responsibilities may include:
- Neural network architecture.
- Model training.
- Dataset preparation.
- Attention optimization.
- Loss calculation.
- Backpropagation.
- Model evaluation.
- Fine-tuning.
The Main Difference
Application Developer:
Uses existing models.
Prompt → API → Response
ML Engineer:
Builds or improves models.
Data → Training → Model
Both roles are important, but their responsibilities are different.
You can build powerful AI applications without training your own language model.
5. Understanding the LLM API
Application developers generally interact with existing models through APIs.
For example, using the OpenAI JavaScript SDK:
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
const response = await client.chat.completions.create({
model: "YOUR_SUPPORTED_MODEL",
messages: [
{
role: "user",
content: "Explain how JavaScript works.",
},
],
});
console.log(response.choices[0].message.content);
Let's understand the process.
- Your application creates an API client.
- It sends a request containing the user's message.
- The API forwards the request for model processing.
- The model generates a response.
- Your application receives and displays the response.
Application
|
v
API
|
v
LLM
|
v
Generated Response
You are using an already trained model. You are not training a new model every time a user sends a message.
Important: Keep secret API keys on your backend. Never expose them in public frontend JavaScript.
6. Tokenization and Vocabulary
Now let's explore how an LLM processes text internally.
One of the most important concepts is that language models process numerical representations called tokens.
A token can represent:
- A complete word.
- Part of a word.
- Punctuation.
- A text fragment.
For example:
Input:
Understanding Artificial Intelligence
Possible Tokens:
["Understanding", " Artificial", " Intelligence"]
The exact tokenization depends on the tokenizer.
Each token is assigned a unique numerical ID.
For example:
Hello → 13225
World → 1917
These values are illustrative. Actual token IDs depend on the tokenizer.
What Is Tokenization?
Tokenization is the process of dividing input text into tokens and mapping those tokens to numerical IDs.
Input Text
|
v
Tokenizer
|
v
Tokens
|
v
Token IDs
The collection of tokens supported by a tokenizer is called its vocabulary.
A model's vocabulary may contain tens or hundreds of thousands of token IDs.
Practical Example Using tiktoken
tiktoken is an OpenAI tokenizer library.
Install it:
pip install tiktoken
Example:
import tiktoken
encoding = tiktoken.encoding_for_model("gpt-4")
text = "Understanding Large Language Models"
tokens = encoding.encode(text)
print(tokens)
print("Token count:", len(tokens))
To convert the token IDs back into text:
decoded_text = encoding.decode(tokens)
print(decoded_text)
The process looks like this:
Text
|
v
Encode
|
v
Token IDs
|
v
Decode
|
v
Text
Why Are Tokens Important?
Tokens directly affect:
- API usage and pricing.
- Context window limits.
- Input and output length.
- Processing requirements.
For developers working with LLMs, understanding tokenization is essential for managing API usage and context limits.
7. Embeddings: Converting Tokens into Vectors
Tokenization converts text into numerical IDs.
However, token IDs are only identifiers. They do not represent the meaning of a token.
This is where embeddings become important.
An embedding is a numerical vector representation of a token or another piece of information.
For example:
King
[0.25, 0.71, 0.93, 0.18, ...]
Real embedding vectors may contain hundreds or thousands of dimensions.
These numerical representations allow neural networks to process information and learn relationships between concepts.
Understanding Embedding Space
Consider these words:
Paris
France
London
England
A trained embedding model can learn relationships between these concepts.
Related concepts can have useful geometric relationships in vector space.
One famous example from traditional word embeddings is:
King - Man + Woman ≈ Queen
This demonstrates how certain semantic relationships can appear as mathematical relationships between vectors.
Modern Transformer models also create contextual representations.
This means a token's representation can change depending on the surrounding context.
For example:
I deposited money at the bank.
I sat beside the river bank.
Although the word "bank" is the same, its contextual representation can differ because the surrounding words provide different meanings.
8. Positional Encoding: Understanding Token Order
A Transformer needs information about the order of tokens in a sequence.
Consider:
The developer created the application.
And:
The application created the developer.
The words are similar, but their meanings are different because their order changes.
Self-attention alone does not inherently represent token order.
Therefore, positional information must be provided to the model.
In the original Transformer architecture, positional encodings were added to token embeddings.
Token Embeddings
+
Positional Encodings
|
v
Position-Aware Representations
The original Transformer used sinusoidal positional encodings.
Modern architectures may use other approaches, including:
- Learned positional embeddings.
- Rotary Position Embeddings (RoPE).
The main purpose is to help the model understand token positions and sequence order.
9. Self-Attention: Understanding Query, Key, and Value
Self-attention is one of the most important components of the Transformer architecture.
It allows each token to calculate how much information it should take from other tokens in the sequence.
Consider:
I deposited money at the bank.
Here, "bank" refers to a financial institution.
Now consider:
I sat beside the river bank.
Here, "bank" refers to the land beside a river.
The surrounding words provide context that helps distinguish between the two meanings.
Query, Key, and Value
The attention mechanism uses three important vectors:
- Query (Q)
- Key (K)
- Value (V)
Think about them this way:
Query: What information am I looking for?
Key: What information does each token contain?
Value: What information should be passed forward?
The attention mechanism compares queries and keys to calculate attention scores.
These scores determine how much information should be taken from each value vector.
Scaled Dot-Product Attention
The mathematical formula is:
[ Attention(Q,K,V)=softmax\left(\frac{QK^T}{\sqrt{d_k}}\right)V ]
Let's understand the operations:
- QKᵀ calculates query-key compatibility scores.
- Division by √dₖ scales the scores.
- Softmax converts scores into attention weights.
- Attention weights are applied to value vectors.
- The result is a context-aware representation.
Multi-Head Attention
Transformers use multiple attention heads instead of relying on a single attention operation.
Each head can learn different relationships within the input.
The outputs from multiple heads are combined to produce a richer representation.
This helps the model capture different types of relationships between tokens.
10. Transformer Architecture
Now let's connect tokenization, embeddings, positional information, and attention.
The original Transformer architecture introduced in 2017 contains two main components:
- Encoder.
- Decoder.
However, GPT-style models generally use a decoder-only Transformer architecture.
A simplified GPT-style processing flow looks like this:
Input Text
|
v
Tokenization
|
v
Token IDs
|
v
Token Embeddings
|
v
Positional Information
|
v
Transformer Blocks
|
|-- Masked Self-Attention
|
|-- Feed-Forward Network
|
|-- Residual Connections
|
|-- Normalization
|
v
Output Projection
|
v
Logits / Token Scores
|
v
Probability Distribution
|
v
Next Token Selection
Let's understand the important components.
Masked Self-Attention
GPT-style models use causal masking.
This prevents a token from attending to future tokens during autoregressive generation.
For example, when predicting token 3, the model can use tokens 1 and 2, but not future tokens.
Feed-Forward Network
The feed-forward network processes the representations produced by attention layers.
It learns additional patterns and transformations.
Residual Connections
Residual connections help information and gradients flow through deeper neural networks.
Normalization
Normalization helps maintain stable computation throughout the network.
Output Projection
The final hidden representation is transformed into scores for possible next tokens.
These scores are called logits.
The logits are converted into probabilities during the generation process.
11. Next Token Prediction: The Core of GPT
GPT-style language models are autoregressive models.
Their fundamental task is to predict the next token based on previously available tokens.
For example:
Input:
I love
The model may produce the following probability distribution:
Ice 0.60
Pizza 0.20
Coding 0.10
Music 0.05
Others 0.05
These values are illustrative.
Suppose the model selects:
Ice
The input now becomes:
I love Ice
The model predicts the next token again.
Suppose it selects:
Cream
Now we have:
I love Ice Cream
This continues until the model generates an ending token or reaches its generation limit.
Prompt
|
v
Predict Next Token
|
v
Select Token
|
v
Append Token
|
v
Predict Again
|
v
Generated Response
This process is called autoregressive generation.
Important: GPT does not normally generate an entire response in one prediction. It generates tokens sequentially, with each generated token becoming part of the context for the next prediction.
12. Temperature and Top-P Sampling
After predicting the next token, the model needs a strategy to select which token to generate.
Two important sampling parameters are Temperature and Top-P.
Temperature
Temperature controls how the probability distribution is adjusted before sampling.
A lower temperature makes the distribution more concentrated around higher-probability tokens.
A higher temperature makes the distribution flatter.
For example:
Temperature = 0
More deterministic token selection.
Temperature = 0.7
Moderate variation.
Temperature = 1.5
More randomness.
These values are illustrative, and supported settings vary by model.
In practice:
- Lower temperature can help with predictable tasks.
- Higher temperature can increase response diversity.
- Excessive randomness can reduce answer quality.
Top-P
Top-P is also called nucleus sampling.
It selects a candidate set containing the most probable tokens whose cumulative probability reaches or exceeds a specified threshold.
Example:
Apple 0.40
Orange 0.30
Banana 0.20
Grapes 0.08
Dog 0.02
If Top-P is 0.90, the candidate set contains:
Apple 0.40
Orange 0.30
Banana 0.20
Total 0.90
The model samples from this candidate set after the applicable probability adjustments.
Both Temperature and Top-P influence the diversity of generated responses.
13. Training vs Inference
Understanding the difference between training and inference is essential for AI developers.
Training
Training is the process of teaching a model using data.
During pre-training, the model learns to predict tokens from training sequences.
The general process looks like this:
Training Data
|
v
Tokenization
|
v
Model Prediction
|
v
Loss Calculation
|
v
Backpropagation
|
v
Optimizer Updates Weights
|
v
Trained Model
The model's parameters, called weights, are adjusted during training.
Inference
Inference means using an already trained model to generate predictions.
For example, when an application sends a request to an LLM API, the model performs inference.
User Prompt
|
v
Trained Model
|
v
Prediction
|
v
Generated Response
The model generally uses its learned weights without updating them during ordinary inference.
Training teaches the model. Inference uses the trained model.
14. Cross-Entropy Loss and Backpropagation
During training, the model predicts the next token.
Its prediction is compared with the actual next token from the training data.
Cross-Entropy Loss measures how well the model's predicted probability distribution matches the target.
A simplified formula is:
[ Loss=-\log(P(\text{correct token})) ]
If the model assigns a high probability to the correct token, the loss is lower.
If it assigns a low probability, the loss is higher.
How Are Model Weights Updated?
The process involves two important operations.
Backpropagation
Backpropagation calculates gradients that describe how changes in model parameters affect the loss.
Optimizer
The optimizer uses these gradients to update the model's parameters.
For example, Adam and AdamW are commonly used optimizers in deep learning.
The complete process:
Input
|
v
Model Prediction
|
v
Calculate Loss
|
v
Backpropagation
|
v
Calculate Gradients
|
v
Optimizer
|
v
Update Weights
This process repeats across training batches.
Over time, the model improves its ability to predict the next token according to its training objective.
15. Context Window: How Much Information Can an LLM Process?
A context window is the maximum amount of token-based context a model can process in a request.
For example, a model may support a context window of 128K tokens.
The actual limit depends on the model.
Context can include:
- System instructions.
- Developer instructions.
- User messages.
- Previous conversation messages.
- Other information provided to the model.
The generated response also consumes context capacity, subject to the model's limits.
Why Does Context Window Matter?
Imagine sending a large document or a long conversation to an LLM.
If the request exceeds the model's context limit, the application must reduce or reorganize the information before sending it.
This is why understanding context limits is important when designing LLM-powered applications.
Context Window vs Memory
These concepts are different.
Context Window: The information available to the model while processing a particular request.
Memory: A separate mechanism for preserving and retrieving selected information across interactions.
The distinction is important: a model does not automatically have unlimited access to every previous conversation.
Conclusion
Understanding LLMs requires more than knowing how to send a prompt to an API.
As an AI developer, you should understand how text becomes tokens, how embeddings represent information, how attention connects different tokens, and how Transformer architectures generate responses.
You should also understand how models are trained, how inference works, and how context limits affect real-world applications.
These concepts form the technical foundation for working with modern Large Language Models.
The goal is not just to use an LLM. The goal is to understand what happens inside it.
What's Next?
This is just the beginning of our journey into Generative AI.
In upcoming articles, we will explore more advanced concepts, practical implementations, and technologies used to build modern AI applications.
We will cover each topic separately, with practical examples and deeper technical explanations.
Stay tuned for the next article. There's a lot more to explore in the world of Generative AI!
