Embeddings are dense numerical vector representations of tokens. After text is tokenized, each token ID is mapped to an embedding vector.
For example:
The model cannot process raw text directly, so embeddings convert discrete token IDs into continuous vectors that neural networks can operate on.
In an LLM, the input flow is:
Embeddings capture semantic and syntactic information. Tokens that appear in similar contexts tend to have similar vector representations.
For example:
But in modern LLMs, the initial token embedding is only the starting point. Once the embedding passes through transformer layers, it becomes a contextual representation.
Example:
The initial embedding of “bank” may be the same, but after self-attention, the representation becomes different based on context.
Causal masking is used in decoder-only models like GPT to prevent a token from attending to future tokens.
GPT-style models generate text left to right. While predicting the next token, the model should only use previous tokens, not future tokens.
Example training sentence:
When predicting “India,” the model should not look ahead and see “New Delhi.”
So we apply a triangular attention mask:
This ensures autoregressive generation.
Without causal masking, the model could cheat during training by looking at future tokens.
GPT-style models use a decoder-only transformer architecture. They are trained to predict the next token given previous tokens.
The structure is:
Each decoder block contains:
Unlike encoder-decoder models used for translation, GPT does not have a separate encoder. It only uses a stack of decoder blocks with causal attention.
This architecture is ideal for generation because it naturally models:
GPT-style models are used for:
The main training objective for GPT-style LLMs is next-token prediction.
Given a sequence of tokens, the model learns to predict the next token.
Example:
Then:
The model predicts a probability distribution over the vocabulary. The correct next token is compared against the predicted distribution using cross-entropy loss. The model weights are updated to reduce this loss.
At scale, next-token prediction teaches the model:
The model is not explicitly trained to know truth. It is trained to predict likely continuations. This is also one reason hallucination can happen.
At each generation step, the LLM produces raw scores for every token in its vocabulary. These raw scores are called logits.
Example:
The model may output logits like:
Logits are not probabilities yet. They can be any real number.
Softmax converts logits into probabilities:
After softmax:
Then the decoding strategy decides which token to choose.
For deterministic output, the model may choose the highest-probability token. For creative output, it may sample from the distribution.
These are decoding controls used during text generation.
Temperature controls randomness.
Low temperature makes output more deterministic.
Technically, temperature adjusts logits before softmax.
Lower temperature sharpens the probability distribution. Higher temperature flattens it.
Top-k sampling restricts the model to only the top k most likely tokens.
Example:
The model samples only from the 5 highest-probability tokens and ignores the rest.
This prevents very unlikely tokens from being selected.
Top-p selects the smallest set of tokens whose cumulative probability reaches p.
Example:
The model considers only tokens that together make up 90% of the probability mass.
Top-p is dynamic. Sometimes it may include 5 tokens; sometimes 50, depending on uncertainty.
For factual tasks, use lower temperature. For creative tasks, use higher temperature and suitable top-p.
KV cache stands for Key-Value cache.
In transformer inference, the model generates one token at a time. For each new token, attention needs Keys and Values from previous tokens.
Without KV cache, the model would recompute attention information for the entire previous context at every generation step.
Example:
This is inefficient.
With KV cache, the model stores the Key and Value vectors of previous tokens. When generating a new token, it only computes Q, K, V for the new token and reuses old K/V values.
This improves inference speed significantly.
KV cache is especially important for:
But it also consumes memory. Longer context and larger batch sizes require more KV cache memory.
These are different stages of making an LLM useful.
Pretraining is the first large-scale training stage. The model learns from massive text corpora using next-token prediction.
It learns:
Pretraining creates the base model.
Fine-tuning continues training the model on a smaller, domain-specific dataset.
Example:
Fine-tuning adapts the model to a specific domain, style, or task.
Instruction tuning trains the model to follow human instructions.
Example:
The goal is to make the model better at understanding and responding to tasks.
RLHF means Reinforcement Learning from Human Feedback.
Humans compare model responses and rank which one is better. A reward model is trained from this feedback, and the LLM is optimized to produce responses humans prefer.
RLHF improves:
Fine-tuning and RAG solve different problems.
Fine-tuning changes the model’s weights. It is useful when you want to improve:
Example:
RAG stands for Retrieval-Augmented Generation. It retrieves relevant external documents and passes them into the prompt so the model can answer using grounded context.
RAG is useful when you need:
Example:
Fine-tuning is not ideal for frequently changing facts because updating model weights repeatedly is expensive and unreliable. RAG is better for dynamic knowledge.
In many production systems, we use both:
Prompt injection is an attack where malicious or untrusted input tries to override the model’s original instructions.
Example:
In RAG systems, prompt injection can appear inside retrieved documents.
Example document content:
The risk is that the LLM may treat untrusted text as instructions instead of data.
Prompt injection is especially dangerous in agents because the model may have access to tools such as:
Mitigation strategies include:
Evaluation depends on the use case. For production GenAI systems, we usually evaluate both quality and operational metrics.
Important RAG questions:
For subjective tasks, human review is still important. Humans can judge helpfulness, correctness, and tone better than automatic metrics alone.
Another LLM can evaluate outputs, but it has risks:
So LLM-as-a-judge should be combined with test sets, human review, and deterministic checks.
Quantization is the process of reducing the numerical precision of model weights and/or activations to make inference cheaper and faster.
Models are often trained using higher precision like FP32 or BF16/FP16. Quantization converts weights into lower precision formats like INT8 or INT4.
Example:
Benefits:
Trade-off:
Quantization is very useful for edge deployment, local models, and cost-sensitive production systems.
There are different types:
LLM cost and latency mainly depend on:
Common optimization techniques:
Do not use the largest model for every task. Use smaller models for simple classification, extraction, routing, or formatting.
Shorter prompts reduce input tokens, cost, and latency.
Techniques:
Set max tokens and ask for concise outputs when appropriate.
Cache:
Streaming improves perceived latency because the user sees output earlier.
Use better chunking, reranking, metadata filters, and hybrid search to reduce irrelevant context.
Batch requests when possible for higher throughput.
KV cache improves autoregressive generation efficiency.
Use a router:
Agents can become expensive if they call tools repeatedly. Use max steps and deterministic workflows.
Production monitoring is critical because LLM systems are probabilistic and can fail in subtle ways.
We monitor several layers:
Model behavior can change due to:
Good production systems log prompts, responses, retrieved context, tool calls, and evaluation signals while respecting privacy and security.
A strong GenAI engineer should understand both LLM internals and production behavior.
Internally, text is tokenized, converted into embeddings, processed through transformer layers using self-attention, and generated token by token using logits, softmax, and decoding strategies. GPT-style models use decoder-only transformers with causal masking and next-token prediction. KV cache makes inference efficient by reusing previous attention states.
For adaptation, pretraining gives general capability, instruction tuning teaches task-following, RLHF aligns behavior with human preferences, and fine-tuning adapts the model to specific styles or tasks. RAG is used when the model needs external, fresh, private, or source-grounded knowledge.
In production, we must handle prompt injection, RAG failure modes, hallucination, latency, cost, quantization, evaluation, and monitoring. A reliable LLM system is not just a prompt around a model; it is an engineered pipeline with retrieval, validation, guardrails, observability, and feedback loops.