Skip to content
ImagineWorld

Advanced Fine-Tuning Techniques and Strategies for Large Language Models

node_idnode-book_llms-in-enterprise_chapter-03-advanced-fine-tuning-techniques-and-strategies-for-large-language-models
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num3
chapter_titleAdvanced Fine-Tuning Techniques and Strategies for Large Language Models
pillar_membershipJ — architecture_design_craft
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 3 — Advanced Fine-Tuning Techniques and Strategies for Large Language Models

Section titled “Chapter 3 — Advanced Fine-Tuning Techniques and Strategies for Large Language Models”

The integration of large language models (LLMs) into business processes represents a significant technological shift, offering massive potential for enhancing productivity, innovation, and customer engagement.

This chapter focuses specifically on strategies for adopting and leveraging LLM technology within enterprises, with an emphasis on fine-tuning pre-trained models and utilizing retrieval-augmented generation (RAG) techniques.

As businesses increasingly recognize the value of generative AI, the demand for AI-powered applications continues to rise. However, the substantial financial costs and technical expertise required to train these models from the ground up aren’t feasible for many organizations. Instead, more accessible approaches, such as utilizing APIs provided by Generative AI leaders like OpenAI, fine-tuning pre-trained models with domain-specific data, and employing intelligent search techniques such as RAG, are more realistic and yet promising alternatives. These methods not only reduce the barrier to entry but also offer customized contextual LLM solutions that can be easily integrated into organizations’ domain-specific data.

This chapter aims to provide:

  • An overview of the common GPT assistant training recipe
  • Different strategies for phased and full integrations of LLMs into business processes
  • Insights into fine-tuning LLMs for enhanced performance, making these powerful tools more relevant and effective for specific business contexts
  • An exploration of using domain-specific data as an external memory, a.k.a RAG, illustrating how this LLM development paradigm can be leveraged to significantly improve the functionality and factuality of LLMs’ outputs

So, let’s dive into the different stages most GPT assistants use to come up with a deployable model that could be used by end-users for many tasks.

day-mode Bookmark

Before diving into RAG implementation, ensure you have the necessary hardware and software set up.

The following are the hardware requirements.

You can run the examples in this chapter on:

  • Google Colab (recommended for easy access to GPUs)
  • A local machine (if you have the required hardware)

For those running locally, the recommended specifications are:

  • CPU: Intel i7/AMD Ryzen 7 (or equivalent)
  • RAM: At least 16 GB (32 GB recommended for large-scale retrieval)
  • GPU: Optional, but recommended for deep learning tasks:
    • Google Colab provides free GPUs (T4, P100, or A100, depending on availability)
      • For local use: NVIDIA RTX 3090 (or higher)

The following are the software requirements:

  • Operating system: Ubuntu 20.04+/Windows 11/macOS 12+
  • Python version: 3.8 or higher
  • Key libraries and dependencies:
    • transformers (for LLMs)
      • faiss (for vector search)
      • langchain (for retrieval pipelines)
      • sentence-transformers (for embeddings)
      • chromadb/pinecone (for vector storage)
      • pypdf (for document processing)
      • bm25 (for sparse retrieval)

You can find the complete code for this chapter at https://github.com/PacktPublishing/LLMs-in-Enterprise.

day-mode Bookmark

The common recipe for training GPT assistants, as you saw in Chapter 1, consists of four main stages. You will find that most of the widely used and most performant models use this approach to come up with a deployable GPT assistant that can be instructed by end users to perform specific tasks. Figure 4.1 shows these stages:

Figure 4.1: Different stages of training GPT assistants

Figure 4.1: Different stages of training GPT assistants

  • Pretraining phase: Starts with raw internet-scale data, where a language model predicts the next token, forming a base model skilled in text completion.
  • Supervised fine-tuning: Utilizes labeled prompt-response pairs to refine the base model, enhancing its precision for specific applications. This approach can be adapted to various data scales and is compatible with methods like weak supervision, which can reduce costs while developing chat-like capabilities across diverse tasks.
  • Reward modeling: Inputs include ranked comparisons of different answers by contractors, using a binary classifier to align the model’s outputs with human preferences, producing a tailored reward model.
  • Reinforcement learning: Involves prompts crafted by experts to guide the reinforcement learning algorithm, optimizing token generation for maximum reward efficacy. Expertly designed prompts help establish effective reward signals and provide high-quality input for the model, thereby improving decision-making in dynamic contexts.

Next, let’s go into a bit more detail for each one of these stages to discuss the size and type of data that is typically used for training, as well as the algorithm and output model, and insights into the visibility of enterprises doing this themselves. It’s worth noting that each of these training recipe stages builds upon the previous ones to finally get to the GPT model.

The pretraining phase is essential in developing a LLM. It involves two main parts: collecting and processing a general-purpose dataset and building and training the base model. The output of this phase is a robust base model ready for fine-tuning.

The dataset for the pretraining stage consists of a massive collection of data sources, including both generic and high-quality specific datasets. Notably, the collection includes CommonCrawl, C4 (also from CommonCrawl), GitHub, Wikipedia, Books, Archives, and stock exchange data, among others. You can see more details in Figure 4.2 from the Llama paper:

Figure 4.2: Different types of data used for the pretraining process (building of the foundation base model

Figure 4.2: Different types of data used for the pretraining process (building of the foundation base model

These datasets are mixed and sampled in defined proportions to form the training set. As covered in detail in Chapter 1, an essential preprocessing step of tokenization converts raw text from these datasets into sequences of integers, which is the format required for the GPT models to process the data.

Base model: pretraining and fine-tuning for text generation

Section titled “Base model: pretraining and fine-tuning for text generation”

The training process uses a transformer-based model architecture. This stage is computationally intensive, involving complex algorithms. The transformer model uses these tokens to predict subsequent tokens, effectively learning language patterns and structures. This base model can then be fine-tuned for various downstream tasks such as sentiment analysis or question-answering, leveraging its ability to generate coherent and contextually relevant text.

The pretraining phase is described as exceptionally computationally intensive, consuming up to 99% of the total training compute time and requiring thousands of GPUs, potentially over several months. Such a scale of resources suggests that only a few well-equipped organizations could realistically undertake this first phase of training a foundation model. Fine-tuning, however, is much more feasible for broader use, allowing customization of the model for specific tasks with less computational expense. Examples of practical applications include creating models that can generate text resembling human-written content, which could be used in various AI applications in technology, customer service, and more. However, base models like GPT-3 and Llama are not released publicly in their raw form, indicating a focus on controlled access and potentially commercial use cases.

After completing the pretraining process of the base model, the next stage is using this base model for supervised fine-tuning (SFT), which relies on the best quality prompt-response pairs from expert contractors to refine the base model.

Supervised fine-tuning is a critical stage in aligning large language models with desired behaviors and performance objectives. It builds upon the initial pretraining phase by refining the model using targeted, high-quality data.

In the supervised fine-tuning stage, the dataset used shifts from large-scale, diverse internet documents to smaller, high-quality datasets specifically constructed for tuning. These are composed of prompt-response pairs, carefully gathered and curated by human contractors to ensure relevance and quality. The data is significantly smaller in volume but higher in quality, with contractors tasked to produce data that is helpful, truthful, and harmless, adhering to detailed labeling guidelines.

The algorithm remains the same with the language modeling approach used in the pre-training phase, but the training set is replaced with a specialized prompt-response dataset. After training on this tailored data, the output is an SFT model. This model is specifically designed to function as a chat model, capable of understanding and generating responses that align closely with the structured input data it was trained on.

While not as computationally intensive as the initial pretraining, the fine-tuning stage still requires precise data handling, model training, and human labor costs. This approach makes it more accessible for a wider range of companies, not just those with substantial resources. Companies typically fine-tune pre-trained models, such as those based on ChatGPT, using their domain-specific data. This fine-tuning process customizes the model to provide responses that are contextually relevant to specific prompts, making it particularly effective for applications like customer service and interactive systems. The base models, already trained through extensive stages including reinforcement learning, serve as a foundation, with fine-tuning enhancing their relevance and performance for particular business needs.

Now that we have the SFT model, we can move on to reinforcement learning from human feedback (RLHF), which consists of both reward modeling and reinforcement learning stages.

Reward modeling and reinforcement learning

Section titled “Reward modeling and reinforcement learning”

The main objective of the RLHF pipeline is optimizing responses using both the reward modeling and the reinforcement learning stages, where the model’s behavior is finely tuned to excel in practical applications.

In the reward modeling phase of the RLHF pipeline, the focus shifts from generating data to evaluating the quality of model outputs through human comparisons. Here, identical prompts are given, and the model generates several responses. Human contractors then rank these responses based on quality. This ranking informs a reward model that scores each completion relative to others based on perceived quality. This scoring is treated almost like a classification task, with the goal of training the model to make accurate reward predictions consistent with human judgments.

Following reward modeling, the reinforcement learning stage utilizes the developed reward model to evaluate and influence the generation of new content. Here, the model, initialized from the SFT stage, generates responses to prompts, which are then scored by the reward model. These scores are used to adjust the probability distribution for generating responses in the future. For instance, if a response receives a high ranked score (e.g., 4 out of 5), the model will increase the probability of generating similar responses in future interactions. Conversely, if a response scores lower (e.g., 2 out of 5), the probability of generating similar responses will be reduced. This adjustment is achieved by modifying the model’s output probabilities, effectively guiding it towards generating responses that align more closely with the desired quality and relevance, as indicated by the ranking scores.

The RLHF pipeline is computationally intensive due to the need for ongoing human feedback and the complexities involved in adjusting model outputs based on this feedback. However, this approach has proven to be highly effective, as models trained with RLHF tend to produce outputs that are more aligned with human preferences compared to other methods. While RLHF models require significant resources and are thus likely to be developed by well-equipped organizations, they are invaluable for applications requiring high fidelity and contextually accurate AI interactions, such as advanced conversational agents and specialized content creation tools.

day-mode Bookmark

Approaches to integration in business processes

Section titled “Approaches to integration in business processes”

Integrating LLMs into business operations offers a transformative pathway for companies looking to enhance their efficiency and innovation. The strategy for adopting LLM technology varies based on organizational needs, technical capability, and budget constraints.

This section explores three primary approaches to LLM integration: utilizing pre-built APIs, fine-tuning pre-trained models with proprietary data, and implementing search retrieval techniques such as RAG. These methods provide scalable and customizable solutions suitable for businesses ranging from small to medium-sized, addressing the challenges associated with the cost and complexity of developing models from scratch.

Figure 4.3: Generative AI adoption approaches with the related complexity listed for each

Figure 4.3: Generative AI adoption approaches with the related complexity listed for each

Figure 4.3, inspired by Gartner, illustrates the decision-making process for determining the optimal AI deployment approach for an organization. Businesses must weigh various factors such as costs, capabilities, and controls to decide whether buying or building AI solutions, and more specifically, Generative AI ones, aligns better with their strategic goals. This figure helps to clarify the trade-offs between the benefits and risks associated with each option, providing a clearer understanding of what influences these decisions.

Now let’s get hands-on and explore the different feasible options that most enterprises could utilize to leverage Generative AI technologies.

In this section, we’ll explore what may technically be the easiest baseline option, though not the most adaptable one from a security and responsible AI development standpoint. In this phase, enterprises can leverage third-party APIs to utilize the most powerful LLMs, such as GPT-4 or Claude-3.5, among others.

Pre-built APIs from established AI providers like OpenAI offer businesses a quick route to integrating advanced AI capabilities. These APIs allow companies to leverage cutting-edge LLM technology without the need for deep AI expertise or significant upfront investment in infrastructure.

Example:

A customer service department can use OpenAI’s API to integrate a chatbot that handles inquiries and support tickets, improving response times and freeing human agents for more complex issues.

In-context learning, also known as few-shot learning, is a powerful technique in natural language processing that leverages pretrained foundational models to perform complex tasks without the need for explicit retraining or parameter updates. This method enables models to quickly adapt to new tasks by using a limited number of input-output examples provided directly in the model’s prompt. This approach helps guide the model in understanding how to process and respond to new types of inputs effectively.

Here’s how in-context learning can be structured in a prompt:

  1. Prefix (optional): This is an introductory text or explanation that sets the stage for what the model is expected to do. It provides context or instructions that can help the model understand the task at hand.
  2. List of class labels: This is a set of possible outputs or categories that the LLM can choose from. Providing these labels helps the model narrow down the possible responses and ensures that the output belongs to a valid class.
  3. Examples (optional): You can add as many examples as you wish, though in some situations there is an upper limit: for example, if using the Banking-77 dataset (which we will explore in a moment), up to 50 examples, one from each class in the 50-class variant, can be included. These examples act as training instances directly within the prompt, allowing the model to “see” what kind of outputs are expected for each type of input. Each example typically pairs a sample input with its corresponding output, demonstrating to the model how to handle similar inputs.
  4. Target text for classification: This is the actual input text that the LLM needs to classify or process. The model uses the provided examples and the context from the prefix and class labels to generate an appropriate response for this target text.
  5. Hyperparameter tuning (optional): This can enhance the model’s performance. For example, setting the max_tokens parameter to 1 ensures a one-word output, which is useful for yes/no classifications. Additionally, adjusting the top_p value allows for control over the diversity of responses, with higher values encouraging more varied outputs.

To illustrate in-context learning, we are going to give an example that uses the widely used 50-class variant of the Banking-77 dataset, which contains online banking queries annotated with their corresponding intents (the label shown below). We evaluate models that predict this label using a fixed test dataset containing ~500 phrases.

Consider a scenario where we have a banking dataset and we want the LLM to classify customer complaints into specific categories such as “Loan,” “Account,” or “Mortgage.”

Here’s how we might structure the prompt for this task:

Prefix (Optional): “Classify the following customer complaint into the correct category based on the examples provided.” List of Class Labels: “Categories: Loan, Account, Mortgage” Examples (Optional): Example 1: “I am not happy with the handling of my loan application.” -> Loan Example 2: “Why was I charged a fee for not maintaining a minimum balance in my account?” -> Account Example 3: “I need to adjust the terms of my mortgage.” -> Mortgage Target Text for Classification: “The interest rate on my loan seems incorrect.”

In this setup:

  • The prefix guides the model’s understanding of the task.
  • The class labels clarify the possible categories.

The examples show the model real instances of how inputs map to categories.

The target text is what the model needs to classify based on its understanding from the above components.

Let’s have a look at the Banking-77 dataset (https://github.com/PolyAI-LDN/task-specific-datasets), which contains online banking queries annotated with their corresponding intents:

import pandas as pd
examples_pool = pd.read_csv(
'https://s.cleanlab.ai/banking-intent-50/examples-pool.csv'
)
examples_pool[​['text', 'label']​].head()

Output:

Textlabel
0I moved to a new city and need to change my addressedit_personal_details
1On my transfer there was a “decline” messagedeclined_transfer
2Help! my wallet was stolen and someone is taking money out. I need this money! what can I do?card_payment_fee_charged
3While abroad I got cash, and a wrong exchange rate was applied.wrong_exchange_rate_for_cash_withdrawal
4Why can’t I get cash?getting_spare_card

Given the dataset above, we can start building our few-shot prompt where this text [Prefix - List of Classes for Valid Completions] will go at the beginning of the prompt and will tell the LLM what the valid classes are so that it can consistently output a class. Without this, the LLM will not choose a valid class and will output something not parsable.

Here, we can also add an optional prefix that we will use later:

# Helper to get prefix for prompt. This gives the LLM all of the labels so that it chooses more accurately.
def get_prefix(examples_pool, prefix=""):
s = ""
if len(prefix) != 0:
s += prefix
s += '\n'
s += "You can choose the label from: "
classes = list(examples_pool.label.unique())
s += ",".join(classes)
return s
print(
get_prefix(
examples_pool, "Please note that some labels in the examples may be inaccurate."
)
)

Output:

Please note that some labels in the examples may be inaccurate. You can choose the label from: edit_personal_details, Declined_transfer, Card_payment_fee_charged, wrong_exchange_rate_for_cash_withdrawal, … Cancel_transfer, Pending_card_payment, Change_pin, Lost_or_stolen_phone, Pending_cash_withdrawal, top_up_reverted,exchange_charge

Here, we randomly choose 50 examples, 1 from each class, to build a 50-shot prompt for the LLM:

# Helper method to get one example from each class for k-shot prompt.
import random
def get_examples(examples_pool):
out = []
unique_classes = examples_pool.label.unique()
for i, cls in enumerate(unique_classes):
temp_pool = examples_pool[examples_pool.label==cls]
random.seed(i)
idx = random.choice(list(range(len(temp_pool))))
text = temp.iloc[idx].text
label = temp.iloc[idx].label
d = {'text':text, 'label':label}
out.append(d)
return out
examples = get_examples(examples_pool)

examples[1:5]

Output:

[{‘text’: ‘i just got married and i need to change my name’, ‘label’: ‘edit_personal_details’}, {‘text’: ‘it declined my transfer.’, ‘label’: ‘declined_transfer’}, {‘text’: “why am i being charged for atm cash withdrawals? the only reason i use it is because it’s been free! now you expect me to pay for them, and how much is that going to cost me?”, ‘label’: ‘card_payment_fee_charged’}, {‘text’: ‘i attempted to get money using a foreign currency at an atm but the rate was highly inaccurate!’, ‘label’: ‘wrong_exchange_rate_for_cash_withdrawal’}, {‘text’: ‘tell me where i can find the auto top up feature and a little bit about it please.’, ‘label’: ‘getting_spare_card’}]

Before diving into the code, it’s important to understand how to generate an entire prompt effectively. This involves constructing a complete and coherent input that the model can process to produce the desired output. The following code demonstrates how to assemble such prompts, ensuring they are structured in a way that optimizes the model’s response:

# - target text for classification
from langchain_core.prompts import PromptTemplate
from langchain_core.prompts.few_shot import FewShotPromptTemplate
def get_prompt_output(example_pool, txt, example, prefix=""):
prompts_template = PromptTemplate(
input_variables=["text", "label"],
template="Text: {text}\nLabel: {label}",
)
p = FewShotPromptTemplate(
example_prompt = prompt_template,
examples = examples,
prefix = get_prefix(examples_pool, prefix),
suffix = "Text: {text}\nLabel:",
input_variables = ['text'],
)
return p.format(text=text).strip()
print( get_prompt_output(examples_pool, "Classify this text!", examples, Please note that some labels in the examples may be inaccurate."))

Quick tip: Enhance your coding experience with the AI Code Explainer and Quick Copy features. Open this book in the next-gen Packt Reader. Click the Copy button

(1) to quickly copy code into your coding environment, or click the Explain button

(2) to get the AI assistant to explain a block of code to you.

![A white background with a black text

AI-generated content may be incorrect.](https://static.packt-cdn.com/products/9781836203070/graphics/Images/image_%282%29.png)

The next-gen Packt Reader is included for free with the purchase of this book. Scan the QR code OR go to packtpub.com/unlock, then use the search bar to find this book by name. Double-check the edition shown to make sure you get the right one.

![A qr code on a white background

AI-generated content may be incorrect.](https://static.packt-cdn.com/products/9781836203070/graphics/Images/Latest_QR.png)

Output:

Beware some labels in the examples may be noisy. You can choose the label from: edit_personal_details,declined_transfer,card_payment_fee_charged,wrong_exchange_rate_for_cash_withdrawal,getting_spare_card,…,lost_or_stolen_phone,pending_cash_withdrawal,top_up_reverted,exchange_charge Text: i just got married and i need to change my name Label: edit_personal_details Text: it declined my transfer. Label: declined_transfer Text: why am i being charged for atm cash withdrawals? the only reason i use it is because it’s been free! now you expect me to pay for them, and how much is that going to cost me? Label: card_payment_fee_charged Text: i attempted to get money using a foreign currency at an atm but the rate was highly inaccurate! Label: wrong_exchange_rate_for_cash_withdrawal Text: tell me where i can find the auto top up feature and a little bit about it please. Label: getting_spare_card Text: Classify this text! Label:

Now that we have generated the entire prompt and provided a few examples, we can use the OpenAI API with the extended prompt to get our answer for the test example at the end:

import openai, os
# Helper method to prompt OpenAI LLM and get responses.
def get_response(prompts):
response = openai.Completion.create(
model="text-davinci-003", # Specifies the LLM model to use (e.g., "text-davinci-003").
prompt=prompt, # The input text or question you are asking the model to respond to.
temperature, # Controls the randomness of the response; 0 makes it deterministic.
max_tokens, # Limits the response to a maximum of 50 tokens.
top_p , # Uses nucleus sampling, with 1 meaning all tokens are considered (equivalent to greedy sampling).
frequency_penalty, # Prevents repetitive text in the response; 0 means no penalty.
presence_penalty# Controls the introduction of new topics; 0 means no penalty.
)
# Parse output to get just the label.
resp = response['choices'][0]['text'].split('\n')[0].split(',')[0]
.strip().lower().rstrip(string.punctuation)
# Just in case a response is not a perfect match, we know.
if resp not in examples_pool.label.unique():
raise ValueError(f"Unexpected response: {resp}")
return resp
text = "\'How can I change my pin?\'"
examples = get_examples(examples_pool)
prompt = get_prompt_output(examples_pool, text, examples)
response = get_response(prompt)
print("Model classified ", text, " as ", response)

Output:

Model classified ‘How can I change my pin?’ as change_pin

For organizations requiring more tailored solutions, fine-tuning pre-trained LLMs with domain-specific data is an effective strategy. This approach allows businesses to adapt robust, general-purpose models to their unique contexts, enhancing relevance and performance.

Example application

A financial analytics firm could fine-tune an LLM on specific financial data and regulatory requirements to develop a tool that generates personalized investment reports for clients, ensuring compliance and relevance.

The goal of this stage is to prepare the data that will be used to fine-tune the model. Data preparation is a critical step because the quality and format of your data significantly impact how well your model learns and performs.

In this example, we chose the Llama model due to its robust architecture and performance capabilities, which make it particularly effective for fine-tuning tasks. Llama is designed to handle a variety of language tasks with high accuracy, making it an excellent choice for our needs. Additionally, its open-source nature allows for greater flexibility and experimentation during the fine-tuning process.

It’s important to note that the techniques discussed here are not limited to Llama; similar methodologies can be applied to other models as well, such as GPT-3 or BERT. Each model may have its unique characteristics, but the foundational principles of data preparation and fine-tuning remain consistent across different architectures.

First, the code installs several Python libraries that are essential for the process. These libraries help with model acceleration, efficient computation, working with transformers, and training the model:

!pip install -q accelerate==0.21.0 peft==0.4.0 bitsandbytes==0.40.2 transformers==4.31.0 trl==0.4.7

Essential Python libraries and modules from the transformers and other packages are imported. These will help load datasets, process data, and define the model architecture:

import os
import torch
from datasets import load_dataset
from transformers import (
AutoModelForCausalLM,
AutoTokenizer,
BitsAndBytesConfig,
HfArgumentParser,
TrainingArguments,
pipeline,
logging,
)
from peft import LoraConfig, PeftModel
from trl import SFTTrainer

Before fine-tuning the LLaMA model, we need to load and prepare the dataset that will be used for training. The following code snippet demonstrates how to load a specific instruction dataset, which is essential for guiding the model’s learning process:

# The instruction dataset to use
dataset_name = "mlabonne/guanaco-llama2-1k"
dataset = load_dataset(dataset_name, split="train")

A tokenizer is loaded using AutoTokenizer.from_pretrained. The tokenizer prepares text data for the model by converting words into tokens (numerical representations) that the model can understand.

The model is initially configured to use specific computational optimizations for efficiency. This includes using a 4-bit quantized version, which reduces the model’s memory footprint:

Model and Tokenizer Configuration Parameters

Section titled “Model and Tokenizer Configuration Parameters”

Purpose: Specifies the data type for computations when using 4-bit precision

Section titled “Purpose: Specifies the data type for computations when using 4-bit precision”
# Here, it's set to use 16-bit floating point numbers (float16)
bnb_4bit_compute_dtype = "float16"
# Parameter: use_4bit

Purpose: Flag to indicate if the model should be loaded with 4-bit quantized weights

Section titled “Purpose: Flag to indicate if the model should be loaded with 4-bit quantized weights”
# Using 4-bit weights can significantly reduce model size and memory footprint
use_4bit = True
# Parameter: bnb_4bit_quant_type

Purpose: Specifies the type of quantization, can be ‘fp4’ or ‘nf4’

Section titled “Purpose: Specifies the type of quantization, can be ‘fp4’ or ‘nf4’”
# 'nf4' is used here, which stands for normal float 4-bit quantization
bnb_4bit_quant_type = "nf4"
# Parameter: use_nested_quant

Purpose: Flag to indicate if nested quantization is used for 4-bit models

Section titled “Purpose: Flag to indicate if nested quantization is used for 4-bit models”
# Nested quantization is not used in this case
use_nested_quant = False
# Parameter: model_name

Purpose: Specifies the identifier of the model to be loaded from Hugging Face model hub

Section titled “Purpose: Specifies the identifier of the model to be loaded from Hugging Face model hub”
# This is the name of the pre-trained model
model_name = "NousResearch/Llama-2-7b-chat-hf"
# Parameter: device_map

Purpose: Maps model layers to specific devices, like GPUs

Section titled “Purpose: Maps model layers to specific devices, like GPUs”
# Here, it maps all layers to GPU 0
device_map = {"": 0}
# Prepare the dtype for model computation based on the bnb_4bit_compute_dtype string
# This converts the string 'float16' to the actual torch.float16 data type
compute_dtype = getattr(torch, bnb_4bit_compute_dtype)
compute_dtype = getattr(torch, bnb_4bit_compute_dtype)
bnb_config = BitsAndBytesConfig(
load_in_4bit=use_4bit,
bnb_4bit_quant_type=bnb_4bit_quant_type,
bnb_4bit_compute_dtype=compute_dtype,
bnb_4bit_use_double_quant=use_nested_quant,
)
model = AutoModelForCausalLM.from_pretrained(
model_name,
quantization_config=bnb_config,
device_map=device_map
)
tokenizer = AutoTokenizer.from_pretrained(
model_name, trust_remote_code=True)
tokenizer.pad_token = tokenizer.eos_token
tokenizer.padding_side = "right"

In this stage, you set up the model with the necessary configurations, especially focusing on adjustments that allow the model to learn from your specific dataset effectively.

LoRA configuration: LoRA (Low-Rank Adaptation) is a technique to adapt large models with minimal additional parameters. Here, specific LoRA configurations are set to adjust the model without extensive retraining:

Parameters for LoRA (Low-Rank Adaptation) Configuration

Section titled “Parameters for LoRA (Low-Rank Adaptation) Configuration”

Purpose: Scaling factor for LoRA layers, which helps in controlling the magnitude

Section titled “Purpose: Scaling factor for LoRA layers, which helps in controlling the magnitude”

of the updates to the attention mechanism.

Here, it’s set to 16, meaning the low-rank matrices will be scaled by this factor.

Section titled “Here, it’s set to 16, meaning the low-rank matrices will be scaled by this factor.”
# Best Practice: A higher lora_alpha value increases the influence of the LoRA updates, # which can enhance learning but may lead to overfitting. # Start with a moderate value (e.g., 16 or 32) and adjust based on validation performance.
lora_alpha = 16

Purpose: Dropout rate for the LoRA layers, which helps prevent overfitting by

Section titled “Purpose: Dropout rate for the LoRA layers, which helps prevent overfitting by”

randomly dropping units (along with their connections) during the training process.

Section titled “randomly dropping units (along with their connections) during the training process.”
# Set to 0.1, so there is a 10% chance that individual neurons will be dropped out.
lora_dropout = 0.1
# Parameter: lora_r

Purpose: The rank of the low-rank matrices that are used to approximate the original

Section titled “Purpose: The rank of the low-rank matrices that are used to approximate the original”

high-rank matrices in the attention layers.

Section titled “high-rank matrices in the attention layers.”
# This is set to 64, meaning the rank of the adaptation matrix is 64.
lora_r = 64
peft_config = LoraConfig(
lora_alpha=lora_alpha,
lora_dropout=lora_dropout,
r=lora_r,
bias="none",
task_type="CAUSAL_LM",
)

Training arguments:These are configurations related to how the model should be trained, including the number of epochs, batch sizes, learning rate, and whether to use mixed precision training for faster computation.

output_dir = "./results" # Directory to save the model
num_train_epochs = 3 # Number of training epochs
per_device_train_batch_size = 8 # Batch size per device (GPU/TPU)
gradient_accumulation_steps = 1 # Number of updates steps to accumulate before performing a backward/update pass
optim = "adamw_torch" # Optimizer to use
save_steps = 500 # Save checkpoint every X updates steps
logging_steps = 100 # Log every X updates steps
learning_rate = 5e-5 # Learning rate
weight_decay = 0.01 # Weight decay
fp16 = False # Use 16-bit (mixed) precision training
bf16 = False # Use bfloat16 precision training
max_grad_norm = 1.0 # Max gradient norm
max_steps = -1 # If > 0: set total number of training steps to perform (overrides num_train_epochs)
warmup_ratio = 0.1 # Ratio of total training steps used for a linear warmup from 0 to learning_rate
group_by_length = False # Group sequences of roughly the same length together when batching
lr_scheduler_type = "linear" # Learning rate scheduler type
training_arguments = TrainingArguments(
output_dir=output_dir,
num_train_epochs=num_train_epochs,
per_device_train_batch_size=per_device_train_batch_size,
gradient_accumulation_steps=gradient_accumulation_steps,
optim=optim,
save_steps=save_steps,
logging_steps=logging_steps,
learning_rate=learning_rate,
weight_decay=weight_decay,
fp16=fp16,
bf16=bf16,
max_grad_norm=max_grad_norm,
max_steps=max_steps,
warmup_ratio=warmup_ratio,
group_by_length=group_by_length,
lr_scheduler_type=lr_scheduler_type,
report_to="tensorboard"
)

Initialize Trainer, The SFTTrainer from the TRL library is used to handle the fine-tuning of the model. It is configured with the model, training dataset, tokenizer, and the training arguments set earlier:

trainer = SFTTrainer(
model=model,
train_dataset=dataset,
peft_config=peft_config,
dataset_text_field="text",
max_seq_length=max_seq_length,
tokenizer=tokenizer,
args=training_arguments,
packing=packing,
)

The model is trained using the train method of the SFTTrainer. This method adjusts the model parameters based on the training data to minimize the prediction error:

trainer.train()

Output:

StepTraining Loss
11.3501
22.0158
31.0487
41.2877
51.4512
61.6599

After training, the model is saved for later use or deployment. The trained model can then generate text based on prompts to evaluate its performance qualitatively:

trainer.model.save_pretrained(new_model)
prompt = "What is a large language model?"
pipe = pipeline(task="text-generation", model=model, tokenizer=tokenizer,
max_length=200)
# This line processes the prompt using the specified tokens for LLaMA or similar models. # <s> denotes the start of the sequence, [INST] marks the beginning of the instruction, # and [/INST] marks the end of the instruction:
result = pipe(f"<s>[INST] {prompt} [/INST]")
print(result[0]['generated_text'])

Output:

[INST] What is a large language model? [/INST] A large language model is a type of artificial intelligence (AI) model that is trained on a large dataset of text to generate human-like language outputs. It is designed to be able to understand and generate text in a way that is similar to human language, and can be used for a wide range of applications such as chatbots, language translation, and text summarization. Large language models are typically trained using deep learning techniques, such as recurrent neural networks (RNNs) or transformer models, and are often based on pre-trained models such as BERT or RoBERTa. These models are trained on large datasets of text, such as books, articles, or websites, and are designed to learn the patterns and structures of language. Some examples of large language models include:

  • BERT (Bidirectional Encoder Representations from Transformers

Fine-tuning strategies for enhanced performance

Section titled “Fine-tuning strategies for enhanced performance”

Fine-tuning LLMs is a crucial step for businesses seeking to enhance the model’s relevance and performance in specific operational contexts. This section explores the comprehensive strategies involved in fine-tuning LLMs, from the initial data selection and preparation to model optimization and ongoing monitoring of performance. By tailoring these models to fit distinct business needs, organizations can significantly improve the efficacy and applicability of their AI solutions.

The process of fine-tuning an LLM begins with the careful selection and preparation of data. The quality and relevance of the data used for training directly influence the model’s performance:

  • Data collection: Gather data that reflects the real-world scenarios the LLM will encounter. This includes internal data from business operations and external data from industry sources.
  • Data cleaning: Clean the data to remove inaccuracies or irrelevant information. This involves correcting errors, removing duplicates, and handling missing values.
  • Data annotation: Annotate data with the correct labels or tags. In the case of an LLM, this could involve tagging text data with thematic labels or categorizing it according to its relevance to specific business functions.
  • Data augmentation: Expand the dataset by artificially enhancing the diversity and volume of data through techniques such as synonym replacement, back translation, or text generation, which can help improve the robustness of the model.

Once the data is prepared, the next step is to adjust the LLM’s parameters to optimize its performance for specific business tasks. This involves both technical adjustments and strategic decisions about the model’s configuration:

  • Hyperparameter optimization: Fine-tune hyperparameters such as learning rate, batch size, and number of epochs to find the best settings for training the model on the specific dataset.
  • Algorithmic adjustments: Modify the model’s architecture (LoRA) or training algorithms to better suit the specific characteristics of the data or the requirements of the task.
  • Transfer learning: Apply transfer learning techniques to adapt a pre-trained model to a new but related problem, which can reduce the need for extensive retraining from scratch. Example Fine-tuning the model on domain-specific data Case Study: A healthcare provider uses an LLM to automate patient interaction in its customer service. By fine-tuning the model on transcripts of actual patient interactions, including specific medical terminology and frequently asked questions, the model becomes better at understanding and responding to patient queries, thereby improving response accuracy and customer satisfaction.

Effective monitoring systems are essential to ensure that the fine-tuned model continues to perform as expected and remains aligned with business objectives:

  • Performance metrics: Establish clear metrics to measure the model’s performance, such as accuracy, response time, and user satisfaction.
  • Regular reviews: Conduct regular assessments to compare the model’s outputs against expected outcomes. This helps in identifying any deviations or areas for improvement.
  • Feedback loops: Implement feedback mechanisms where end-users can report issues or provide insights about the model’s performance. This real-time data is invaluable for continuous improvement.

RAG combines the generative power of LLMs with the precision of information retrieval systems. This method is ideal for applications where up-to-date accuracy is crucial, such as dynamic content creation or complex decision support systems. Some examples of where RAG can be incredibly useful are:

  • Academic research: An academic research group can implement a RAG system to streamline literature reviews, where the model retrieves and synthesizes the latest research findings, aiding in the rapid assimilation of new knowledge and trends.
  • Bing chat (Copilot): Microsoft’s Bing Chat uses RAG to enhance user interactions by retrieving up-to-date information from the web and providing contextually relevant answers, making it a powerful tool for research and casual inquiries.
  • Customer support: Companies like Salesforce utilize RAG systems to improve customer support. By retrieving relevant information from a vast database of customer interactions and product documentation, the system provides agents with synthesized insights, enabling faster and more accurate responses to customer inquiries.

RAG represents a significant advancement in the application of LLMs, combining the generative capabilities of these models with sophisticated information retrieval techniques. The following diagram shows how this process is structured:

Figure 4.4: High-level block diagram of the RAG architecture

Figure 4.4: High-level block diagram of the RAG architecture

This approach significantly enhances the accuracy and relevance of the content produced by LLMs, making them more effective and applicable across a variety of industries. This section delves into the RAG framework, its implementation in real-world scenarios, and methods for assessing its impact on business operations.

RAG integrates traditional LLMs with a retrieval system that can access a vast database of information in real time. This integration allows the model to augment its generative outputs with precise, contextually relevant data pulled from the database, thereby enhancing the accuracy and specificity of its responses.

The addition of retrieval capabilities addresses one of the primary limitations of standard LLMs their reliance on fixed training data. RAG allows LLMs to incorporate the most current information, making them highly effective for tasks requiring up-to-date knowledge or specific expertise.

RAG can be adapted to various industries, enhancing applications where accuracy and timeliness of information are crucial. From customer service to research and development, RAG expands the utility of LLMs beyond traditional generative tasks.

In sectors like healthcare, finance, and legal services, RAG can provide professionals with real-time, accurate information, greatly aiding decision-making processes. For instance, in healthcare, RAG could be used to fetch the latest clinical guidelines or research findings to assist in patient diagnosis and treatment planning.

Example:

RAG implementation

Case Study: A legal firm implements RAG to enhance its document automation tool, as shown in Figure 4.5. The system dynamically retrieves relevant case laws and statutes while drafting legal documents, ensuring that all references and legal precedents are current and accurately integrated into the documents. This implementation not only speeds up the drafting process but also improves the accuracy and compliance of the legal documents produced.

Figure 4.5: An example of building a RAG solution for the task of chatting with documents

Next, we’ll delve into specific use cases that illustrate how a well-structured knowledge base can enhance RAG performance. This progression will help you understand the practical applications and relevance of each component, connecting back to the implementations and use cases discussed in the previous section.

This is a collection of relevant and up-to-date information that serves as a foundation for RAG. It can be a database, a set of documents, or a combination of both. In this case, it’s a PDF provided by you that will be used as a source of truth to provide answers to user queries.

The following code will load PDF documents from a directory specified by the user using LlamaIndex’s SimpleDirectoryReader:

from llama_index.core import SimpleDirectoryReader # Replace with the actual import path if different
# Define the path to the directory containing PDFs
input_dir_path = "./pdfs"
data_file = ['./pdfs/dummy.pdf', './pdfs/EJ1245288.pdf' ]
# Initialize the SimpleDirectoryReader
# Load the data from the directory
documents = SimpleDirectoryReader(input_files=data_file).load_data()
# Print the loaded documents to verify
if documents:
print("Loaded the following documents:")
for doc in documents:
print(doc)
else:
print("No documents loaded.")

This is a technique for representing text data as numerical vectors, which can be input into machine learning models. The embedding model is responsible for converting text into vectors.

from llama_index.embeddings.huggingface import HuggingFaceEmbedding
embed_model = HuggingFaceEmbedding(
model_name="BAAI/bge-large-en-v1.5", trust_remote_code=True
)

These are collections of pre-computed numerical vector representations of text data for fast retrieval and similarity search, with capabilities like CRUD operations, metadata filtering, and horizontal scaling. By default, LlamaIndex uses a simple in-memory vector store that’s great for quick experimentation.

from llama_index.core import Settings
from llama_index.core import VectorStoreIndex
# ====== Create vector store and upload indexed data ======
Settings.embed_model = embed_model # we specify the embedding model to be used
index = VectorStoreIndex.from_documents(documents
)

The retriever takes a query string to fetch relevant context and then sends them both as a prompt to the LLM to generate a final natural language response. The LLM used here is Llama 3, which is served locally, thanks to Ollama, which is a platform that enables local model execution and provides compatibility with the OpenAI API, on their official website. Ollama supports running models like Llama 3 and Llama 2, allowing users to integrate these models into applications effectively. The final response is displayed in the user interface.

from llama_index.llms.ollama import Ollama
from llama_index.core import Settings
from langchain_core.prompts import PromptTemplate
# setting up the llm
llm = Ollama(model="llama3", request_timeout=120.0)
# ====== Setup a query engine on the index previously created ======
Settings.llm = llm # specifying the llm to be used
query_engine = index.as_query_engine(streaming=True, similarity_top_k=4)

Note

Setting the streaming parameter to True in the code allows the query engine to stream results incrementally as they become available, rather than waiting for the entire response to be generated before displaying it. This can enhance the user experience by providing quicker feedback, allowing users to see partial results or intermediate responses while the model continues processing the query.

A custom prompt template is used to refine the response from the LLM and include the context as well:

examples = [
[
{
"question": "Between Muhammad Ali and Alan Turing, who lived longer?",
"answer": """
Analysis required: Yes.
Step 1: Determine Muhammad Ali's age at death.
Result: Muhammad Ali died at 74 years old.
Step 2: Determine Alan Turing's age at death.
Result: Alan Turing died at 41 years old.
Conclusion: Muhammad Ali lived longer.
"""
},
{
"question": "What is the birthdate of the person who founded Craigslist?",
"answer": """
Analysis required: Yes.
Step 1: Identify the founder of Craigslist.
Result: The founder of Craigslist is Craig Newmark.
Step 2: Find Craig Newmark's birthdate.
Result: Craig Newmark was born on December 6, 1952.
Conclusion: Craig Newmark was born on December 6, 1952.
"""
},
{
"question": "Who was George Washington's maternal grandfather?",
"answer": """
Analysis required: Yes.
Step 1: Identify George Washington's mother.
Result: George Washington's mother was Mary Ball Washington.
Step 2: Identify Mary Ball Washington's father.
Result: Mary Ball Washington's father was Joseph Ball.
Conclusion: George Washington's maternal grandfather was Joseph Ball.
"""
},
{
"question": "Are the directors of Jaws and Casino Royale from the same country?",
"answer": """
Analysis required: Yes.
Step 1: Identify the director of Jaws and their nationality.
Result: The director of Jaws is Steven Spielberg, who is from the United States.
Step 2: Identify the director of Casino Royale and their nationality.
Result: The director of Casino Royale is Martin Campbell, who is from New Zealand.
Conclusion: No, the directors of Jaws and Casino Royale are not from the same country.
"""
}
]
]
example_prompt = PromptTemplate(
input_variables=["question", "answer"],
template="Question: {question}\n{answer}"
)
print(example_prompt.format(**examples[0][0]))

To fully understand the value brought by RAG, it is essential to evaluate its impact on business processes comprehensively:

  • Business process efficiency: Assess how RAG reduces time and labor costs by automating complex information retrieval tasks that would otherwise require significant human effort.
  • Customer satisfaction: Measure improvements in customer service and satisfaction resulting from faster response times and more accurate, informed interactions.
  • Operational efficiency: Analyze the broader effects on operational efficiency, including the speed and quality of decision-making processes, and the ability to maintain high standards of accuracy in dynamic environments.

day-mode Bookmark

This chapter explored the integration of LLMs into business processes. It began by providing a high-level overview of the common training recipe used to train most GPT systems, as well as offering some insight into the different strategies that businesses could use to leverage Generative AI technology. The chapter covered the use of APIs, fine-tuning pre-trained models, and the innovative application of RAG to tailor solutions that integrate smoothly with existing IT infrastructure.

The chapter detailed two primary approaches for LLM integration: fine-tuning pre-trained models with domain-specific data for customized solutions and implementing RAG to improve accuracy by combining generative models with information retrieval systems. For example, customer service departments can enhance response times using OpenAI’s API to integrate chatbots, while financial analytics firms might fine-tune LLMs on specific data for personalized client reports.

The exploration of RAG highlighted its role in addressing the limitations of traditional LLMs that rely on fixed training data. By enabling real-time access to extensive databases, RAG enhances the accuracy and specificity of LLM outputs while significantly reducing the occurrence of hallucinations, making them more effective for applications that require up-to-date knowledge or expertise. This is particularly useful in sectors like healthcare and legal services, where RAG can fetch the latest guidelines or case laws to assist professionals.

In the next chapter, we will move from theory to practice, implementing RAG pipelines in re­al-world applications using tools such as LangChain and FAISS.

day-mode Bookmark