Skip to content
ImagineWorld

Text Classification Using Deep Learning Language Models

node_idnode-book_mastering-nlp-from-foundations-to-agents_chapter-06-text-classification-using-deep-learning-language-models
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num6
chapter_titleText Classification Using Deep Learning Language Models
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 6 — Text Classification Using Deep Learning Language Models

Section titled “Chapter 6 — Text Classification Using Deep Learning Language Models”

In Chapter 5, we explored text classification using traditional ML approaches, emphasizing feature engineering techniques such as TF-IDF and Word2Vec, along with classical models and evaluation practices. While these methods are effective for many well-defined problems, organizations increasingly encounter limitations when dealing with large-scale, heterogeneous text data. In such settings, manually designed features struggle to capture nuanced semantics, long-range dependencies, and domain-specific language variations, leading to brittle models that require extensive tuning and frequent maintenance.

This challenge highlights a central pain point in modern NLP systems: the gap between surface-level text representations and the deep contextual understanding required for real-world applications. To address these limitations, this chapter transitions from feature-driven methods to deep-learning-based text classification, where representations are learned directly from data rather than being handcrafted. Deep learning models, particularly those based on Transformer architectures, have changed how text is modeled by enabling rich, context-aware representations that adapt across tasks and domains. Unlike earlier neural approaches such as recurrent neural networks (RNNs) or convolutional neural networks (CNNs), transformers can model long-range dependencies efficiently and leverage attention mechanisms to capture global context within text.

By the end of this chapter, you will understand not only how deep learning models such as BERT and GPT are used for text classification, but also why they are necessary in modern NLP systems and how they extend the concepts introduced in Chapter 5.

In a nutshell, the following topics will be covered in this chapter:

  • Understanding deep learning basics
  • The architecture of different neural networks and the challenges of training them
  • Understanding Transformers
  • Learning more about large language models and the challenges of training them

To successfully navigate through this chapter, certain technical prerequisites are necessary, as follows:

  • Programming knowledge: A strong understanding of Python is essential, as it’s the primary language used for most deep learning (DL) and NLP libraries.
  • ML fundamentals: A good grasp of basic ML concepts, such as training/testing data, overfitting, underfitting, accuracy, precision, recall, and F1 score, will be valuable.
  • Deep learning basics: Familiarity with DL concepts and architectures, including neural networks, backpropagation, activation functions, and loss functions, is essential. Knowledge of RNNs and CNNs would be advantageous but not strictly necessary, as we will focus more on Transformer architectures.
  • NLP basics: Some understanding of basic NLP concepts such as tokenization, stemming, lemmatization, and word embeddings (such as Word2Vec or GloVe) would be beneficial.
  • Libraries and frameworks: Experience with libraries such as TensorFlow and PyTorch for building and training neural models is crucial. Familiarity with NLP libraries such as NLTK or SpaCy can also be beneficial. For working with BERT specifically, knowledge of the transformers library from Hugging Face would be very helpful.
  • Hardware requirements: DL models, especially Transformer-based models such as BERT, are computationally intensive and typically require a modern graphics processing unit (GPU) to train in a reasonable amount of time. Access to a high-performance computer or cloud-based solutions with GPU capabilities is highly recommended.
  • Mathematics: A good understanding of linear algebra, calculus, and probability is helpful for understanding the inner workings of these models, but most of the chapter can be understood without in-depth mathematical knowledge.

These prerequisites are intended to equip you with the necessary background to understand and implement the concepts discussed in the chapter. With these in place, you should be well-prepared to delve into the fascinating world of DL for text classification using BERT.

In this section, we explain what neural networks and deep neural networks are, what the motivation is for using them, and the different types (architectures) of deep learning models.

Neural networks are a subfield of artificial intelligence (AI) and ML that focuses on algorithms inspired by the structure and function of the brain. It is also known as “deep” learning because these neural networks often consist of many stacked layers, creating a deep architecture.

These DL models are capable of “learning” from large volumes of complex, high-dimensional, and unstructured data. The term learning refers to the ability of the model to automatically learn and improve from experience without being explicitly programmed to do so for any one particular task of the tasks it learns.

DL can be supervised, semi-supervised, or unsupervised. It’s used in numerous applications, including NLP, speech recognition, image recognition, and even playing games. The models can identify patterns and make data-driven predictions or decisions.

One of the critical advantages of DL is its ability to process and model data of various types, including text, images, sound, and more. This versatility has led to a vast range of applications, from self-driving cars to sophisticated web search algorithms and highly responsive speech recognition systems.

It’s worth noting that DL, despite its high potential, also requires significant computational power and large amounts of high-quality data to train effectively, which can be a challenge.

In essence, DL is a powerful and transformative technology that is at the forefront of many of today’s technological advancements.

Neural networks are used for a variety of reasons in the field of ML and AI. Here are some of the key motivations:

  • Nonlinearity: Neural networks, with their intricate structure and use of activation functions, can capture nonlinear relationships in data. Many real-world phenomena are nonlinear in nature, and neural networks offer a way to model these complexities.
  • Universal approximation theorem: This theorem states that a neural network with enough hidden units can approximate virtually any function with a high degree of accuracy. This makes them highly flexible and adaptable to a wide range of tasks. We keep in mind that approximation is existence, not learnability, and does not guarantee generalization.
  • Ability to handle high-dimensional data: Neural networks can handle data with a large number of features or dimensions effectively, which makes them useful for tasks such as image or speech recognition, where data is highly dimensional.
  • Pattern recognition and prediction: Neural networks excel at identifying patterns and trends within large datasets, making them especially useful for prediction tasks, such as forecasting sales or predicting stock market trends.
  • Parallel processing: Neural networks’ architecture allows them to perform many operations simultaneously, making them highly efficient when implemented on modern hardware.
  • Learning from data: Neural networks can improve their performance as they are exposed to more data. This ability to learn from data makes them highly effective for tasks where large amounts of data are available.
  • Robustness: Neural networks can handle noise in the input data and are robust to small variations in the input.

Additionally, neural networks are extensively used in NLP tasks due to several reasons. Here are some of the primary motivations:

  • Handling sequential data: Natural language is inherently sequential (words follow one another to make coherent sentences). RNNs and their advanced versions, such as long short-term memory (LSTM) and gated recurrent units (GRUs), are types of neural networks that are capable of processing sequential data by maintaining a form of internal state or memory about the previous steps in the sequence.
  • Context understanding: Neural networks, especially recurrent types, are capable of understanding the context in a sentence by taking into account the surrounding words or even previous sentences, which is crucial in NLP tasks.
  • Distributed representations via embeddings: Neural networks, through the use of word embeddings (such as Word2Vec and GloVe), can encode words in a way that preserves their semantic meaning. Words with similar meanings are placed closer together in the vector space, which is highly valuable for many NLP tasks.
  • End-to-end learning: Neural networks can learn directly from raw data. For example, in image classification, a neural network can learn features from the pixel level without needing any manual feature extraction steps. This is a significant advantage, as the feature extraction process can be time-consuming and require domain expertise. Similarly, neural networks can learn to perform NLP tasks from raw text data without the need for manual feature extraction. This is a big advantage in NLP, where creating hand-engineered features can be challenging and time-consuming.
  • Performance: Neural networks, especially with the advent of Transformer-based architectures such as BERT, GPT, and so on, have been shown to achieve state-of-the-art results in many NLP tasks, including but not limited to machine translation, text summarization, sentiment analysis, and question answering.
  • Handling large vocabularies: Neural networks can effectively handle large vocabularies and continuous text streams, which is typical in many NLP problems.
  • Learning hierarchical features: Deep neural networks can learn hierarchical representations. In the context of NLP, lower layers often learn to represent simple things such as n-grams, whereas higher layers can represent complex concepts such as sentiment.

