Demystifying LLM Theory, Design, and Implementation
local graph
Chapter 7 — Demystifying LLM Theory, Design, and Implementation
Section titled “Chapter 7 — Demystifying LLM Theory, Design, and Implementation”In this chapter, we delve deep into the intricate world of LLMs and the underpinning mathematical concepts that fuel their performance. The advent of these models has revolutionized the field of natural language processing (NLP), offering unparalleled proficiency in understanding, generating, and interacting with human language.
As we explore the operations of LLMs, we will introduce the key metric of perplexity, a measurement of uncertainty that is pivotal in determining the performance of these models. A lower perplexity indicates the confidence that a language model (LM) has in predicting the next word in a sequence, thus showcasing its proficiency. Adding to that, while perplexity remains an important indicator of a model’s confidence during training, recent modern LLMs are evaluated using a range of new benchmarks, measuring not only language modeling ability, but also reasoning, factuality, safety, and robustness. We will introduce these new evaluation standards later in the chapter.
This chapter draws on multiple insightful publications that delve into the mathematical insights of LLMs. These include A Neural Probabilistic Language Model, Attention is All You Need, and PaLM: Scaling Language Modeling with Pathways. These sources will guide us in understanding the robust mechanisms that underpin LLMs and their exceptional capabilities.
With a comprehensive understanding of the mathematical foundations of LLMs, we will gain a robust knowledge of these advanced AI systems, paving the way for future innovations and advancements in the field.
Finally, we will discuss the detailed architecture and design of the most recent models, including the recent GPTs from OpenAI, the Claude 4 family, and Gemini, alongside open source advancements such as Llama, DeepSeek, and the Mistral family.
Now, let’s look at the topics covered in this chapter:
- What are LLMs and how are they different from LMs?
- Motivations for developing and using LLMs
- Challenges in developing LLMs
- Current state-of-the-art LLMs
- Evaluation metrics and methods
Technical requirements
Section titled “Technical requirements”For this chapter, you are expected to possess a solid foundation in ML concepts, particularly in the areas of Transformers and reinforcement learning. An understanding of Transformer-based models, which underpin many of today’s LLMs, is vital. This includes familiarity with concepts such as self-attention mechanisms, positional encoding, and the structure of encoder-decoder architectures.
Familiarity with concepts such as policy gradients, reward functions, and Q-learning will greatly enhance your comprehension of this content.
Lastly, coding proficiency, specifically in Python, is crucial. This is because many of the concepts will be demonstrated and explored through the lens of programming. Experience with PyTorch or TensorFlow, popular ML libraries, and Hugging Face’s Transformers library, a key resource for working with transformer models, will also be beneficial.
However, don’t be discouraged if you feel you’re lacking in some areas. This chapter aims to walk you through the complexities of these subjects, bridging any knowledge gaps along the way. So, come prepared with a mindset for learning, and let’s delve into the fascinating world of LLMs!
What are LLMs and how are they different from LMs?
Section titled “What are LLMs and how are they different from LMs?”A LM is a type of machine learning model that learns a probability distribution over sequences of tokens, such as words, subwords, or characters. Depending on the model architecture and training objective, this may involve predicting the next token in a sequence, reconstructing masked tokens, or estimating token probabilities given surrounding context. By learning these statistical patterns from large text corpora, language models are able to generate fluent text that follows learned linguistic structures and styles.
Before the advent of Transformer-based models such as generative pretrained Transformers (GPTs) and Bidirectional Encoder Representations from Transformers (BERT), there were several other types of LMs widely used in NLP tasks. Let’s discuss a few of them:
- n-gram models:These are some of the simplest LMs. An n -gram model uses the (n -1) previous words to predict the n th word in a sentence. For example, in a bigram (2-gram) model, we would use the previous word to predict the next word. These models are easy to implement and computationally efficient, but they typically don’t perform as well as more complex models because they don’t capture long-range dependencies between words. Their performance also degrades as n increases, as they suffer from data sparsity issues (not having enough data to accurately estimate the probabilities for all possible n -grams).
- Hidden Markov models (HMMs):These models consider the “hidden” states that generate the observed data. In the context of language modeling, each word would be an observed state, and the “hidden” state would be some kind of linguistic feature that’s not directly observable (such as the part of speech of the word). However, like n -gram models, HMMs struggle to capture long-range dependencies between words.
- Recurrent neural networks (RNNs):These are a type of neural network where connections between nodes form a directed graph along a temporal sequence. This allows them to use their internal state (memory) to process sequences of inputs, making them ideal for language modeling. They can capture long-range dependencies between words, but they struggle with the so-called vanishing gradient problem, which makes it difficult to learn these dependencies in practice.
- Long short-term memory (LSTM) networks:An LSTM network is a special kind of RNN that is designed to learn long-term dependencies. They do this by using a series of “gates” that control the flow of information in and out of the memory state of the network. LSTMs were a big step forward in the state of the art of language modeling.
- Gated recurrent unit (GRU) networks:These are a variation of LSTMs that use a slightly different set of gates in their architecture. They’re often simpler and faster to train than LSTMs, but whether they perform better or worse than LSTMs tends to depend on the specific task at hand.
Because LLMs are trained via next-token prediction, their performance during training is traditionally measured using perplexity, a metric we revisit later in the chapter.
Each of these models has its own strengths and weaknesses, and none of them are better or worse than the others; it all depends on the specific task and dataset.
Why LLMs stand out
Section titled “Why LLMs stand out”LLMs are a class of large-scale LMs capable of understanding and generating human-like language. During pretraining, many LLMs learn by modeling the probability of token sequences over vast and diverse corpora, which enables them to capture linguistic structure, factual knowledge, and contextual relationships.
Through subsequent alignment and instruction tuning, these models go beyond raw sequence modeling to produce coherent, goal-directed, and contextually appropriate responses across a wide range of tasks.
LLMs, such as GPT-4.X and Llama, are originally LMs that are trained on a very large amount of text and have a very large number of parameters. The larger the model (in terms of parameters and training data), the more capable it is of understanding and generating complex and varied texts. We saw this transition from LMs to LLMs in the early 2020’s.
More recently, the definition of LLM has evolved. Beyond sheer scale, modern LLMs often incorporate advanced architectural innovations, such as Mixture-of-Experts (MoE) layers for efficiency, or multi-modal capabilities that allow them to process text, images, and even audio. The distinction between closed and open source models, as well as the role of community-driven benchmarks, now also shapes how we assess LLM progress.
Here are some key differences between LLMs and the smaller LMs:
- Data: LLMs are trained on vast amounts of data. This allows them to learn from a wide range of linguistic patterns, styles, and topics.
- Parameters: LLMs have a huge number of parameters. Parameters in an ML model are the parts of the model that are learned from the training data. The more parameters a model has, the more complex patterns it can learn.
- Performance: Because they’re trained on more data and have more parameters, LLMs generally perform better than smaller ones. They’re capable of generating more coherent and diverse texts, and they’re better at understanding context, making inferences, and even answering questions or generating texts on a wide range of topics.
- Compute resources: LLMs require a significant amount of computational resources to train, both in terms of processing power and memory. They also take longer to train.
- Storage and inference time: Large models also require more storage space, and it takes longer to generate predictions (although this inference time is still typically quite fast on modern hardware).
Thus, we can say that LLMs are scaled-up versions of smaller LMs. They’re trained on more data, have more parameters, and are generally capable of producing higher-quality results, but they also require more resources to train and use. Besides that, an important advantage of an LLM is that we can train them unsupervised on a large corpus of data and then fine-tune them with a limited amount of data for different tasks.
We can now look into one of the core mechanisms of LLMs, the Transformer.
Transformer models
Section titled “Transformer models”Transformer models have been at the forefront of the recent wave of LLMs. They are based on the “Transformer” architecture, which uses self-attention mechanisms to weigh the relevance of different words in the input when making predictions. Transformers are a type of neural network architecture introduced in the paper Attention is All You Need by Vaswani et al. One of their significant advantages, particularly for training LLMs, is their suitability for parallel computing.
In traditional RNN models, such as LSTM and GRU, the sequence of tokens (words, subwords, or characters in the text) must be processed sequentially. That’s because each token’s representation depends not only on the token itself but also on the previous tokens in the sequence. The inherent sequential nature of these models makes it difficult to parallelize their operations, which can limit the speed and efficiency of the training process.
Transformers, in contrast, eliminate the necessity for sequential processing by using a mechanism called self-attention (or scaled dot-product attention). In the self-attention process, each token’s representation is computed as a weighted sum of all tokens in the sequence, with the weights determined by the attention mechanism. Importantly, these computations for each token are independent of the computations for other tokens, and thus they can be performed in parallel.
This parallelization capability brings several advantages for training LLMs:
- Speed: By parallelizing the computations, Transformers can process large amounts of data more quickly than RNNs. This speed can significantly reduce the training time of LLMs, which often need to process vast amounts of data.
- Scalability: Transformers’ parallelization makes it easier to scale up the model size and the amount of training data. This capability is crucial for developing LLMs, as these models often benefit from being trained on larger datasets and having a larger number of parameters.
- Long-range dependencies: Transformers can better capture long-range dependencies between tokens because they consider all tokens in the sequence simultaneously, rather than processing them one at a time. This capability is valuable in many language tasks and can improve the performance of LLMs.
Motivations for developing and using LLMs
Section titled “Motivations for developing and using LLMs”The motivation to develop and use LLMs arises from several factors related to the capabilities of these models and the potential benefits they can bring in diverse applications. The following subsections detail a few of these key motivations.
Improved performance
Section titled “Improved performance”LLMs, when trained with sufficient data, generally demonstrate far better performance compared to earlier and smaller models. They are now capable of understanding context, identifying subtle nuances, and generating coherent, contextually relevant responses across a wide range of tasks, spanning text classification, named entity recognition, sentiment analysis, machine translation, question answering, and text generation.
In the past, model progress was typically measured using the General Language Understanding Evaluation (GLUE) benchmark, which evaluates models across a suite of natural language understanding (NLU) tasks such as sentiment analysis, question answering, and textual entailment. While GLUE played a pivotal role in advancing NLU research, recent years have seen a shift toward more challenging and comprehensive benchmarks that better reflect the capabilities of LLMs.
Today, the Massive Multitask Language Understanding (MMLU) benchmark has emerged as a key standard for comparing state-of-the-art LLMs. MMLU tests models on a diverse set of academic and professional subjects, providing a rigorous measure of broad knowledge, reasoning, and world knowledge. The results in Table 7.1 demonstrate the substantial leap in performance achieved by leading closed and open source LLMs on this benchmark.
| Model | Developer | MMLU Score (%) |
|---|---|---|
| o1 | OpenAI | 91.8 |
| GPT-4.5 | OpenAI | 90.8 |
| Claude 3.5 Sonnet | Anthropic | 90.4 |
| Gemini 1.5 Pro | 85.9 | |
| Mistral Large 2 | Mistral | 84.0 |
| Llama 3.1 405B Instruct | Meta | 87.3 |
| DeepSeek-V3 | DeepSeek | 88.5 |
Table 7.1 – Performance of Recent LLMs on the MMLU benchmark (llm-stats.com)
In addition to MMLU, other modern benchmarks, such as the Graduate-Level Professional Question Answering (GPQA) benchmark, have been introduced to evaluate LLMs on advanced reasoning and specialized knowledge, pushing the boundaries of what these models can achieve.
As the field rapidly evolves, these benchmarks play a central role in highlighting the remarkable improvements of the latest LLMs over their predecessors.
Broad generalization
Section titled “Broad generalization”LLMs trained on diverse and expansive datasets can generalize better across a wide spectrum of tasks, domains, and linguistic styles. Their ability to absorb patterns from varied data makes them effective not only for classic NLP tasks, but also for entirely new frontiers. Modern LLMs can adapt seamlessly to applications ranging from chatbots and information retrieval to creative writing, document summarization, and technical question answering.
Crucially, today’s LLMs exhibit generalization capabilities that extend beyond basic language understanding. The newest models, such as GPT-4.5, Claude 3.5, Gemini, Llama 3.1, Mistral Large 2, and DeepSeek-V3, have shown strong proficiency in the following:
- Reasoning and logic, including solving complex problems and performing multi-step deductions
- Code generation and software understanding, enabling high-quality code completion, explanation, and debugging across multiple programming languages
- Multi-modal understanding, where models process not only text, but also images, tables, and in some cases audio or video
- Long-context management, with support for context windows of up to 1 million tokens, allowing the models to synthesize, summarize, and reason over large documents or extended conversations
The increased parameter counts and more sophisticated training strategies of these models enable them to capture and represent more complex relationships, yielding much greater versatility across both familiar and novel tasks. As illustrated in Figure 7.1, larger and more capable LLMs continue to demonstrate superior performance on a variety of benchmarks.

