GenAI Model Optimization for Domain-Specific Use Cases
local graph
Chapter 4 — GenAI Model Optimization for Domain-Specific Use Cases
Section titled “Chapter 4 — GenAI Model Optimization for Domain-Specific Use Cases”This chapter will start building on the basic concepts of GenAI that were introduced in Part 1 and cover options for optimizing general-purpose foundational models (FMs) for domain-specific use cases, such as chatbots and personalized recommendations. We will explore specific techniques, including retrieval-augmented generation (RAG) and fine-tuning methods, offering an in-depth understanding of how these approaches can be used to enhance model performance for targeted applications. Additionally, we will focus on the key concepts and functionalities of the Transformer architecture and the LangChain framework so that we can implement these techniques in K8s in the next chapter.
In this chapter, we’re going to cover the following main topics:
- The need for domain-specific optimization
- The LangChain framework – the concept of memory and agents
- RAG
- Model fine-tuning with a Llama3 example
Technical requirements
Section titled “Technical requirements”In this chapter, we will be using the following libraries and packages. Some of these libraries require you to create an account and provide an API key while making function calls:
- Hugging Face: https://huggingface.co/join.
- OpenAI: https://platform.openai.com/signup. Once you’ve signed in, you can request API keys by going to https://platform.openai.com/api-keys.
- You can access the Llama3 model for this chapter via Hugging Face: https://huggingface.co/meta-llama/Meta-Llama-3-8B
The code in this chapter can be run on Google Colab (https://colab.research.google.com/) or localhost using Jupyter Notebook available in an Anaconda environment. You can download Anaconda from https://www.anaconda.com/download.
The code in this chapter can be downloaded from this book’s GitHub repository: https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/tree/main/ch4.
The need for domain-specific optimization
Section titled “The need for domain-specific optimization”Large language models (LLMs) are general-purpose models that are trained on diverse datasets to ensure they can handle a wide range of inputs. However, these general-purpose models are not well suited to solve problems within a specific domain that requires a deep understanding of that domain, such as healthcare, finance, or law. This is where domain-specific optimization comes into play.
Some of these options also help to fix knowledge cut-off issues – for instance, to let an LLM address certain scenarios that occur after the LLM has been trained, or to ensure the proprietary dataset is used to optimize the LLM. Unlike general-purpose models, which are designed to be versatile, domain-specific optimization enhances model performance in specialized tasks, improving accuracy, efficiency, and reliability.
The core idea behind domain-specific optimization is that by leveraging unique characteristics, data patterns, and knowledge of a specific domain, we can create models that are not only more effective but also more efficient in their execution.
The following are some of the techniques you can use to optimize a model. We will discuss these in detail later in this chapter:
- Prompt engineering: This involves designing prompts that guide the model to generate more relevant outputs for specific domains. This might involve structuring questions or inputs in ways that results in more accurate and domain-appropriate responses.
- Knowledge integration: This includes techniques, such as RAG, that can augment an LLM with external knowledge sources during the generation process so that when the model encounters a query, it can retrieve relevant documents or pieces of information from a specialized knowledge base (e.g., medical databases, financial reports, and legal documents) and use this retrieved information to generate more accurate and contextually appropriate responses.
- Fine-tuning: Fine-tuning involves conducting further training – that is, training a pre-trained LLM on a domain-specific dataset. This process adjusts the model’s weights so that they better align with the nuances, jargon, and specific knowledge of the domain.
In the next section, we will cover LangChain, an open source framework that can be used for different model optimization techniques.
LLM model selection
Section titled “LLM model selection”For some of the applications discussed in this chapter, we will need to perform LLM model selection so that we can run them. Users have the choice to pick an LLM. Some of the most popular LLM providers are Anthropic, OpenAI, Cohere, and open-weight models such as Llama, which is provided by Meta.
For AWS deployment, Amazon Bedrock provides a simple interface for selecting and using FMs. It is a fully managed service offered by AWS that provides access to a wide variety of pre-trained models from leading AI providers, including Anthropic, Cohere, and Stability AI.
Through the Bedrock console or API, developers can easily choose the most suitable model for their use case – whether it’s for text generation, embeddings, or image generation. Bedrock abstracts away the complexities of model deployment, allowing these FMs to be integrated seamlessly into applications with just a few API calls. The following link explains how to use Amazon Bedrock via an API: https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started-api.html.
Throughout this book, we will be using different model providers, such as Amazon Bedrock and OpenAI, in K8s to showcase different usage patterns. In this chapter, we will be using GPT models from OpenAI via APIs.
The LangChain framework
Section titled “The LangChain framework”LangChain is a powerful open source framework designed to streamline the development of LLM-based applications. It provides a set of libraries and tools that facilitate the integration of LLMs with various data sources, allowing for complex workflows such as (RAG, decision-making, and multi-step reasoning and agents. LangChain can be used to create pipelines where LLMs can interact with external APIs, databases, or documents, enabling more dynamic, context-aware, and domain-specific responses. It’s widely used in building sophisticated AI applications such as chatbots, intelligent agents, and knowledge-driven systems.
Here are some of the key capabilities of LangChain:
- Memory: LangChain’s memory module allows an LLM to remember prior conversations within a session, thereby enabling context continuity. It can also be used to remember prior user responses. There are several memory options available. Based on the memory type that’s selected, a chain can read from its history/memory system and augment user inputs, as well as write the user’s input and output to memory for future runs so that there is continuity in the LLM’s response.
- Agents: These are autonomous components that can make decisions for the user, take actions, and interact with the environment or users by invoking tools or APIs. This is a new and exciting area in the GenAI space and can help us with the future – for example, we can ask an LLM to help us plan a “three-day excursion in Paris.” The LLM could not only make recommendations but also make reservations for a guided tour of the Louvre Museum and a Seine River cruise.
- Chains: Chains are sequences of prompts that can link multiple LLM operations together, allowing for complex workflows and multi-step reasoning.
- Tool integration: This allows LLMs to interact with external tools and APIs, expanding their functionality beyond text generation to include tasks such as querying databases or performing web searches.
In the following example, we will show you how to use LangChain’s PythonREPLTool to create Python code to solve a given problem. PythonREPLTool is an agent that can evaluate Python code dynamically as part of a workflow while engaging with an LLM.
The following code block will install the necessary LangChain modules:
!pip install langchain langchain_core langchain_experimentalfrom langchain.agents import AgentTypefrom langchain_experimental.tools.python.tool import PythonREPLToolfrom langchain.chat_models import ChatOpenAINext, we will install the openai module, provide an OpenAI key, and define the model:
!pip install openaillm_model = "gpt-3.5-turbo"llm = ChatOpenAI(model=llm_model,api_key=<OPEN_AI_KEY>)Here, we are creating the agent using PythonREPLTool:
agent = create_python_agent( llm,tool=PythonREPLTool(),verbose=False)Now, let’s say we have a task where we have to sort the following list of fruits and count how many times a fruit appears in the list:
fruit_list=["Apple","Banana","Apple","Peaches"]Let’s make the agent call:
import langchainlangchain.debug=Trueagent.run(f"""Count how many times a fruit is in this list and list every fruit and the numbers: {fruit_list}""")Answer: {‘Apple’: 2, ‘Banana’: 1, ‘Peaches’: 1}
In the preceding code, we turned on LangChain’s debugger to see how the code is analyzing the aforementioned prompt – Count how many times a fruit is in this list and list every fruit and the numbers: {fruit_list} – with the fruit list defined previously. Behind the scenes, LangChain highlighted the problem and told the LLM you have access to the Python REPL tool to execute Python code:
prompts: [ "Human: You are an agent designed to write and execute python code to answer questions.\nYou have access to a python REPL, which you can use to execute python code. Use this to execute python commands. Input should be a valid python command.The following Python code was created by the GPT model as part of this command. Note that this code can also be run as a standalone Python program:
[tool/start] [chain:AgentExecutor > tool:Python_REPL] Entering Tool run with input:"fruits = ['Apple', 'Banana', 'Apple', 'Peaches']fruit_count = {}for fruit in fruits: if fruit in fruit_count: fruit_count[fruit] += 1 else: fruit_count[fruit] = 1print(fruit_count)"This example shows how LangChain agents and modules provide extensibility to what we can achieve with general-purpose LLMs.
As we have seen in this section, LangChain is a powerful open source framework that enhances the development of applications using LLMs. It integrates LLMs with diverse data sources for sophisticated AI functions such as RAG, enabling complex workflows and dynamic, domain-specific responses. LangChain supports creating pipelines that interact with external APIs and databases, and it also features components such as memory for context continuity, autonomous agents for interactive decision-making, and tool integration for expanded functionalities. In the next section, we will discuss RAG and how some of the LangChain concepts covered in this section can be used for it.
Understanding RAG
Section titled “Understanding RAG”RAG is a technique that’s used to enhance the capabilities of generative models by combining the generative power of models such as Transformers (explained in Chapter 1) with information that can be extracted from a vector database using similarity search.
How RAG works
Section titled “How RAG works”The following are the key steps for implementing RAG:
- Embedding: The first step in RAG is to convert input text data into a form that can be processed by ML models. This involves embedding documents and queries into high-dimensional vector spaces so that these embeddings can capture the semantic meaning of the text, enabling similarity comparisons between different pieces of text.
- Vector database and indexing: Once the relevant documents have been embedded, these vectors are stored in a vector database. This database is optimized so that vectors that are similar to a given query vector can be retrieved quickly. In this example, we will be using DocArrayInMemorySearch, an open source vector store database offered by DocArray under the Apache License. It is a document index that keeps databases in memory. This may be useful when we start working with smaller datasets. Other examples of vector databases include Qdrant, PineCone, Facebook AI Similarity Search (FAISS), and Elasticsearch with vector plugins.
The next step is indexing, which involves organizing the data in the vector database to optimize retrieval. Efficient indexing is crucial for performance, especially as the dataset grows, as it helps with locating data quickly without scanning the entire dataset. Indexes can be built based on flat architectures for small datasets or more complex partitioning techniques such as trees, graphs, or clusters for larger datasets, facilitating faster search operations by narrowing down the search space.
- Retrieval: When a query comes into an LLM, it is converted into an embedding using the same method that’s used for the supporting document embeddings. This query vector is then used to search the vector database, where the most similar document vectors are retrieved.
- Final interaction with the LLM: The retrieved documents (or their embeddings) are then fed into an LLM, along with the original query. The LLM uses this augmented input to generate a response that is informed by the retrieved documents. This step allows the LLM to produce responses that are not only contextually relevant but also factually accurate and rich in detail, drawing on the specific information that was retrieved from the external documents.
Running a query
Section titled “Running a query”Now, let’s go through an example. Here, we’ll use an outdoor clothing catalog dataset to find the relevant products for our query by performing a similarity search. After, we’ll use OpenAI to summarize these products in the format we desire.
First, let’s install the necessary modules and libraries:
!pip install langchain openAI langchain-community docarray tiktokenfrom langchain.chat_models import ChatOpenAIfrom langchain.document_loaders import CSVLoaderfrom langchain.vectorstores import DocArrayInMemorySearchfrom IPython.display import display, Markdownfrom langchain.llms import OpenAINow, we will download the Fashion Clothing Products Dataset from Kaggle for the e-commerce company Myntra, a major Indian fashion e-commerce website. This dataset is shared under the public domain (CC0) at https://www.kaggle.com/datasets/shivamb/fashion-clothing-products-catalog.
import pandas as pddf = pd.read_csv('<file_path>/myntra_products_catalog.csv')df.to_csv('processed_file.csv', index=False)from langchain.document_loaders import CSVLoaderloader = CSVLoader(file_path='processed_file.csv')documents = loader.load()This CSV file contains 12,491 product descriptions, with the column headers being ProductID, ProductName, ProductBrand, Gender, Price (INR), NumImages, Description, and PrimaryColor.
If you are using Google Colab to run this code, you can also download the file from Google Drive and mount it by running the following command:
from google.colab import drivedrive.mount('/content/drive')Now, we will install openai and generate embeddings using OpenAI models:
!pip install langchain-openai openaifrom langchain_openai import OpenAIEmbeddingsimport openaiembeddings = OpenAIEmbeddings(openai_api_key=<open_ai_key>)To test the dimensionality of these embeddings, we can embed a string, such as Apple, and print its embedding dimensions. From the output, we can see that these embeddings are stored in a 1,536-dimensional space:
embed = embeddings.embed_query("Apple")print(f"Dimensionlaity of these embeddings are {len(embed)}")Dimensionlaity of these embeddings are 1536Due to this high dimensionality, it is hard to visualize the embeddings. However, we can use dimensionality reduction techniques, such as principal component analysis (PCA), to reduce these high-dimensionality vectors to a two or three-dimensional space so that we can visualize them.
Now, we will create a vector database using the document object we created previously:
db = DocArrayInMemorySearch.from_documents( documents, embeddings)At this point, we can define the query so that it finds regular-fit shirts that are either blue or white and can be worn for formal occasions. By default, the similarity search function reports the four closest matches. However, by defining k=5, we are asking it to respond with the five closest matches:
query = "Shirts which are good for Men, have regular fit and not the slim fit and can be used for a Formal occasion and have a color of either Blue or white"docs = db.similarity_search(query, k=5)We can use the docs[0:5] command to see the five shirts that the vector database has identified. Once we’ve done that, we can start the openai module:
llm_model = "gpt-3.5-turbo"llm =ChatOpenAI(model=llm_model,openai_api_key=<open_ai_key>)Now, we can feed this new information from the similarity search as a context to the LLM and ask it to summarize camping gear. We can do this by creating a variable called qdocs that combines all five documents that were returned by the similarity search:
qdocs = ".".join([docs[i].page_content for i in range(len(docs))])response = llm.call_as_llm(f"{qdocs} Question: please summarize results in a nice summary table and then summarize each one in one line and finally recommend the one with good reasons.-{query}")The following screenshot shows an example response:

Figure 4.1 – LLM output for the query
Now, let’s say we would like to achieve geolocalization and want to convert the same recommendations into French. We could add the following to our query:
response = llm.call_as_llm(f"{qdocs} Question: summarize results in a nice summary table converting everything to French and then summarize each one in one line and finally recommend the one with good reasons. Respond in French-{query}")
Figure 4.2 – The LLM’s response (translated into French)
Lastly, let’s assume that we also have demographics data. We could use the following demographics data to further personalize the recommendation. In the following code, we have created two fictional personas, John and Adam, and have asked the LLM to keep this demographics data in mind while recommending a shirt:
demographics ={"John": {'Age':30, 'Education': "Bachelor's Degree in Computer Science", 'Occupation': "Software Engineer"}, "Adam": {'Age':60, 'Occupation': "Retired"}}response = llm.call_as_llm(f"{qdocs}, Question: Recommend one shirt each for both individuals and provide good reasoning {demographics}.-{query}")print (response)The following output is generated by the LLM:
For John, the Software Engineer:I recommend the Next Look Men Blue Regular Fit Solid Formal Shirt. This shirt is a solid blue color, perfect for a formal occasion. It has a regular fit, which will provide comfort and a professional look. As John is a software engineer, this shirt will allow him to maintain a polished appearance while also being comfortable for long hours at work.For Adam, the Retired individual:I recommend the ColorPlus Men Blue & Off-White Regular Fit Printed Casual Shirt. This shirt has a mix of blue and off-white colors, making it versatile for various occasions. It has a regular fit, providing a comfortable wear for Adam. The printed design adds a touch of style without being too bold, suitable for a retired individual looking for a casual yet put-together look.As we can see, RAG can integrate Transformer models with information extracted via similarity search from a vector database to enhance generative responses. The process begins with embedding input text into vectors for semantic similarity comparisons and storing these in a vector database optimized for fast retrieval. During a query, these embeddings are utilized to fetch the most relevant documents, which are then fed into an LLM to generate informed and detailed responses. This method improves the contextuality and factual accuracy of the model’s outputs.
Next, let’s look at model fine-tuning.
Model fine-tuning
Section titled “Model fine-tuning”Model fine-tuning is an important technique in GenAI as it helps to optimize a pre-trained general-purpose model for a specific task or domain. Fine-tuning involves taking a pre-trained model and training it further on a smaller, domain-specific dataset.
This process allows the model to learn and internalize specific information, making it more specialized in that domain. While pre-trained LLMs, such as Llama3, possess extensive general knowledge, fine-tuning enables them to perform specialized tasks or use proprietary data that is not available for training a general-purpose LLM.
Model fine-tuning can help in the following ways:
- It reduces model hallucinations – that is, the likelihood of the model generating incorrect or misleading information
- It provides higher consistency in the model’s outputs by fine-tuning training data
- It leverages proprietary data without exposing it externally
- It reduces the cost associated with each query or task via quantization and optimization
- It offers better control over the model’s behavior and performance
As we can see, fine-tuning offers multiple benefits for domain-specific optimization. However, on the flip side, fine-tuning is computationally expensive and time-consuming as it requires a high-quality, domain-specific dataset and the model may become outdated quickly without regular re-fine-tuning.
RAG, on the other hand, can dynamically update information and provide answers based on the most current data available. RAG requires less computational power and data compared to fine-tuning and gives us the flexibility to use different or updated data sources without the need to retrain the model based on the use case at hand.
Choosing between RAG and fine-tuning depends on the use case and KPIs such as latency, cost per inference, accuracy, and so on. For example, if we are developing a domain-specific chatbot, such as one that provides medical advice, fine-tuning a language model on domain-specific medical documents might offer better accuracy because the model learns to understand specific terminologies and context. However, if the goal is to provide real-time question-answering over a constantly changing dataset, such as product information on an e-commerce site, RAG might provide better-quality results.
Fine-tuning LLMs can be resource-intensive if we are training all the weights of the model. This has led to the development of Parameter-Efficient Fine-Tuning (PEFT) techniques such as adapter-based tuning and Low-Rank Adaptation (LoRA), which significantly reduce the computational cost while retaining high performance. In adapter-based tuning, small, trainable modules, called adapters, are inserted between the layers of a frozen pre-trained model. These adapters learn task-specific behavior without modifying the original model weights, enabling efficient and modular fine-tuning. In the upcoming sub-sections, we will explore LoRA fine-tuning variations and their implementation.
LoRA
LoRA is a technique that’s used in neural network models to make training more computationally efficient, something that’s particularly useful for large models. Typically, training a neural network involves updating a large matrix of weights, which can be quite resource-intensive. Instead of updating the entire weight matrix, LoRA uses a low-rank approximation, which modifies the weight matrix by adding a smaller, easier-to-compute update.
In LoRA, this update is represented by two smaller matrices that are multiplied together. This results in a significant reduction in the number of parameters that need to be updated during training. In the following fine-tuning example, using LoRA, we will reduce the parameters that require updates from around 4.62 billion to around 88 million, or approximately 2% of the original total, making the process much more efficient without a substantial loss of performance. The scaling factor in LoRA helps adjust the impact of these updates, ensuring that the model remains effective while being less demanding to train.
Fine-tuning example
Section titled “Fine-tuning example”In this example, we will be using the Llama3 model. To fine-tune Llama3, we have created a synthetic loyalty program FAQ dataset using ChatGPT. We have called it MyElite Loyalty Program and have created it with the following guidelines in mind:
- The
MyEliteprogram has a $99 annual subscription fee - It offers benefits such as extended support for wear and tear
- It offers early access to sales events such as Black Friday, Labor Day, Cyber Monday, Christmas, and more
Using ChatGPT, we have created two files, loyalty_qa_train and loyalty_qa_eval, which contain prompts and responses for training and evaluation, respectively.
The following is an example prompt and response from this dataset:
{"prompt": "[MyElite Loyalty Program FAQ]: What is the cost of the MyElite Loyalty Program?", "response": "The MyElite Loyalty Program costs 99 USD per year. This fee is non-refundable, even if you cancel the membership."},{"prompt": "[MyElite Loyalty Program FAQ]: Can I cancel my MyElite Loyalty Program membership?", "response": "Yes, you can cancel your membership at any time. However, you will still enjoy the benefits until the end of your subscription period."},Both files are in JSON format. Note that we have added a string, [MyElite Loyalty Program FAQ], before every prompt so that we get better training outcomes and can differentiate this dataset from other loyalty program FAQs that the Llama3 model might have been trained on.
Now, let’s go through the code:
- Install the necessary libraries and dependencies: First, we must install the necessary libraries and load the training and evaluation datasets:
Let’s look at the different libraries we will be using:!pip install bitsandbytes transformers accelerate peft datasets wandbfrom huggingface_hub import login, login(token="<hf_token>")from datasets import load_datasettrain_dataset = load_dataset('json', data_files='loyalty_qa_train.jsonl', split='train')eval_dataset = load_dataset('json', data_files='loyalty_qa_val.jsonl', split='train')
bitsandbytes: This is a lightweight Compute Unified Device Architecture (CUDA) implementation for low-level GPU computations that’s been optimized for memory efficiency and provides efficient implementations of matrix multiplication, quantization, and other tensor operations. In this example, we will be downloading it using the Llama3 model with int 4 precision.transformers: Hugging Face’stransformerslibrary provides pre-trained models for a wide range of transformer-based models, including Mistral and Llama for easy integration for GenAI use cases.accelerate: This library by Hugging Face is designed to simplify the process of training and deploying PyTorch models on multiple GPUs or TPUs. It abstracts away the complexity of distributed training, making it easier to scale models across different hardware configurations.peft: This library focuses on parameter-efficient fine-tuning techniques for large pre-trained models, thus reducing computational cost and memory requirements. It only allows fine-tuning to be performed on a small subset of parameters, such as adapters or low-rank updates, rather than the entire model.datasets: Thedatasetslibrary by Hugging Face provides easy access to a wide range of datasets for ML, including tools for loading, processing, and analyzing datasets. Next, we must download the Weights & Biases library. This is an optional library that can provide great insights into resource utilization during the fine-tuning process. We’ll take a closer look at this when we cover model training:
import wandb, osos.environ["WANDB_API_KEY"]="<wandb_API_Key>"wandb.login()os.environ["WANDB_PROJECT"] = "Llama_finetune" - Download Llama3: Now, we will download the Llama3 model with 4-bit quantization. Quantization reduces the precision of the model’s parameters from their original 32-bit floating-point values to lower-bit representations, such as 4-bit. This reduces the memory footprint significantly and can potentially speed up inference while maintaining reasonable model performance. For reference, Llama3 has 8 billion parameters. If we use full precision (32-bit), it will take 32 GB of RAM just to hold the model weights as each weight would require 4 bytes of memory. With 4-bit precision (1/2 byte), the same model weights could fit into ~4 GB
import torchfrom transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfigbase_model_id = "meta-llama/Meta-Llama-3-8B"bnb_config = BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_use_double_quant=True,bnb_4bit_quant_type="nf4",bnb_4bit_compute_dtype=torch.bfloat16)model = AutoModelForCausalLM.from_pretrained(base_model_id, quantization_config=bnb_config, device_map="auto")
- Tokenize the training and evaluation data: Now, we can initialize a tokenizer to convert text inputs into embeddings using a pre-trained model tokenizer. We’ll add special tokens at the beginning and end of sequences to ensure that the dataset is of uniform length for tensor processing. Finally, we’ll assign the end-of-sequence (EOS) token as the padding token, ensuring that sequences are handled consistently:
Next, we’ll define the formatting function to load training and evaluation datasets for fine-tuning. The following code takes each line in the training and validation dataset and formats it by parsing it fortokenizer = AutoTokenizer.from_pretrained(base_model_id, padding_side="left", add_eos_token=True,add_bos_token=True,)tokenizer.pad_token = tokenizer.eos_token
promptandresponsepurposes and then tokenizing it:def formatting_func(example):text = f»### Question: {example[‹prompt›]}\n ### Answer: {example['response']}"return textdef tokenize_prompt(prompt):return tokenizer(formatting_func(prompt))tokenized_train_dataset= train_dataset.map(tokenize_prompt)tokenized_val_dataset = eval_dataset.map(tokenize_prompt) - Apply LoRA/PEFT: At this point, the dataset is ready to be trained. The following code sets up the model for parameter-efficient fine-tuning using the LoRA method. In this example, we are setting the rank of the low-rank update matrices (
r) to32and the scaling factor (alpha) to64. We are also defining the target modules where LoRA will be applied, such as the Query (Q), Key (K), and Value (V) vectors; we discussed these in Chapter 1. By settingbias="none", we are telling the model that no bias terms are to be adapted during fine-tuning. Finally, we are applying a dropout of 5% to the LoRA layers to prevent overfitting:Now, we can use thefrom peft import LoraConfig, get_peft_modelconfig = LoraConfig(r=32,lora_alpha=64,target_modules=[«q_proj","k_proj","v_proj", "o_proj",«gate_proj","up_proj","down_proj", "lm_head",],bias=»none",lora_dropout=0.05, task_type="CAUSAL_LM",)model = get_peft_model(model, config)param.requires_gradflag in PyTorch to see which model parameters require gradients to be calculated during the backpropagation process and compare this with all the parameters in the Llama3 model. For this example, we get the following:- All model parameters: 4,628,721,664
- all trainable parameters: 88,121,344 This means that LoRA/PEFT has reduced the original parameters by ~98%.
- All model parameters: 4,628,721,664
- Model training: Now that the LoRA/PEFT configuration has been set up, we need to set up the training configuration details, such as the number of warmup steps (
per_device_train_batch_size) that define the batch size per device (GPU/TPU) during training. If we have multiple GPUs, the total batch size will be this number multiplied by the number of GPUs. We can also make the following configurations:gradient_accumulation_step: This defines the number of steps that it will take to accumulate gradients before a backward pass is performedmax_steps=200: This defines the maximum number of training stepsoptim="paged_adamw_8bit": This specifies the optimizer that’s used during training Since we are using Weights & Biases, a popular tool for experiment tracking and model monitoring, we’ll define its configuration as part of the trainer configuration:
import transformersfrom datetime import datetimerun_name = "llama_fine_tune"output_dir = "<output_dir>" + run_nametrainer = transformers.Trainer(model=model,train_dataset=tokenized_train_dataset,eval_dataset=tokenized_val_dataset,args=transformers.TrainingArguments(output_dir=output_dir,warmup_steps=2,per_device_train_batch_size=2,gradient_accumulation_steps=1, gradient_checkpointing=True,max_steps=200,learning_rate=2.5e-5, bf16=True,optim="paged_adamw_8bit",logging_steps=25,logging_dir="./logs", save_strategy="steps"save_steps=25, eval_strategy="steps",eval_steps=25, do_eval=True, report_to="wandb"run_name=<w&B_run_name>),data_collator=transformers.DataCollatorForLanguageModeling(tokenizer, mlm=False),)trainer.train()
The last line of this code trains/fine-tunes the model.
Configuring the wandb library could provide us with great insights and matrices about training and evaluation losses, time per step, and system utilization. The graph on the left shows that the training loss decreases steadily as the number of global steps increases, indicating that the model is learning and improving on the training data:

Figure 4.3 – Training and evaluation loss reported by the wandb library
Initially, the loss drops sharply, which shows rapid learning early in the training, and then it starts to flatten out as the model continues to train. By step 200, the training loss is quite low (below 0.5), suggesting that the model has fit the training data well.
On the evaluation dataset, evaluation loss also decreases over time but less sharply compared to the training loss. At step 200, the evaluation loss is around 0.75, indicating that the model still generalizes reasonably well to the validation data but may be close to overfitting if further training continues. This is quite possible since both our training and validation datasets are quite small.
The wandb library also provides great insights into resource utilization, such as GPU, CPU, memory, and disk access. For example, the following graph shows GPU utilization over time:

Figure 4.4 – GPU utilization during the training process
As we can see, GPU utilization fluctuated significantly between 50% and 80% for the first 5 minutes, indicating that the GPU was being actively used during this period by the training/evaluation process. After that, GPU utilization starts to fall. This might correspond to tasks that don’t rely heavily on GPU, such as data loading, CPU-bound operations, or idle time between steps.
- Run inference: Now that our model has been trained, it is our turn to test the quality of our inference. For this example, we have created a function called
generate_text()that takes a user’s prompt and generates a continuation of the text using our fine-tuned model. The input prompt is tokenized and processed on a CUDA-enabled device, with the model generating new tokens based on specified parameters such asmax_new_tokensandrepetition_penalty. The generated text is then decoded and returned as a string that excludes any special tokens:def generate_text(user_prompt, max_new_tokens=100, repetition_penalty=1.2):model_input = tokenizer(user_prompt, return_tensors="pt").to("cuda")model.eval()with torch.no_grad():generated_output = model.generate(**model_input,max_new_tokens=max_new_tokens,repetition_penalty=repetition_penalty)generated_text = tokenizer.decode(generated_output[0], skip_special_tokens=True)return generated_text
Now, let’s test our fine-tuned model on a few prompts:
| Question | Does the MyElite Loyalty Program offer any discount on purchases? |
|---|---|
| **Training dataset (**correct answer) | While the program does not directly offer discounts, members can earn up to 2% cashback on all purchases. The cashback is paid annually via a gift card. |
| Fine-tuned response | The program does not currently offer discounts. Members enjoy early access to sales events, special promotions, and other exclusive perks. |
| Non-fine-tuned response | We are happy to announce that we have launched a new loyalty program called "My Elite" for our customers. Customers who spend $50 or more will be automatically enrolled in this elite customer club and earn points with every purchase. |
In this example, the Llama3 model (non-fine-tuned) has created a response that doesn’t align with our FAQ since our membership has annual fees of $99. This is not surprising since the original model has not seen this dataset before. After fine-tuning, the model correctly predicts that there are no discounts, and it also picks up another aspect of our loyalty program – that it offers access to early sales events.
Now, let’s look at another example:
| Question | What is the maximum cashback I can earn? |
|---|---|
| **Training dataset (**correct answer) | The maximum cashback you can earn is 2% of your purchases, capped at 1000 USD per year. The cashback is provided as a gift card. |
| Fine-tuned response | The maximum cashback you can earn is 2% of your purchases, capped at $1000 per year. The cashback is paid annually via a gift card. You will receive the cashback as a gift card once a year if your account balance exceeds $25. |
| Non-fine-tuned response | If you are a member of My Elite, then there's no limit on how much money your wallet could make. You will continue to receive rewards as long as our site has new offers and deals. In case if any offer doesn't work for some reason or another it won't be counted in this amount but we'll still try to find out what went wrong so that next time around when someone tries something similar they don't run into problems like these ones did today! |
In this example, we can see that the non-fine-tuned model has made up an answer that might be reflective of lots of other loyalty programs’ FAQs that this model has been trained on. The fine-tuned model correctly predicts that you can earn up to 2% cashback on a purchase and that it’s capped at 25, which is not in our training dataset. This highlights one of the challenges/focus areas for GenAI – that is, how to keep the model’s response within the assigned guardrails so that it doesn’t hallucinate while responding. This is something we will discuss in Part 3` of this book.
Summary
Section titled “Summary”In this chapter, we discussed optimizing a general-purpose LLM for domain-specific applications, such as chatbots and personalized recommendations. This adaptation is critical because it enhances model accuracy, efficiency, and reliability when dealing with specialized tasks.
First, we discussed the LangChain library, which is instrumental in developing applications that leverage LLMs. LangChain facilitates complex workflows involving external APIs, databases, and retrieval systems, which help in generating context-aware and domain-specific responses. We also learned about techniques such as prompt engineering and knowledge integration. Prompt engineering involves crafting input prompts that guide the model to generate outputs that are more relevant to a specific domain, while knowledge integration uses approaches such as RAG to supplement the model’s responses with external, domain-specific data.
Model fine-tuning is another focus area that we covered in this chapter. This involves additional training of a pre-trained model, typically on domain-specific data, allowing it to better align with the specific terminology and knowledge of a domain. This chapter also introduced parameter-efficient fine-tuning techniques such as LoRA, which reduces computational costs while maintaining performance.
In the next chapter, we will implement some of the techniques mentioned here, such as RAG and fine-tuning, within a K8s environment to show how K8s can help in creating a scalable GenAI application.
Further reading
Section titled “Further reading”To learn more about the topics that were covered in this chapter, take a look at the following resources:
- LangChain – [Beta] Memory: https://python.langchain.com/v0.1/docs/modules/memory/
- LangChain for LLM Application Development: https://www.deeplearning.ai/short-courses/langchain-for-llm-application-development/
- Fine-tuning Mistral on your own data: https://github.com/brevdev/notebooks/blob/main/mistral-finetune-own-data.ipynb
Get This Book's PDF Version and Exclusive Extras
|