Despite these advantages, it’s worth noting that neural networks also have their challenges, including their “black box” nature, which makes their decision-making process difficult to interpret, and their need for large amounts of data and computational resources for training. However, the benefits they provide in terms of performance and their ability to learn from raw text data and model complex relationships make them a go-to choice for many NLP tasks.

A neural network consists of multiple layers of interconnected nodes, or “neurons,” each of which performs a simple computation on the data it receives, passing its output to the neurons of the next layer. Each connection between neurons has an associated weight that is adjusted during the learning process.

The architecture of a basic neural network consists of three types of layers, as shown in Figure 6.1:

Figure 6.1 – Basic architecture of neural networks

In the following list, we explain each layer of the model in more detail:

  • Input layer: This is where the network receives its input. If the network is designed to process an image with dimensions of 28x28 pixels, for instance, there would be 784 neurons in the input layer, each representing the value of one pixel.
  • Hidden layer(s): These are the layers between the input and output layers. Each neuron in a hidden layer takes the outputs of the neurons from the previous layer, multiplies each of these by the weight of the respective connection, and sums these values up. This sum is then passed through an “activation function” to introduce nonlinearity into the model, which helps the network learn complex patterns. There can be any number of hidden layers in a neural network, and a network with many hidden layers is often referred to as a “deep” neural network.
  • Output layer: This is the final layer in the network. The neurons in this layer produce the final output of the network. For a classification problem, for instance, you might design the network to have one output neuron for each class in the problem, with each neuron outputting a value indicating the probability that the input belongs to its respective class.

The neurons in the network are interconnected. The weights of these connections, which are initially set to random values, represent what the network has learned once it has been trained on data.

During the training process, an algorithm such as backpropagation is used to adjust the weights of the connections in the network in response to the difference between the network’s output and the desired output. This process is repeated many times, and the network gradually improves its performance on the training data.

Let’s now look at some of the most commonly used terms in the context of neural networks.

This is the basic unit of computation in a neural network; typically, a simple computation involves inputs, weights, a bias, and an activation function. A neuron, also known as a node or unit, is a fundamental element in a neural network. It receives input from some other nodes or from an external source if the neuron is in the input layer. The neuron then computes an output based on this input.

Each input has an associated weight (), which is assigned based on its relative importance to other inputs. The neuron applies a weight to the inputs, sums them up, and then applies an activation function to the sum plus a bias value ().

Here’s a step-by-step breakdown:

  1. Weighted sum: Each input () to the neuron is multiplied by a corresponding weight (). These weighted inputs are then summed together with a bias term (). The bias term allows for the activation function to be shifted to the left or the right, helping the neuron model a wider range of patterns. Mathematically, this step can be represented as follows:
  2. Activation function: The result of the weighted sum is then passed through an activation function. The purpose of the activation function is to introduce nonlinearity into the output of a neuron. This nonlinearity allows the network to learn from errors and make adjustments, which is essential when it comes to performing complex tasks such as language translation or image recognition. Common choices for activation functions include the sigmoid function, hyperbolic tangent (tanh), and rectified linear unit (ReLU), among others.

The output of the neuron is the result of the activation function. It serves as the input to the neurons in the next layer of the network.

The weights and bias in the neuron are learnable parameters. In other words, their values are learned over time as the neural network is trained on data.

  • Weights: The strength or amplitude of the connection between two neurons. During the training phase, the neural network learns the correct weights that better map inputs to outputs. Weight is used in the neuron, as explained previously.
  • Bias: An additional parameter in the neuron that allows for the activation function to be shifted to the left or right, which can be critical for successful learning (also used in the neuron).

The function (in each neuron) that determines the output a neuron should produce given its input is called an activation function. Common examples include sigmoid, ReLU, and tanh.

Here are some of the most common types of activation functions:

  • Sigmoid function: This is where we’re essentially classifying the input as either 0 or 1. The sigmoid function takes a real-valued input and squashes it to a range between 0 and 1. It’s often used in the output layer of a binary classification network:

However, it has two major drawbacks: the vanishing gradients problem (gradients are very small for large positive or negative inputs, which can slow down learning during backpropagation) and the outputs are not zero-centered.

  • Hyperbolic tanh function: The tanh function also takes a real-valued input and squashes it to a range between -1 and 1. Unlike the sigmoid function, its output is zero-centered because its range is symmetric around the origin:

It also suffers from the vanishing gradients problem, as does the sigmoid function.

  • ReLU function: The ReLU function has become very popular in recent years. It computes the function as follows:

In other words, the activation is simply the input if the input is positive; otherwise, it’s zero.

It doesn’t activate all the neurons at the same time, meaning that the neurons will only be deactivated if the output of the linear transformation is less than 0. This makes the network sparse and efficient. However, ReLU units can be fragile during training and can “die” (they stop learning completely) if a large gradient flows through them.

  • Leaky ReLU: Leaky ReLU is a variant of ReLU that addresses the “dying ReLU” problem. Instead of defining the function as 0 for negative, we define it as a small linear component of:

This allows the function to “leak” some information when the input is negative and helps to mitigate the dying ReLU problem.

  • Exponential linear unit (ELU): ELU is also a variant of ReLU that modifies the function to be a non-zero value for negative, which can help the learning process:

Here, alpha () is a constant that defines the function’s smoothness when inputs are negative. ELU tends to converge the cost to zero faster and produce more accurate results. However, it can be slower to compute because of the use of the exponential operation.

  • Softmax function: The softmax function is often used in the output layer of a classifier, where we’re trying to assign the input to one of several classes. It gives the probability that any given input belongs to each of the possible classes:

The denominator normalizes the probabilities, so they all sum up to 1 across all classes. The softmax function is also used in multinomial logistic regression.

Each of these activation functions has pros and cons, and the choice of activation function can depend on the specific application and context of the problem at hand.

A layer is a set of neurons that processes signals at the same level of abstraction. The first layer is the input layer, the last layer is the output layer, and all layers in between are called hidden layers.

In the context of training a neural network, an epoch is a term used to denote one complete pass through the entire training dataset. During an epoch, the neural network’s weights are updated in an attempt to minimize the loss function.

The number of epochs hyperparameter sets how many times the deep learning algorithm processes the entire training dataset. Too many epochs can cause overfitting, where the model performs well on training data but poorly on new data. Conversely, training for too few epochs may mean the model is underfitting—it could improve with further training.

It’s also important to note that the concept of an epoch is more relevant in the batch and mini-batch variants of gradient descent. In stochastic gradient descent, the model’s weights are updated after seeing each individual example, so the concept of an epoch is less straightforward.

Batch size is the number of training examples processed in a single training iteration. When you start training a neural network, you have a couple of options for how you feed your data into the model:

  • Batch gradient descent: Here, the entire training dataset is used to compute the gradient of the loss function for each iteration of the optimizer (as with gradient descent). In this case, the batch size is equal to the total number of examples in the training dataset.
  • Stochastic gradient descent (SGD): SGD uses a single example at each iteration of the optimizer. Therefore, the batch size for SGD is 1.
  • Mini-batch gradient descent: This is a compromise between batch gradient descent and SGD. In mini-batch gradient descent, the batch size is usually between 10 and 1,000 and is chosen depending on the computational resources you have.

The batch size can significantly impact the learning process. Larger batch sizes result in faster progress in training, but don’t always converge as fast. Smaller batch sizes update the model frequently, but the progress in training is slower.

Moreover, smaller batch sizes have a regularizing effect and can help the model generalize better, leading to better performance on unseen data. However, using a batch size that is too small can lead to unstable training, less accurate estimates of the gradient, and, ultimately, a model with worse performance.

