Page
1
Transformers and Large Language Models A Hands-On Guide to RAG and Agentic AI — Ahmed Fawzy Gad
Page
2
Transformers and Large Language Models A Hands-On Guide to RAG and Agentic AI Ahmed Fawzy Gad
Page
3
Transformers and Large Language Models: A Hands-On Guide to RAG and Agentic AI ISBN-13 (pbk): 979-8-8688-2784-6 ISBN-13 (electronic): 979-8-8688-2785-3 https://doi.org/10.1007/979-8-8688-2785-3 Copyright © 2026 by Ahmed Fawzy Gad This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director, Apress Media LLC: Welmoed Spahr Acquisitions Editor: Celestin Suresh John Editorial Assistant: Gryffin Winkler Cover designed by eStudioCalamar Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 New York Plaza, New York, NY 10004. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a Delaware LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail booktranslations@springernature.com; for reprint, paperback, or audio rights, please e-mail bookpermissions@springernature.com. Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web page at http://www.apress.com/bulk-sales. Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub. For more detailed information, please visit https://www.apress.com/gp/services/ source-code. If disposing of this product, please recycle the paper Ahmed Fawzy Gad Ottawa, ON, Canada
Page
4
To Egypt, the land that shaped me, and to the people of the Arab and Islamic world. To those who recognize their true adversaries and believe that their strength lies in their unity and collaboration, not in conflict with one another or petty side disputes. May we stand as an unbroken front until our civilization reclaims its rightful place, shining as it once did, and as it must again.
Page
5
v Table of Contents About the Author ix About the Technical Reviewer xi Acknowledgments xiii Chapter 1: Introduction to Machine Learning 1 1.1 What Is Artificial Intelligence? ................................................................................................. 1 1.2 Application of Generative AI .................................................................................................... 8 1.3 Machine Learning Pipeline .................................................................................................... 11 1.3.1 Tokenization .................................................................................................................. 12 1.3.2 Encoding ....................................................................................................................... 16 1.4 Modeling ............................................................................................................................... 22 1.4.1 Supervised Learning ..................................................................................................... 23 1.4.2 Unsupervised Learning ................................................................................................. 26 1.5 Feed-Forward Neural Network.............................................................................................. 29 1.5.1 Forward Pass ................................................................................................................ 31 1.5.2 Backward Pass ............................................................................................................. 32 1.5.3 Limitations .................................................................................................................... 33 1.6 Recurrent Neural Network .................................................................................................... 34 1.6.1 Drawbacks .................................................................................................................... 38 1.7 Long Short-Term Memory ..................................................................................................... 40 1.7.1 Forget Gate ................................................................................................................... 41 1.7.2 Input Gate ..................................................................................................................... 42 1.7.3 Cell Gate ....................................................................................................................... 43 1.8 Gated Recurrent Unit (GRU) ................................................................................................... 44 1.8.1 Reset Gate .................................................................................................................... 44 1.8.2 Update Gate .................................................................................................................. 45 1.8.3 Candidate Hidden State and Final Update .................................................................... 45
Page
6
vi Chapter 2: Transformers 47 2.1 Encoder–Decoder Architecture ............................................................................................. 47 2.2 Transformer Encoder ............................................................................................................. 51 2.2.1 Input Embedding .......................................................................................................... 52 2.2.2 Positional Encoding ...................................................................................................... 57 2.2.3 Encoder Block Internals ................................................................................................ 68 2.2.4 Scaled Dot-Product Attention ....................................................................................... 71 2.2.5 Multi-Head Attention..................................................................................................... 88 2.2.6 Add Layer ...................................................................................................................... 91 2.2.7 Normalization Layer ..................................................................................................... 93 2.2.8 Multi-Layer Perceptron (MLP) ....................................................................................... 95 2.2.9 Layers Stack ............................................................................................................... 100 2.3 Key Value (KV) Cache .......................................................................................................... 101 2.4 Encoder As a Feature Extractor ........................................................................................... 104 2.5 Transformer Decoder .......................................................................................................... 107 2.5.1 Masked Scaled Dot-Product Attention ........................................................................ 108 2.5.2 Cross-Attention ........................................................................................................... 112 2.5.3 Linear and Softmax Layers ......................................................................................... 117 2.5.4 Sampling .................................................................................................................... 119 Chapter 3: Advanced Transformer Architectures 123 3.1 Rotary Positional Embedding (RoPE) ................................................................................... 123 3.2 Other Attention Techniques ................................................................................................. 127 3.2.1 Multi-Query Attention (MQA) ....................................................................................... 128 3.2.2 Grouped-Query Attention (GQA) .................................................................................. 130 3.2.3 Multi-Head Latent Attention (MLA) ............................................................................. 132 3.2.4 Sliding Window Attention (SWA) ................................................................................. 136 3.3 Mixture of Experts (MoE) ..................................................................................................... 140 3.4 Small Language Model (SLM) ............................................................................................. 146 3.4.1 Knowledge Distillation ................................................................................................ 148 Table of ConTenTs
Page
7
vii 3.5 Training ............................................................................................................................... 162 3.5.1 Self-Supervised Learning (SSL) .................................................................................. 164 3.5.2 Supervised Fine-Tuning (SFT) ..................................................................................... 164 3.5.3 Reward Model ............................................................................................................ 165 3.5.4 Reinforcement Learning (RL) ...................................................................................... 165 3.6 Evaluation ........................................................................................................................... 166 3.6.1 Metrics ....................................................................................................................... 168 3.7 Evolution of Popular Models ............................................................................................... 171 3.7.1 DeepSeek ................................................................................................................... 172 3.7.2 OpenAI ........................................................................................................................ 175 3.7.3 Other Vendors ............................................................................................................. 181 Chapter 4: Model Customization 185 4.1 Model Customization Techniques ........................................................................................ 185 4.2 Fine-Tuning ......................................................................................................................... 186 4.2.1 Sequence Classification Fine-Tuning ......................................................................... 189 4.2.2 Parameter-Efficient Fine-Tuning (PEFT)...................................................................... 197 4.2.3 Text Generation ........................................................................................................... 212 4.3 Prompt Engineering ............................................................................................................ 217 4.3.1 In-Context Learning (ICL) ............................................................................................ 218 4.3.2 Chain of Thought Prompting ....................................................................................... 222 4.4 Quantization ........................................................................................................................ 223 Chapter 5: Retrieval-Augmented Generation 225 5.1 Introduction ......................................................................................................................... 225 5.2 RAG Types ........................................................................................................................... 228 5.2.1 RAG with Bi-Encoder .................................................................................................. 228 5.2.2 RAG with Cross-Encoder ............................................................................................ 236 5.2.3 Hybrid ......................................................................................................................... 238 5.3 Multi-Query Prompt ............................................................................................................ 242 5.4 RAG Disadvantages ............................................................................................................. 244 5.4.1 Safety ......................................................................................................................... 244 5.4.2 Latency ....................................................................................................................... 244 Table of ConTenTs
Page
8
viii 5.4.3 Retrieval Quality ......................................................................................................... 245 5.4.4 Overhead .................................................................................................................... 245 5.4.5 Adversarial Queries .................................................................................................... 245 5.5 Retrieval Evaluation ............................................................................................................ 246 5.5.1 Confusion Matrix ........................................................................................................ 247 5.5.2 Mean Reciprocal Rank (MRR) ..................................................................................... 249 5.6 Generation Evaluation ......................................................................................................... 250 5.6.1 Semantic Similarity .................................................................................................... 250 5.6.2 RAGAS ........................................................................................................................ 254 5.7 Advanced RAG Architectures and Variations ....................................................................... 264 5.7.1 GraphRAG ................................................................................................................... 264 5.7.2 HybridRAG .................................................................................................................. 264 5.7.3 SelfRAG ....................................................................................................................... 265 5.7.4 AgenticRAG ................................................................................................................. 265 Chapter 6: Agentic AI 267 6.1 Introduction ......................................................................................................................... 267 6.2 Model Context Protocol (MCP)............................................................................................. 274 6.2.1 MCP Python SDK ......................................................................................................... 279 6.2.2 Football Match Result ................................................................................................. 298 6.2.3 Elicitation .................................................................................................................... 302 6.2.4 Sampling .................................................................................................................... 302 6.3 Agent2Agent (A2A) Protocol ................................................................................................ 302 6.3.1 A2A Python SDK .......................................................................................................... 306 6.3.2 Recipe Agent .............................................................................................................. 322 6.4 Google Agent Development Kit ............................................................................................ 331 6.4.1 Build an Agent Using Google ADK ............................................................................... 331 6.4.2 Run Agent ................................................................................................................... 333 6.4.3 Tools with Arguments ................................................................................................. 335 Index 337 Table of ConTenTs
Page
9
ix About the Author Ahmed Fawzy Gad, M.Sc., is a senior AI engineer and researcher based in Ontario, Canada, with experience bridging the gap between academic theory and industrial application. His career spans multiple domains in the AI landscape, including cybersecurity work at Trend Micro and applied machine learning in healthcare at Medicia Research, where he focused on oncology. Ahmed has a strong research background with multiple peer-reviewed publications. He is the creator of PyGAD, a widely adopted open-source library for solving optimization problems using genetic algorithms. As an educator and technical author, Ahmed has written five books covering machine learning, computer vision, and Python programming. He has also authored dozens of widely read tutorials and articles helping thousands of learners understand complex AI concepts. Known for his ability to deconstruct sophisticated architectures into clear, step-by-step explanations, Ahmed is passionate about making advanced AI accessible to both beginners and professionals, a mission he continues with this deep dive into large language models. Ahmed is the founder of Vilvik, an early-stage Canadian startup focused on building AI-powered solutions and developing tools for optimization and intelligent systems. Currently in its initial phase, the company provides specialized AI consultation and offers an online application focused on solving optimization problems.
Page
10
xi About the Technical Reviewer Siddhant Agarwal is a seasoned Developer Relations professional with over a decade of experience building and scaling global developer ecosystems. He is currently a Senior Developer Advocate at ClickHouse, leading developer engagement across the APJ region, where he works at the intersection of real-time analytics, data infrastructure, and developer experience. Previously, Sid led Developer Relations across APAC at Neo4j, where he was responsible for building and scaling the regional DevRel strategy by driving developer adoption, growing communities, launching programs and events, and representing the region across product, engineering, and go-to-market initiatives. In his prior role, Sid has also managed flagship developer programs at Google. A recognized Google Developer Expert (GDE) in Gen-AI, he is passionate about empowering developers to reimagine how data and AI systems are built and understood. Known for his ability to tell powerful stories through technology, Siddhant translates complex systems into narratives that inspire action and innovation. With his signature “Local to Global” approach, he helps grassroots developer communities scale their ideas into global impact. He continues to shape communities, share insights, and drive meaningful connections across the tech ecosystem.
Page
11
xiii Acknowledgments In the Name of Allah, the Most Gracious, the Most Merciful. Writing this book has been a journey of discovery, growth, and persistence. It would not have been possible without the grace of the Almighty and the support, guidance, and encouragement of many individuals. All praise is due to Allah, the Lord of the Worlds. I am profoundly grateful for the strength, patience, and clarity bestowed upon me to complete this work. As it is written in the Holy Quran: “And if you should count the favor of Allah, you could not enumerate them” (Surah Ibrahim, 14:34), I also hold close the verse: “My Lord, enable me to be grateful for Your favor which You have bestowed upon me and upon my parents and to do righteousness of which You approve” (Surah Al-Naml, 27:19). Every insight within these pages is a reflection of the wisdom He provides, and any shortcoming is entirely my own. To my mother and my family, you are my constant source of stability and my first home. Your frequent calls and check-ins were a lifeline through the most demanding hours of research and writing. Your patience and support provided the sanctuary I needed to turn this project into a reality. This book is as much yours as it is mine. I would like to express my sincere gratitude to Frankie Wong, my former manager at Medicia Research Inc. Our time working together was formative to my professional development, and I remain deeply appreciative of the mentorship and support he continued to offer long after our formal collaboration ended. His industry insight and steady leadership have left a lasting impression and have been invaluable. My deepest thanks go to my colleague Kawtar Harakat, a dedicated Moroccan researcher whose remarkable kindness sustained me through some of the most challenging periods of my life. Her commitment to charitable work is a constant reminder that our greatest contribution lies not only in what we know but in how generously we give of ourselves. Beyond those named here, I extend my gratitude to the many friends, colleagues, and members of the wider community who offered encouragement along the way through a thoughtful discussion, a shared insight, or a simple word of support. No contribution was too small; each one played a part in bringing this work to life.
Page
12
1 © Ahmed Fawzy Gad 2026 A. F. Gad, Transformers and Large Language Models, https://doi.org/10.1007/979-8-8688-2785-3_1 CHAPTER 1 Introduction to Machine Learning Artificial intelligence is the field of embedding human-like intelligence into machines, enabling them to perform tasks efficiently that would typically require human capability. Over the years, machine intelligence has evolved from simply following human instructions to making autonomous decisions. In this chapter, we will explore the fundamentals of machine learning by examining its typical pipeline and the types of problems it can solve. We will explore the basic model of deep learning and, for sure, the transformers model, which is the neural network. To understand the motivation behind the transformer model, we will first review traditional recurrent neural networks and long short-term memory models, highlighting their limitations. By the end of this chapter, you will have the essential knowledge needed to begin exploring more advanced aspects of the transformer model. 1.1 What Is Artificial Intelligence? Artificial Intelligence (AI) is a transformative field within computer science that aims to imbue machines with human-like intelligence, enabling them to perform complex tasks with little to no human intervention. At its inception, AI development heavily relied on humans to break down complex problems into structured, manageable components that machines could tackle with logical reasoning and decision-making capabilities. Over time, the machines became more intelligent to do many autonomous tasks. Throughout the evolution of AI, some subfields are introduced as illustrated in Figure 1-1.
Page
13
2 Figure 1-1. Transformation from artificial intelligence to machine learning, deep learning, and large language models, illustrating the hierarchical relationship between these fields One classic illustration of AI in action is the game of tic-tac-toe (XO), played on a 3x3 grid where the goal is to align three identical symbols in a row, column, or diagonal. In this scenario, the machine is pre-equipped with human knowledge of all possible game states and potential moves. Figure 1-2 shows the possible options when the player X Chapter 1 IntroduCtIon to MaChIne LearnIng
Page
14
3 plays for the first time, where there is a total of 9 possible states. It also shows the states for the player O, assuming the first X is placed at the top-left corner. This makes the number of possible positions for placing the O as 8. Figure 1-2. A subset of the tic-tac-toe (XO) game state tree. A database of all possible states is generated to enable the machine to select the best move at each step At each turn or state, the machine evaluates its options, exploring various pathways to select the state that maximizes its chances of winning or minimizing the risk of losing. The machine looks intelligent when it plays the game and takes the correct decisions. But intelligence is hardcoded by a human, so the machine cannot go beyond it to respond to any new unseen states. Another foundational example of early AI applications is the development of rule- based chatbots designed to assist customers with basic inquiries. These chatbots operated on predefined templates structured as sets of rules, typically using “if-else” statements. For instance, if a user greeted the chatbot with “Hi” or “Hello”, the bot would respond with a welcoming message like “Hi, how can I help you?”. Chapter 1 IntroduCtIon to MaChIne LearnIng
Page
15
4 While these systems had limited problem-solving capabilities, they served a valuable function in routing users to human agents when queries became too complex. When provided with a description of a user’s issue, the chatbot would employ basic keyword detection to identify terms such as “stopped,” “failed,” or “not working” to infer potential service disruptions. The bot would then collect essential information like the user’s name and account number before forwarding the query to a human representative. Simpler variations of chatbots required even less natural language processing, offering users a set of predefined options to select from. Each selection would guide the user through a decision tree, narrowing the inquiry until a final action or solution was reached. This approach ensured clarity and efficiency but underscored the limitations of early AI systems, which struggled to handle queries beyond their scripted rules. While placing an X or O or building a basic chatbot may seem trivial to a human, the machine’s ability to analyze the options, foresee outcomes, and make optimal decisions represents the core principles of artificial intelligence. As AI continues to evolve, another sub-field called machine learning (ML) is developed that goes beyond simple rule-based systems. While AI makes the machine memorize each possible input-output pair, machine learning teaches the machine how to solve some problems so that the machine can have a degree of autonomy to take actions even if it was not taught the same example before. This is like teaching a kid how to sum numbers with examples. The teacher (or supervisor) gives the kid some examples in the form of the inputs and the expected outputs. The teacher keeps repeating such examples until they are satisfied that the student has the ability to solve the operation independently. This is done by testing the student using exams or quizzes to assess the student’s ability to understand the problem. Using machine learning, the supervisor prepares a dataset of examples for a specific problem by which the model is trained. The dataset is usually created by experts because the model’s ability to solve the problem is highly affected by the quality of the data samples. There is a data engineering step that usually transforms the raw data into cleaner data that is easier for the machines to understand. After this step, each sample in the raw data is represented by a numerical feature vector that is ready to be used by the machine. Chapter 1 IntroduCtIon to MaChIne LearnIng
Page
16
5 The supervisor keeps feeding the examples to the model until making sure the model understands how to solve the problem, not just memorize the examples. This is by using evaluation metrics such as the accuracy for the classification problems. Once the model is doing well on the training data, it is tested by some new unseen test dataset to make sure the model is generalized enough to handle new samples. The field of machine learning allowed the machines to understand natural language, recognize patterns, classify problems, recognize objects in images, and more. But it is usually used to solve simple problems that are well designed by humans and have its data manually engineered to increase its quality. This almost restricted the use of machine learning to solve shallow problems. Shallow refers to the ability of the model to find the patterns that map the inputs to the outputs using few transformations. As the volume of data generated by individuals and systems has grown, traditional machine learning approaches that rely on hand-crafted features have become increasingly impractical. Processing such vast amounts of data, often involving millions or even trillions of samples, requires models capable of learning directly from raw inputs without extensive manual feature engineering. This challenge led to the emergence of deep learning, a subfield of machine learning that leverages artificial neural networks to automatically learn hierarchical representations from raw data. A neural network is a special machine/deep learning model that forms the base of generative AI. It will be covered later in this book. Neural networks are still used in traditional machine learning, but such models are usually shallow with just a few layers and few neurons in each layer, as indicated in Figure 1-3. Chapter 1 IntroduCtIon to MaChIne LearnIng
Page
17
6 Figure 1-3. Shallow and deep neural networks. Deep networks contain more layers than shallow networks, allowing them to learn more complex patterns Chapter 1 IntroduCtIon to MaChIne LearnIng
Page
18
7 Deep learning models are particularly effective at solving complex problems where the data require multiple layers of transformation to extract meaningful patterns and produce accurate outputs. Deep learning allowed the machines to be used in applications such as virtual assistants, autonomous vehicles, medical diagnostics, and financial forecasting. Before the advent of the Internet and electronic devices, textbooks served as the primary source of knowledge for people. With the emergence of the Internet, text became the dominant medium of communication on websites. The rise of social media platforms further amplified the importance of text. People began sharing their experiences and opinions publicly, creating an invaluable source of real-time information. Businesses leveraged this data to gauge user satisfaction, while competitors analyzed negative feedback to improve their products and services, ultimately striving to attract and retain more customers. As text became ubiquitous and carried vast amounts of information, it became a key objective for computer scientists to develop machines capable of understanding and learning it. The traditional natural language processing (NLP) techniques are able to understand humans’ everyday languages. Through NLP, machines can perform a variety of tasks, including but not limited to: 1. Text Classification: Categorizing text into predefined classes. 2. Sentiment Analysis: Identifying and interpreting the emotional tone behind text. 3. Text Generation: Producing coherent and contextually relevant text. 4. Summarization: Condensing large volumes of text into concise summaries. 5. Information Retrieval: Extracting relevant information from vast data sources. 6. Named Entity Recognition (NER): Identifying names, locations, dates, and other entities. Chapter 1 IntroduCtIon to MaChIne LearnIng
Page
19
8 But traditional NLP models were limited to understanding only short paragraphs. As the length of the fed text increases, the models start to lose some information from the text. This heavily affected its overall understanding of the text and ability to create high- quality responses. Since users need to process large amounts of text data, the traditional small models will not work anymore. Moreover, such models are usually designed to solve a specific task. They are not general-purpose. The previous reasons are among the drivers to use the new class of models called “large language models (LLMs),” which have been heavily used in the last few years. Such models are large because they use large amounts of data and also have large model sizes in terms of number of layers and neurons. LLMs aim to achieve a human-like comprehension of natural language, including grammar, semantics, emotions, and other linguistic aspects. Some of these models are multimodal and able to comprehend and correlate information in different data types. An example is asking a model a textual question about an image. Its impact is transforming the way humans interact with technology, bridging the gap between natural language and machine understanding. It is also a step toward artificial general intelligence (AGI). 1.2 Application of Generative AI To show an example of how LLMs combine multiple applications within the same model, this is a question I asked for the Google Gemini 2.5 Flash model, accessible through this link https://gemini.google.com, while attaching the image in Figure 1-4. How many times can this power bank charge an iPhone 16 Pro Max? Chapter 1 IntroduCtIon to MaChIne LearnIng
Page
20
9 Figure 1-4. Image of a power bank’s specifications used as input for asking a question to Google Gemini, which determined that it could charge an iPhone 16 Pro Max approximately 1.8 times Chapter 1 IntroduCtIon to MaChIne LearnIng