Generative AI Fundamentals
local graph
Chapter 1 — Generative AI Fundamentals
Section titled “Chapter 1 — Generative AI Fundamentals”Generative AI (GenAI) has revolutionized our world and has grabbed everyone’s attention since the introduction of ChatGPT in November of 2022 by OpenAI (https://openai.com/index/chatgpt/). However, the foundational concepts of this technology have been around for quite some time. In this chapter, we will introduce the key concepts of GenAI and how it has evolved over time. We will then discuss how to think about a GenAI project and align it with the business objectives, covering the entire process for developing and deploying GenAI workloads, along with potential use cases across different industries.
In this chapter, we’re going to cover the following main topics:
- Artificial intelligence versus GenAI
- The evolution of machine learning
- Transformer architecture
- The GenAI project life cycle
- The GenAI deployment stack
- GenAI project use cases
Free Benefits with Your Book
Your purchase includes a free PDF copy of this book along with other exclusive benefits. Check the Free Benefits with Your Book section in the Preface to unlock them instantly and maximize your learning experience.
Artificial Intelligence versus GenAI
Section titled “Artificial Intelligence versus GenAI”Before we dive deeper into GenAI concepts, let’s discuss the differences between Artificial Intelligence (AI), Machine Learning (ML), Deep Learning (DL), and GenAI, as these terms are often used interchangeably.
Figure 1*.1* shows the relationships between these concepts.

Figure 1.1 – Relationships between AI, ML, DL, and GenAI
Let’s learn more about these relationships:
- AI: AI refers to a system or algorithm that is capable of performing tasks that would otherwise typically require human intelligence. These tasks include reasoning, learning, problem-solving, perception, and language understanding. AI is a broad category and can include rule-based systems, expert systems, neural networks, and GenAI algorithms. The evolution of AI algorithms has provided machines with human-like senses and capabilities, such as vision to analyze the world around them, listening and speaking to understand natural language and respond verbally, and using sensor data to understand the external environment and respond accordingly.
- ML: ML is a subset of AI that involves algorithms and models that enable machines to learn from data and make predictions without requiring explicit coding. In traditional programming, developers write explicit instructions for a computer to execute, whereas in ML, algorithms learn from the patterns and relationships in data and make predictions. ML can further be divided into the following sub-categories:
- Supervised learning: This uses labeled datasets to train the models. It can further be subdivided into classification and regression problems:
- Classification problems use labeled data, such as labeled pictures of dogs and cats, to train the model. Once the model is trained, it can classify a user-provided picture using the classes it has been trained on. - Regression problems, on the other hand, use numerical data to understand the relationship between dependent and independent variables, such as house pricing based on different attributes. Once a model establishes a relationship, it can then forecast the pricing for different sets of attributes, even if the model has not been trained on these specific attributes. Some popular regression algorithms are linear regression, logistic regression, and polynomial regression.
- Unsupervised learning: This uses ML algorithms to analyze and cluster unlabeled datasets to discover hidden patterns in data. Unsupervised learning can further be divided into the following two sub-categories:
- Clustering algorithms group data based on similarities or differences. A popular clustering algorithm is the k-means clustering algorithm, which uses Euclidian distances between data points to measure the similarity between data points and assign them in k distinct, non-overlapping clusters. It iterates to refine the clusters to minimize the variance within each cluster. A typical use case is segmenting customers based on purchasing behavior, demographics, or preferences to target marketing strategies effectively. - Dimensionality reduction is another form of unsupervised learning, which is used to reduce the number of features/dimensions in a given dataset. It aims to simplify models, reduce computational costs, and improve overall model performance. Principal Component Analysis (PCA) (https://towardsdatascience.com/a-one-stop-shop-for-principal-component-analysis-5582fb7e0a9c) is a popular algorithm used for dimensionality reduction. It achieves this by finding a new set of features called components, which are composites of the original features that are uncorrelated with one another.
- Semi-supervised learning: This is a type of ML that combines supervised and unsupervised learning by leveraging both labeled and unlabeled data for training. This is particularly useful when obtaining labeled data is time-consuming and expensive because you can use small amounts of labeled data for training and then iteratively apply it to the large amounts of unlabeled data. This can be applied in both classification and regression use cases, such as spam/image/object detection, speech recognition, and forecasting.
- Reinforcement learning: In reinforcement learning, there is an agent and reward system, and algorithms learn by trial and error to maximize the reward for the agent. An agent is an autonomous system, like a computer program or robot, that can make decisions and act in response to its environment without direct human instructions. Rewards are given from the environment when agent actions lead to a positive outcome. For example, if we want to train a robot to walk without falling over, positive rewards are given for actions that help the robot to remain upright, and negative rewards are given for actions that cause it to fall over. The robot begins by trying different actions randomly, such as leaning forward, moving its legs, or shifting its weight. As it performs these actions, it observes the resulting changes in its state. The robot uses feedback (rewards) to update its understanding of which actions are beneficial and thus learns to walk over time.
We have summarized the different categories of ML in Figure 1*.2*:

- Supervised learning: This uses labeled datasets to train the models. It can further be subdivided into classification and regression problems:
Figure 1.2 – Different categories of ML
- DL: DL is a subset of ML that involves deep neural networks with many layers. Conceptually, it is inspired by the human brain, which has billions of deeply connected neurons and provides humans with very advanced cognition. Some popular examples of deep neural nets are Convolutional Neural Networks (CNNs), used for image processing, and Recurrent Neural Networks (RNNs), which are used for analyzing time series data or natural language processing.
- GenAI: GenAI is a further subset of DL and focuses on creating new data, such as text, images, music, and other forms of content. Lots of generative applications are based on Foundational Models (FMs), which are large-scale AI models trained on vast amounts of diverse data, serving as a base for a wide range of downstream tasks. They are pre-trained on broad datasets and can be fine-tuned for specific applications. Large Language Models (LLMs) are a subset of FMs specifically designed for understanding and generating human language. GenAI is the primary focus of this book; we will be diving into its details later in the book.
Now that we understand the key differences between AI, ML, DL, and GenAI, let’s explore the evolution of ML and how transformer architecture has revolutionized the ML landscape, particularly in the field of Natural Language Processing (NLP).
Evolution of machine learning
Section titled “Evolution of machine learning”Since this book is about GenAI, what could be a better way to start it than asking ChatGPT to summarize the evolution of AI and ML over the last decade?
Prompt: "Why did the chicken cross the road?" Describe how that question's answer evolved using AI/ML over the last decade.
ChatGPT Response (ChatGPT-4o, June 16th, 2024):
The evolution of AI/ML responses to the question "Why did the chicken cross the road?" over the past decade reflects significant advancements in language processing and understanding. Here's a detailed description of how these responses have evolved:Early 2010s: Rule-Based SystemsResponse Type: Traditional, rule-basedExample Answer: "To get to the other side."Description: In the early 2010s, AI systems were primarily rule-based. These systems relied on pre-defined patterns and rules coded by developers. When asked "Why did the chicken cross the road?" the AI would output the standard punchline "To get to the other side" because it was programmed to recognize this classic joke and respond accordingly. The response lacked creativity and was limited to what was explicitly coded into the system.Mid 2010s: Statistical and Early Machine Learning ModelsResponse Type: Basic machine learning-generated variationsExample Answer: "To find some food on the other side."Description: As machine learning techniques began to develop, early models could generate responses based on statistical patterns in the data they were trained on. These models, such as simple neural networks or early natural language processing (NLP) algorithms, could create variations of the joke. However, the answers were still relatively straightforward and sometimes nonsensical, as these models had limited understanding of context and nuance.Late 2010s: Advanced Neural Networks and NLPResponse Type: Context-aware and more sophisticatedExample Answer: "Because it wanted to explore the other side of the road."Description: The late 2010s saw the rise of advanced neural networks and NLP (natural language processing) techniques, such as LSTM (Long Short-Term Memory) networks and early transformer models. These models had a better grasp of context and could generate more sophisticated responses. They could recognize the structure of the joke but also provide contextually appropriate variations that made sense and were more engaging.Early 2020s: Transformer-Based ModelsResponse Type: Highly fluent and creativeExample Answer: "To escape from the boredom of farm life and seek adventure!"Description: With the advent of transformer-based models like GPT-3 and BERT, AI's ability to generate human-like text improved dramatically. These models, trained on vast amounts of internet text, could produce responses that were not only fluent but also creative and contextually rich. They could understand humor better and generate answers that went beyond the traditional punchline, incorporating more complex wordplay or humor styles.Present Day: LLMs and PersonalizationResponse Type: Personalized and contextually relevantExample Answer: "Because its AI model predicted a 95% chance of finding a better grain on the other side."Description: Today's LLMs, such as GPT-4, are capable of highly personalized and contextually aware responses. They can take into account previous conversational history, the user's preferences, and cultural context. The AI might generate responses that are tailored to the individual user, offering a wide range of humorous and inventive answers that reflect a deep understanding of language and context. This level of personalization and creativity was unimaginable a decade ago.As can be seen from the preceding example, transformers revolutionized NLP by enabling parallel processing and improving scalability and efficiency; however, prior to transformers, deep neural networks, such as CNNs and RNNs, dominated the DL field since being introduced in the 1980s. Here are some brief descriptions of these neural networks:
- CNNs are similar in functionality to how our visual cortex functions. Our brain processes images from the retina by using specialized neurons that handle specific types of information or features. Similarly, the different filters in a CNN can detect various sets of features in an image or dataset. To learn more, refer to the paper by Yann LeCun et al. Backpropagation Applied to Handwritten Zip Code Recognition (https://ieeexplore.ieee.org/document/6795724), presented in 1989. CNNs are still commonly used for image analysis.
- RNNs are commonly used for sequences of data, or time series data, to analyze patterns and potentially forecast future events, such as analyzing historical stock market data to predict future trade options. RNNs are also frequently used in NLP, as natural language is a sequence of words where the order matters and can significantly impact the meaning. The concept of RNNs was introduced in the 1986 paper by David Rumelhart, Geoffrey Hinton, et al., Learning representations by back-propagating errors (https://www.nature.com/articles/323533a0). This seminal paper introduced the concept of the backpropagation algorithm, based on the gradient descent concept, which is an essential technology for training neural networks and has revolutionized the entire AI field. In Appendix 1A, we have included a brief mathematical introduction to RNNs and their popular variants, such as Long Short-Term Memory (LSTM) networks and Gated Recurrent Units (GRUs).
In 2007, Fei-Fei Li, then a professor of Computer Science at Stanford University, started the ImageNet competition (https://www.image-net.org/), which included a massive dataset of images available on the internet that were labeled for training and testing. Every year, different AI/ML teams try to automate the prediction and improve the accuracy of their models using this training dataset.
Until 2011, the state-of-the-art technologies in the ImageNet competition were based on classical ML approaches, such as Support Vector Machines (SVMs), which tried to create an isolation plane between two different categories with the maximum margin in between. A breakthrough came with the introduction of AlexNet in 2012, developed by Alex Krizhevsky, Ilya Sutskever, and Geoffrey Hinton. This paper (https://papers.nips.cc/paper_files/paper/2012/hash/c399862d3b9d6b76c8436e924a68c45b-Abstract.html) won the ImageNet competition using deep CNNs and brought GPU programming to the forefront of AIML development.
- Transformers: In 2017, the transformer architecture was introduced by Vaswani et al. in their seminal paper Attention Is All You Need (https://arxiv.org/abs/1706.03762). It revolutionized NLP by enabling parallel processing and improving the scalability and efficiency of NLP. Bidirectional Encoder Representations from Transformers (BERT), developed by Google, significantly improved the understanding of context in language models. Since then, there have been lots of LLMs introduced by different companies, such as the GPT series by OpenAI and Claude by Anthropic.
Over the last two decades, ML has evolved from basic algorithmic models that were rule-based and dependent on manually curated features to advanced, context-aware models using deep learning frameworks such as neural networks and transformers. Let’s take a closer look at the transformer architecture now.
Transformer architecture
Section titled “Transformer architecture”A transformer model uses an encoder-decoder architecture, where the encoder maps the input sequences/tokens through a self-attention mechanism. This mapped data is used by the decoder to generate the output sequence. The mapping of input tokens retains not only their intrinsic values but also their context and weight in the original sequence. Let’s go through some key aspects of the encoder architecture in the following figure:

Figure 1.3 – Transformer architecture from the Attention Is All You Need paper
Here is a breakdown of the concepts highlighted in Figure 1*.3*:
- Input embeddings: Marked as 1 in the figure, this is a key part of the transformer model, which converts input sequences/tokens into high-dimensional vector embeddings. In real-world applications, output embeddings from a trained model may be stored in high-dimensional vector databases, such as Elasticsearch, Milvus, or PineCone. Vector databases help to find similar searches in high-dimensional space using either Euclidian distance or cosine similarity, and similar objects are assigned closer to each other in this high-dimensional vector space, as shown in the following figure.

Figure 1.4 – Assignment of similar objects in high-dimensional space
- Positional encoding: Positional encoding, marked as 2 in Figure 1*.2*, provides information about the order of tokens in an input sequence. Unlike RNNs, which have the knowledge of time step t or the notion of the sequence, transformer models rely on self-attention mechanisms and lack awareness of intrinsic token order. Positional encoding injects sequential information into the token embeddings.
For example, if the input sequence is The Brown hat, here is how the mechanism would work:
- Token embeddings: Each word in the sentence is converted into a vector representation (embedding). Let’s say we have these simple embeddings for demonstration:
The-> [0.1, 0.2]Brown-> [0.3, 0.4]hat-> [0.5, 0.6]
- Positional encoding vectors: We generate positional encodings for each position in the sentence. Transformer models typically use sinusoidal functions for positional encoding, however for illustration purposes, let’s use the following example:
- Position 0: [0.01, 0.02]
- Position 1: [0.03, 0.04]
- Position 2: [0.05, 0.06]
- Position 0: [0.01, 0.02]
- Adding positional encodings to token embeddings: We add the positional encoding vectors to the token embeddings to incorporate positional information:
The+ Position 0: [0.1, 0.2] + [0.01, 0.02] = [0.11, 0.22]Brown+ Position 1: [0.3, 0.4] + [0.03, 0.04] = [0.33, 0.44]hat+ Position 2: [0.5, 0.6] + [0.05, 0.06] = [0.55, 0.66]
Now, each word has a unique vector that includes both the word’s meaning and its position in the sentence.
- Multi-head attention mechanism: In a multi-head attention mechanism, marked as 3 in Figure 1*.2*, the model calculates the query, key, and value vectors for every I/P sequence and each attention head. A possible analogy for thinking about the multi-head attention mechanism is a team of detectives solving a very complex case, where each detective is an attention head. Every attention head has its own query vectors, which is an aspect of the case that a detective is focused upon, such as motive for the crime, weapon used, and so on. Finally, the key is the clues or pieces of evidence related to that given motive. So, if the query is the weapon used, the detective would investigate the crime scene for anything that could be used as a weapon, and the value would be the insights gained from each bit of evidence (e.g., fingerprints on a weapon). By having multiple attention heads, a model can focus on different parts of the input simultaneously, capturing various patterns or dependencies in the data, such as word meanings, words’ relative positions, and sentence structures, similar to our analogy, where different detectives are focusing on different aspects of the case. Besides that, multi-head attention also allows the parallel processing of inputs, making it highly efficient and speeding up both training and inference by distributing them across different devices. In Appendix 1B, we cover the mathematical model and complexities of key-value pairs, as well as feed-forward networks and the concept of temperature in transformer models.
Now that we understand how transformer architecture has revolutionized DL by using an encoder-decoder framework that relies on self-attention mechanisms to enable the parallel processing of input data, let’s explore a typical GenAI project life cycle.
GenAI project life cycle
Section titled “GenAI project life cycle”Enterprise spending on GenAI projects has been growing exponentially since 2023, with c-suite executives planning to spend even more on GenAI projects (https://www.gartner.com/en/newsroom/press-releases/2023-10-11-gartner-says-more-than-80-percent-of-enterprises-will-have-used-generative-ai-apis-or-deployed-generative-ai-enabled-applications-by-2026). However, there is growing concern about how to quantify the Return on Investment (ROI) of these efforts, such as revenue impact, efficiency, and accuracy gains. Moving forward, ROI will become a critical part of the conversation, as enterprises look for new GenAI projects. So, before starting a new GenAI project, it is recommended to think about the entire project life cycle. In this section, we will be covering the project life cycle.
Let’s first look at the following figure, which outlines the end-to-end GenAI project life cycle, starting from defining business objectives, or KPIs. This is followed by selecting or training FMs and optimizing them using techniques such as fine tuning and prompt tuning. Then, the model is evaluated, deployed, and continuously monitored to ensure that business goals are met.

Figure1.5 – GenAI project life cycle
Let’s take a closer look at each stage of the GenAI project life cycle:
- Business objectives and FM selection: The GenAI project life cycle starts with the business objective/problem statement we are trying to solve with GenAI. Business objectives could be increasing customer conversion or retention, creating personalized marketing campaigns, or creating a customer chatbox using enterprise internal data:
- Critical KPIs: After the use case, the next consideration is business-critical KPIs, such as cost per inference. For example, if we are creating a personalized marketing campaign, we should ensure that the cost per customization is less than the product of the Lifetime Value (LTV) of the customer and the probability of customer conversion. If the cost of inference is more than the business value the project is expected to deliver, the project might not have long-term sustainability. Other KPIs to think about could include latency, as sub-second response times might be needed for certain use cases or throughput, if a certain number of tokens is expected per second.
- Selecting and training a FM: The next step is to either pick an existing FM or train a new one. Training a new FM could be extremely resource intensive and cost billions of dollars and significant time, so in the majority of applications, it is better to pick an existing FM and do domain-specific optimization. When picking an existing model, you can select either an open source model or a proprietary model that can be accessed through web interfaces or over APIs, such as Claude or ChatGPT. It is always a good idea to check the licensing terms of these models to ensure that they meet application requirements and can scale with your enterprise needs.
- Critical KPIs: After the use case, the next consideration is business-critical KPIs, such as cost per inference. For example, if we are creating a personalized marketing campaign, we should ensure that the cost per customization is less than the product of the Lifetime Value (LTV) of the customer and the probability of customer conversion. If the cost of inference is more than the business value the project is expected to deliver, the project might not have long-term sustainability. Other KPIs to think about could include latency, as sub-second response times might be needed for certain use cases or throughput, if a certain number of tokens is expected per second.
- Model optimization: Once the FM is selected, the next step is to optimize the model for the business use case using techniques such as fine tuning, prompt tuning, Reinforcement Learning from Human Feedback (RLHF), and DPO:
- Fine tuning: In fine tuning, a domain-specific labeled dataset with prompt and completion data is used to train the model for a specific domain or set of domains. Since all model weights can be updated in fine tuning, the compute requirements for fine tuning are similar to those for full training. However, the training time is smaller, as we are training the model on a smaller dataset. To reduce the training resources, there are options such as Performance-Efficient Fine Tuning (PEFT), which only updates a small set of weights and thus reduces the compute requirements. Low Rank Adoption (LoRA) is a very popular form of PEFT, where the original model matrix is reparametrized using a low-rank representation to significantly reduce the number of model parameters to be updated. As an example, in Vaswani’s paper, each attention head has the dimensionality [512, 64], that is, 32,768 parameters to train per head. With LoRA, we train much smaller weight matrices to offer 80% or higher weight reduction. We will cover this topic in detail in Chapter 4. Another version of LoRA is QLoRA (Quantized Lower Rank Adoption). In QLoRA, we use quantization to compress the model weights from 32-bit precision to 8-bit or 4-bit precision, which dramatically reduces the model size and makes it easier to run on GPUs with less memory.
- Prompt tuning is a low-cost technique where soft prompt tokens are added to the input query to optimize model performance for domain-specific tasks. These tokens are optimized as the model is retrained on the labeled domain-specific data. Unlike traditional fine tuning, which adjusts the model’s parameters across numerous training iterations, prompt tuning focuses on refining the prompts to guide the model more effectively.
- In RLHF (https://huggingface.co/blog/rlhf), human feedback is used to train LLMs to align with human preferences using RL techniques. In this approach, the LLM generates multiple responses to a variety of prompts, which humans evaluate and rank based on criteria such as accuracy, relevance, and ethical standards. Using the ranked responses, a reward model is trained to predict the human preference score for any given LLM response, and the LLM is fine-tuned using RL algorithms guided by the developed reward model.
- In Direct Preference Optimization (DPO) (https://huggingface.co/papers/2305.18290), a policy is trained with a simple classification objective to best align with human preferences without using RL. Similar to RLHF, multiple outputs are generated by the LLM for a set of input prompts. Human evaluators compare these outputs in pairs and indicate which output they prefer. This creates a dataset of preference pairs, such as (Ap, Anp), where Ap indicates a preferred answer and Anp indicates a not-preferred answer. A loss function is then designed to maximize the probability that the preferred output is ranked higher than the less-preferred output as the LLM output. The model parameters are optimized to minimize this loss function over all collected preference pairs. This directly tunes the model to produce outputs that are more aligned with human preferences.
- Evaluation: After the models are trained, you need to evaluate them for accuracy using metrics such as ROUGE (https://huggingface.co/spaces/evaluate-metric/rouge) or BLEU (https://huggingface.co/spaces/evaluate-metric/bleu), based on the use case:
- Bilingual Evaluation Understudy (BLEU) measures how closely machine-generated text matches a set of reference texts. This metric was originally designed for machine translation and is also commonly used to evaluate text generation tasks, such as n-grams (contiguous sequences of n words) in generated text against reference texts. - Recall-Oriented Understudy for Gisting Evaluation (ROUGE) is a set of metrics used to evaluate the quality of summaries and translations generated by models. It compares the overlap between the generated text and a set of reference texts. ROUGE metrics are particularly popular in evaluating the performance of summarization systems.
- Fine tuning: In fine tuning, a domain-specific labeled dataset with prompt and completion data is used to train the model for a specific domain or set of domains. Since all model weights can be updated in fine tuning, the compute requirements for fine tuning are similar to those for full training. However, the training time is smaller, as we are training the model on a smaller dataset. To reduce the training resources, there are options such as Performance-Efficient Fine Tuning (PEFT), which only updates a small set of weights and thus reduces the compute requirements. Low Rank Adoption (LoRA) is a very popular form of PEFT, where the original model matrix is reparametrized using a low-rank representation to significantly reduce the number of model parameters to be updated. As an example, in Vaswani’s paper, each attention head has the dimensionality [512, 64], that is, 32,768 parameters to train per head. With LoRA, we train much smaller weight matrices to offer 80% or higher weight reduction. We will cover this topic in detail in Chapter 4. Another version of LoRA is QLoRA (Quantized Lower Rank Adoption). In QLoRA, we use quantization to compress the model weights from 32-bit precision to 8-bit or 4-bit precision, which dramatically reduces the model size and makes it easier to run on GPUs with less memory.
Besides those metrics, developers should also evaluate generated responses against the Honesty, Harmlessness, and Helpfulness (3H) metric and ensure that training data is free of biases and harmful content.
- Deployment optimization: Once the model training/fine tuning is complete, the next step is to explore options to reduce the model size and optimize it for latency and cost. Some possible options are quantization, distillation, and pruning:
- Quantization: In quantization, we can explore model precision tradeoffs, such as changing model weights from FP32 (floating point, 32 bit), which requires 4 bytes of memory per parameter, to FP16 or Bfloat16, which requires 2 bytes of memory per parameter, or even Int 8, which requires only 1 byte per parameter. So, by moving from FP32 to Int8, we could reduce memory requirements by 4X; however, that could impact model accuracy. So, we need to evaluate model performance/accuracy to see whether these trade-offs are acceptable.
- Distillation: In distillation, we can train a student model with a smaller size than the original model by minimizing the distillation loss. The goal of distillation is to create a student model that approximates the performance of the teacher model, while being more efficient in terms of computational resources, such as memory and inference time.
- Pruning: In pruning, we try to reduce the size and complexity of a model by removing less important parameters, such as weights close to zero, while maintaining/improving the model’s performance. The main goal of pruning is to create a more efficient model that requires fewer computational resources for inference and training without significantly affecting accuracy.
- Quantization: In quantization, we can explore model precision tradeoffs, such as changing model weights from FP32 (floating point, 32 bit), which requires 4 bytes of memory per parameter, to FP16 or Bfloat16, which requires 2 bytes of memory per parameter, or even Int 8, which requires only 1 byte per parameter. So, by moving from FP32 to Int8, we could reduce memory requirements by 4X; however, that could impact model accuracy. So, we need to evaluate model performance/accuracy to see whether these trade-offs are acceptable.
- Deployment options: Once the model is ready, the next choice is to pick the deployment options, such as cloud, on-premises, or hybrid approach. The selection depends on criteria such as hardware availability, cost, CapEx versus OpEx, and data residency requirements. Usually, cloud deployment offers the most simplicity due to the managed services and scalability; however, there could be data residency requirements, requiring either on-premises or hybrid deployments.
- Inference size improvements: After the model is ready and deployed, we can focus on imporving results on the inference side. Two options for this are Retrieval Augmentation Generation (RAG) and prompt engineering:
- RAG: In RAG, we provide the model with relevant information and documents besides the prompt to fix knowledge cutoff issues. This technique provides real-time information within the prompt without the need for continuous model training, thus reducing the overall training costs. RAG combines the capabilities of retrieval-based models and generation-based models to improve the quality of text generation tasks. We will discuss RAG implementation in detail in Chapter 4.
- Prompt engineering: In prompt engineering, we provide the model with some examples or context while asking a question. It could be zero-shot learning, where the model is given direct instructions without examples, such as
summarize this text. In few-shot learning, the user includes a few examples within the input prompt, which helps the model learn the desired output format and style.
- Prompt engineering: In prompt engineering, we provide the model with some examples or context while asking a question. It could be zero-shot learning, where the model is given direct instructions without examples, such as
- RAG: In RAG, we provide the model with relevant information and documents besides the prompt to fix knowledge cutoff issues. This technique provides real-time information within the prompt without the need for continuous model training, thus reducing the overall training costs. RAG combines the capabilities of retrieval-based models and generation-based models to improve the quality of text generation tasks. We will discuss RAG implementation in detail in Chapter 4.
Once the model is deployed, we need to keep monitoring it to ensure that the model’s results don’t drift or get stale over time. We will explore model monitoring, performance, and drift in detail in Chapter 11.
In this section, we looked at the various stages of the GenAI project life cycle. It starts with defining the business objectives and KPIs, which is followed by model selection and various fine-tuning techniques. We evaluate model accuracy using metrics such as BLEU and ROGUE, and finally we deploy and continuously optimize the model. Now, let’s look at the various layers of the GenAI deployment stack for deploying models.
GenAI deployment stack
Section titled “GenAI deployment stack”As we discuss GenAI application development and deployment over Kubernetes, it is a good idea to understand the entire deployment stack, which can help us to think about the right infrastructure, orchestration platform, and libraries. The following figure shows the various layers of the GenAI deployment stack, from the foundational infrastructure layer comprising compute, storage, and networking through to the orchestration, tools, and deployment layers.

Figure1.6 – Deployment stack for GenAI applications
Let’s a closer look at each of these layers:
- Infrastructure layer: We will start from the foundation layer of the stack and move upward. The foundation of this stack is the infrastructure layer, which covers compute, networking, and storage options:
- Compute: For compute, we can use options such as CPUs, GPUs, custom accelerators, or a combination of these. As explained previously, LLMs are very computationally intensive. GPUs offer massively parallel matrix multiplication capabilities and are mostly favored for training workloads. For inference, both CPUs and GPUs are used, but for LLMs with billions of model parameters, GPUs are often needed for inference as well. Besides CPUs and GPUs, there are custom accelerators, such as AWS Inferentia and Trainium, which are custom silicon chips specially designed for ML and highly optimized for mathematical operations.
- Networking: Networking is the next critical infrastructure component. For language models that are very large, both training and inference could become a distributed system problem. To explain this, let’s look at recent LLM model trends:
- Compute: For compute, we can use options such as CPUs, GPUs, custom accelerators, or a combination of these. As explained previously, LLMs are very computationally intensive. GPUs offer massively parallel matrix multiplication capabilities and are mostly favored for training workloads. For inference, both CPUs and GPUs are used, but for LLMs with billions of model parameters, GPUs are often needed for inference as well. Besides CPUs and GPUs, there are custom accelerators, such as AWS Inferentia and Trainium, which are custom silicon chips specially designed for ML and highly optimized for mathematical operations.
| Year | Model | Model Size (in billion parameters) |
|---|---|---|
| 2018 | BERT-L | 0.34 |
| 2019 | T5-L | 0.77 |
| 2019 | GPT2 | 1.5 |
| 2020 | GPT3 | 175 |
| 2023 | GPT4 | Trillions |
Table 1.1 – Evolution of GenAI model sizes
It’s evident here that GenAI models are growing exponentially, and more parameters generally mean a more complex model that can capture more intricate patterns in data, thus requiring more computational resources for training and inference.
To clarify, if we say a model has 1 billion parameters, it usually refers to model weights after training has been completed. However, for training these models, we need the model weights, gradients, Adam Optimizers, activations terms, and some temporary variables throughout the training epochs (https://huggingface.co/docs/transformers/v4.33.3/perf_train_gpu_one#batch-size-choice).
So, during training, we might need to store up to six parameters per training weight, which could take up to 24 bytes at FP32 precision, 12 bytes at FP16 (or Bfloat16) precision, or 6 bytes at FP8 or Int8. Actual precision depends on the accuracy requirements versus the training cost.
Now, let’s say we are training or fine tuning a 70B-parameter model, such as Llama3. It would require 840 GB (70B*12 bytes) of memory to store all the model weights and temporary variables with Bfloat16 or FP16 for precision. If we are using the latest NVIDIA H200 GPUs, which were introduced in 2024 and offer up to 141 GB of memory, we would still need about six GPUs to store these model parameters during training or full fine tuning, assuming the model is fully sharded.
In reality, the actual GPU count could be higher, if we would like to train these models in a reasonable time. This explains that East-West traffic, that is, the traffic flowing within the data center nodes or GPUs, could become a performance bottleneck for large model training or fine tuning. For this reason, non-blocking networking technologies such as memory coherence and Remote Direct Memory Access (RDMA) could help scale performance across nodes. RDMA is a technology that lets nodes in a distributed system access the memory of other nodes without involving either the core processor or operating system. Similarly, memory coherence technology ensures that all the caches in the system have up-to-date memory information and that write operations by one node to memory are visible to all the nodes/caches that are connected coherently. These two technologies result in lower latency and increased throughput for distributed training and fine-tuning problems.
- Storage: After networking, the next infrastructure choice is storage, with choices such as block storage, file storage, or Lustre. In a block storage system, such as Amazon S3, data is stored in data blocks. These block sizes range from 512 bytes to 64 KB, and multiple blocks can be accessed in parallel, which could provide higher I/O bandwidth. In a file storage system, data is stored in files and directories, making it easier to manage and structure the data. However, a file storage system creates an additional overhead of managing the file hierarchy and metadata. Lustre is a popular storage system that is now gaining traction for GenAI applications and has been in use for quite some time in high-performance computing. Lustre provides a massively parallel file storage system and can be scaled horizontally by adding more resources. If you are planning to store data in databases, you might choose SQL for fixed schema data or NoSQL databases for unstructured data, such as images and videos.
- Compute unit: After infrastructure, the next thing is to select the compute unit. The possible options are bare-metal machines, Virtual Machines (VMs), or containers. Containers pack all software dependencies, such as language runtimes and libraries, into an image, and multiple containers can share the same node/kernel. This allows much tighter bin packing or resource utilization as compared to VMs. For VMs, each VM requires a separate OS and runtime before the application can be deployed. Bare-metal machines are physical servers that are dedicated to a single tenant or customer, unlike VMs, which run on shared physical servers through a hypervisor.
- Orchestration platform: After compute unit selection, we choose the orchestration platform to manage the underlying infrastructure life cycle. This orchestration platform needs to be capable of scaling up or down based on workload demand and should be able to withstand network outages or hardware failures. Kubernetes (K8s) has emerged as a leading orchestration platform for containers and will be the primary focus in this book, as lots of leading companies, such as OpenAI (https://openai.com/research/scaling-kubernetes-to-7500-nodes) and Anthropic, are using it for their GenAI workload orchestration. OpenStack is an open source orchestration platform for VMs.
- Frameworks: After the orchestration platform comes the AI framework, such as TensorFlow or PyTorch. PyTorch Fully Sharded Data Parallel ( FSDP ) and TensorFlow distributed libraries allow model parameters and training data to be distributed across multiple GPUs and help the system to scale for large model sizes.
- IDEs: After orchestration, the next selection is what Integrated Development Environment (IDE) to use, such as JupyterHub, as well as what libraries to use, such as cuDNN, NumPy, or pandas, based on the infrastructure selection made earlier.
- Endpoints: Finally, the user can select the final deployment endpoint, such as offering models as an API, a platform, or a workload. Considering this stack for scalability, cost, latency, and disaster recovery could help users avoid very expensive rearchitecting once application use starts to scale. In our experience, data science teams often pick a simple architecture for proofs of concept, but these implementations sometimes don’t scale well and are very expensive during deployment.
In this section, we discussed various layers of the GenAI deployment stack, from the foundational infrastructure layer to the high-level abstraction layer. We also looked at the challenges these models present as model sizes grow and the different ways to solve them. Let’s take a look at GenAI use cases across industries.
GenAI use cases
Section titled “GenAI use cases”GenAI is transforming all industries. As per McKinsey (https://www.mckinsey.com/capabilities/mckinsey-digital/our-insights/the-economic-potential-of-generative-ai-the-next-productivity-frontier#key-insights), it is expected to add trillions of dollars to the economy by 2030. The following are some of the industry verticals affected and use cases. It is by no stretch a comprehensive list, as the list of applications is growing very rapidly.
However, learning about some of these will give you an idea of the potential GenAI carries:
- Retail/e-commerce:
- Product design: GenAI can be used with every stage of product design, such as summarizing market and user research, creating visuals/animations of possible product options, refining concepts based on user feedback, and creating product descriptions and marketing campaigns.
- Personalized recommendation: GenAI can enable more natural engagement for e-commerce websites. Users can ask in natural language for product recommendations, such as
the best running shoes under $100 with red stripes. GenAI can comprehend the user’s request and provide recommendations accordingly. - Review summarization: GenAI can help summarize user reviews and overall sentiments, so users don’t have to read through all the different reviews.
- Personalized recommendation: GenAI can enable more natural engagement for e-commerce websites. Users can ask in natural language for product recommendations, such as
- Product design: GenAI can be used with every stage of product design, such as summarizing market and user research, creating visuals/animations of possible product options, refining concepts based on user feedback, and creating product descriptions and marketing campaigns.
- Finance:
- Financial reporting/analysis: GenAI can help create financial reports and summaries based on the data and trend analysis.
- Customer service: GenAI can help with personalized marketing and chatbots to address user questions based on their data.
- Financial reporting/analysis: GenAI can help create financial reports and summaries based on the data and trend analysis.
- Healthcare:
- Drug discovery: GenAI models can predict how different drugs interact with various biological targets (proteins, enzymes, etc.) by analyzing existing interaction data. This can help in identifying promising drug candidates more efficiently. They can also propose novel molecular structures that have the potential to be effective drugs. These models can be further optimized for properties such as binding affinity, bioavailability, and toxicity.
- Personalized medicine: LLMs can integrate and analyze diverse types of patient data, such as medical records, lab results, imaging data, and genetic information, to create comprehensive patient profiles and identify genetic biomarkers that predict a patient’s response to particular treatments.
- Drug discovery: GenAI models can predict how different drugs interact with various biological targets (proteins, enzymes, etc.) by analyzing existing interaction data. This can help in identifying promising drug candidates more efficiently. They can also propose novel molecular structures that have the potential to be effective drugs. These models can be further optimized for properties such as binding affinity, bioavailability, and toxicity.
- Education:
- Personalized learning: GenAI can help develop personalized learning paths, based on user journeys and responses.
- New language learning: GenAI can help create personalized content and conversation examples.
- Personalized learning: GenAI can help develop personalized learning paths, based on user journeys and responses.
- Legal:
- Document review and summarization: GenAI can help automate the review and summarization of legal documents and prior similar cases for legal precedents.
- Contract generation: GenAI can help create legal contracts based on the parameters provided.
- Customer interaction: GenAI can help in developing chatbots for client inquiries and support.
- Document review and summarization: GenAI can help automate the review and summarization of legal documents and prior similar cases for legal precedents.
- Entertainment:
- Content creation: GenAI can help create scripts, music, artwork, and characters.
- Virtual reality: GenAI can help create immersive VR environments and experiences.
- Personalized content: GenAI can help in tailoring entertainment content and recommendations to individual preferences.
- Content creation: GenAI can help create scripts, music, artwork, and characters.
In this section, we looked at various GenAI use cases across different industries, from enhancing customer experience in retail to drug discovery and personalized medicine in healthcare. This is not an exhaustive list and it continues to grow as technology and models evolve.
Summary
Section titled “Summary”In this chapter, we covered the differences between AI and GenAI. AI is a very broad term that refers to technologies that enable machines to emulate human intelligence and encompasses a broad range of applications, including GenAI, whereas GenAI specifically focuses on creating new content, such as text, images, and videos.
We then looked at the evolution of ML, understanding its progression from CNNs/RNNs to the transformer architecture introduced in 2017. Transformers have revolutionized AI with their ability to process sequences of data efficiently, making them fundamental to many GenAI applications, particularly in NLP.
The chapter also outlined the life cycle of a GenAI project, which includes business objectives and KPIs, foundational model selection, model training, evaluation, and deployment. Each stage is critical, with continuous iterations based on performance feedback.
Finally, the chapter covered various use cases of GenAI across different sectors, including retail/e-commerce, finance, healthcare, and legal, that can leverage GenAI for summarization, recommendation, and personalization. This exploration underscores the versatile and transformative potential of GenAI in augmenting human creativity and transforming our day-to-day lives. In the next chapter, we will introduce the concepts of containers, K8s, and cover how K8s can manage the deployment, scaling, and operations of containerized workloads. We will also cover the specific advantages of using K8s in GenAI projects and what makes it attractive for GenAI applications.
Get This Book's PDF Version and Exclusive Extras
Appendix 1A – RNNsSection titled “Appendix 1A – RNNs”In this section, we will provide a basic overview of how RNNs work, including a mathematical explanation of their functionality. RNNs handle sequential data by maintaining a hidden state (or memory cell) that can capture information from previous time steps. The following is a very simplistic and mathematical representation of an RNN.
Figure 1.7 – Simple representation of an RNN In this figure, ht represents the hidden state at a given time step t and can be presented as: ht = f(wh * ht-1 +wx * Xt ) Where wh is the weight for the hidden stage and ht-1 is the output of this hidden stage at step t-1. Xt is the input, wx is the weight of the input stage, and f is the activation function. Output Yt = wy * ht + by In RNNs, the output at time t depends upon the hidden stage, which includes the weighted output of the prior steps, such as ht-1, ht-2, and so on. This architecture can process inputs of any length, and the model size does not increase with the size of the input. However, this implementation is sequential in nature and can’t be accelerated beyond a point through parallel processing. There are four different types of RNN topologies:
Significant advancements in RNNs came with the introduction of LSTM networks. LSTM networks addressed the problem of vanishing and exploding gradients in standard RNNs, making it possible to learn long-range dependencies in sequences more effectively. LSTM cells maintain separate short-term and long-term states. GRU is another optimization over LSTM and gives better training performance. Appendix 1B – Transformer mathematical models for the self-attention mechanismSection titled “Appendix 1B – Transformer mathematical models for the self-attention mechanism”In this section, we will provide a basic overview of how the transformer model works, including a mathematical explanation of its functionality. We discussed the concepts of queues, keys, and values as part of transformer analysis earlier in this chapter. For a given attention head i, the following are the query, key, and value vectors: Q= X* Wi Q K= X* Wi K V= X* Wi V Where WiQ, WiK, and WiV are the weight vectors for the attention head i for the query, key, and values. These weights are the parameters that we optimize as we train the model. To understand the computational complexity of these calculations, let’s look over the dimensionality of these vectors:
In the Attention Is All You Need paper, dmodel was 512 and the number of attention heads was 8, so dk =512/8 =64. During a forward pass, each of the Q, K, and V vector calculations would require ~262,144 multiplications (8*64*512) and 261,632 additions (8*64*511). During training, model goes through multiple forward and backward passes for each head across multiple sets of training data. This explains the complexity and compute resource requirements for these transformer models. For each attention head, the attention score is calculated with the following equation:
After computing the attention outputs for each head, they are concatenated to create multi-head attention, where Wo is the weight matrix for the output: This final output is then used in subsequent layers of the transformer model to perform various tasks, such as translation, text generation, or classification. Understanding the temperature parameter for GenAI use casesSection titled “Understanding the temperature parameter for GenAI use cases”In the softmax function used as a part of the attention score, temperature refers to a parameter that controls the smoothness or sharpness of the probability distribution produced by the softmax function. Adjusting the temperature can influence how confident the model is about its prediction of the output:
Lower temperature settings make the softmax distribution sharper (more confident predictions), while higher temperatures make the distribution smoother (less confident predictions) and could lead to more creative responses. The following is a sample response from ChatGPT for two temperature settings with the input prompt of Temperature = 2.0: Temperature = 0.75: |