Choosing the right batch size is a matter of trial and error and depends on the specific problem and the computational resources at hand:

  • Iterations: The number of batches of data the algorithm has seen (or the number of passes it has made on the dataset).
  • Learning rate: A hyperparameter that controls the speed of convergence of the learning algorithm by adjusting the weight update rate based on the loss gradient.
  • Loss function (cost function): Evaluates the neural network’s performance on the dataset. Higher deviations between predictions and actual results result in a larger output from the loss function. The goal is to minimize this output, which will give the model more accurate predictions.
  • Backpropagation: The primary algorithm for performing gradient descent on neural networks. It calculates the gradient of the loss function at the output layer and distributes it back through the layers of the network, updating the weights and biases in a way that minimizes the loss.
  • Overfitting: A situation where a model learns the details and noise in the training data to the extent that it performs poorly on new, unseen data.
  • Underfitting: A situation where a model is too simple to learn the underlying structure of the data and, thus, performs poorly on both training and new data.
  • Regularization: A technique used to prevent overfitting by adding a penalty term to the loss function, which, in turn, constrains the weights of the network.
  • Dropout: A regularization technique where randomly selected neurons are ignored during training, which helps prevent overfitting.
  • CNN: A type of neural network well-suited to image processing and computer vision tasks.
  • RNN: A type of neural network designed to recognize patterns in sequences of data, such as time series or text.

Let’s move on to the architecture of different neural networks next.

The architecture of different neural networks

Section titled “The architecture of different neural networks”

Neural networks come in various types, each with a specific architecture suited to a different kind of task. The following list contains general descriptions of some of the most common types:

  • Feedforward neural network (FNN): This is the most straightforward type of neural network. Information in this network moves in one direction only, from the input layer through any hidden layers to the output layer. There are no cycles or loops in the network; it’s a straight, “feedforward” path.

Figure 6.2 – FNN

  • Multi-layer perceptron (MLP): This is a specific class of FNNs characterized by fully connected layers and at least one hidden layer between the input and output layers. In an MLP, each neuron in a layer is connected to every neuron in the subsequent layer, and information flows strictly in one direction—from input to output—without any feedback or recurrence.

More generally, the term feedforward neural network describes a broader family of models defined by this one-way flow of information. While all MLPs are feedforward networks, not all feedforward networks are MLPs; for example, CNNs are also feedforward but impose structured connectivity rather than full connectivity.

MLPs are capable of modeling complex nonlinear patterns and have been widely used in tasks such as classification, regression, speech recognition, and other ML applications, particularly when working with tabular or fixed-size feature representations.

Figure 6.3 – MLP

  • CNN: This is particularly well-suited to tasks involving spatial data, such as images. Its architecture includes three main types of layers: convolutional layers, pooling layers, and fully connected layers. The convolutional layers apply a series of filters to the input, which allows the network to automatically and adaptively learn spatial hierarchies of features. Pooling layers decrease the spatial size of the representation, thereby reducing parameters and computation in the network to control overfitting and decrease the computation cost in the following layers. Fully connected layers get the output of the pooling layer and conduct high-level reasoning on the output.

Figure 6.4 – CNN

  • RNN: Unlike feedforward networks, RNNs have connections that form directed cycles. This architecture allows them to use information from their previous outputs as inputs, making them ideal for tasks involving sequential data, such as time series prediction or NLP. A significant variation of RNNs is the LSTM network, which uses special units in addition to standard units. LSTM includes a memory cell and gating mechanisms that can maintain information in memory for long periods of time, a feature that is particularly useful for tasks that require learning from long-distance dependencies in the data, such as handwriting or speech recognition.

Figure 6.5 – RNN

  • Autoencoder (AE): This is a type of neural network used to learn the efficient coding of input data. It has a symmetrical architecture and is designed to apply backpropagation, setting the target values to be equal to the inputs. AEs are typically used for feature extraction, learning representations of data, and dimensionality reduction. They’re also used in generative models, noise removal, and recommendation systems.

Figure 6.6 – AE architecture

  • Generative adversarial network (GAN): This consists of two parts, a generator and a discriminator, which are both neural networks. The generator creates data instances that aim to come from the same distribution as the training dataset. The discriminator’s goal is to distinguish between instances from the true distribution and instances from the generator. The generator and the discriminator are trained together, with the goal that the generator produces better instances as training progresses, whereas the discriminator becomes better at distinguishing true instances from generated ones.

Figure 6.7 – GAN in computer vision

These are just a few examples of neural network architectures, and many variations and combinations exist. The architecture we choose for a task will depend on the specific requirements and constraints of your task.

The challenges of training neural networks

Section titled “The challenges of training neural networks”

Training neural networks is a complex task and comes with challenges during the training, such as local minima and vanishing/exploding gradients, as well as computational costs and interpretability. All challenges are explained in detail in the following list:

  • Local minima: The objective of training a neural network is to find the set of weights that minimizes the loss function. This is a high-dimensional optimization problem, and there are many points (sets of weights) where the loss function has local minima. A suboptimal local minimum is a point where the loss is lower than for the nearby points but higher than the global minimum, which is the overall lowest possible loss. The training process can get stuck in such suboptimal local minima. It’s important to remember that the local minima problem exists even in convex loss functions due to the discrete representation that is a part of digital computation.
  • Vanishing/exploding gradients: This is a difficulty encountered, especially when training deep neural networks. The gradients of the loss function may become very small (vanish) or very large (explode) in deeper layers of the network during the backpropagation process. Vanishing gradients make it hard for the network to learn from the data because the weight updates become very small. Exploding gradients can cause the training process to fail because weight updates become too large, and the loss becomes undefined (e.g., NaN).
  • Overfitting: One of the common problems in training ML models is when our model is too complex, and we train it too much. In this case, the model learns even the noises in the training data and works very well on the training data, but poorly on the unseen test data.
  • Underfitting: Conversely, underfitting occurs when the model is too simple and can’t capture the underlying structure of the data. Both overfitting and underfitting can be mitigated by using proper model complexity, regularization techniques, and a sufficient amount of training data.
  • Computational resources: Training neural networks, particularly deep networks, requires significant computational resources (CPU/GPU power and memory). They also often require a large amount of training data to perform well, which can be a problem when such data is not available.
  • Lack of interpretability: While not strictly a training issue, the lack of interpretability of neural networks is a significant problem. They are often referred to as “black boxes” because it is challenging to understand why they are making the predictions they do.
  • Difficulty in selecting appropriate architecture and hyperparameters: There are many types of neural network architectures to choose from (such as CNNs and RNNs), and each has a set of hyperparameters that need to be tuned (such as learning rate, batch size, number of layers, and number of units per layer). Selecting the best architecture and tuning these hyperparameters for a given problem can be a challenging and time-consuming task.
  • Data preprocessing: Neural networks often require the input data to be in a specific format. For instance, data might need to be normalized, categorical variables might need to be one-hot encoded, and missing values might need to be imputed. This preprocessing can be a complex and time-consuming step.

These challenges make training neural networks a non-trivial task, often requiring a combination of technical expertise, computational resources, and trial and error.

A language model is a statistical model in NLP that is designed to learn and understand the structure of human language. More specifically, it is a probabilistic model that is trained to estimate the likelihood of words when provided with a given word scenario. For instance, a language model could be trained to predict the next word in a sentence, given the previous words.

Language models are fundamental to many NLP tasks. They are used in machine translation, speech recognition, part-of-speech tagging, and named entity recognition, among other things. More recently, they have been used to create conversational AI models such as chatbots and personal assistants and to generate human-like text.

Traditional language models were often based on explicitly statistical methods, such as n-gram models, which consider only the previous n words when predicting the next word, or hidden Markov models (HMMs).

More recently, neural networks have become popular for creating language models, leading to the rise of neural language models. These models use the power of neural networks to consider the context of each word when making predictions, resulting in higher accuracy and fluency. Examples of neural language models include RNNs, the Transformer model, and various Transformer-based architectures such as BERT and GPT.