Figure 7.1 – LLMs performance based on their size and training
Figure 7.1 – LLMs’ performance based on their size and training
To view the preceding figure in color, access the free PDF version of this book and other associated benefits. Instructions are available in the Free benefits with your book section in the Preface.
Another major development is the emergence of multi-agent LLM systems, where multiple specialized LLMs or agents can collaborate, each leveraging unique strengths or domain knowledge, to tackle complex workflows and provide more robust, accurate results. This “collaborative AI” paradigm is opening new doors for real-world applications, from research assistants to autonomous business processes.
As the field continues to progress, broad generalization is not just about understanding language, but also about reasoning, integrating multiple modalities, and orchestrating intelligent systems composed of many cooperating models.
However, it’s important to note that while larger models tend to be more generalizable, they also pose challenges such as increased computational requirements and the risk of overfitting. It is also essential to ensure that the training data is representative of the tasks and domains the model is expected to perform in, as models might carry over any biases present in the training data.
Few-shot learning
Section titled “Few-shot learning”The ability of LLMs to learn from just a handful of examples, known as few-shot learning, was first popularized by models such as GPT-3. Since then, this capability has advanced dramatically with new generations of models such as GPT-4, GPT-4.5, Claude 3.5, and Gemini. These state-of-the-art LLMs now demonstrate not only robust few-shot learning, but also zero-shot reasoning: solving new problems without any task-specific examples!
Today’s top models excel at in-context learning across a wide variety of domains:
- Complex reasoning tasks (multi-step logic, symbolic manipulation)
- Code generation and debugging
- Tool use (API calls, function invocation, integrating with external systems)
- Dialogue safety and alignment (responding appropriately to adversarial or ambiguous prompts)
This is made possible by massive context windows and improved model architectures, allowing the LLM to process more information and follow longer or more nuanced chains of reasoning.
Modern benchmarks specifically evaluate these abilities:
- MT-Bench (developed by LMSYS) focuses on multi-turn dialogue and reasoning, providing an automated and human-rated comparison of LLMs’ conversational and task-solving skills
- Chatbot Arena is a crowd-sourced leaderboard that pits models head-to-head in blind comparisons, measuring real-world user preferences and dialogue robustness
- Holistic Evaluation of Language Models (HELM) and other leaderboards further assess generalization, robustness, and fairness in in-context and zero-shot scenarios
A practical advantage of in-context learning is that developers can rapidly adapt LLMs to new domains or tasks simply by providing a small set of relevant examples or instructions, without the need for model retraining. For instance, when using an LLM as a research or coding assistant, you can “teach” it your preferred style or requirements simply by including those examples in your prompt.
With these advances, modern LLMs not only perceive the intention from a few examples, but they can often compete with or surpass domain-specific models on many reasoning and generation tasks, simply through in-context adaptation.
Understanding complex contexts
Section titled “Understanding complex contexts”LLMs excel at understanding complex contexts thanks to their deep neural architectures, extensive training on diverse data, and ever-increasing parameter counts. This enables them to comprehend subtle nuances in topics, styles, and intent, even when reasoning over ambiguous or technical language.
Recent state-of-the-art models have further advanced these capabilities by dramatically expanding their context window: the amount of information they can process in a single interaction. Where earlier models were limited to just a few thousand tokens, today’s leading LLMs, such as Gemini 1.5, Claude 3 Sonnet, GPT-4.5, and others, support context windows ranging from 200,000 to over 1 million tokens. This leap allows these models to read, synthesize, and summarize entire books, lengthy reports, or multi-document conversations. It also enables the models to support advanced use cases such as RAGs, where the LLM can reference and reason over large external knowledge bases or document collections. Moreover, having such large context windows lets LLMs maintain continuity across extended dialogues or complex workflows.
In addition, the newest LLMs are increasingly multi-modal, making them capable of understanding and generating not just text, but also images, tables, and even audio. For instance, Gemini 1.5, GPT-4.5, and Claude 3 Sonnet can analyze images and charts, answer questions about them, and seamlessly blend visual and textual reasoning. This unlocks new applications in fields such as document analysis, medical imaging, scientific research, and multimedia content creation.
For example, a modern LLM can now summarize a complicated scientific article with embedded figures, extract key trends from a financial report, or assist a user in analyzing both the written and visual content of a technical manual, all within a single, unified workflow.
By combining long-context understanding and multi-modal processing, the latest LLMs set a new bar for contextual comprehension, making them powerful tools for complex real-world tasks.
Multilingual capabilities
Section titled “Multilingual capabilities”Modern LLMs have pushed the boundaries of multilingual understanding, making it possible to support high-quality language tasks for users around the globe. Unlike earlier models that focused on translation or single-task multilinguality, today’s leading LLMs demonstrate robust, near-human-level performance across dozens or even hundreds of languages, enabling global applications in research, business, education, and beyond.
State-of-the-art multilingual LLMs include the following:
- Gemini 1.5: Excels in cross-lingual tasks, supports over 100 languages, and achieves top scores on multilingual reasoning and translation benchmarks
- GPT-4o: Delivers strong multilingual capabilities, offering high-quality text generation, understanding, and translation for more than 50 languages, with especially notable improvements in low-resource languages
- Claude 3 models: Demonstrates competitive performance in multilingual dialogue and comprehension, with strengths in both high-resource and underrepresented languages
- DeepSeek-V3: An open source model showing impressive results in language generation and translation tasks across many languages
- Llama 3 and 4: Open-weight models with advanced multilingual coverage, achieving parity or near-parity with top closed models on major benchmarks
Recent models are evaluated on rigorous benchmarks such as FLORES-200, which measures translation quality across 200 languages, and XTREME, which assesses cross-lingual understanding and information retrieval, covering 40 typologically diverse languages. For the first time, open source models such as Llama 3 and DeepSeek-V3 are rivaling or exceeding the performance of proprietary models in many languages, especially for widely spoken or well-resourced languages.
Here are the key leaderboard results:
- On FLORES-200, Gemini 1.5, GPT-4o, and Llama 3/4 all achieve BLEU and COMET scores approaching or matching human-level performance in translation for many language pairs
- On XTREME, Claude 3 and Llama 3/4 demonstrate robust performance in cross-lingual retrieval, NER, and QA, further closing the gap between open and closed models
This new era of multilingual LLMs means organizations can deploy global, language-inclusive applications with confidence, whether leveraging closed platforms or fully open models. Multilingual LLMs now enable use cases such as multilingual chatbots, document search, automated translation, and inclusive digital assistants, supporting a truly global user base.
Human-like text generation
Section titled “Human-like text generation”Today’s leading LLMs set a new bar for human-like text generation, producing responses that are increasingly indistinguishable from those written by people. They can conduct nuanced conversations, write essays and technical articles, compose poetry and stories, and even adapt their style to match a specific user’s preferences or a particular domain.
Recent advances have been validated by large-scale human evaluations:
Benchmarks such as MT-Bench and Chatbot Arena crowdsource and aggregate direct human ratings for qualities such as coherence, helpfulness, harmlessness, and creativity. On these leaderboards, models such as GPT-4o, Claude 3.5, Gemini 1.5 Pro, and Mistral Large have scored at or near human-level performance, sometimes even exceeding the ratings given to expert human annotators in structured tests.
MT-Bench evaluates models across multi-turn conversations, requiring them to maintain consistency, remember context, and follow nuanced instructions. Chatbot Arena uses head-to-head “blind” conversations to collect user preferences, revealing which models users prefer in real-world dialogue.
Modern LLMs excel not only in single-turn tasks, but also in multi-turn dialogue, demonstrating memory, reasoning, and contextual awareness over extended conversations. They can leverage tool use (such as calling APIs or integrating with databases), generate code, and create structured data (such as JSON or tables). We will touch on all of those in later chapters, and we will apply those in code. Also, thanks to multi-modal models such as Gemini 1.5, GPT-4o, and Claude 3 Sonnet, modern LLMs produce or interpret images, charts, and even audio.
Risks and considerations
Section titled “Risks and considerations”While the progress is remarkable, deploying human-like LLMs comes with new challenges. These include ensuring the models do not produce misleading or biased outputs, managing resource and energy demands, and addressing privacy and safety risks. Research continues into responsible deployment, model interpretability, and robust evaluation, helping organizations take full advantage of these generative models while minimizing potential harm. In the next section, we will expand on risk causes.
As shown in Table 7.2, the scale and diversity of state-of-the-art LLMs have expanded rapidly, getting bigger, with more capabilities and functionalities.
| Model | Developer | Params | Multi-modal? | Context Window | Reference |
|---|---|---|---|---|---|
| OpenAI’s LLMs | OpenAI | Estimated above 1T | Text, Code, Image | 128K-1M | OpenAI’s Models page |
| Claude 4 Opus | Anthropic | Estimated above 1T | Text, Code, Image | 200K | Anthropic’s Models page |
| Gemini 2.5 Pro | Google DeepMind | Unknown | Text, Code, Image, Audio | 1M+ | Google’s 2.5 Pro model page |
| Mistral Large 2 | Mistral AI | 123B | Text, Code | 128K | Mistral’s Models page |
| Llama 3.1 405B Instruct | Meta AI | 405B | Text, Code, Image | 128K | Llm-stats.com |
| DeepSeek-V3 | DeepSeek | 671B | Text, Code, Image | 131K | Llm-stats.com |
Table 7.2 – Newer LMs and their details
Challenges in developing LLMs
Section titled “Challenges in developing LLMs”Developing LLMs poses a unique set of challenges, including but not limited to handling massive amounts of data, requiring vast computational resources, and the risk of introducing or perpetuating bias. The following subsections outline the detailed explanations of these challenges.
Amounts of data
Section titled “Amounts of data”LLMs require enormous amounts of data for training. As the model size grows, so does the need for diverse, high-quality training data. However, collecting and curating such large datasets is a challenging task. It can be time-consuming and expensive. There’s also the risk of inadvertently including sensitive or inappropriate data in the training set. To have more of an idea, BERT has been trained using 3.3 billion words from Wikipedia and BookCorpus. GPT-2 has been trained on 40 GB of text data, and GPT-3 has been trained on 570 GB of text data. Table 7.3 shows the number of parameters and the size of training data of a few early LMs.
| Mode l | Parameters | Size of training data |
|---|---|---|
| GPT-3.5 | 175 B | 300 billion tokens |
| GPT-3 | 175 B | 300 billion tokens |
| PaLM | 540 B | 780 billion tokens |
| LLaMA | 65 B | 1.4 trillion tokens |
| Bloom | 176 B | 366 billion tokens |
Table 7.3 – Number of parameters and training data of a few early models
Recent LLMs such as GPT-4o, Claude 4, and Gemini 2.5 are trained on corpora estimated at trillions of tokens, collected from multilingual, multi-modal, and high-quality domain-specific sources. The details are often proprietary, but the data scale is at least an order of magnitude larger than earlier LLMs.
Computational resources
Section titled “Computational resources”Training LLMs requires substantial computational resources. These models often have billions or even trillions of parameters and need to process vast amounts of data during training, which requires high-performance hardware (such as GPUs or TPUs) and a significant amount of time. This can be costly and could limit the accessibility of developing such models to only those who have these resources. For example, training GPT-3 took 1 million GPU hours, which cost around 4.6 million dollars (in 2020). Table 7.4 shows the computational resources and training time of a few early models.
| Model | Hardware | Training time |
|---|---|---|
| LLaMA | 2048 80G A100 | 21 days |
| Bloom | 384 80G A100 | 105 days |
| GPT-3 | 1024x A100 | 34 days |
| GPT-4 | 25000 A100 | 90–100 days |
Table 7.4 – The hardware and training time of a few early LMs
Training the latest models, which are more demanding than GPT-4, may involve tens of thousands of high-end GPUs or TPUs over months, with compute budgets measured in tens of millions of dollars.
Risk of bias
Section titled “Risk of bias”LLMs can learn and perpetuate biases present in their training data. This could be explicit bias, such as racial or gender bias in the way language is used, or more subtle forms of bias, such as the underrepresentation of certain topics or perspectives. This issue can be challenging to address because bias in language is a deeply rooted societal issue, and it’s often not easy to even identify what might be considered bias in a given context.
The scale and diversity of today’s LLMs do help mitigate some forms of bias, but new risks emerge, especially for languages, dialects, or modalities that are underrepresented in the training data. Prompt injection, social engineering, and adversarial prompts can trigger biases or undesirable behavior.
Model robustness
Section titled “Model robustness”It’s challenging to ensure that LLMs will perform well in all possible scenarios, particularly on inputs that differ from their training data. This includes dealing with ambiguous queries, handling out-of-distribution data, and ensuring a level of consistency in the responses. Making sure that the model is not overtrained can help to have a more robust model, but much more is needed to have a robust model.
Robustness is also challenged by the rise of multi-modal and multi-agent systems. Ensuring consistent, safe, and reliable outputs when LLMs are exposed to novel visual or audio inputs, or when collaborating as part of larger agentic systems, remains an open research area.
Interpretability and debugging
Section titled “Interpretability and debugging”LLMs, like most deep learning models, are often described as “black boxes.” Understanding why a model makes a particular prediction or how it arrives at a conclusion remains a significant challenge. This lack of transparency complicates debugging, especially when the model produces incorrect, unexpected, or inappropriate outputs. Improving interpretability is an active and critical area of research.
Classic interpretability methods include feature importance analysis and input perturbation, where parts of the input (such as individual words) are removed or altered and the resulting change in output is observed. Gradient-based methods can help identify which input components have the greatest influence on the model’s prediction. Libraries such as LIME and SHAP provide practical tools for these analyses, making model interpretation more accessible.
In today’s LLM landscape, interpretability efforts have expanded in scope and complexity. Here are some aspects of the modern interpretability of language models:
- For multi-modal models, researchers are now developing attribution techniques that highlight which parts of an image, table, or audio file most influenced the model’s response, in addition to textual explanations.
- With multi-turn and agentic workflows, using tools such as LangGraph and AutoGen, which we’ll touch on later in the book, interpretability includes tracking the internal state and decision paths of the LLM across an extended dialogue or task sequence. This is especially important for debugging when the model is used as part of a larger, tool-using, or agentic system.
- As LLMs increasingly integrate with external tools such as APIs, databases, and code executions, it becomes necessary to trace not just the model’s textual reasoning, but also the sequence of actions and tool calls, and to understand how external data shapes the final output.
Safety and security considerations
Section titled “Safety and security considerations”As LLMs boom, especially open source models, new safety and supply-chain risks have emerged:
- Open source models are easier for adversaries to modify or “jailbreak,” making it possible to bypass safety filters, introduce malicious behaviors, or repurpose models for harmful tasks.
- The risk of malicious model modifications—for example, inserting backdoors, trojans, or data poisoning during pretraining—is an increasing concern, both for proprietary and open models. This threat extends across the supply chain: from training data curation to model distribution.
- Prompt injection and adversarial inputs remain active attack vectors, especially for LLMs that are integrated into software tools, browsers, or cloud services.
Best practices for interpretability and safety now include the following:
- Regular auditing and red teaming of models to identify vulnerabilities
- Transparency in model architecture, training processes, and data sources
- Provenance tracking and cryptographic signing of open model weights to help guard against supply-chain attacks
- Ongoing research into explainable AI for multi-modal and multi-agent systems
With multi-modal and open source models, data leakage and privacy risks are growing. Attackers may use prompt injection to extract confidential data or exploit model outputs for social engineering. As LLMs continue to expand their reach, the intertwined challenges of interpretability, debugging, and safety are more important than ever for both researchers and practitioners.
Environmental impact
Section titled “Environmental impact”The high computational resources needed for training LLMs can have significant environmental implications. The energy required for training these models can contribute to carbon emissions, which is a concern from a sustainability perspective.
The community has begun to address environmental concerns via shared compute facilities, more energy-efficient architectures (e.g., sparsity, quantization), and carbon impact tracking/reporting.
Example designs of state-of-the-art LLMs
Section titled “Example designs of state-of-the-art LLMs”In this section, we examine the design and architectural choices behind several state-of-the-art LLMs. The goal is not to catalog models exhaustively, nor to rank them. We will instead illustrate how the concepts introduced earlier in this chapter materialize in real systems. You will see how foundational ideas such as Transformer architectures, scaling laws, training objectives, alignment techniques, and evaluation considerations are applied in practice. These examples highlight both shared design patterns across modern LLMs and the trade-offs different organizations make depending on their priorities.
This discussion also serves a broader purpose within the book. Understanding how leading LLMs are built provides context for later chapters that focus on fine-tuning, retrieval-augmented generation, agentic systems, evaluation, and real-world deployment. Rather than treating LLMs as black boxes, we encourage you to reason about model behavior in terms of architectural and training decisions.
It’s important to note that while specific models may change over time, the design principles explored here are durable and transferable. You’ll have the conceptual tools needed to evaluate new LLMs as they emerge, rather than relying solely on benchmark scores or marketing claims.
GPT models and their use in ChatGPT
Section titled “GPT models and their use in ChatGPT”LLMs in the GPT series have evolved rapidly. Early versions of ChatGPT were powered by GPT-3.5, an autoregressive model trained on large corpora of text to predict the next token in a sequence. As OpenAI has developed more advanced models, ChatGPT has been updated: it now uses GPT-5.X models with enhanced intelligence, faster performance, and broader multimodal capabilities.
It is important to distinguish between GPT models and ChatGPT itself. GPT-3.5, GPT-4, and GPT-5.X are LLMs (i.e., statistical engines that generate text by modeling token sequences). ChatGPT, on the other hand, is a user interface product built on top of these models. It wraps a GPT engine in a conversational interface and adds layers for memory, safety filtering, user preferences, and tool integration. In other words, GPT provides the core language-generation engine, while ChatGPT provides a polished, user-friendly experience with additional controls and plugins.
What GPT models are
Section titled “What GPT models are”GPT models are Transformer-based, autoregressive LLMs. They process text from left to right and are trained to predict the next token given the preceding tokens. This unidirectional design makes them well-suited for generating coherent sequences of text. GPT-3, one of the early models underpinning ChatGPT, contains around 175 billion parameters. Later models such as GPT-4 and GPT-5 scale to much larger sizes, widely estimated to exceed one trillion parameters, although OpenAI has not officially disclosed the exact parameter counts or architectural details. Each new generation typically expands the context window, improves factuality and reasoning, and adds multimodal capabilities. Starting from GPT-4 and GPT-4o, LLMs have been accepting both text and images in prompts. GPT-4o also introduces faster token processing and improved memory handling for interactive use.
Training pipeline: pretraining and alignment
Section titled “Training pipeline: pretraining and alignment”The development of GPT models follows a two-phase training pipeline. In the pretraining phase, the model learns general language patterns using causal (next-token) language modeling. It is trained on a diverse mixture of publicly available and licensed text data to maximize the likelihood of each token given its previous context.
Formally, the training dataset
consists of tokenized text sequences, where each sequence
. The model is trained to maximize the log-likelihood of each token
, conditioned on its preceding tokens, across the entire dataset:

where θ denotes the model parameters and is the autoregressive probability distribution implemented using Transformer-based architecture, typically a decoder-style variant such as GPT. This training paradigm is known as causal language modeling (CLM).
Importantly, the dataset is composed of publicly accessible text, but the model does not memorize or store specific documents. Rather, it learns to model general statistical patterns and syntactic-semantic relationships in language.
After pretraining, the model undergoes a fine-tuning phase designed to align its outputs more closely with human intent and safety standards. This phase includes both supervised learning and reinforcement learning with human feedback (RLHF). Initially, supervised fine-tuning (SFT) is performed using a dataset, where each is a human-written prompt and is the ideal response. Supervised fine-tuning and RLHF will be explained in detail in the next chapter.
Efficiency and rumors of mixture-of-experts
Section titled “Efficiency and rumors of mixture-of-experts”OpenAI’s GPT-4 technical report notes that GPT-4 is still a Transformer-based model, but it does not disclose the model size or detailed architecture. Industry analysts and independent researchers have speculated that GPT-4 might use MoE techniques to scale efficiently, where only a subset of specialized experts is activated for each token. However, these details remain unverified; the key takeaway for practitioners is that GPT-4 and GPT-4o achieve higher performance without a proportional increase in inference cost. When comparing models, it is better to focus on measurable improvements such as reasoning ability, factual accuracy, and speed rather than speculative internal designs.
GPT-5 series
Section titled “GPT-5 series”Since late 2025, OpenAI has released GPT-5 and incremental updates such as GPT-5.1 and GPT-5.2. These models are marketed as a unified system with multi-stage routing and improved reasoning. Public announcements highlight features such as enhanced conversational warmth, better tool use, and expanded multimodal capabilities, but there are no official technical specifications regarding parameter counts, architecture, or training data. Analysts therefore treat the GPT-5 series as an evolutionary step focused on product experience rather than a disclosed architectural breakthrough. For now, the important point is that ChatGPT continues to evolve alongside its underlying GPT engine, and newer versions of the model offer practical improvements even if their internal details remain proprietary.
Understanding how GPT models are constructed and trained lays the groundwork for subsequent chapters. The next chapter delves deeper into alignment, explaining supervised fine-tuning, RLHF and direct preference optimization. These methods convert a powerful but generic language model into a helpful, safe, and task-adaptable assistant.
Large Language Model Meta AI (LLaMA) is a family of autoregressive, decoder-only Transformer models designed to achieve strong performance with fewer parameters compared to models such as GPT-3. Architecturally, it follows the standard Transformer design with stacked self-attention and feed-forward layers connected via residual paths, but it introduces several innovations to improve efficiency, stability, and long-context performance.
One of the first changes is the replacement of LayerNorm with Root Mean Square Normalization (RMSNorm), which normalizes activations using only their root mean square instead of subtracting the mean. Given a hidden vector, RMSNorm is defined as:

where is a learned weight vector. This design reduces computation and improves stability for deep networks by avoiding mean subtraction.
The feed-forward networks in LLaMA use SwiGLU, a gated activation variant that improves expressiveness. Given an input x and learned weight matrices, SwiGLU is defined as:
where σ is the SiLU (Swish) activation function and ⊙ denotes elementwise multiplication. The gating mechanism allows the network to control information flow more effectively than ReLU or GELU.
Another key novelty is Rotary Position Embeddings (RoPE), which injects relative positional information directly into the query and key vectors of the self-attention mechanism. For a token at position with embedding vector, RoPE applies a rotation in 2D subspaces of the embedding dimension:
where is a block-diagonal rotation matrix with angles proportional to the position. This allows the attention mechanism to natively handle relative positions and extrapolate better to longer sequences.
Together, these innovations—RMSNorm for stable normalization, SwiGLU for more expressive feed-forward layers, and RoPE for efficient positional encoding—allow LLaMA to deliver high performance with optimized training efficiency and strong generalization to long-context scenarios. Later versions further extend context length using Grouped Query Attention (GQA), enabling the models to scale to 8K tokens or more without a proportional increase in computational cost.

Figure 7.2: The Llama architecture
Claude
Section titled “Claude”Claude, developed by Anthropic, is a family of LLMs that follows the standard decoder-only Transformer architecture, similar to models such as GPT, but with several unique optimizations aimed at efficiency, safety, and alignment. At its core, Claude is built on stacked Transformer blocks that consist of causal self-attention layers and feed-forward networks connected via residual connections and pre-normalization layers. These blocks process token embeddings augmented with positional information, possibly through rotary or relative positional embeddings, which enable the model to handle long sequences efficiently. Claude’s feed-forward layers possibly use modern activations such as SwiGLU, which improve expressiveness while maintaining computational efficiency, and pre-normalization (e.g., RMSNorm) is used to stabilize very deep models.
The architectural novelties of Claude focus heavily on long-context handling and safety-oriented training. Claude models, especially Claude 2 and 3, can process sequences exceeding 100K tokens, which is achieved through memory-efficient attention mechanisms such as Grouped Query Attention (GQA) or similar optimizations. This allows Claude to retain performance on long documents without a proportional increase in computation or memory usage. Another notable aspect is its integration of constitutional AI during training and fine-tuning. Instead of relying solely on traditional RLHF, Claude uses a “constitution” of predefined ethical and behavioral principles to guide self-critique and self-revision. This approach allows the model to evaluate its own outputs, reduce harmful or biased responses, and align with safety principles without requiring extensive human ranking for every response.
Overall, Claude’s novelty lies in its combination of efficient, scalable Transformer design and a unique alignment methodology. Its architecture is optimized for handling extremely long contexts, and its fine-tuning pipeline leverages constitutional AI to produce outputs that are helpful, honest, and harmless (HHH). By pairing modern Transformer efficiency techniques with principled self-alignment, Claude achieves a balance between raw language modeling performance and trustworthy, safe interactions.
Gemini
Section titled “Gemini”Gemini, the multimodal LLM developed by Google DeepMind, represents a significant evolution in artificial intelligence, extending beyond the capabilities of traditional LLMs and even advanced systems such as GPT-4. Unlike prior models that are primarily text-centric with added visual capabilities, Gemini is conceived as natively multimodal, integrating text, images, audio, and potentially video into a unified architecture. This design enables seamless cross-modal reasoning and allows the model to perform tasks that require a holistic understanding of both linguistic and visual information.
At its core, Gemini is built upon the Transformer architecture but incorporates substantial innovations inspired by Google’s Pathways framework. The model leverages a combination of an autoregressive Transformer decoder for language modeling and a multimodal encoder-projection system that aligns various input modalities into a shared latent space. Images, audio, and other non-text inputs are first converted into embeddings and projected into the same representational space as text tokens. This alignment allows the attention mechanism of the Transformer to operate across modalities in a unified manner, enabling the model to reason about relationships between language and perception.
Another notable innovation in Gemini is its possible use of MoE and conditional computation. Rather than activating all parameters for every input, the model dynamically routes tokens to a subset of specialized expert networks, selected via a gating function.
This approach allows Gemini to scale to trillions of parameters without incurring the full computational cost of a dense model while enabling specialization among experts for different modalities or task domains. In practice, this results in improved efficiency and enhanced performance on complex reasoning tasks, long-context analysis, and multimodal comprehension.
Gemini also distinguishes itself in its handling of long-context reasoning. Experimental reports suggest that the model supports input lengths extending to hundreds of thousands, and in some cases up to one million tokens. Achieving this capability requires efficient attention mechanisms, such as those inspired by Flash Attention, and positional encoding methods with strong extrapolation properties, likely rotary position embeddings (RoPE). This extended context window allows the model to process long documents, multi-step instructions, or even extended video and audio sequences while maintaining coherence and contextual understanding across large spans of input.
Safety and alignment are central to Gemini’s design, reflecting DeepMind’s emphasis on responsible AI. The model employs RLHF and reinforcement learning from AI feedback (RLAIF), integrating both text and multimodal reward signals. The reward function is defined over entire output trajectories, accounting for correctness, safety, and human preference:
where is a multimodal reward model, and the KL term stabilizes alignment with a reference policy. This approach allows the model not only to generate accurate outputs but also to remain sensitive to safety constraints in both textual and visual contexts.
Through this combination of native multimodality, expert-based conditional computation, long-context reasoning, and robust alignment, Gemini achieves a level of performance and versatility that surpasses previous models in real-world applicability. It can synthesize information across text and visual inputs, navigate large code bases, analyze complex documents, and interpret diagrams or multimedia content with a unified reasoning approach. More than a scaled-up language model, Gemini embodies a new generation of AI systems designed to operate as general-purpose, multimodal reasoning agents, moving closer to practical artificial general intelligence.
DeepSeek
Section titled “DeepSeek”DeepSeek represents a major advancement in the field of LLMs, originating from the Hangzhou-based firm under the High-Flyer hedge fund. Established in 2023, the initiative has rapidly gained international attention for producing models that rival the capabilities of state-of-the-art systems such as GPT-4 and Claude 3, while operating at a fraction of their computational and financial cost. This achievement is enabled through an innovative sparsely activated MoE architecture, combined with highly efficient optimization techniques that reduce both resource requirements and training overhead.
The flagship model, DeepSeek-V3, is a 671-billion-parameter Transformer with MoE specialization, of which approximately 37 billion parameters are activated per token. This sparse-activation mechanism is managed by DeepSeekMoE, which incorporates an auxiliary-loss-free load-balancing strategy, ensuring that expert networks are effectively utilized without introducing instability during training. In addition, the model introduces Multi-head Latent Attention (MLA), designed to improve long-context reasoning efficiency, and adopts multi-token prediction objectives to accelerate convergence. Leveraging these design principles, DeepSeek-V3 was trained on 14.8 trillion tokens, consuming fewer than 3 million GPU-hours on NVIDIA H800 clusters, at a total cost of reportedly under 6 million USD—demonstrating a drastic improvement in training efficiency relative to comparable large-scale LLM projects.
Expanding upon this foundation, DeepSeek-R1 was developed as a reasoning-centric model, capable of advanced multi-step problem-solving and chain-of-thought generation. Its initial variant, R1-Zero, was trained exclusively via reinforcement learning (RL) without any prior supervised fine-tuning, resulting in emergent reasoning behaviors such as self-reflection and verification. However, the outputs of R1-Zero were often poorly structured and exhibited language mixing. The refined DeepSeek-R1 overcomes these limitations by integrating cold-start supervised data and adopting Group Policy Optimization (GPO), a novel RL-based training paradigm that enhances the model’s reasoning stability and alignment.
GPO generalizes standard policy-gradient reinforcement learning by optimizing model policies over groups of related trajectories rather than individual samples, thereby improving sample efficiency and consistency across semantically linked inputs. Let denote the model’s policy, and Rϕ a multimodal or text-based reward function. For a group of related prompts G⊂g, the objective function can be expressed as:

where is a reference policy, and β controls the trade-off between reward maximization and divergence from the reference distribution. This approach allows DeepSeek-R1 to generate coherent reasoning chains across similar queries while maintaining stability and alignment throughout the optimization process.
Through the combination of MoE sparsity, multi-token prediction, and GPO, DeepSeek models have achieved exceptional results on reasoning and knowledge benchmarks such as MMLU, GSM8K, HumanEval, and USMLE, often approaching or surpassing the performance of leading proprietary systems. The reasoning-enhanced architecture also enables efficient long-context inference and chain-of-thought generation, making DeepSeek models particularly effective in mathematics, coding, and scientific domains.
Despite these advancements, DeepSeek models still present notable safety challenges, including hallucinations, cultural and linguistic biases, and susceptibility to adversarial prompts. Evaluations such as CHiSafetyBench emphasize the necessity for continued research in alignment and robustness. Nevertheless, the open source release of R1’s distilled models (ranging from 1.5 billion to 70 billion parameters) under permissive licenses has made DeepSeek a disruptive force in global AI research. By demonstrating that competitive frontier-level LLMs can be trained at low cost while maintaining high reasoning capability, DeepSeek fundamentally challenges existing paradigms in large-scale AI development and deployment.
PaLM is a 540-billion-parameter, densely activated Transformer LM that was trained on 6,144 TPU v4 chips using Pathways, a new ML system that enables highly efficient training across multiple TPU pods.
PaLM has been shown to achieve breakthrough performance on a variety of natural language tasks, including the following:
- Multi-step reasoning tasks
- The recently released Beyond the Imitation Game Benchmark (BIG-bench)
- Multilingual tasks
- Source code generation
The BIG-bench benchmark is worth expanding on as it serves as a recognized collection of benchmarks to measure against. BIG-bench is an extensive assessment mechanism specifically designed for large-scale LMs. It is a broad-based, community-focused benchmark that presents a diversity of tasks to evaluate a model’s performance in different disciplines and its competence in natural language comprehension, problem-solving, and reasoning. With a total of 204 tasks from 450 contributors across 132 institutions, BIG-bench covers an eclectic mix of subjects, including linguistics, childhood development, mathematics, common-sense reasoning, biology, physics, software development, and even social bias. It concentrates on challenges believed to be currently beyond the reach of existing LMs. The primary goal of BIG-bench extends beyond mere imitation or Turing test-style evaluations, aiming instead for a deeper, more nuanced appraisal of the abilities and constraints of these large models. This initiative is founded on the conviction that an open, collaborative approach to evaluation paves the way for a more comprehensive understanding of these LMs and their potential societal ramifications.
PaLM 540B excels beyond the fine-tuned state-of-the-art across various multi-step reasoning tasks and surpasses average human performance on the BIG-bench benchmark. Many BIG-bench tasks exhibit significant leaps in performance as PaLM scales to its largest size, demonstrating discontinuous improvements from the model scale. PaLM also has strong capabilities in multilingual tasks and source code generation. For example, PaLM can translate between 50 languages, and it can generate code in a variety of programming languages.
The authors of the PaLM paper also discuss the ethical considerations related to LLMs, and they discuss potential mitigation strategies. For example, they suggest that it is important to be aware of the potential for bias in LLMs and that it is important to develop techniques for detecting and mitigating bias.
PaLM employs the conventional Transformer model architecture in a decoder-exclusive setup, which allows each timestep to attend only to itself and preceding timesteps. Several modifications were applied to this setup, including the following:
- SwiGLU activation: Instead of standard ReLU, GeLU, or Swish activations, PaLM utilizes SwiGLU activations (Swish(xW) · xV) for multilayer perceptron (MLP) intermediate activations due to their superior performance in enhancing quality. This approach, however, requires three matrix multiplications in the MLP as opposed to the conventional two.
- Parallel layers: Rather than the typical “serialized” approach, PaLM uses a “parallel” formulation for each Transformer block.
- The standard structure is given by the following:

- The parallel structure is instead the following:
- The standard structure is given by the following:
This leads to roughly 15% quicker training speed at larger scales due to the fusion of MLP and attention input matrix multiplications.
- Multi-query attention: In the conventional Transformer formulation, k attention heads are employed. For each timestep, the input vector is linearly projected into query, key, and value tensors, which have a shape of [k, h], where h denotes the size of the attention head. In the new approach, the projections for “key” and “value” are shared across all heads, meaning “key” and “value” are projected to [1, h], while “query” maintains the shape [k, h]. The authors claimed that this approach doesn’t notably affect model quality or training speed, while it does result in significant cost reductions during autoregressive decoding. The reason for this lies in the inefficiency of standard multi-headed attention on accelerator hardware during autoregressive decoding, as the key/value tensors are not shared across examples and only one token is decoded at each moment.
- Rotary Position Embedding (RoPE) embeddings: RoPE embeddings, shown to perform better on longer sequence lengths, are preferred over absolute or relative position embeddings.
- Shared input-output embeddings: The input and output embedding matrices are shared, a practice that is common, though not universal, in previous work.
- No biases: The model abstains from using biases in any dense kernels or layer norms, which enhances training stability for larger models.
- Vocabulary: PaLM uses a 256k-token
SentencePiecevocabulary designed for diverse languages in the training corpus, ensuring efficient training without excessive tokenization. This preserves all whitespaces and out-of-vocabulary Unicode characters while splitting numbers into individual digit tokens for clarity.
Overall, PaLM is a powerful LM that has the potential to be used for a wide variety of applications. It is still under development, but it has already demonstrated the ability to achieve breakthrough performance on a number of tasks.
It is interesting to note that each of these models has its own strengths and weaknesses, and the best choice of model can depend on the specific task, the amount and type of available training data, and the computational resources available.
Evaluation
Section titled “Evaluation”Evaluation in generative AI is fundamentally different from evaluation in traditional supervised learning. In classification tasks, performance can often be summarized with a single metric such as accuracy or F1 score against a fixed ground truth. Generative models, however, produce open-ended outputs where multiple answers may be acceptable, partially correct, stylistically different, or subtly flawed. As a result, evaluation is no longer just about matching labels but instead about assessing behavior across reasoning, factual grounding, safety, robustness, and overall linguistic quality.
This distinction matters because a model can achieve low perplexity or strong benchmark accuracy while still hallucinating facts, failing under adversarial prompts, or producing unsafe outputs in edge cases. Project-level deployment exposes these failure modes quickly, especially in domains such as healthcare, legal analysis, or financial decision-making. For this reason, evaluation frameworks have expanded beyond traditional training metrics to include multiple dimensions that reflect how LLMs are actually used.
In the following sections, we examine these dimensions in detail, beginning with perplexity as a foundational language modeling metric and then moving toward broader assessments of reasoning, factuality, safety, robustness, fluency, coherence, and diversity.
Perplexity and language modeling performance
Section titled “Perplexity and language modeling performance”A foundational metric in language modeling is perplexity, which measures how well a language model predicts a sequence of tokens. Perplexity is derived directly from the probabilistic objective used during model training and is closely tied to next-token prediction.
Intuitively, perplexity reflects a model’s uncertainty when generating text. A lower perplexity indicates that the model assigns higher probability to the observed tokens and is therefore more confident in its predictions. Formally, perplexity is defined as the exponential of the average negative log-likelihood of the tokens in a dataset. For a token sequence, perplexity can be expressed as:

Because autoregressive LLMs such as GPT models are trained to maximize this likelihood, perplexity has historically served as a primary metric for evaluating language models during training and benchmarking. Improvements in perplexity generally correlate with better fluency and grammatical correctness in generated text.
However, perplexity has important limitations. It evaluates a model’s ability to predict the next token, not its ability to reason, follow instructions, remain factual, or behave safely. Two models with similar perplexity scores can exhibit markedly different behavior when performing tasks such as multi-step reasoning, code generation, or conversational interaction.
As LLMs have evolved from pure language models into general-purpose reasoning and interaction systems, evaluation has expanded beyond perplexity. Modern assessment frameworks incorporate task-specific benchmarks for reasoning, factuality, robustness, safety, and human preference alignment. In practice, perplexity remains a useful diagnostic metric during training and ablation studies, but it is no longer sufficient as a standalone measure of overall LLM quality.
The following subsections introduce evaluation methods that better capture these broader capabilities.
Reasoning evaluation
Section titled “Reasoning evaluation”Reasoning measures whether a model can solve tasks using logical, step-by-step thinking rather than memorization or pattern-matching. It is crucial for tasks such as multi-hop question answering, mathematics, coding, and structured problem-solving. A model’s reasoning ability can be evaluated using datasets such as GSM8K (arithmetic reasoning), MMLU (multi-task reasoning), and ARC-Challenge (commonsense reasoning).
To measure reasoning, accuracy is commonly computed as

However, modern reasoning evaluation also considers chain-of-thought (CoT) consistency, where each intermediate step is assessed for logical validity. In some evaluations, step-level accuracy is calculated:

Reasoning evaluation often combines automatic scoring with human assessment, especially when intermediate steps are complex or require domain expertise.
Factuality evaluation
Section titled “Factuality evaluation”Factuality measures whether model outputs are truthful and grounded in real-world knowledge, avoiding hallucinations. This is critical in knowledge-intensive applications such as medical, legal, or scientific question answering.
In closed-domain tasks with reference answers, factuality is often evaluated using BLEU and ROUGE metrics:
- BLEU (Bilingual Evaluation Understudy) measures n-gram precision, evaluating how much of the generated output overlaps with the reference text:

Where:
- = precision of n-grams of length n
- = weight for each n-gram (usually uniform)
- BP = brevity penalty to penalize overly short outputs
- ROUGE (Recall-Oriented Understudy for Gisting Evaluation) primarily measures n-gram recall, checking how much of the reference appears in the generated output:

Factuality in open-domain settings often uses TruthfulQA,FactScore, or automated LLM-based verifiers that compare outputs against retrieved documents. Retrieval-augmented pipelines are commonly used to validate outputs against authoritative knowledge bases.
Safety evaluation
Section titled “Safety evaluation”Safety ensures the model is harmless, unbiased, and aligned with ethical principles. Unsafe outputs include toxicity, hate speech, illegal instructions, or content that violates privacy or fairness.
Safety evaluation often measures the probability of generating unsafe content:

Toxicity scoring can use classifiers such as Perspective API or Detoxify, producing a probability. Models are also evaluated using bias metrics, such as StereoSet or BiasBench, which measure the preference of a model toward stereotypical completions. Human red-teaming complements automatic evaluations, testing the model against adversarial prompts to ensure it avoids producing harmful outputs.
Robustness evaluation
Section titled “Robustness evaluation”Robustness measures whether a model is resilient to noise, adversarial prompts, and distribution shifts. A robust model should respond consistently even if inputs are paraphrased, contain typos, or include adversarial triggers.
A simple robustness score can be defined as:

Robustness is often tested with adversarial datasets such as AdvGLUE or Dynabench, and against prompt-injection attacks. Stability can also be quantified using output variance—models that generate widely different outputs for similar inputs are considered less robust.
Fluency, coherence, and diversity
Section titled “Fluency, coherence, and diversity”Beyond the core evaluation dimensions, fluency and coherence measure how natural and readable the outputs are, while diversity ensures the model avoids repetitive or generic responses.
- Fluency is often judged with BLEU, ROUGE, or BERTScore, and via human ratings
- Coherence measures whether the generated text is logically consistent across sentences
- Diversity is measured using Distinct-n:

High indicates the model avoids repetitive or dull outputs, improving user experience.
Some of the evaluation metrics for generative AI models, particularly in open-ended NLP tasks, are inherently difficult to assess using only human evaluators. While humans can reliably judge attributes such as fluency or coherence, evaluating reasoning correctness, factuality, and robustness can be challenging, time-consuming, and prone to inconsistency.
For example, reasoning evaluation often requires validating each step of a CoT to ensure the logic is sound. Humans may miss subtle reasoning errors, especially in long or technical outputs such as mathematical proofs, legal arguments, or programming tasks. Factuality is even more challenging because humans need to fact-check outputs against large knowledge bases or domain-specific sources. In tasks such as scientific QA or medical diagnosis, this requires subject-matter expertise, which is costly and limited. Similarly, robustness testing involves generating and reviewing hundreds of adversarial or paraphrased inputs, something that is tedious and error-prone for humans alone.
LLM-as-a-judge
Section titled “LLM-as-a-judge”Modern evaluation frameworks in generative AI increasingly rely on LLM-as-a-judge, a paradigm in which LLMs themselves serve as evaluators. In this approach, an LLM is either fine-tuned or carefully prompted to score, rank, or critique the outputs of other models according to predefined criteria such as reasoning validity, factual accuracy, safety, or stylistic quality. This method offers several notable advantages over purely human evaluation. First, it provides scalability, as an LLM can assess thousands of samples far more quickly than human annotators. Second, it offers consistency, because an LLM judge delivers reproducible scores and avoids the variability and fatigue that can affect human evaluators. Additionally, LLMs enable multi-dimensional evaluation, since they can assess reasoning, factuality, and stylistic alignment in a single pass. Through techniques such as self-consistency or cross-model voting, LLM judges can also enhance self-improvement by reducing biases when combining multiple judgments.
Formally, if we define an evaluation prompt, where x is the input and y is the model output, the LLM judge produces a score or a ranking among candidate responses:
In some cases, these judges act as chain-of-thought evaluators, generating intermediate reasoning steps that justify their scoring decisions. This methodology has been widely adopted in evaluation frameworks such as OpenAI’s Eval, Anthropic’s Constitutional AI, and DeepMind’s Gemini pipelines, forming the backbone of scalable model assessment.
Despite these advantages, human oversight remains critical to ensure reliability. LLM judges may inherit biases or produce hallucinated judgments, so hybrid evaluation strategies are considered best practice. In such an approach, LLMs conduct the first-pass scoring for reasoning, factuality, safety, and robustness across large datasets, while humans audit a subset of the results to validate and calibrate the scores. Any discrepancies are analyzed to refine prompts, evaluation protocols, or the LLM judge itself. This hybrid pipeline combines the efficiency of automated evaluation with the reliability and ethical oversight of human review.
Summary
Section titled “Summary”In this chapter, we examined the dynamic world of state-of-the-art LLMs, focusing on their architectures, capabilities, and evaluation methods. Modern models such as GPT-4, LLaMA, DeepSeek, and Gemini illustrate remarkable generalization across a wide variety of tasks, excelling at understanding nuanced contexts, performing complex reasoning, and generating coherent and contextually appropriate outputs.
We explored how these models achieve their performance through architectural innovations. LLaMA introduced efficiency-oriented features such as RMSNorm, SwiGLU activations, and RoPE positional encodings, enabling strong results with smaller models. GPT-4 pushed the frontier of language understanding and reasoning through advanced scaling and alignment methods. DeepSeek leveraged MoE to balance high capacity with cost-effective inference, while Gemini expanded into multi-modal reasoning and integrated stronger safety and reliability measures.
The chapter also discussed the evaluation of LLMs, emphasizing reasoning, factuality, safety, and robustness as critical dimensions of assessment. While traditional metrics such as BLEU and ROUGE remain useful for measuring n-gram similarity and summarization quality, modern evaluation increasingly employs LLM-as-a-judge approaches, where large models assess the outputs of other models at scale. These automated evaluations are combined with human auditing to ensure reliability and to detect subtle biases or errors.
Overall, this chapter provided a concise yet comprehensive overview of today’s LLM landscape, covering the key models, their architectural innovations, and the evolving methodologies used to evaluate their reasoning, factual correctness, and safety.
Questions
Section titled “Questions”- What is a language model (LM), and what makes an LLM meaningfully different in practice?
- Why did transformers become the dominant architecture over RNN-style models for large-scale language modeling?
- What does perplexity measure, and how should we interpret a lower perplexity score?
- Why does the chapter argue that perplexity alone is not sufficient to evaluate modern LLMs?
- Which evaluation dimensions does the chapter highlight beyond traditional language modeling performance?
- How does the chapter describe reasoning evaluation, and which benchmark examples does it mention?
- What are the major practical challenges in developing LLMs that the chapter highlights?
- How does the chapter distinguish GPT models from ChatGPT as a product?
- What is the chapter’s main point about rumors of mixture-of-experts architectures in GPT-4-class models?
- Why does the chapter introduce LLM-as-a-judge, and what advantage does it claim over purely human evaluation?
References
Section titled “References”- Hugging Face: huggingface.co
- Large language model: https://en.m.wikipedia.org/wiki/Large_language_model#
- Zhao, Wayne Xin, Kun Zhou, Junyi Li, Tianyi Tang, Xiaolei Wang, Yupeng Hou, Yingqian Min et al. “A survey of large language models.” arXiv preprint arXiv:2303.18223 (2023).
- LLM Leaderboard and descriptions: https://llm-stats.com/
- Introducing LLaMA: A foundational, 65-billion-parameter large language model: https://ai.facebook.com/blog/large-language-model-llama-meta-ai/
- Model Details: https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md
- Touvron, Hugo, Thibaut Lavril, Gautier Izacard, Xavier Martinet, Marie-Anne Lachaux, Timothée Lacroix, Baptiste Rozière et al. “Llama: Open and efficient foundation language models.” arXiv preprint arXiv:2302.13971 (2023).
- Elo rating system: https://en.wikipedia.org/wiki/Elo_rating_system
- Chowdhery, Aakanksha, Sharan Narang, Jacob Devlin, Maarten Bosma, Gaurav Mishra, Adam Roberts, Paul Barham et al. “Palm: Scaling language modeling with pathways.” arXiv preprint arXiv:2204.02311 (2022).
- BIG-bench: https://github.com/google/BIG-bench
- Srivastava, Aarohi, Abhinav Rastogi, Abhishek Rao, Abu Awal Md Shoeb, Abubakar Abid, Adam Fisch, Adam R. Brown et al. “Beyond the imitation game: Quantifying and extrapolating the capabilities of language models.” arXiv preprint arXiv:2206.04615 (2022).
- Liu, A., Feng, B., Xue, B., Wang, B., Wu, B., Lu, C., & Piao, Y. (2024). Deepseek-v3 technical report. arXiv preprint arXiv:2412.19437.
- Guo, D., Yang, D., Zhang, H., Song, J., Zhang, R., Xu, R., & He, Y. (2025). Deepseek-r1: Incentivizing reasoning capability in llms via reinforcement learning. arXiv preprint arXiv:2501.12948.
- Dubey, A., Jauhri, A., Pandey, A., Kadian, A., Al-Dahle, A., Letman, A., & Ganapathy, R. (2024). The llama 3 herd of models. arXiv e-prints, arXiv-2407.
- Team, G., Anil, R., Borgeaud, S., Alayrac, J. B., Yu, J., Soricut, R., & Blanco, L. (2023). Gemini: a family of highly capable multimodal models. arXiv preprint arXiv:2312.11805.
Join our Discord and Reddit Space
Section titled “Join our Discord and Reddit Space”You’re not the only one navigating fragmented tools, constant updates, and unclear best practices. Join a growing community of professionals exchanging insights that don’t make it into documentation.
Join our Discord at or scan the QR code below: A qr code on a white background AI-generated content may be incorrect. | Follow us on Reddit at or scan the QR code below: A qr code on a white background AI-generated content may be incorrect. |
|---|
A qr code on a white background AI-generated content may be incorrect.
A qr code on a white background AI-generated content may be incorrect.