Tuning for a specific domain
local graph
Chapter 2 — Tuning for a specific domain
Section titled “Chapter 2 — Tuning for a specific domain”Part 2
Core domain-specific LLMs
The first three chapters in this part of the book discuss training domain-specific SLMs. We’ll look at different approaches to SLM specialization and explore an end-to-end example of model specialization. We’ll also look at how to calculate up front how much memory you’ll need to run inference with a given SLM and how to spot areas for improvements. Chapters 5 and 6 dive deeper into SLM quantization with the ONNX framework and explore different precision formats for model quantization.
This chapter covers
- Preparing data for LLM customization
- The basics of retrieval-augmented generation
- Fine-tuning an LLM
- Alternatives to fine-tuning
Now that you understand the fundamentals of domain-specific LLMs, we’ll look at how you can customize popular open source foundation models using your own data. This chapter and chapters 13 and 15 are the only chapters that will cover tuning; most of the book will focus on inference.
2.1 Data preparation
Section titled “2.1 Data preparation”Fine-tuning a Transformer model for a given task starts with formatting your dataset for training. In this section, we’ll look at two PyTorch examples using Hugging Face Transformers (https://github.com/huggingface/transformers): an encoder-only model (BERT) and a decoder-only model (GPT-2). You’ll see that the workflow is largely the same, with only minor changes based on the model architecture and task. Finally, you’ll see how to prepare data for cases where retrieval-augmented generation (RAG) is a better choice than fine-tuning.
2.1.1 Data preparation for BERT fine-tuning
Section titled “2.1.1 Data preparation for BERT fine-tuning”Let’s consider a classification task using the pretrained bert-base-uncased model (https://huggingface.co/bert-base-uncased). We first need to gather our data, making sure each text sample has a class label. Format it as a list of tuples like this:
dataset = [("This movie is a masterpiece!", "Positive"), ("Not worth watching!", "Negative"), ("Terrific!", "Positive") go here]Next, we need to tokenize the training texts, because BERT models work with tokens rather than raw text.
Notes on tokens
For LLMs, a token is a unit of text the model processes during training and inference. Tokens can represent words, subwords, characters, punctuation, and special characters.
How text is tokenized directly affects model performance and language understanding by shaping how well it manages vocabulary, handles out-of-vocabulary words, and generates coherent responses.
Tokenization is vital in NLP: the token count determines input size and affects processing time and memory use. LLMs have a maximum number of tokens they can accept in a single prompt.
Most pretrained models on the Hugging Face Hub include a custom tokenizer, since each architecture expects a specific token format. For this example, we’ll use the bert-base-uncased tokenizer:
from transformers import BertTokenizer
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')For this kind of transformer, special tokens are used to mark the start and end of each input sequence, and a separator token is used between segments:
max_length = 128formatted_data = [(f"[CLS] {text} [SEP]", label) for text, label in dataset]tokenized_data = tokenizer(formatted_data, padding=True, truncation=True, max_length=max_length, return_tensors='pt')Here, [CLS] marks the beginning, and [SEP] separates segments. A best practice is to keep input sequences a consistent length by padding shorter ones or truncating longer ones, as in previous tokenizer parameters.
We now need to convert the tokenized, formatted text into numerical representations. We’ll assign each token a unique ID (or index) and then represent sequences—and labels—as sequences of these IDs:
import torchfrom sklearn.preprocessing import LabelEncoder
input_ids = tokenized_data['input_ids']attention_mask = tokenized_data['attention_mask']labels = torch.tensor(LabelEncoder() .fit_transform([label for _, label in dataset]))We can now split the initial dataset into training and validation sets:
from sklearn.model_selection import train_test_split
train_inputs, val_inputs, train_labels, val_labels,train_mask, val_mask = train_test_split( input_ids, labels, attention_mask, random_state=42, test_size=0.1)The split is performed with the scikit-learn package (https://scikit-learn.org/stable/), as is standard in many machine learning (ML) and deep learning (DL) use cases.
Before feeding data to the model, we need training and validation data loaders for our custom data. First, let’s define a custom dataset class:
from torch.utils.data import Dataset
class CustomDataset(Dataset): def __init__(self, input_ids, attention_mask, labels): self.input_ids = input_ids self.attention_mask = attention_mask self.labels = labels
def __len__(self): return len(self.input_ids)
def __getitem__(self, idx): return {'input_ids': self.input_ids[idx], 'attention_mask': self.attention_mask[idx], 'labels': self.labels[idx]}We’ll use this class to create the data loaders:
from torch.utils.data import DataLoader
batch_size = 4train_dataset = CustomDataset(train_inputs, train_mask, train_labels)train_dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
val_dataset = CustomDataset(val_inputs, val_mask, val_labels)val_dataloader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False)We can now load the model from the Hugging Face Hub:
from transformers import BertForSequenceClassification
model = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=len(set(labels)))Now we can start the fine-tuning, which will be discussed in sections 2.3 and 2.4.
2.1.2 Data preparation for GPT fine-tuning
Section titled “2.1.2 Data preparation for GPT fine-tuning”For this example, we’ll consider a text completion task using the pretrained GPT-2 base model (the smallest version, with 124M parameters, available at https://huggingface.co/gpt2). Gather your own private data, and ensure that each sample is a piece of text with a clear context (or prompt) and an associated target (or completion):
dataset = [("Once upon a time in a faraway swamp,", "there lived an ugly ork."), # More samples ]We need to pair each context (input) with its target (output) so the model learns to generate the target from the context. Then, as with the BERT model, we tokenize the inputs using the GPT-2 tokenizer:
from transformers import GPT2Tokenizer
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')formatted_data = [f"[CLS] {context} [SEP]" f"{target} [SEP]" for context, target in dataset]numerical_data = [tokenizer.encode(example[0], add_special_tokens=True) for example in formatted_data]In this case, we again need special tokens to mark the beginning and end of each input sequence, plus a separator token. We must ensure that all sequences have a consistent length by padding shorter ones or truncating longer ones to match our desired length. We then convert the tokenized, formatted text into numbers by assigning each token a unique ID and representing sequences as lists of these IDs:
import torch
max_length = max(len(seq) for seq in numerical_data)padded_data = [seq + [tokenizer.pad_token_id] * (max_length - len(seq)) for seq in numerical_data]
input_ids = torch.tensor(padded_data)Before feeding data to the model, we need to create a training data loader for our custom dataset. Let’s first define a custom dataset class:
from torch.utils.data import Dataset
class CustomDataset(Dataset): def __init__(self, input_ids): self.input_ids = input_ids
def __len__(self): return len(self.input_ids)
def __getitem__(self, idx): return {'input_ids': self.input_ids[idx]}The implementation is similar to the BERT use case; what differs is the definition of the __init__ and __getitem__ functions, which reflect the model architecture’s input configuration. We’ll use this class to create the training data loader:
from torch.utils.data import DataLoader
batch_size = 4custom_dataset = CustomDataset(input_ids)dataloader = DataLoader(custom_dataset, batch_size=batch_size, shuffle=True)Finally, we can load the model from the Hugging Face Hub:
from transformers import GPT2LMHeadModel
model = GPT2LMHeadModel.from_pretrained('gpt2')We can now start the fine tuning, as discussed in sections 2.3 and 2.4.
As you’ve seen, thanks to the Transformers library’s friendly API, switching between pretrained models keeps the code largely the same.
2.1.3 Data preparation for RAG
Section titled “2.1.3 Data preparation for RAG”For cases where RAG (discussed in section 2.2) is the best way to specialize a pretrained language model, you must convert your knowledge base to embeddings and store them in a vector database. This makes it easy to retrieve information on demand without sacrificing performance or scalability. Many open source and commercial options are available for this purpose.
In this chapter, we’ll use Facebook AI Similarity Search (FAISS, https://github.com/facebookresearch/faiss), released as open source under an MIT license and maintained by Meta Research. FAISS is a library for efficient similarity search and clustering of dense vectors. It’s implemented in C++ and provides a Python API, so developers don’t need to worry about implementation details. Used internally at Meta, it supports searches that are inefficient or impractical with other approaches. It includes nearest-neighbor implementations for million-to-billion-scale datasets, optimizing the memory/speed/accuracy tradeoff, and it supports GPUs via the Compute Unified Device Architecture (CUDA). FAISS offers several similarity-search methods and assumes that instances are represented as vectors (each identified by an integer) that can be compared using Euclidean (L2) distance. The most similar vectors to a query vector are those with the smallest L2 distance.
To get familiar with FAISS, I’ve provided a companion Colab notebook. We’ll walk through its code in this section. You’ll classify a new input text by calculating its similarity to other text samples in a given category.
In addition to FAISS, we’ll use the sentence-transformers package (https://www.sbert.net), a framework for sentence, text, and image embeddings.
We’ll first set up the sample data, which is a few sentences about Marvel superheroes, categorized into three labels: spiderman, ironman, and captainamerica:
data = [['His secret identity is Peter Parker', 'spiderman'], ['A businessman and engineer who ' + 'runs the company Stark Industries', 'ironman'], ['Superhuman spider-powers and abilities ' + 'after being bitten by a radioactive spider', 'spiderman'], ['A frail man enhanced to the peak of human ' + 'physical perfection by an experimental' + 'super-soldier serum', 'captainamerica']]We’ll put them into a pandas DataFrame with two columns, text and context:
import pandas as pd
df = pd.DataFrame(data, columns = ['text', 'context'])We’ll use the sentence_transformers API to generate embeddings for each text row in the DataFrame:
from sentence_transformers import SentenceTransformer
text = df['text']encoder = SentenceTransformer("paraphrase-mpnet-base-v2")vectors = encoder.encode(text)Now that we have the word embeddings, we can create a FAISS index and add them to it:
import faiss
vector_dimension = vectors.shape[1]l2_index = faiss.IndexFlatL2(vector_dimension)faiss.normalize_L2(vectors)l2_index.add(vectors)An index object makes similarity search efficient in FAISS. If you’re familiar with relational databases, you’re familiar with a table index: a pointer to data in a table used to speed up retrieval. Think of FAISS indexes the same way. Here, they speed up retrieval within a data cluster, so FAISS doesn’t rely on brute-force search. Note that embeddings are normalized before being added to the index so they share a common scale.
The Euclidean distance is the length of a line segment between two points. FAISS calculates it using the standard formula, where and are the Cartesian coordinates of two points and :
Let’s look at a search example. Set a search text related to Spider-Man:
search_text = 'He throws webs'As a result of the search, we expect smaller distances between the search string and the two spiderman samples in the original text corpus. Before searching, we need a few transformations to generate embeddings for the search text—in the same way as we previously did for all the embeddings in scope for this example before adding them to the FAISS index—convert them to a NumPy array, and normalize them:
import numpy as np
search_vector = encoder.encode(search_text)search_vector_as_array = np.array([search_vector])faiss.normalize_L2(search_vector_as_array)Now perform the search:
k = l2_index.ntotaldistances, ann = l2_index.search(search_vector_as_array, k=k)The k argument sets the number of neighbors; here, it’s set to the total number of vectors in the index. The search function returns two arrays: distances, the L2 distances from the query embedding to each of the top k vectors, and ann, the corresponding vector positions in the index. We’ll merge these results into a single DataFrame with the original corpus and labels:
search_results = pd.DataFrame({'distances': distances[0], 'ann': ann[0]})merged_df = pd.merge(search_results, df, left_on='ann', right_index=True)From the results, you can see that the shortest distances between the search text and the other indexed samples occur in the spiderman category:
distances ann text \0 1.501069 2 Superhuman spider-powers and abilities after b... 1 1.552392 0 His secret identity is Peter Parker 2 1.667212 1 A businessman and engineer who runs the compan... 3 1.731641 3 A frail man enhanced to the peak of human phys...context0 spiderman1 spiderman2 ironman3 captainamericaThis example used a small dataset, but the same FAISS workflow can scale to production, unlike a brute-force similarity search.
2.2 Retrieval-augmented generation
Section titled “2.2 Retrieval-augmented generation”Retrieval-augmented generation (RAG) integrates data retrieval into LLM content generation. As shown in figure 2.1, it retrieves relevant data from a larger corpus and feeds it to a pretrained LLM as an external knowledge base, helping the model produce more accurate, up-to-date answers.
This is a way to select external information to improve a model’s response. We can identify two phases:
1 Retrieval phase—The algorithm searches for and retrieves information based on the user’s prompt, from private or public data sources, or both.
2 Content generation phase—After retrieving the relevant embeddings, an LLM uses the context to generate a natural-language response. The pipeline can also check the output against the sources to improve transparency and accuracy.
For domain-specific data and tasks, or unstructured text that isn’t natural language, prompt engineering (few-shot, chain-of-thought, and so on) often won’t produce
graph LR
TD[("Large training dataset")]
LLM["Base LLM"]
App["Web application for Q&A"]
DB[("Domain-specific data")]
User(["User"])
TD -->|Pretraining| LLM
User -->|Query| App
App -->|Response| User
App -->|Search| DB
DB -->|Query and relevant data| LLM
LLM -->|Response| App
[!visual-conversion] Figure 2.1 — The typical RAG workflow (p. 35)
acceptable results. Prompt engineering is faster and can be cheaper because it doesn’t require training, but in these cases, you should consider RAG or fine-tuning the LLM you plan to use.
Which is preferable—RAG or fine-tuning? There’s no silver bullet: the answer depends on the specific use case you’re trying to address. We’ll cover the key considerations in section 2.5 after we look at both strategies.
You can implement RAG-based solutions with LangChain (https://github.com/langchain-ai/langchain) or other dedicated frameworks, covered in chapters 13 and 14. RAG code samples and notebooks are provided in chapters 13 and 14.
2.3 Fine-tuning
Section titled “2.3 Fine-tuning”Fine-tuning further trains a pretrained LLM on a smaller, task-specific dataset to adapt it for a particular task. It updates the model’s weights using your data, tailoring it to your organization’s needs. Figure 2.2 shows the fine-tuning process at a high level.
graph LR
TD[("Large training dataset")]
Base["Base LLM"]
FT["Fine-tuned LLM"]
DS[("Domain-specific data")]
User(["User"])
TD -->|Pretraining| Base
Base --> FT
DS -->|Fine tuning| Base
User -->|Query| FT
FT -->|Response| User
[!visual-conversion] Figure 2.2 — A typical fine-tuning workflow (p. 35)
Fine-tuning is similar to pretraining, but it uses a smaller, task-specific, labeled dataset.
To explain the fine-tuning steps, I have provided a companion Colab notebook. This section walks through the code in that notebook. Note that this section covers the full fine-tuning of a pretrained LLM (that is, updating all the parameters). In contrast, section 2.4 introduces one of the most effective PEFT (parameter-efficient fine-tuning) techniques, an alternative for adapting a pretrained model to a domain by training only a small number of parameters; that section also surveys other PEFT methods.
The pretrained LLM in this example is DistilBERT-base, available on the Hugging Face Hub. It’s a Transformer model that’s smaller and faster than BERT, pretrained on the same corpus via self-supervised learning, with BERT-base as the teacher. It was trained on raw text, using an automatic process to generate inputs and labels (no human labeling), again based on BERT-base. DistilBERT is uncased, meaning it doesn’t distinguish between uppercase and lowercase letters. In this example, we’ll fine-tune the model for question answering.
The training dataset must have these three important fields:
- question—The question the model should answer
- context—The background information from which the model needs to extract the answer
- answers—The starting location of the answer token and the answer text
Several question-answering datasets are available on the Hugging Face Hub. Choose one for this exercise using the Hugging Face Datasets library (https://github.com/huggingface/datasets):
from datasets import load_dataset
training_set = load_dataset("<dataset_id>")Split into training and test sets (80/20):
training_set = training_set.train_test_split(test_size=0.2)Load the DistilBERT tokenizer to process the training set’s question and context fields:
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")Next, we need to preprocess the data by implementing a custom function, preprocess_function. In the function body, we’ll first truncate any context that exceeds the model’s maximum input length:
def preprocess_function(examples): questions = [q.strip() for q in examples["question"]] inputs = tokenizer(questions,examples["context"],max_length=384,truncation="only_second",return_offsets_mapping=True,padding="max_length",We’ll map the answer’s start and end positions to the original context and find the start and end tokens for each answer:
offset_mapping = inputs.pop("offset_mapping")answers = examples["answers"]start_positions = []end_positions = []
for i, offset in enumerate(offset_mapping): answer = answers[i] start_char = answer["answer_start"][0] end_char = answer["answer_start"][0] + len(answer["text"][0]) sequence_ids = inputs.sequence_ids(i)
idx = 0 while sequence_ids[idx] != 1: idx += 1 context_start = idx while sequence_ids[idx] == 1: idx += 1 context_end = idx - 1
# If the answer is not fully inside the context, label it (0, 0) if offset[context_start][0] > end_char or offset[context_end][1] < start_char: start_positions.append(0) end_positions.append(0) else:
idx = context_start while idx <= context_end and offset[idx][0] <= start_char: idx += 1 start_positions.append(idx - 1)
idx = context_end while idx >= context_start and offset[idx][1] >= end_char: idx -= 1 end_positions.append(idx + 1)
inputs["start_positions"] = start_positionsinputs["end_positions"] = end_positionsreturn inputsNext, we’ll apply the custom function to the entire dataset with Datasets’ map function. Set batched=True to process multiple elements at once:
tokenized_dataset = training_set.map(preprocess_function,batched=True, remove_columns=training_set["train"].column_names)We can now load the model:
from transformers import AutoModelForQuestionAnswering
model = AutoModelForQuestionAnswering.from_pretrained("distilbert-base-uncased")We’ll create a batch of examples using the Transformers library’s DefaultDataCollator class, which builds training batches from a list of dataset elements:
from transformers import DefaultDataCollator
data_collator = DefaultDataCollator()Although the Transformers library provides multiple specializations, we’ll use the default data collator here because we’ve already defined a custom preprocessing function and don’t need additional transformations.
We can now define the training hyperparameters:
from transformers import TrainingArguments, Trainer
training_args = TrainingArguments(output_dir="my_awesome_qa_model",evaluation_strategy="epoch",learning_rate=2e-5,per_device_train_batch_size=16,per_device_eval_batch_size=16,num_train_epochs=3,weight_decay=0.01,push_to_hub=False,)We’ll create a Trainer object and pass it the training arguments, along with the model, dataset, tokenizer, and data collator:
trainer = Trainer(model=model,args=training_args,train_dataset=tokenized_dataset["train"],eval_dataset=tokenized_dataset["test"],tokenizer=tokenizer,data_collator=data_collator,)A Trainer object in the Transformers library is a high-level abstraction for training a model (either on a single GPU or distributed across multiple accelerators). It uses the data collator to build batches and the tokenizer to tokenize the training and validation data. To start LLM training, just call the train method:
trainer.train()After training, you can use the fine-tuned model for inference. Provide a question and context for the model to answer:
question = "How many titles has Juventus won?"context = "Juventus Football Club (from Latin: iuventūs), colloquially known as Juve, is a professional football club based in Turin, Piedmont, Italy, that competes in the Serie A, the top tier of the Italian football league system. Founded in 1897 by a group of Torinese students, the club has worn a black and white striped home kit since 1903 and has played home matches in different grounds around its city, the latest being the 41,507-capacity Juventus Stadium. Nicknamed la Vecchia Signora (the Old Lady), the club has won 36 official league titles, 14 Coppa Italia titles and nine Supercoppa Italiana titles, being the record holder for all these competitions;"Tokenize these texts:
inputs = tokenizer(question, context, return_tensors="pt")Pass these inputs to the model, which will return the logits:
import torch
with torch.no_grad(): outputs = model(**inputs)Select the highest-probability start and end positions from the model’s output:
answer_start_index = outputs.start_logits.argmax()answer_end_index = outputs.end_logits.argmax()Finally, decode the predicted tokens to get the answer:
predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]tokenizer.decode(predict_answer_tokens)It should return 36 (as of this writing).
2.4 LoRA
Section titled “2.4 LoRA”Parameter-efficient fine-tuning (PEFT) is a set of techniques for adapting a pretrained model by updating only a small fraction of its parameters. An LLM pretrained on a large dataset already captures many language patterns and facts, so it’s often unnecessary—and inefficient—to tune the entire model for a new task. PEFT fine-tunes only a small subset of parameters, reducing computational costs compared with full fine-tuning while maintaining comparable accuracy and robustness.
These are some major PEFT methods:
- LoRA (Low-rank Adaptation)—The main topic of this section
- Prefix tuning—Keeps the LLM parameters frozen and optimizes a sequence of continuous, task-specific vectors called the prefix
- LoftQ—A framework that quantizes an LLM and provides a low-rank initialization for LoRA fine-tuning
- AdaLoRA—A LoRA variant that adaptively allocates the parameter budget across weight matrices based on importance scores
- P-tuning—Uses trainable continuous prompt embeddings concatenated with discrete prompts
- Prompt tuning—A simpler form of prefix tuning that scales better to larger models
One of the most widely used and efficient approaches is LoRA (low-rank adaptation), introduced in 2021 for LLMs and later adapted to vision transformers. Figure 2.3, from the “LoRA: Low-Rank Adaptation of Large Language Models” paper (https://arxiv.org/abs/2106.09685), summarizes the LoRA process: the pretrained weights are kept frozen, and only a subset of parameters is fine-tuned.
A companion Colab notebook has been provided to show how LoRA works; this section walks through its code. We’ll start with a pretrained model called FLAN-T5 (80M parameters, https://huggingface.co/google/flan-t5-small). FLAN-T5 combines FLAN (Finetuned Language Net) with T5, a language model Google released in 2020. It uses an encoder–decoder architecture and extends the original T5 model to improve zero-shot performance. It’s open source under the Apache License 2.0. Although we’ll use the smallest FLAN-T5 model, the same code and considerations apply to larger versions (250M to 11B parameters).
The dataset used in this example is samsum (https://huggingface.co/datasets/knkarthick/samsum):
from datasets import load_datasetdataset = load_dataset("samsum") h ▲ ┌──┴──┐ │ + │ (element-wise sum) └▲───▲┘ ┌───────────────┘ └───────────────┐ ┌───────┴────────┐ ┌─────┴──────┐ │ Pretrained │ │ B = 0 │ │ weights │ └─────▲──────┘ │ │ │ r (rank) │ W ∈ R^(d×d) │ ┌─────┴──────┐ │ │ │ A = N(0,σ²)│ └───────▲────────┘ └─────▲──────┘ │ <───── d ─────> │ └───────────────┐ ┌───────────────┘ └─┬─┘ x[!visual-conversion] Figure 2.3 — The LoRA fine-tuning process (p. 40)
It contains messenger-style conversations in English and their summaries (our target in this example). The dataset is already split into training and test sets: 14,732 training samples and 819 test samples.
Before preprocessing the data, we need to load the flan-t5-small tokenizer:
from transformers import AutoTokenizer
model_id = "google/flan-t5-small"tokenizer = AutoTokenizer.from_pretrained(model_id)We’ll first preprocess the data by truncating input and target sequences that exceed the maximum lengths and padding shorter ones:
import numpy as npfrom datasets import concatenate_datasets
tokenized_inputs = concatenate_datasets([dataset["train"], dataset["test"]]).map(lambda x: tokenizer(x["dialogue"], truncation=True, batched=True, remove_columns=["dialogue", "summary"])input_lengths = [len(x) for x in tokenized_inputs["input_ids"]]max_source_length = int(np.percentile(input_lengths, 85))
tokenized_targets = concatenate_datasets([dataset["train"], dataset["test"]]).map(lambda x: tokenizer(x["summary"], truncation=True, batched=True, remove_columns=["dialogue", "summary"])target_lengths = [len(x) for x in tokenized_targets["input_ids"]]max_target_length = int(np.percentile(target_lengths, 90))The second pass tokenizes the preprocessed input and target sequences:
def preprocess_function(sample, padding="max_length"): inputs = ["summarize: " + item for item in sample["dialogue"]]
model_inputs = tokenizer(inputs, max_length=max_source_length, padding=padding, truncation=True)
labels = tokenizer(text_target=sample["summary"], max_length=max_target_length, padding=padding, truncation=True)
if padding == "max_length": labels["input_ids"] = [ (l if l != tokenizer.pad_token_id else -100) for l in labels["input_ids"] ]for l in label] for label in labels["input_ids"]]model_inputs["labels"] = labels["input_ids"]return model_inputs
tokenized_dataset = dataset.map(preprocess_function, batched=True, remove_columns=["dialogue", "summary", "id"])Save the processed training and test datasets to disk—we’ll use them later:
tokenized_dataset["train"].save_to_disk("data/train")tokenized_dataset["test"].save_to_disk("data/eval")Now we can load the pretrained model in 8-bit precision:
from transformers import AutoModelForSeq2SeqLM
model = AutoModelForSeq2SeqLM.from_pretrained(model_id, load_in_8bit=True, device_map="auto")To avoid reinventing the wheel, we’ll use Hugging Face’s PEFT library (https://github.com/huggingface/peft), which supports LoRA along with other PEFT methods. As you’ll see in the next code snippets, it provides a high-level API.
We’ll first set up the LoRA configuration with the LoraConfig class:
from peft import LoraConfig, get_peft_model, prepare_model_for_int8_training, TaskType
lora_config = LoraConfig( r=16, lora_alpha=32, target_modules=["q", "v"], lora_dropout=0.05, bias="none", task_type=TaskType.SEQ_2_SEQ_LM)Next, prepare the model for training:
model = prepare_model_for_kbit_training(model)Now add a LoRA adaptor:
model = get_peft_model(model, lora_config)At the end of this process, you’ll train 688,128 parameters—about 0.89% of the model’s total. This training is far less computationally demanding than fine-tuning the full model.
The training process is the same as for regular fine-tuning or full training with the Transformers library; only the model differs, because it has been prepared with LoRA.
We’ll now define a data collator
from transformers import DataCollatorForSeq2Seq
label_pad_token_id = -100data_collator = DataCollatorForSeq2Seq( tokenizer, model=model, label_pad_token_id=label_pad_token_id, pad_to_multiple_of=8)and set the training arguments (for these small models, two or three epochs may be enough):
from transformers import Seq2SeqTrainer, Seq2SeqTrainingArguments
output_dir="lora-flan-t5-small"
training_args = Seq2SeqTrainingArguments( output_dir=output_dir, auto_find_batch_size=True, learning_rate=1e-3, num_train_epochs=3, logging_dir=f"{output_dir}/logs", logging_strategy="steps", logging_steps=500, save_strategy="no", report_to="tensorboard",)Then we’ll create a Trainer instance
trainer = Seq2SeqTrainer( model=model, args=training_args, data_collator=data_collator, train_dataset=tokenized_dataset["train"],)and finally start the training:
trainer.train()After training, save the checkpoint to disk so it can be loaded for inference and testing, and then upload it to the Hugging Face Hub:
peft_model_id="results"trainer.model.save_pretrained(peft_model_id)tokenizer.save_pretrained(peft_model_id)Inference with a LoRA-fine-tuned model works much like standard Transformers inference; the main difference is that we need to load the PEFT configuration for the pretrained checkpoint and the LoRA weights:
import torchfrom peft import PeftModel, PeftConfig
peft_model_id = "results"config = PeftConfig.from_pretrained(peft_model_id)
model = AutoModelForSeq2SeqLM.from_pretrained(config.base_model_name_or_path, load_in_8bit=True, device_map={"":0})tokenizer = AutoTokenizer.from_pretrained(config.base_model_name_or_path)
model = PeftModel.from_pretrained(model, peft_model_id, device_map={"":0})model.eval()Then we can run summarization tasks on the test data as usual:
from random import randrange
dataset = load_dataset("samsun")sample = dataset['test'][randrange(len(dataset["test"]))]
input_ids = tokenizer(sample["dialogue"], return_tensors="pt",truncation=True).input_ids.cuda()outputs = model.generate(input_ids=input_ids, max_new_tokens=10,do_sample=True, top_p=0.9)print(f"input sentence: {sample['dialogue']}\n{'-'*20}")
print(f"summary:\n{tokenizer.batch_decode(outputs.detach().cpu().numpy(), skip_special_tokens=True)[0]}")2.5 RAG or fine-tuning?
Section titled “2.5 RAG or fine-tuning?”Which of these two strategies for specializing LLMs should we prefer—RAG or fine-tuning? As is often the case, it depends on the specific situation.
RAG is useful when you need up-to-date information (recent data or new data sources) that wasn’t part of an LLM’s initial training set. It can reduce hallucinations and improve interpretability because you can trace each answer back to its sources. RAG is usually less costly than fine-tuning because it requires less labeling and no model training. But RAG has downsides. In some cases, extra context isn’t enough: if an LLM struggles with the task it was trained for, additional context won’t help. And at large data volumes, you also need to account for the infrastructure costs of a vector database and the implementation and maintenance of data pipelines.
Fine-tuning often outperforms RAG on tasks that require learning complex patterns and relationships, such as drug discovery or code generation. By training on a task-specific dataset, an LLM can learn domain nuances, including specialized jargon, concepts, and structures. As a result, when it encounters new examples from that domain, a fine-tuned model is more likely to produce accurate, relevant outputs. Fine-tuning typically costs more than RAG, but as you learned in section 2.4, PEFT techniques can make it less computationally hungry (and cheaper) than full fine-tuning—sometimes comparable to, or even lower than, the infrastructure costs of a RAG solution. Fine-tuning also requires more ML engineering expertise than RAG to optimize training and control costs.
RAG is usually more interpretable, while fine-tuning requires more careful training-data curation to mitigate hallucinations. Fine-tuning or PEFT can reduce domain-specific hallucinations, whereas more generic domain hallucinations can be better mitigated with RAG.
Take time to choose the right path for each use case; no single strategy fits all situations.
Summary
Section titled “Summary”-
BERT tokenization adds special tokens [CLS] and [SEP] to mark sequence boundaries for classification tasks.
-
GPT models use context-target pairs, learning to generate target text from the input context.
-
Tokenizers convert text to numerical representations that models can process during training and inference.
-
FAISS builds vector indexes for efficient similarity search over large text embedding datasets.
-
RAG combines retrieval and text generation to give models access to external knowledge.
-
RAG retrieves relevant information from vector databases before generating responses, improving accuracy.
-
Fine-tuning adjusts all parameters of a pretrained model using task-specific labeled datasets.
-
LoRA fine-tunes only a small subset of a model’s parameters, retaining the original weights.
-
PEFT techniques like LoRA cut computational costs compared with full fine-tuning while maintaining performance.
-
RAG works better for up-to-date information and reduces hallucinations through source traceability.
-
Fine-tuning produces better results for complex, domain-specific tasks that require specialized knowledge.
-
Vector databases store embeddings and support fast similarity search for RAG implementations.