Language models are essential for understanding, generating, and interpreting human language in a computational setting, and they play a vital role in many applications of NLP.

Here are several motivations for using language models:

  • Machine translation: Language models are a crucial component in systems that translate text from one language to another. They can assess the fluency of translated sentences and help choose between multiple possible translations.
  • Speech recognition: Language models are used in speech recognition systems to help distinguish between words and phrases that sound similar. By predicting what word is likely to come next in a sentence, they can improve the accuracy of transcription.
  • Information retrieval: When you search for something on the internet, language models help to determine what documents are relevant to your query. They can understand the semantic similarity between your search terms and potential results.
  • Text generation: Language models can generate human-like text, which is useful in various applications such as chatbots, writing assistants, and content creation tools. For example, a chatbot can use a language model to generate appropriate responses to user queries.
  • Sentiment analysis: By understanding the structure of language, language models can help determine whether the sentiment of a piece of text is positive, negative, or neutral. This is useful in areas such as social media monitoring, product reviews, and customer feedback.
  • Grammar checking: Language models can predict what word should come next in a sentence, which can help identify grammatical errors or awkward phrasing.
  • Named entity recognition: Language models can help identify named entities in text, such as people, organizations, locations, and more. This can be useful for tasks such as information extraction and automated summarization.
  • Understanding context: Language models, especially recent models based on DL, such as Transformers, are excellent at understanding the context of words and sentences. This capability is vital for many NLP tasks, such as question-answering, summarization, and dialogue systems.

All these motivations stem from a central theme: language models help machines understand and generate human language more effectively, which is crucial for many applications in today’s data-driven world.

In the following section, we introduce the use of self-supervised learning to train language models.

Using self-supervised learning to train language models

Section titled “Using self-supervised learning to train language models”

Self-supervised learning is a form of unsupervised learning where the data provides the supervision. In other words, the model learns to predict certain parts of the input data from other parts of the same input data. It does not require explicit labels provided by humans, hence the term self-supervised.

In the context of language models, self-supervision is typically implemented by predicting parts of a sentence when given other parts. For example, given the sentence “ The cat is on the __,” the model would be trained to predict the missing word (“ mat,” in this case).

Let’s look at a couple of popular self-supervised learning strategies for training language models next.

This strategy, used in the training of BERT, randomly masks some percentage of the input tokens and tasks the model with predicting the masked words based on the context provided by the unmasked words. For instance, in the sentence “ The cat is on the mat,” we could mask “ cat,” and the model’s job would be to predict this word. Please note that more than one word can also be masked.

Mathematically, the objective of MLM is to maximize the following likelihood:

Here, is a masked word, are the non-masked words, and represents the model parameters.

In autoregressive language modeling, which is used in models such as GPT, the model predicts the next word in a sentence given all the preceding words. It’s trained to maximize the likelihood of a word given its previous words in the sentence.

The objective of an autoregressive language model is to maximize the following:

Here, is the current word, are the previous words, and represents the model parameters.

These strategies enable language models to obtain a rich understanding of language syntax and semantics directly from raw text without the need for explicit labels. The models can then be fine-tuned for various tasks such as text classification, sentiment analysis, and more, leveraging the language understanding gained from the self-supervised pretraining phase.

Transfer learning is an ML technique where a pretrained model is reused as the starting point for a different but related problem. Compared to traditional ML approaches, where you start by initializing your model with random weights, transfer learning has the advantage of kick-starting the learning process from patterns that have been learned from a related task, which can both speed up the training process and improve the performance of the model, especially when you have limited labeled training data.

In transfer learning, a model is typically trained on a large-scale task, and then parts of the model are used as a starting point for another task. The large-scale task is often chosen to be broad enough that the learned representations are useful for many different tasks. This process works particularly well when the input data for both tasks is of the same type and the tasks are related. Here are two examples of transfer learning:

  • In image classification, a CNN pretrained on ImageNet can be fine-tuned on a small dataset of medical images to accurately detect diseases, reducing the need for large labeled datasets and long training times
  • In NLP, a pretrained language model such as BERT can be fine-tuned for text classification tasks such as sentiment analysis or clinical note categorization, leveraging its learned language representations to achieve strong performance with limited task-specific data

There are several ways to apply transfer learning, and the best approach can depend on how much data you have for your task and how similar your task is to the original task the model was trained on.

In this approach, the pretrained model is used as a feature extractor, leveraging the rich representations it has already learned from large-scale data. The final layer—or in some cases, several of the top layers—of the pretrained network is removed, while the remaining layers are kept fixed to preserve their learned knowledge. Input data is then passed through this truncated network to generate high-level feature representations that capture relevant patterns and semantics. These extracted features serve as input to a new, typically smaller model or classification head, which is trained specifically for the target task. By training only this new component, the model can adapt to the task efficiently while reducing training time, computational cost, and the risk of overfitting.

You use the pretrained model as a starting point and update all or some of the model’s parameters for your new task. In other words, you continue the training where it left off, allowing the model to adjust from generic feature extraction to features more specific to your task. Often, a lower learning rate is used during fine-tuning to avoid overwriting the prelearned features entirely during training.

Transfer learning is a powerful technique that can be used to improve the performance of ML models. It is particularly useful for tasks where there is limited labeled data available. It is commonly used in DL applications. For instance, it’s almost a standard in image classification problems where pretrained models on ImageNet, a large-scale annotated image dataset (ResNet, VGG, Inception, and so on), are used as the starting point. The features learned by these models are generic for image classification and can be fine-tuned on a specific image classification task with a smaller amount of data.

Here are some examples of how transfer learning can be used:

  • A model trained to classify images of cats and dogs can be used to fine-tune a model to classify images of other animals, such as birds or fish
  • A model trained to translate text from English to Spanish can be used to fine-tune a model to translate text from Spanish to French
  • A model trained to predict the price of a house can be used to fine-tune a model to predict the price of a car

Similarly, in NLP, large pretrained models, such as BERT or GPT, are often used as the starting point for a wide range of tasks. These models are pretrained on a large corpus of text and learn a rich representation of language that can be fine-tuned for specific tasks such as text classification, sentiment analysis, question answering, and more.

Transformers are a type of neural network architecture that was introduced in a paper called Attention Is All You Need by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, and Illia Polosukhin (Advances in Neural Information Processing Systems 30, 2017). They have been very influential in the field of NLP and have formed the basis for state-of-the-art models such as BERT and GPT.

Attention Is All You Need: https://proceedings.neurips.cc/paper_files/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf

The key innovation in Transformers is the self-attention mechanism, which allows the model to weigh the relevance of each word in the input when producing an output, thereby considering the context of each word. This is unlike previous models such as RNNs or CNNs, which process the input sequentially and, therefore, have a harder time capturing the long-range dependencies between words.

A Transformer is composed of an encoder and a decoder, both of which are made up of several identical layers, as shown in Figure 6.8. Each layer in the encoder contains two sub-layers: a self-attention mechanism and a position-wise fully connected feedforward network. A residual connection is employed around each of the two sub-layers, followed by layer normalization:

Figure 6.8 – Transformer architecture (encoder-decoder) with self-attention and cross-attention

Similarly, each layer in the decoder has three sub-layers. The first is a self-attention layer, the second is a cross-attention layer that attends to the output of the encoder stack, and the third is a position-wise fully connected feedforward network. Like the encoder, each of these sub-layers has a residual connection around it, followed by layer normalization. Please note that in the figure, just one head is being shown, and we can have multiple heads working in parallel (N heads).

The self-attention mechanism, or scaled dot-product attention, calculates the relevance of each word in the sequence to the current word being processed. The input to the self-attention layer is a sequence of word embeddings, each of which is split into a query (), a key (), and a value () using separately learned linear transformations.

