Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Training framework summary

Over the previous 16 chapters, we started from scratch and extended the code a little in every chapter, building step by step the tensor, computational graph, network layers, loss functions, optimizers, scheduler, trainer, and more, which are the building blocks for crossing from deep learning to large language models.

Now it is time to collect all these modules and assemble them into a complete, reusable training framework for network models.

This chapter is a summary of the code of the previous 16 chapters, and also the starting point of the next part, large language models. We gather the basic components into one code library, so that later parts no longer have to repeat the code of these components every time.

Tensor

The tensor is the cornerstone of the whole framework and the carrier of automatic differentiation. We have extended it with some important features:

  • Operator overloading: we had already implemented tensor addition, and now we have fully implemented subtraction, multiplication, division, matrix multiplication, and matrix transpose. Tensors can be combined directly with +, -, *, /, and @, just like numbers, and the computational graph is recorded automatically, so they blend into the whole multi-layer model;

  • Broadcasting support: computation between tensors of different shapes, for example adding a (2, 6) tensor and a (1, 6) tensor. This is very common with complex models and multi-dimensional data;

  • Disabling gradients (no_grad): when the computational graph is not needed, such as during inference, gradient computation can be switched off temporarily to save memory and compute;

  • A unified data type (DTYPE = np.float32): the values of tensors are explicitly defined as 32-bit floating-point numbers.

⚠️ Note: Both sides of an operator must be tensors. Operating directly between a tensor and a Python number (for example x * 2) raises an error; wrap the number in a tensor first, for example x * Tensor(2.0).

Model

A neural network model is made up of multiple network layers. All layers support the basic functions defined by the abstract layer.

Abstract layer

The abstract layer defines the most important method interfaces:

  • forward (inference method): implements forward propagation;

  • parameters (parameter list): provides all the parameters that need training;

  • train (training method): enters training mode;

  • eval (test method): enters evaluation and inference mode.

Linear layer

Weighted sum, the most basic network layer.

Composite layer

An abstract layer that can serve as a container for sublayers, and the foundation of complex network layers.

Sequential layer

The most basic container of network layers, in which all the sublayers run in order.

Embedding layer

Converts the index encodings of characters or words into dense embedding vectors by table lookup, avoiding the sparse vectors of one-hot encoding.

Mean pooling layer

Merges a group of vectors in a sequence into one vector by taking their mean.

Activation functions

Activation functions introduce nonlinearity into the network model, so that the model can learn complex relationships.

Rectified linear unit (ReLU)

The default first choice for hidden layers. It is fast to compute and does not cause vanishing gradients.

Hyperbolic tangent (Tanh)

The output is centered on 0 and limited to the range (-1, 1). It suffers from gradient saturation.

Sigmoid

Used in the output layer for binary classification problems.

Softmax

Used in the output layer for multi-class classification problems.

Loss functions

A loss function measures the error between the prediction and the label. It is the “baton” of training and the starting point of backpropagation.

Abstract class

The abstract class of loss functions defines a single method interface:

  • loss (loss method): computes the loss.

Mean squared error loss function

Used for regression problems.

Cross-entropy loss function

Used for multi-class classification problems. It already includes the Softmax computation internally.

Binary cross-entropy loss function

Used for binary classification problems.

Optimizers

An optimizer updates the parameters according to the gradients and the learning rate.

Abstract class

The abstract class of optimizers defines two basic method interfaces:

  • step (step method): updates the parameters;

  • zero_grad (zero-gradient method): clears the gradients of the parameters before each iteration.

Stochastic gradient descent optimizer

The simplest and fastest, with a fixed learning rate.

Adaptive moment estimation optimizer

Adjusts the effective step size of each parameter individually, and comes with gradient clipping.

Adaptive moment estimation with weight decay optimizer

Adam with weight decay.

Learning rate scheduler

A learning rate scheduler adjusts the learning rate dynamically during training (automatic tuning).

Abstract class

The abstract class of learning rate schedulers defines a single method interface:

  • step (step method): adjusts the learning rate according to the current step count.

Warmup cosine annealing scheduler

Lets the learning rate climb from 0 (warmup) and then fall smoothly along a cosine curve (cosine annealing). This is the standard practice for training large models.

Dataset

A dataset loads the data, splits it into training and test sets, and walks through all the samples in batches.

Abstract class

The abstract class of datasets defines the basic method interfaces:

  • load (load method): loads the data;

  • train (training method): provides the training set data;

  • eval (test method): provides the test set data;

  • all (all samples): reads all the samples;

  • __len__ (number of samples): returns the number of samples;

  • __getitem__ (a single sample): reads a sample by index.

Trainer

A trainer packages the model, the loss function, and the optimizer together, and implements the training and testing logic.

Abstract class

The abstract class of trainers defines two basic method interfaces:

  • train (training method): trains for multiple epochs on the training set of a dataset, and can be connected to a learning rate scheduler;

  • test (test method): evaluates the model on the test set of a dataset.

With this, our core framework has basically taken shape.

Although this framework is written with only NumPy, it has the core features of a modern deep learning framework. In the next part, we will build on it to construct a real GPT model.

Exercises

  1. Tensors currently do not support direct operations with Python numbers. Modify __add__, __sub__, __mul__, and __truediv__ so that x * 2 and x + 1.0 also work, and the gradients in backpropagation remain correct. Hint: at the start of each operation, wrap the number in a tensor first.