The attention score for each word is then calculated as follows:

Here, is the dimensionality of the queries and keys, which is used to scale the dot product to prevent it from growing too large. The softmax operation ensures that the attention scores are normalized and sum to 1. These scores represent the weight given to each word’s value when producing the output for the current word.

The output of the self-attention layer is a new sequence of vectors, where the output for each word is a weighted sum of all the input values, with the weights determined by the attention scores.

Since the self-attention mechanism does not take into account the position of the words in the sequence, the Transformer adds a positional encoding to the input embeddings at the bottom of the encoder and decoder stacks. This encoding is a fixed function of the position and allows the model to learn to use the order of the words.

In the original Transformer paper, positional encoding is a sinusoidal function of the position and the dimension, although learned positional encodings have also been used effectively.

Since their introduction, Transformers have been used to achieve state-of-the-art results on a wide range of NLP tasks, including machine translation, text summarization, sentiment analysis, and more. They have also been adapted for other domains, such as computer vision and reinforcement learning.

The introduction of Transformers has led to a shift in the NLP field toward pretraining large Transformer models on a large corpus of text and then fine-tuning them on specific tasks, which is an effective form of transfer learning. This approach has been used in models such as BERT, GPT-2, GPT-3, and GPT-4.

Large language models (LLMs) are a class of ML models that have been trained on a broad range of internet text.

The term large in large language models refers to the number of parameters that these models have. For example, GPT-3 has 175 billion parameters. These models are trained using self-supervised learning on a large corpus of text, which means they predict the next word in a sentence (such as GPT) or a word based on surrounding words (such as BERT, which is also trained to predict whether a pair of sentences is sequential). Because they are exposed to such a large amount of text, these models learn grammar, facts about the world, reasoning abilities, and also biases in the data they’re trained on.

These models are Transformer-based, meaning they leverage the Transformer architecture, which uses self-attention mechanisms to weigh the importance of words in input data. This architecture allows these models to process long-range dependencies in text, making them very effective for a wide range of NLP tasks.

LLMs can be fine-tuned on specific tasks to achieve high performance. Fine-tuning involves additional training on a smaller, task-specific dataset and allows the model to adapt its general language understanding abilities to the specifics of the task. This approach has been used to achieve state-of-the-art results on many NLP benchmarks.

While LLMs have demonstrated impressive abilities, they also raise important challenges. For example, because they’re trained on internet text, they can reproduce and amplify biases present in the data. They can also generate outputs that are harmful or misleading. Additionally, due to their size, these models require significant computational resources to train and deploy, which raises issues around cost and environmental impact.

Despite these challenges, LLMs represent a significant advance in the field of AI and are a powerful tool for a wide range of applications, including translation, summarization, content creation, question answering, and more.

The challenges of training language models

Section titled “The challenges of training language models”

Training LLMs is a complex and resource-intensive task that poses several challenges. Here are some of the key issues:

  • Computational resources: The training of LLMs requires substantial computational resources. These models have billions of parameters that need to be updated during training, which involves performing a large amount of computation over an extensive dataset. This computation is usually carried out on high-performance GPUs or tensor processing units (TPUs), and the costs associated can be prohibitive.
  • Memory limitations: As the size of the model increases, the amount of memory required to store the model parameters, intermediate activations, and gradients during training also increases. This can lead to memory issues on even the most advanced hardware. Techniques such as model parallelism, gradient checkpointing, and offloading can be used to mitigate these issues, but they add complexity to the training process.
  • Dataset size and quality: LLMs are trained on extensive text corpora. Finding, cleaning, and structurally organizing such massive datasets can be challenging. Moreover, the quality of the dataset directly impacts the performance of the model. Since these models learn from the data they’re trained on, biases or errors in the data can lead to a biased or error-prone model.
  • Overfitting: While large models have a high capacity to learn complex patterns, they can also be overfit to the training data, especially when the amount of available data is limited compared to the size of the model. Overfitting leads to poor generalization of unseen data. Regularization techniques, such as weight decay, dropout, and early stopping, can be used to combat overfitting.
  • Training stability: As models get larger, stably training them becomes more difficult. The challenges include managing learning rates and batch sizes, and dealing with issues such as vanishing or exploding gradients.
  • Evaluation and fine-tuning: Evaluating the performance of these models can also be challenging due to their size. Moreover, fine-tuning these models on a specific task can be tricky, as it can lead to “catastrophic forgetting,” where the model forgets the pretraining knowledge.
  • Ethical and safety concerns: LLMs can generate content that is harmful or inappropriate. They can also propagate and amplify biases present in the training data. These issues necessitate the development of robust methods to control the behavior of the model, both during training and at runtime.

Despite these challenges, progress continues in the field of LLMs. Researchers are developing new strategies to mitigate these issues and to train large models more effectively and responsibly.

Here, we are going to explain two popular architectures of language models, BERT and GPT, in detail.

BERT, which we mentioned already and will now expand on, stands for bidirectional encoder representations from Transformers and is a Transformer-based ML technique for NLP tasks. It was developed by Google and introduced in a paper by Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova titled BERT: Pre-training of deep bidirectional transformers for language understanding (arXiv preprint arXiv:1810.04805, 2018).

You can access the paper here: https://aclanthology.org/N19-1423/?utm\_campaign=The+Batch&utm\_source=hs\_email&utm\_medium=email&\_hsenc=p2ANqtz-\_m9bbH\_7ECE1h3lZ3D61TYg52rKpifVNjL4fvJ85uqggrXsWDBTB7YooFLJeNXHWqhvOyC.

BERT is designed to pretrain deep bidirectional representations from the unlabeled text by joint conditioning on both left and right contexts in all layers. This is in contrast to previous methods, such as GPT and ELMo, which pretrain text representations from only the left context or from left and right contexts separately. This bidirectionality allows BERT to understand the context and the semantic meaning of a word more accurately.

BERT is based on the Transformer model architecture, which is shown in Figure 6.8, originally introduced by Vaswani et al. in the paper Attention Is All You Need. The model architecture consists of stacked self-attention and point-wise fully connected layers.

BERT comes in two sizes: BERT Base and BERT Large. BERT Base is composed of 12 Transformer layers, each with 12 self-attention heads, and a total of 110 million parameters. BERT Large is much bigger and has 24 Transformer layers, each with 16 self-attention heads, for a total of 340 million parameters.

BERT’s training process involves two steps: pretraining and fine-tuning.

The very first step in training or using a language model is to create or load its dictionary. We usually use a tokenizer to achieve this goal.

In order to use the language models efficiently, we need to use a tokenizer that maps input text into a sequence of tokens or token IDs drawn from a fixed-size vocabulary. Subword tokenization algorithms, such as the byte pair encoding (BPE), unigram language model (ULM), and WordPiece, split words into smaller subword units. This is useful for handling out-of-vocabulary words and allows the model to learn meaningful representations for subword parts that often carry semantic meaning.

The BERT tokenizer is a critical component of the BERT model, performing the initial preprocessing of text data necessary for input into the model. BERT uses WordPiece tokenization, a subword tokenization algorithm that breaks words into smaller parts, allowing BERT to handle out-of-vocabulary words, reduce the size of the vocabulary, and deal with the richness and diversity of languages.

Here’s a detailed breakdown of how the BERT tokenizer works:

  1. Basic tokenization: First, the BERT tokenizer performs basic tokenization, breaking text into individual words by splitting on whitespace and punctuation. This is similar to what you might find in other tokenization methods.
  2. WordPiece tokenization: After basic tokenization, the BERT tokenizer applies WordPiece tokenization. This step breaks words into smaller subword units or “WordPieces.” If a word isn’t in the BERT vocabulary, the tokenizer will iteratively break the word down into smaller subwords until it finds a match in the vocabulary or until it has to resort to character-level representation. For example, the word unhappiness might be broken down into two WordPieces: un and ##happiness. The ## symbol is used to denote subwords that are part of a larger word and not a whole word on their own.
  3. Special tokens addition: The BERT tokenizer then adds special tokens necessary for specific BERT functionalities. The [CLS] token is appended at the beginning of each sentence, serving as an aggregate representation for classification tasks. The [SEP] token is added at the end of each sentence to signify sentence boundaries. If two sentences are input (for tasks that require sentence pairs), they are separated by this [SEP] token.
  4. Token to ID conversion: Finally, each token is mapped to an integer ID corresponding to its index in the BERT vocabulary. These IDs are what the BERT model actually uses as input.

So, in summary, the BERT tokenizer works by first tokenizing the text into words, then further breaking these words down into WordPieces (if necessary), adding special tokens, and finally, converting these tokens into IDs. This process allows the model to understand and generate meaningful representations for a wide variety of words and subwords, contributing to BERT’s powerful performance on various NLP tasks.

During pretraining, BERT was trained on a large corpus of text (the entire English Wikipedia and BooksCorpus are used in the original paper). The model was trained to predict masked words in a sentence (masked language model) and to distinguish whether two sentences come in order in the text (next sentence prediction), as explained here:

  • Masked language model: In this task, 15% of the words in a sentence are replaced by a [MASK] token, and the model is trained to predict the original word from the context provided by the non-masked words
  • Next sentence prediction: When the model is given a pair of two sentences, it is also trained to predict whether sentence B is the next sentence following sentence A

After pretraining, BERT can be fine-tuned on a specific task with a significantly smaller amount of training data. Fine-tuning involves adding an additional output layer to BERT and training the entire model end-to-end on the specific task. This approach has been shown to achieve state-of-the-art results on a wide range of NLP tasks, including question answering, named entity recognition, sentiment analysis, and more.

BERT’s design and its pretraining/fine-tuning approach revolutionized the field of NLP and have led to a shift toward training large models on a broad range of data and then fine-tuning them on specific tasks.

How to fine-tune BERT for text classification

Section titled “How to fine-tune BERT for text classification”

As mentioned, BERT has been pretrained on a large corpus of text data, and the learned representations can be fine-tuned for specific tasks, including text classification. Here is a step-by-step process on how to fine-tune BERT for text classification:

  1. Preprocessing input data: BERT requires a specific format for input data. The sentences need to be tokenized into subwords using BERT’s own tokenizer, and special tokens such as [CLS] (classification) and [SEP] (separation) need to be added. The [CLS] token is added at the beginning of each example and is used as the aggregate sequence representation for classification tasks. The [SEP] token is added at the end of each sentence to denote sentence boundaries. All sequences are then padded to a fixed length to form a uniform input.
  2. Loading the pretrained BERT model: BERT has several pretrained models, and the right one should be chosen based on the task at hand. The models differ in terms of the size of the model and the language of the pretraining data. Once the pretrained BERT model is loaded, it can be used to create contextualized word embeddings for the input data.
  3. Adding a classification layer: A classification layer, also known as the classification head, is added on top of the pretrained BERT model. This layer will be trained to make predictions for the text classification task. Usually, this layer is a fully connected neural network layer that takes the representation corresponding to the [CLS] token as input and outputs the probability distribution over the classes.
  4. Fine-tuning the model: Fine-tuning involves training the model on the specific task (in this case, text classification) using the labeled data. This process can be done in multiple ways. The more common approach is to update the weights of the pretrained BERT model and the newly added classification layer to minimize a loss function, typically the cross-entropy loss for classification tasks. It is important to use a lower learning rate during fine-tuning, as larger rates can destabilize the pre-learned weights. Additionally, the number of recommended epochs is 2–4 epochs, so the model learns the task but does not overfit. The benefit of this approach is that the model weights will be adjusted to perform well on specific tasks. Alternatively, we can freeze BERT layers and just update the classifier layer weights.
  5. Evaluating the model: Once the model has been fine-tuned, it can be evaluated on a validation set to assess its performance. This involves calculating metrics such as accuracy, precision, recall, and F1 score. During the training and evaluation task, similar to other ML and DL models, we can perform hyperparameter tuning.
  6. Applying the model: The fine-tuned model can now be used to make predictions on new, unseen text data. As with the training data, these new data also need to be preprocessed into the format that BERT expects.

Important note

Working with BERT requires considerable computational resources, as the model has a large number of parameters. A GPU is typically recommended for fine-tuning and applying BERT models. There are some models that are lighter than BERT with slightly lower performance, such as DistilBERT, that we can use in the case of being constrained by computation or memory resources. Additionally, BERT is able to process 512 tokens, which limits the length of our input text. If we want to process longer text, Longformer or BigBird are good choices. What we explained here works for similar language models such as RoBERTa, XLNet, and so on.

In summary, fine-tuning BERT for text classification involves preprocessing the input data, loading the pretrained BERT model, adding a classification layer, fine-tuning the model on the labeled data, and then evaluating and applying the model.

We will demonstrate the preceding paradigm of fine-tuning BERT and then apply it at the end of this chapter. You will have the opportunity to employ it firsthand and adjust it to your needs.

GPT-style generative models for text classification

Section titled “GPT-style generative models for text classification”

Generative Pretrained Transformers (GPT) are a class of autoregressive language models that build upon the foundational Transformer architecture introduced by Vaswani et al. in 2017. While both GPT and BERT are grounded in the Transformer design, their architectural choices, training objectives, and directional properties differ substantially, leading to distinct modeling capabilities and downstream use cases.

At the core of GPT lies a decoder-only Transformer structure. Let denote a sequence of input tokens. Each token,, is first mapped into a dense vector space using an embedding matrix,, and positional information is added via a learned or sinusoidal positional embedding,. The initial input to the first Transformer block is therefore given by the following:

This embedded sequence is then propagated through a stack of identical Transformer blocks. Each block consists of a masked multi-head self-attention mechanism followed by a position-wise feedforward network, with residual connections and layer normalization applied after each sublayer. The hidden states are updated recursively as follows:

The final hidden representation,, for each position is projected onto the vocabulary space using a learned output matrix,, yielding a probability distribution over possible next tokens. The model is trained to minimize the negative log-likelihood of the next token in the sequence, as follows:

Here,

A defining characteristic of GPT is its use of causal self-attention, which ensures that token can only attend to tokens, thereby preserving the autoregressive property.

Architecturally, GPT and BERT differ primarily in three areas: directionality, attention masking, and training objectives. GPT is inherently autoregressive and unidirectional, enabling natural language generation but constraining its ability to fully leverage future context during training. BERT, on the other hand, is bidirectional and discriminative, excelling in understanding tasks such as sentence classification, named entity recognition, and question answering, but requiring additional components (e.g., decoders) for generation. Now, we will discuss more about how we can use such models for classification tasks. We can use the models, without any sample training data, called zero-shot learning, or provide a few samples in our prompt (few-shot learning). Alternatively, we can fine-tune the models using training data.

Zero-shot prompting refers to the ability of an LLM, such as GPT-3 or GPT-4, to perform a task without having seen any explicit training examples of that task during inference. Instead of fine-tuning the model with task-specific labeled data, we provide a carefully designed prompt in natural language that describes the task. The model relies on its pretrained knowledge to understand and perform the task based on that prompt alone.

Formally, let be a pretrained language model that, given a prompt,, outputs a probability distribution over possible continuations. In zero-shot prompting, the prompt,, is composed in such a way that it implicitly defines a task,, and the model attempts to solve by predicting the following:

For instance, consider the task of sentiment classification, where the goal is to classify a given sentence as having positive, negative, or neutral sentiment. In a traditional supervised setting, a classifier would be trained on a dataset with labeled examples. In contrast, with a zero-shot prompt, we encode the task as part of the input text.

For example, suppose we want to classify the sentiment of the following sentence:

“The movie was surprisingly good and had great performances.”

We can construct a zero-shot prompt as follows:

“Classify the sentiment of the following sentence as positive, negative, or neutral: The movie was surprisingly good and had great performances.”

We feed this prompt into the language model, which then generates the output:

“Positive”

Even though the model has not been fine-tuned for this specific classification task, it uses its pretrained knowledge of language and semantics to interpret the task description embedded in the prompt and infer the correct label.

This approach generalizes to a wide variety of tasks such as translation, question answering, topic classification, and summarization. For example, in a zero-shot translation task, one might use the following prompt:

“Translate the following English sentence to French: ‘Where is the nearest train station?’”

The model could output the following:

“Où est la gare la plus proche ?”

In essence, zero-shot prompting leverages the vast generalization capabilities of generative language models by encoding the desired task in natural language, requiring no task-specific training examples at inference time. This marks a major shift from traditional ML paradigms, where models are typically trained or fine-tuned for each specific task.

Few-shot learning is a paradigm in which a language model performs a task by being provided with only a few example input-output pairs within the prompt itself—without requiring any gradient updates or fine-tuning. Unlike zero-shot prompting, which relies solely on a natural language description of the task, few-shot prompting gives the model concrete demonstrations of how the task should be performed. This allows the model to generalize its pretrained knowledge to the task at hand by pattern matching or meta-learning from the given examples.

This approach uses in-context learning, where the model conditions on prior examples embedded in the input text, without updating its internal parameters.

Consider the same sentiment classification task, but this time using few-shot learning. The prompt might look like this:

Classify the sentiment of the following sentences as positive, negative, or neutral.
Sentence: “I absolutely loved the food.” → Sentiment: Positive
Sentence: “It was an average experience, nothing special.” → Sentiment: Neutral
Sentence: “The service was terrible and the place was dirty.” → Sentiment: Negative
Sentence: “The movie was surprisingly good and had great performances.” → Sentiment:

Given this prompt, the model infers the correct sentiment for the final sentence. Here is the output:

Positive

The few examples help the model infer what the task is, what format the output should follow, and how to align inputs with labels. It simulates the behavior of a traditional supervised learner—except the training occurs inside the prompt and does not involve gradient descent or parameter updates.

Few-shot prompting leverages the model’s pretraining across diverse data to perform tasks with minimal task-specific data. This flexibility was one of the most striking capabilities demonstrated by GPT-3, which showed that models trained at very large scales can generalize to novel tasks with just a handful of examples provided at inference time. The performance improves as the number and diversity of examples increase, though it is bounded by the model’s context length and pretrained capabilities.

Supervised fine-tuning refers to the process of adapting a pretrained language model to a specific downstream task using labeled data. Unlike zero-shot or few-shot prompting, which keep model parameters fixed during inference, fine-tuning updates the model weights via backpropagation. This allows the model to internalize task-specific patterns that were not necessarily captured during pretraining, or perform better on a specific task.

Let be a pretrained language model with parameters, and let be a labeled dataset, where each is an input (e.g., a sentence) and is the corresponding label (e.g., a class). SFT aims to minimize the empirical risk:

Here, is a loss function such as cross-entropy, and is the model’s output for input. Training proceeds using gradient descent:

Here, is the learning rate.

Although this process can yield highly accurate models for specific tasks, it becomes computationally and memory-expensive when dealing with LLMs, such as LLaMA-2, GPT-J, or Falcon, especially when deployed on limited hardware.

QLoRA, or Quantized Low-Rank Adapter, is a recent method designed to make fine-tuning efficient and memory-friendly for large-scale language models. It combines two powerful techniques:

  1. Quantization: The pretrained model weights are frozen and stored in low-bit precision (e.g., 4-bit), drastically reducing memory usage without altering the model’s behavior.
  2. LoRA (low-rank adaptation): Instead of updating the full weight matrices, QLoRA introduces trainable low-rank matrices and that are injected into linear transformations of the model. The original weight matrix is kept frozen, and a small delta is learned during fine-tuning:

Formally, during fine-tuning, the modified transformation becomes the following:

Here, is the frozen pretrained weight, and is the low-rank, trainable component.

This structure reduces the number of trainable parameters from to, allowing training on consumer-grade GPUs. The quantization of base weights further reduces memory usage, and gradient checkpointing or paged optimizers (such as bitsandbytes) help fit larger models during training.

LLMs typically consist of billions of parameters, rendering traditional full-parameter fine-tuning impractical in many environments. QLoRA addresses this challenge by enabling the training of LLMs on consumer-grade hardware, including GPUs. It preserves the general knowledge embedded in the pretrained model by keeping the original weights unchanged. This approach allows for efficient adaptation to various downstream tasks while requiring only a minimal increase in memory usage. Furthermore, QLoRA facilitates rapid experimentation by allowing different LoRA modules to be interchanged without necessitating retraining of the entire model.

QLoRA can be effectively applied to supervised classification by reframing the problem as a sequence-to-label generation task, typically using a prompt-and-response structure. In this formulation, the classification task is cast as a text generation problem where the model is prompted with a descriptive input and trained to generate the corresponding label in natural language.

To begin, the classification task is reformulated into a generation format. For instance, in sentiment classification, the prompt might be as follows:

“Review: The food was excellent and the service was fast.\nSentiment:”

The expected model output in this case would be: “Positive”.

A training dataset is then constructed as a collection of prompt-output pairs, where represents the input prompt and is the corresponding target label expressed in text.

The base language model is loaded in 4-bit quantized form using tools such as Hugging Face’s “ transformers” library in combination with “ bitsandbytes”, thereby significantly reducing memory requirements and enabling training on consumer-grade GPUs.

LoRA adapters are injected into the model architecture, typically within the attention and feed-forward layers using libraries such as “ peft” provided by Hugging Face. The training process then fine-tunes only these LoRA modules using standard supervised loss functions, such as cross-entropy applied over the vocabulary tokens that represent the target label. Since the label is generally a single word or short phrase, this approach remains computationally efficient.

During inference, the model generates textual output, which is then mapped back to the appropriate class label. This methodology enables high-performance, resource-efficient fine-tuning of LLMs for a wide variety of classification tasks.

The sample code for fine-tuning Llama using QLORA is available in Ch6_qlora_fine_tuning.ipynb in the GitHub repository of this book.

Reviewing our use case – ML/DL system design for NLP classification in a Jupyter notebook

Section titled “Reviewing our use case – ML/DL system design for NLP classification in a Jupyter notebook”

In this section, we are going to work on a real-world problem and see how we can use an NLP pipeline to solve it. The sample code for this use case is available in Ch6_Text_Classification_DL.ipynb in the GitHub repository of this book.

In this scenario, we are in the healthcare sector. Our objective is to develop a general medical knowledge engine that is very up to date with recent findings in the world of healthcare.

The CTO derives several technical objectives from the business objective. One objective is for the ML team: given the growing collection of conclusions that correspond to medical publications, identify the ones that represent advice. This will allow us to identify the medical advice that stems from the underlying research.

Let’s review the parts of the pipeline, as depicted in Figure 6.9:

Figure 6.9 – The structure of a typical exploration and model pipelines

Notice how this design is different from the design we saw in Figure 5.2. There, the exploration and evaluation parts leverage the same feature engineering technique that is later used by the ML models. Here, with LMs, feature engineering is not a part of the preparation for the modeling. The pretrained model, and particularly the tokenizer, performs feature engineering, which yields very different and less interpretable features than the binary, Bag of Words (BoW), or TF-IDF features.

In this part of the code, we employ a deep learning language model.

When looking to apply transfer learning via LMs and fine-tuning them per our objective and data, there are several stacks to choose from. The ones that stand out the most are Google’s TensorFlow and Meta’s PyTorch. A package called Transformers was built as a wrapper around these stacks to allow for a simpler implementation of the code. In this example, we leverage the simplicity and richness of Transformers models.

It is worth highlighting the company that built and supports the Transformers package: Hugging Face. Hugging Face took it upon themselves to create an entire ecosystem around the collection and sharing of free, open source DL models, which includes the many components that accommodate implementing these models. The most actionable tool is the Transformers package, which is a Python package dedicated to picking, importing, training, and employing a large and growing set of DL models.

The code we are reviewing here provides more than just an example of ML/DL system design in the real world; it also showcases Hugging Face’s Transformers.

Here, we set the data up in a format that suits the transformers library. The column names must be very specific.

We decided which metric we wished to optimize and plugged it into the training process. For this problem of binary classification, we optimized for accuracy and evaluated our result in comparison to the dataset’s baseline accuracy, also known as the prior.

This is the core object for training the LM in Transformers. It holds a set of predefined configurations. Some of the key training configurations are the following:

  • The neural network’s mathematical learning hyperparameters, such as the following:
    • The learning rate
      • The gradient descent settings
  • The number of training epochs
  • The computation hardware usage
  • Logging settings for capturing the progression of the objective metric throughout the training process

The fundamental concept around fine-tuning LMs is transfer learning. Neural networks lend themselves so well to transfer learning because one can simply strip any number of layers from the end of the structure and replace them with untrained layers that would be trained based on the underlying problem. The rest of the layers that weren’t removed and aren’t trained continue to operate exactly in the same way they did when the LM was originally trained (when it was originally built). If we replace the last layer but leave the rest of the original layers, then we could view those layers as supervised feature engineering or, conversely, as an embedding mechanism. This trait reflects the concept of transfer learning. Ideally, the model is expected to lend itself well to our underlying problem so that we will choose to keep the vast majority of the original layers, and only a small minority would be replaced and trained. In this way, a large DL model that took many weeks to be pretrained can be transferred and adapted to a new problem in minutes.

In our code, we set the model up in a way that we dictate exactly which of its layers we are looking to fine-tune. It is a design choice for us for this to be based on performance and also computation resources. One choice is to fine-tune the last layer right before the final output, also known as the classification head. The alternative is to fine-tune all the layers. In our code, we explicitly call the model’s configuration, which controls which layer is fine-tuned, so the code can be changed in any way that suits the design.

We configure the trainer to log the performance of the training in real time. It prints those out for us in a table so we can observe and monitor them. When the training is complete, we plot the progress of the training and the evaluation. This helps us see the relation between the evolution of the training results and the evaluation results. Since the evaluation set that the trainer uses can be viewed as a held-out set in the context of the trainer, this plot allows us to investigate underfitting and overfitting.

Generating the training results – use for design choices

Section titled “Generating the training results – use for design choices”

We reviewed the results of the training set, along with the logs that the trainer printed out. We compared them to the baseline accuracy and observed an increase in accuracy. We learned about the quality of our design by iterating over several different design choices and comparing them. That process of iterating over many sets of design parameters would be automated into code to allow for a systematic evaluation of the optimal setting. We didn’t do that in our notebook, just to keep things simple in the example. Once we believed we had found the optimal setting, we could say that the process was finished.

Generating the testing results – use for presenting performance

Section titled “Generating the testing results – use for presenting performance”

As with the code in Chapter 5, here, too, we finished by reviewing the test results. It is worth noting the difference between the evaluation set and the test set. One could suggest that since the trainer doesn’t use the evaluation set for training, it could be used as a held-out test set, thus saving the need to exclude so many observations from training and supplying the model with more labeled data. However, while the trainer, indeed, didn’t use the evaluation set, we did use it to make our design decisions. For instance, we observed the plot from the preceding section and judged the number of epochs that is optimal to achieve optimal fitting. In Chapter 5, an evaluation set was used, too, but we didn’t need to explicitly define it; it was carried out as a part of the K-fold cross-validation mechanism.

In this chapter, we examined how deep learning has reshaped text classification by enabling models to learn rich, contextual representations directly from data. We discussed why Transformer-based architectures have become the dominant approach in modern NLP and how pretrained language models such as BERT and GPT can be efficiently adapted to real-world classification tasks through fine-tuning. Rather than focusing on architectural details alone, the chapter emphasized the practical shift from feature engineering to representation learning and the implications of this shift for building scalable and robust NLP systems.

This chapter established the conceptual and practical groundwork needed to understand LLMs as a whole. In Chapter 7, we move beyond task-specific fine-tuning to demystify LLMs themselves, exploring what defines them, how they differ from earlier models, and why they represent a new paradigm in AI systems. We will examine the design and implementation of modern state-of-the-art LLMs—including GPT-4 Turbo, GPT-4o, Claude, Gemini, and the Mistral family—along with the technical requirements, training challenges, and deployment considerations that arise at scale. The chapter will also introduce modern LLM evaluation benchmarks such as MT-Bench, HELM, andthe Open LLM Leaderboard, and provide an overview of reward modeling and RLHF, including updated open source tools used in practice.

  1. What are the three main layer types in a basic neural network, and what does each one do?
  2. What computation is performed by a single neuron, and which parameters are learned during training?
  3. Why do we use activation functions, and which ones does the chapter identify as common choices?
  4. What role does backpropagation play in training a neural network?
  5. What is the key innovation of transformers compared with sequential models like RNNs, and why does it matter for NLP?
  6. What are the main components inside the transformer encoder and decoder layers?
  7. How does scaled dot-product self-attention work at a high level, and what are Q, K, and V?
  8. Why do transformers need positional encoding, and what form can it take?
  9. How do BERT and GPT differ in their self-supervised pretraining objectives, based on this chapter?
  10. In the chapter’s real-world pipeline example, what changes when moving from traditional ML to language models, and what does the Transformers Trainer configure?
  • Bommasani, Rishi, Drew A. Hudson, Ehsan Adeli, Russ Altman, Simran Arora, Sydney von Arx, et al. “On the Opportunities and Risks of Foundation Models.” arXiv, August 2021. https://arxiv.org/abs/2108.07258.
  • Dettmers, Tim, Artidoro Pagnoni, Ari Holtzman, and Luke Zettlemoyer. “QLoRA: Efficient Finetuning of Quantized LLMs.” In Advances in Neural Information Processing Systems 36 (NeurIPS 2023): 10088–10115, 2023.
  • Devlin, Jacob, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. “BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding.” In Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, Volume 1 (Long and Short Papers), 4171–4186, 2019.
  • Hu, Edward J., Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, et al. “LoRA: Low-Rank Adaptation of Large Language Models.” In International Conference on Learning Representations (ICLR), 2022.
  • Kaplan, Jared, Sam McCandlish, Tom Henighan, Tom B. Brown, Benjamin Chess, Rewon Child, et al. “Scaling Laws for Neural Language Models.” arXiv, January 2020. https://arxiv.org/abs/2001.08361.
  • Liu, Yinhan, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, et al. “RoBERTa: A Robustly Optimized BERT Pretraining Approach.” arXiv, July 2019. https://arxiv.org/abs/1907.11692.
  • Rong, Yuxuan, Katharina Seßler, and Enkelejda Kasneci. “Benchmarking In-Context Learning Strategies of Large Language Models for Math Reasoning Tasks.” IEEE Transactions on Learning Technologies, 2025.
  • Vaswani, Ashish, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, and Illia Polosukhin. “Attention Is All You Need.” In Advances in Neural Information Processing Systems 30 (NeurIPS 2017), 2017.