Writing LSTM from Scratch in C++

Recommended read:

Linear transformations are the structural foundation of modern neural networks, pair it with non-linear steps and you got the heart of neural networks.

$$ y = Wx + b $$

This means that our very first requirement is a data structure capable of holding weights $W$, storing biases $b$, and performing matrix multiplications. Before we create the Matrix class, let’s decide first the data structure of our matrix.

Matrix

It is incredibly common to lean towards a nested 2D structure because it matches how we draw matrices. However, in practice, this is a huge performance trap.

CPU Cache Locality

When we use a nested structure like std::vector<std::vector<double>>, we are not creating a single block of data. We are creating an array of pointers, and each pointer points to a different array scattered randomly across the computer’s heap memory.

During a matrix multiplication, our CPU performs thousands of read/write operations in a tight loop. If the memory is scattered, then our CPU has to constantly jump around to different physical addresses. This causes “cache misses”, forcing the CPU to stall and wait for the RAM to fetch the data.

Index Mapping Trick

We address the issue above by using a single, flattened 1D std::vector<double>, instead of a 2D nested structure. By using this flattened 1D structure, we allocate one contiguous block of memory.

To make a 1D array act like a 2D grid, we simply calculate the 1D index using the row and column coordinates:

index = (row * total_columns) + column

When the CPU reads the first number, it automatically pulls the next several numbers into its fast L1 cache. This makes iterating through the data fast!

#include <vector>  

class Matrix {  
public:  
    int rows;  
    int cols;  
    std::vector<double> data;  
  
    Matrix(int r, int c) : rows(r), cols(c) {  
        data.resize(r * c, 0.0);  
    }  
  
    double get(int r, int c) const {  
        return data[ (r * cols) + c ];  
    }  
  
    void set(int r, int c, double value) {  
        data[ (r * cols) + c ] = value;  
    }  
};

Matrix Multiplication

As you saw in the linear transformation equation above, we are constantly multiplying a Weight Matrix $W$ by an Input Matrix $x$. When multiplying two matrices together, the fundamental rule is that their “inner dimensions” must match. This means the number of columns in the first matrix must equal the number of rows in the second matrix.

$$ A = r \times c $$ $$ B = n \times m $$ To perform matrix multiplication, $c = n$ must be true. Then Matrix C will have the size: $$ C = r \times m $$

Here’s a concrete example:

$$ \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{bmatrix} \begin{bmatrix} 7 & 8 \\ 9 & 10 \\ 11 & 12 \end{bmatrix} = \begin{bmatrix} (1*7) + (2*9) + (3*11) & (1*8) + (2*10) + (3*12) \\ (4*7) + (5*9) + (6*11) & (4*8) + (5*10) + (6*12) \end{bmatrix} = \begin{bmatrix} 58 & 64 \\ 139 & 154 \end{bmatrix} $$
Matrix multiply(const Matrix&B) const {
	// Safety check: The inner dimensions must match
	if (this->cols != B.rows) {
		throw std::invalid_argument("Incompatible matrices size!");
	}

	// Create the output matrix (with other dimensions).
	Matrix C(this->rows, B.cols);

	// 1. Iterate through A's rows.
	for ( int i = 0; i < this->rows; ++i ) {
		// 2. Iterate through B's columns.
		for ( int j = 0; j < B.cols; ++j ) {
			double sum = 0.0;

			// 3. Compute the dot products along the shared inner dimension.
			for ( int k = 0; k < this->cols; ++k ) {
				sum += this->get(i, k) * B.get(k, j);
			}

			// Store the final computed value.
			C.set(i, j, sum);
		}
	}

	return C;
}

Matrix Addition

With the above, we can now compute for the first half of our linear transformation: $W \cdot x$. To complete this, we need to add the bias $b$.

Remember that Matrix addition is a strict element-wise operation. To add Matrix A and Matrix B, we add every single pairing for every single position.

Here’s a concrete example:

$$ A = \begin{bmatrix} 1 & 3 \\ 2 & 4 \end{bmatrix}, \quad B = \begin{bmatrix} 5 & 7 \\ 6 & 8 \end{bmatrix} $$ $$ A + B = \begin{bmatrix} 1 + 5 & 3 + 7 \\ 2 + 6 & 4 + 8 \end{bmatrix} = \begin{bmatrix} 6 & 10 \\ 8 & 12 \end{bmatrix} $$
void add(const Matrix& B) {
	if ( this->rows != B.rows || this->cols != B.cols ) {
		throw std::invalid_argument("Incompatible matrices size!");
	}

	for ( int i = 0; i < this->data.size(); i++ ) {
		this->data[i] += B.data[i];
	}
}

Element-wise Multiplication

When we update our Candidate $\tilde{C_t}$, we use element-wise multiplication $\odot$. It’s similar to matrix addition but instead of addition, we multiply each of the pair in every single position.

$$F_t = \begin{bmatrix} 0.1 \\ 0.9 \end{bmatrix}, \quad C_{t-1} = \begin{bmatrix} 50 \\ 20 \end{bmatrix}$$ $$F_t \odot C_{t-1} = \begin{bmatrix} 0.1 \times 50 \\ 0.9 \times 20 \end{bmatrix} = \begin{bmatrix} 5 \\ 18 \end{bmatrix}$$
void elementMultiply(const Matrix& B) {
	if ( this->rows != B.rows || this->cols != B.cols ) {
		throw std::invalid_argument("Incompatible matrices size!");
	}

	for ( size_t i = 0; i < this->data.size(); i++ ) {
		this->data[i] *= B.data[i];
	}
}

Concatenation

Every gate equation in LSTM begins by combining the previous short-term memory and the new input: $[h_{t-1}, x_t]$.

For example, let us define $h_{t-1}$ as 3 x 1 matrix, and $x_t$ as a 2 x 1 matrix:

$$h_{t-1} = \begin{bmatrix} 0.5 \\ -0.2 \\ 0.8 \end{bmatrix}, \quad x_t = \begin{bmatrix} 1.0 \\ 0.0 \end{bmatrix}$$

To compute the concatenation $[h_{t-1}, x_t]$, we literally stack the second matrix directly underneath the first:

$$[h_{t-1}, x_t] = \begin{bmatrix} 0.5 \\ -0.2 \\ 0.8 \\ \hdashline 1.0 \\ 0.0 \end{bmatrix}$$

This results in a single, unified $5 \times 1$ matrix.

Matrix concatenate(const Matrix&B) const {
	// Safe check: Vertical stacking requires identical column size.
	if ( this->cols != B.cols ) {
		throw std::invalid_argument("Incompatible matrices size!");
	}

	Matrix C( this->rows + B.rows, this->cols);
	C.data = this->data;

	C.data.insert(C.data.end(), B.data.begin(), B.data.end());

	return C;
}

Activation Functions

The next step is turning the raw linear numbers into actual gate filters using activation functions. Activation functions are also element-wise. They look at every single number completely independently and squash it into a safe range. Because it is an element-wise operation, we get to benefit with the 1D loop that we used in our matrix.

We need two specific activation functions for our LSTM:

1. Sigmoid $\sigma$: Squashes numbers between 0 and 1. We use this for the Forget, Input, and Output gates so they act as percentage filters.

$$ \frac{1}{1 + e^{-x}} $$

2. Tanh: Squashes numbers between -1 and 1. We use this to stabilize the Candidate $\tilde{C_t}$ and the hidden state $h_t$.

void applySigmoid() {
	for ( size_t i = 0; i < this->data.size(); i++ ) {
		this->data[i] = 1.0 / (1.0 + std::exp(-this->data[i]));
	}
}

void applyTanh() {
	for ( size_t i = 0; i < this->data.size(); i++ ) {
		this->data[i] = std::tanh(this->data[i]);
	}
}

LSTM Unit Class

Now that we’re done building our mathematical core engine, we can now build the LSTM Unit class itself.

First, let’s figure out what data we need to hold that should not be lost between time steps. Let’s look at all the equations we are going to use.

$$ F_t = \sigma(W_{xf} X_t + W_{hf} H_{t-1} + b_f) $$ $$ I_t = \sigma(W_{xi} X_t + W_{hi} H_{t-1} + b_i) $$ $$ \tilde{C_t} = tanh(W_{xc} X_t + W_{hc} H_{t-1} + b_c) $$ $$ O_t = \sigma(W_{xo} X_t + W_{ho} H_{t-1} + b_o) $$ $$ C_t = F_t \odot C_{t-1} + I_t \odot \tilde{C_t} $$ $$ H_t = O_t \odot \text{tanh}(C_t) $$ It’s guaranteed that we want to store the weights and biases: $$ W_{xf}, W_{hf}, W_{xi}, W_{hi}, W_{xc}, W_{hc}, W_{xo}, W_{ho} $$ $$ b_f, b_i, b_c, b_o $$

Then we can see that both Hidden State $H_t$ and Cell State $C_t$ is also passed through the time steps.

Stitching Trick (Block Matrix Multiplication)

Before we continue, there’s another technique we can use to optimize our operations. This will also decrease the number of data we need to store in our LSTM Unit class.

Consider the equation for the forget gate:

$$ F_t = \sigma(W_{xf} X_t + W_{hf}H_{t-1} + b_f) $$

To compute for the forget gate, we need to:

  1. Multiply $W_{xf}$ and $X_t$.
  2. Multiple $W_{hf}$ and $H_{t-1}$.
  3. Add the two results together.
  4. Add the bias $b_f$.

Doing these as separate steps forces the CPU to allocate multiple temporary matrices in memory and jump across three separate loops (multiply, multiply, and add). Let’s see how we can merge them into a single pass. First, remember that matrix multiplication is distributive, so the following are true:

$$ A(B + C) = AB + AC $$ $$ (A + B)C = AC + BC $$

And because of this, $W_{xf} \cdot x_t + W_{hf} \cdot h_{t-1}$ is mathematically identical to sticking the two Weight matrices side-by-side, sticking the two input vectors on top of each other, and doing a single multiplication.

For a concrete example:

$$h_{t-1} = \begin{bmatrix} 1 \\ 2 \end{bmatrix}, \quad x_t = \begin{bmatrix} 3 \\ 4 \\ 5 \end{bmatrix}$$ $$W_{hf} = \begin{bmatrix} 2 & 1 \\ -1 & 3 \end{bmatrix}, \quad W_{xf} = \begin{bmatrix} 1 & 1 & 1 \\ 0 & -1 & 2 \end{bmatrix}$$

Method 1: The Textbook Way (Separate)

Equation: $W_{hf} \cdot h_{t-1} + W_{xf} \cdot x_t$

Step 1: Multiply the hidden state

$$W_{hf} \cdot h_{t-1} = \begin{bmatrix} 2(1) + 1(2) \\ -1(1) + 3(2) \end{bmatrix} = \begin{bmatrix} 4 \\ 5 \end{bmatrix}$$

Step 2: Multiply the new input

$$W_{xf} \cdot x_t = \begin{bmatrix} 1(3) + 1(4) + 1(5) \\ 0(3) – 1(4) + 2(5) \end{bmatrix} = \begin{bmatrix} 12 \\ 6 \end{bmatrix}$$

Step 3: Add the results together

$$\begin{bmatrix} 4 \\ 5 \end{bmatrix} + \begin{bmatrix} 12 \\ 6 \end{bmatrix} = \mathbf{\begin{bmatrix} 16 \\ 11 \end{bmatrix}}$$

Method 2: Stitch Trick

Equation: $W_f \cdot [h_{t-1}, x_t]$

Step 1: Stitch the data.
Notice how the numbers are exactly the same, just glued into larger continuous blocks:

$$[h_{t-1}, x_t] = \begin{bmatrix} 1 \\ 2 \\ 3 \\ 4 \\ 5 \end{bmatrix}, \quad W_f = \begin{bmatrix} 2 & 1 & 1 & 1 & 1 \\ -1 & 3 & 0 & -1 & 2 \end{bmatrix}$$

Step 2: Do the ONE matrix multiplication.

$$W_f \cdot [h_{t-1}, x_t] = \begin{bmatrix} 2(1) + 1(2) + 1(3) + 1(4) + 1(5) \\ -1(1) + 3(2) + 0(3) – 1(4) + 2(5) \end{bmatrix} = \mathbf{\begin{bmatrix} 16 \\ 11 \end{bmatrix}}$$

As we can see, both methods yield the exact same result and perform the exact same number of scalar multiplications. So why do we use the stitching trick?

Remember our discussion on CPU Cache Locality. Instead of managing 8 separate weight matrices ($W_{xf}$, $W_{hf}$, …), allocating temporary result matrices, and running three separate loops per gate, we cut our weight variables in half ($W_f$, $W_i$, $W_c$, $W_o$) and let the CPU execute one tight loop over a single contiguous block of memory.

Broadcasting

One last thing before we write our LSTM Unit class. Let’s review again the formula to get the forget gate.

$$ F_t = \sigma(W_f \cdot [h_{t-1}, x_t] + b_f) $$

Let’s review the data shape (dimension) of each the variables in the formula.

$[h_{t-1}, x_t]$: is from stitching. So it’s data shape will be (hidden_size + input_size, batch_size).

$W_f$: is the forget gate’s weight parameter. Since we are going to perform dot multiplication with $[h_{t-1}, x_t]$ then math dictates that it’s size should be (hidden_size, hidden_size + input_size). Remember that dot multiplication requires the inner dimensions of the variables to match.

$b_f$: A bias’ size/shape should be number of neurons X 1 (hidden_size, 1). But as we discussed above, Matrix addition is an element-wise operation. So after the dot product $W_f \cdot [h_{t-1}, x_t]$, the data shape for the addition operation would be something (hidden_size, batch_size) + (hidden_size, 1), clearly we can’t perform matrix addition with this. What we can do is “stretch” (hidden_size, 1), to make it (hidden_size, batch_size).

With this in mind, let’s update our Matrix::add() method.

void add(const Matrix& B) {
	if ( this->rows != B.rows ) {
		throw std::invalid_argument("Row dimensions must match!");
	}

	if ( B.cols == 1 ) { // Broadcasting
		for ( size_t i = 0; i < this->rows; ++i ) {
			for ( size_t j = 0; j < this->cols; ++j ) {
				this->set(i, j, this->get(i, j) + B.get(i, 0) );
			}
		}
	}
	else if ( this->cols == B.cols ) {
		for ( size_t i = 0; i < this->data.size(); i++ ) {
			this->data[i] += B.data[i];
		}
	}
	else {
		throw std::invalid_argument("Incompatible matrices size!");
	}
}

Now going back to our LSTM Unit class. You should have noticed by now that instead of having both $W_{hf}$ and $W_xf$, we stitch them together to form a single $W_f$. This reduces the number of data we need to store.

class LSTMUnit {  
public:  
	int input_size;
	int hidden_size;
	int batch_size;

	// Cell State (Long-Term memory)  
	Matrix C;  
	// Hidden State (Short-Term memory)  
	Matrix H;  
  
	// Forget gate.  
	Matrix W_f;  
	Matrix b_f;  
  
	// Input gate.  
	Matrix W_i;  
	Matrix b_i;  
  
	// Candidate.  
	Matrix W_c;  
	Matrix b_c;  
  
	// Output gate.  
	Matrix W_o;  
	Matrix b_o;

	// Cached states for backpropagation of a single step.
	Matrix C_prev;
	Matrix stacked_H_x;
	Matrix forget_gate;
	Matrix input_gate;
	Matrix candidate;
	Matrix output_gate;
    
	// Constructor to set sizes.
	LSTMUnit(int input_size, int hidden_size, int batch_size = 1)
		: input_size(input_size),
		  hidden_size(hidden_size),
		  batch_size(batch_size),
		  C(hidden_size, batch_size),
		  H(hidden_size, batch_size),
		  W_f(hidden_size, hidden_size + input_size),
		  b_f(hidden_size, 1),
		  W_i(hidden_size, hidden_size + input_size),
		  b_i(hidden_size, 1),
		  W_c(hidden_size, hidden_size + input_size),
		  b_c(hidden_size, 1),
		  W_o(hidden_size, hidden_size + input_size),
		  b_o(hidden_size, 1),
		  C_prev(hidden_size, batch_size),
		  stacked_H_x(hidden_size + input_size, batch_size),
		  forget_gate(hidden_size, batch_size),
		  input_gate(hidden_size, batch_size),
		  candidate(hidden_size, batch_size),
		  output_gate(hidden_size, batch_size) {
	}
};

The constructor looks a handful but it’s just initializing our properties. Let’s go over each of the variables:

input_size: The Feature Dimension. Computers can’t read letters or words the same as we can, so we convert the words into arrays of numbers. If you pass the word “knight” through an embedding model like Word2Vec, it translates the word into an array of numbers (for example an array of 300 numbers). Then the input_size is 300.

hidden_size: The Memory Capacity. This is a hyperparameter. It’s fancy name but to put it simply, unlike regular parameters such as the weights or biases that the model learns automatically through training, we set hyperparameters manually to guide how much our model can “learn”. In our RPG analogy, we can think of the hidden_size as the size of our characters “backpack” and “action hotbar”. A larger hidden size makes the network smarter but slower to train (it’s up to us to fine tune it to a balanced value).

batch_size: The Parallel Pipeline. Think of a factory. If batch_size is 1, we have a single conveyor belt processing one item at a time. If batch_size is 32, we have 32 identical conveyor belts running side-by-side. In the factory, having more conveyor belts means that our factory is producing more goods simultaneously. In our model, having a larger batch_size means that we are processing more items at the same time, making our training significantly faster.

(hidden_size, hidden_size + input_size): The Weight Dimensions. This is the actual, direct manifestation of the stitching trick that we learned earlier.

When we multiply our weight matrix by our stitched data $W_f \cdot [h_{t-1}, x_t]$, the dimensions of the weight matrix are dictated by two rules:

  1. The Rows (The Output Target): The number of rows in the weight matrix dictates the size of the output. Because we want the result of the gate to match the size of the internal memory (hidden state), we force the weight matrix to have exactly hidden_size rows.
  2. The Columns (Input Match): As mentioned above, matrix multiplication requires the inner dimensions to match. Because we stack the hidden state (hidden_size) on top of the new word (input_size), the incoming data vector has a total height of hidden_size + input_size. Therefore, our weight matrix must have the same exact column size to match it.

Forward Pass

Let’s review the LSTM diagram and write the forward pass implementation.

void forward(const Matrix& x) {
	// Save previous cell state for backpropagation
	this->C_prev = this->C;

	// 1. Stack the hidden state and input [H, x]
	this->stacked_H_x = this->H.concatenate(x); // (hidden_size + input_size, batch_size)

	// 2. Compute the forget gate.
	this->forget_gate = this->W_f.multiply(this->stacked_H_x); // (hidden_size, batch_size)
	this->forget_gate.add(this->b_f); // (hidden_size, batch_size)
	this->forget_gate.applySigmoid(); // (hidden_size, batch_size)

	// 3. Compute the input gate.
	this->input_gate = this->W_i.multiply(this->stacked_H_x); // (hidden_size, batch_size)
	this->input_gate.add(this->b_i); // (hidden_size, batch_size)
	this->input_gate.applySigmoid(); // (hidden_size, batch_size)

	// 4. Calculate the candidate.
	this->candidate = this->W_c.multiply(this->stacked_H_x); // (hidden_size, batch_size)
	this->candidate.add(this->b_c); // (hidden_size, batch_size)
	this->candidate.applyTanh(); // (hidden_size, batch_size)

	// 5. Calculate the output gate.
	this->output_gate = this->W_o.multiply(this->stacked_H_x); // (hidden_size, batch_size)
	this->output_gate.add(this->b_o); // (hidden_size, batch_size)
	this->output_gate.applySigmoid(); // (hidden_size, batch_size)

	// 6. Calculate the new cell state (long-term memory).
	this->C.elementMultiply(this->forget_gate); // (hidden_size, batch_size)
	Matrix temp_input_gate = this->input_gate; // Copy so we don't overwrite this->input_gate!
	temp_input_gate.elementMultiply(this->candidate); // (hidden_size, batch_size)
	this->C.add(temp_input_gate); // (hidden_size, batch_size)

	// 7. Calculate the hidden state (short-term memory).
	this->H = this->C; // (hidden_size, batch_size)
	this->H.applyTanh(); // (hidden_size, batch_size)
	this->H.elementMultiply(this->output_gate); // (hidden_size, batch_size)
}

Backpropagation

Now we want to “know” how to improve our LSTM unit. We want to know how much our “tunable” parameters (weights and biases) contributes to the prediction’s error and update them to reduce the error in future predictions. For now, let’s focus on the LSTM unit.

$$ F_t = \sigma(W_f \cdot [H_{t-1}, x_t] + b_f) $$ $$ I_t = \sigma(W_i \cdot [H_{t-1}, x_t] + b_i) $$ $$ \tilde{C_t} = tanh(W_c \cdot [H_{t-1}, x_t] + b_c) $$ $$ O_t = \sigma(W_o \cdot [H_{t-1}, x_t] + b_o) $$ $$ C_t = F_t \odot C_{t-1} + I_t \odot \tilde{C_t} $$ $$ H_t = O_t \odot \text{tanh}(C_t) $$

Before we dive into the equations, let’s establish one rule to keep the math clean: we will first look at a single, isolated time step.

In an isolated step, all of the error (blame) enters our LSTM unit through the Hidden State $H_t$, which we will denote as $\partial H_t$ (short for $\frac{\partial L}{\partial H_t}$). Later, when we link multiple time steps together, we will see how a second stream of error also enters from the future Cell State and how easily it plugs into what we are about to derive.

Let’s get the gradients of the weights and biases for this single step.

Forget Gate

$W_f$

Let’s trace backwards.

$$ \frac{\partial{H_t}}{\partial{C_t}} = O_t \odot [1 – \text{tanh}^2(C_t)] $$

Remember that when we performed the forward pass, we used element-wise when we used the activation function tanh. So when we trace back, we also want to perform element-wise.

$$ \frac{\partial{C_t}}{\partial{F_t}} = C_{t-1} $$ $$ \frac{\partial{F_t}}{\partial{W_f}} = [F_t \odot (1 – F_t)] \cdot [H_{t-1}, x_t]^T $$

The same is also true above, we used element-size multiplication when we used the sigmoid activation, so we also have to perform element-wise when tracing backward the error signal. Also remember that $[F_t \odot (1 – F_t)]$ has the shape (hidden_size, batch_size) while $[H_{t-1}, x_t]$ has the shape (hidden_size + input_size, batch_size). By now, we know that we can only perform dot multiplication when the inner dimensions match. So to be able to do this, we get the transpose instead $[H_{t-1}, x_t]^T$. This will align the shapes to (hidden_size, batch_size)ยท (batch_size, hidden_size + input_size).

The final equation would be:

$$ \frac{\partial{L}}{\partial{W_f}} = \partial{H_t} \odot \frac{\partial{H_t}}{\partial{C_t}} \odot \frac{\partial{C_t}}{\partial{F_t}} \odot \frac{\partial{F_t}}{\partial{W_f}} $$ $$ \frac{\partial{L}}{\partial{W_f}} = (\partial{H_t} \odot O_t \odot [1 – \text{tanh}^2(C_t)] \odot C_{t-1} \odot [F_t \odot (1 – F_t)]) \cdot [H_{t-1}, x_t]^T $$

One way to check if we are computing correctly is to compare the shape of the gradient and it’s corresponding variable. The general rule is that they must match.

This part has the shape:(hidden_size, batch_size)

$$ (\partial{H_t} \odot O_t \odot [1 – \text{tanh}^2(C_t)] \odot C_{t-1} \odot [F_t \odot (1 – F_t)]) $$

and this part has the shape:(batch_size, hidden_size + input_size). So getting the dot product of the two must return a shape of (hidden_size, hidden_size + input_size). And as we already know $W_f$ is shaped (hidden_size, hidden_size + input_size).

$$ [H_{t-1}, x_t]^T $$

$b_f$

$$ \frac{\partial{H_t}}{\partial{C_t}} = O_t \odot [1 – \text{tanh}^2(C_t)] $$ $$ \frac{\partial{C_t}}{\partial{F_t}} = C_{t-1} $$ $$ \frac{\partial{F_t}}{\partial{b_f}} = F_t \odot (1 – F_t) $$ $$ \frac{\partial{L}}{\partial{b_f}} = \partial{H_t} \odot \frac{\partial{H_t}}{\partial{C_t}} \odot \frac{\partial{C_t}}{\partial{F_t}} \odot \frac{\partial{F_t}}{\partial{b_f}} $$ $$ \frac{\partial{L}}{\partial{b_f}} = \partial{H_t} \odot O_t \odot [1 – \text{tanh}^2(C_t)] \odot C_{t-1} \odot [F_t \odot (1 – F_t)] $$

Again let’s check the shape:

$$ \partial{H_t} \odot O_t \odot [1 – \text{tanh}^2(C_t)] \odot C_{t-1} \odot [F_t \odot (1 – F_t)] $$

has the shape: (hidden_size, batch_size). But $b_f$ has the shape: (hidden_size, 1). Why is this the case? And how to we correct this?

Reversing the Broadcasting

Recall that during the forward pass, we perform broadcasting when we added the bias, we stretch the single bias column (hidden_size, 1), to match (hidden_size, batch_size). Because the same bias parameter influenced multiple outputs, the chain dictates that the total error for that parameter is the sum of the errors from all the outputs it touched.

To mathematically reverse the broadcast, we must sum the error matrix across the batch_size columns. This collapses the (hidden_size, batch_size) matrix perfectly back into a (hidden_size, 1) column vector.

So the final equation is:

$$ \frac{\partial{L}}{\partial{b_f}} = \sum_{\text{batch}}{(\partial{H_t} \odot O_t \odot [1 – \text{tanh}^2(C_t)] \odot C_{t-1} \odot [F_t \odot (1 – F_t)])} $$

Input Gate

$W_i$

$$ \frac{\partial{H_t}}{\partial{C_t}} = O_t \odot [1 – \text{tanh}^2(C_t)] $$ $$ \frac{\partial{C_t}}{\partial{I_t}} = \tilde{C_t} $$ $$ \frac{\partial{I_t}}{\partial{W_i}} = [I_t \odot (1 – I_t)] \cdot [H_{t-1}, x_t]^T $$ $$ \frac{\partial{L}}{\partial{W_i}} = (\partial{H_t} \odot O_t \odot [1 – \text{tanh}^2(C_t)] \odot \tilde{C_t} \odot [I_t \odot (1 – I_t)]) \cdot [H_{t-1}, x_t]^T $$

$b_i$

$$ \frac{\partial{L}}{\partial{b_i}} = \partial{H_t} \odot \frac{\partial{H_t}}{\partial{C_t}} \odot \frac{\partial{C_t}}{\partial{I_t}} \odot \frac{\partial{I_t}}{\partial{b_i}} $$ $$ \frac{\partial{I_t}}{\partial{b_i}} = I_t \odot (1 – I_t) $$ $$ \frac{\partial{L}}{\partial{b_i}} = \sum_{\text{batch}}{\partial{H_t} \odot O_t \odot [1 – \text{tanh}^2(C_t)] \odot \tilde{C_t} \odot [I_t \odot (1 – I_t)]} $$

Candidate

$W_c$

$$ \frac{\partial{L}}{\partial{W_c}} = \partial{H_t} \odot \frac{\partial{H_t}}{\partial{C_t}} \odot \frac{\partial{C_t}}{\partial{\tilde{C_t}}} \odot \frac{\partial{\tilde{C_t}}}{\partial{W_c}} $$ $$ \frac{\partial{C_t}}{\partial{\tilde{C_t}}} = I_t $$

Let:

$$ U = W_c \cdot [H_{t-1}, x_t] + b_c $$ $$ \frac{\partial{\tilde{C_t}}}{\partial{W_c}} = [1 – \text{tanh}^2(U)] \cdot [H_{t-1}, x_t]^T $$ $$ \frac{\partial{L}}{\partial{W_c}} = (\partial{H_t} \odot O_t \odot [1 – \text{tanh}^2(C_t)] \odot I_t \odot [1 – \text{tanh}^2(U)]) \cdot [H_{t-1}, x_t]^T $$

$b_c$

$$ \frac{\partial{L}}{\partial{b_c}} = \partial{H_t} \odot \frac{\partial{H_t}}{\partial{C_t}} \odot \frac{\partial{C_t}}{\partial{\tilde{C_t}}} \odot \frac{\partial{\tilde{C_t}}}{\partial{b_c}} $$ $$ \frac{\partial{\tilde{C_t}}}{\partial{b_c}} = [1 – \text{tanh}^2(U)] $$ $$ \frac{\partial{L}}{\partial{b_c}} = \sum_{\text{batch}}{\partial{H_t} \odot O_t \odot [1 – \text{tanh}^2(C_t)] \odot I_t \odot [1 – \text{tanh}^2(U)]} $$

Output Gate

$W_o$

$$ \frac{\partial{L}}{\partial{W_o}} = \partial{H_t} \odot \frac{\partial{H_t}}{\partial{O_t}} \odot \frac{\partial{O_t}}{\partial{W_o}} $$ $$ \frac{\partial{H_t}}{\partial{O_t}} = \text{tanh}(C_t) $$ $$ \frac{\partial{O_t}}{\partial{W_o}} = [O_t \odot (1 – O_t)] \cdot [H_{t-1}, x_t]^T $$

Final equation:

$$ \frac{\partial{L}}{\partial{W_o}} = (\partial{H_t} \odot \text{tanh}(C_t) \odot [O_t \odot (1 – O_t)]) \cdot [H_{t-1}, x_t]^T $$

$b_o$

$$ \frac{\partial{L}}{\partial{b_o}} = \partial{H_t} \odot \frac{\partial{H_t}}{\partial{O_t}} \odot \frac{\partial{O_t}}{\partial{b_o}} $$ $$ \frac{\partial{O_t}}{\partial{b_o}} = [O_t \odot (1 – O_t)] $$

Final equation:

$$ \frac{\partial{L}}{\partial{b_o}} = \sum_{\text{batch}}{\partial{H_t} \odot \text{tanh}(C_t) \odot [O_t \odot (1 – O_t)]} $$

Passing the Blame

Recall that every layer in a neural network has two distinct jobs during backpropagation:

  1. Fixing itself by updating its parameters. We already did this when we compute for the gradients of the weights and biases.
  2. Passing the blame. A layer doesn’t just use weights and biases; it processes incoming data. Our LSTM Unit, the incoming data are the Cell State from the previous time step $C_{t-1}$ and $[H_{t-1}, x_t]$.

$C_t$

Let’s focus on $C_{t}$ for now. If we look in our forward pass, we can see that $C_t$ branches into two distinct paths.

1. The Local Prediction is pushed through a tanh activation and multiplied by the Output Gate to create the Short-Term memory.

$$ \text{Local} \frac{\partial{L}}{\partial{C_t}} = \frac{\partial{L}}{\partial{H_t}} \odot \frac{\partial{H_t}}{\partial{C_t}} $$ $$ \text{Local} \frac{\partial{L}}{\partial{C_t}} = \frac{\partial{L}}{\partial{H_t}} \odot O_t \odot [1-\text{tanh}^2(C_t)] $$

2. The Future Step. We can also see that a copy of $C_t$ is also passed directly to the next LSTM unit in the sequence to act as the Long-Term memory. We can just denote this as $\partial{C_{\text{next}}}$

Since we need to find the total blame assigned to $C_t$, we must sum the error from both paths.

$$ \partial{C_t} = \text{Local} \frac{\partial{L}}{\partial{C_t}} + \partial{C_{\text{next}}} $$

You might notice that this might change our equation gates earlier. Look back at our equations for the Forget Gate ($W_f, b_f$), Input Gate ($W_i, b_i$), and Candidate ($W_c, b_c$). Every single one of them started with the local cell state error:

$$\partial{H_t} \odot O_t \odot [1 – \text{tanh}^2(C_t)]$$

When our LSTM is part of a sequence, those three gates don’t just affect the current output $H_t$, they also affect the future step $C_{\text{next}}$. So when coding a full sequence, we simply swap that local term with our combined $\partial{C_t}$ above.

Now that we have the total error for the current state, we need to hand the error backward to the previous LSTM unit so it can learn.

Look at the original equation that created the current cell state:

$$ C_t = (F_t \odot C_{t-1}) + (I_t \odot \tilde{C}_t) $$

Let’s get the local derivative.

$$ \frac{\partial{C_t}}{\partial{C_{t-1}}} = F_t $$

Then finally, we can compute for the error of $C_{t-1}$.

$$ \frac{\partial{L}}{\partial{C_{t-1}}} = \partial{C_t} \odot F_t $$ $$ \frac{\partial{L}}{\partial{C_{t-1}}} = (\frac{\partial{L}}{\partial{H_t}} \odot O_t \odot [1 – \text{tanh}^2(C_t)] + \partial{C_{\text{next}}}) \odot F_t $$

$[H_{t-1}, x_t]$

During our forward pass, we know that $[H_{t-1}, x_t]$ is used into four different paths:

  • Forget Gate
$$ Z_f = W_f \cdot [H_{t-1}, x_t] + b_f $$
  • Input Gate
$$ Z_i = W_i \cdot [H_{t-1}, x_t] + b_i $$
  • Candidate
$$ Z_{\tilde{c}} = W_c \cdot [H_{t-1}, x_t] + b_c $$
  • Output Gate
$$ Z_o = W_o \cdot [H_{t-1}, x_t] + b_o $$

So we have to get the error from each of the four paths.

  • Error from Forget Gate
$$ W_f^T \cdot \partial{Z_f} $$
  • Error from Input Gate
$$ W_i^T \cdot \partial{Z_i} $$
  • Error from Candidate
$$ W_c^T \cdot \partial{Z_{\tilde{c}}} $$
  • Error from Output Gate
$$ W_o^T \cdot \partial{Z_o} $$

For the sake of completeness, this is how we get $\partial{Z_f}$, $\partial{Z_i}$, $\partial{Z_{\tilde{c}}}$, and $\partial{Z_o}$.

$$ \frac{\partial L}{\partial Z_f} = \frac{\partial L}{\partial C_t} \odot \frac{\partial C_t}{\partial F_t} \odot \frac{\partial F_t}{\partial Z_f} $$ $$ \partial{Z_f} = \partial{C_t} \odot C_{t-1} \odot F_t \odot (1 – F_t) $$ $$\partial{Z_f} = \left[ \left( \partial{H_t} \odot O_t \odot [1-\text{tanh}^2(C_t)] \right) + \partial{C_{next}} \right] \odot C_{t-1} \odot F_t \odot (1 – F_t)$$ $$\frac{\partial L}{\partial Z_i} = \frac{\partial L}{\partial C_t} \odot \frac{\partial C_t}{\partial I_t} \odot \frac{\partial I_t}{\partial Z_i}$$ $$\partial Z_i = \partial C_t \odot \tilde{C}_t \odot I_t \odot (1 – I_t)$$ $$\partial Z_i = \left[ \left( \partial H_t \odot O_t \odot [1-\text{tanh}^2(C_t)] \right) + \partial{C_{next}} \right] \odot \tilde{C}_t \odot I_t \odot (1 – I_t)$$ $$\frac{\partial L}{\partial Z_{\tilde{c}}} = \frac{\partial L}{\partial C_t} \odot \frac{\partial C_t}{\partial \tilde{C}_t} \odot \frac{\partial \tilde{C}_t}{\partial Z_{\tilde{c}}}$$ $$\partial Z_{\tilde{c}} = \partial C_t \odot I_t \odot [1 – \text{tanh}^2(\tilde{C}_t)]$$ $$\partial Z_{\tilde{c}} = \left[ \left( \partial H_t \odot O_t \odot [1-\text{tanh}^2(C_t)] \right) + \partial{C_{next}} \right] \odot I_t \odot [1 – \text{tanh}^2(\tilde{C}_t)]$$ $$\frac{\partial L}{\partial Z_o} = \frac{\partial L}{\partial H_t} \odot \frac{\partial H_t}{\partial O_t} \odot \frac{\partial O_t}{\partial Z_o}$$ $$\partial Z_o = \partial H_t \odot \text{tanh}(C_t) \odot O_t \odot (1 – O_t)$$

Then we need to combine the errors from these four paths to get the total error.

$$ \partial{[H_{t-1}, x_t]} = (W_f^T \cdot \partial{Z_f}) + (W_i^T \cdot \partial{Z_i}) + (W_c^T \cdot \partial{Z_{\tilde{c}}}) + (W_o^T \cdot \partial{Z_o}) $$

The size of $\partial{[H_{t-1}, x_t]}$ is (hidden_size + input_size, batch_size). Remember that we concatenate the matrix for efficient computation, but during backpropagation these two components travel in different paths.

$\partial H_{t-1}$ (The Top Half): This error signal flows horizontally backward through time. It acts as the incoming hidden state error that you will feed into the previous LSTM unit at step $t-1$.

$\partial x_t$ (The Bottom Half): This error signal flows vertically downward. It acts as the incoming loss for whatever neural network layer or embedding matrix supplied the raw data for the current step $t$.

LSTM Unit Backprop C++

Here are our equations:

$$ \frac{\partial{I_t}}{\partial{W_i}} = [I_t(1 – I_t)] \cdot [H_{t-1}, x_t]^T $$ $$ \frac{\partial{L}}{\partial{W_i}} = (\partial H_t \odot O_t \odot [1 – \text{tanh}^2(C_t)] \odot \tilde{C_t} \odot [I_t (1 – I_t)]) \cdot [H_{t-1}, x_t]^T $$

Forget Gate

$$ \frac{\partial{L}}{\partial{W_f}} = \partial{H_t} \odot \frac{\partial{H_t}}{\partial{C_t}} \odot \frac{\partial{C_t}}{\partial{F_t}} \odot \frac{\partial{F_t}}{\partial{W_f}} $$ $$ \frac{\partial{L}}{\partial{b_f}} = \sum_{\text{batch}} \partial{H_t} \odot \frac{\partial{H_t}}{\partial{C_t}} \odot \frac{\partial{C_t}}{\partial{F_t}} \odot \frac{\partial{F_t}}{\partial{b_f}} $$

Input Gate

$$ \frac{\partial{L}}{\partial{W_i}} = \partial{H_t} \odot \frac{\partial{H_t}}{\partial{C_t}} \odot \frac{\partial{C_t}}{\partial{I_t}} \odot \frac{\partial{I_t}}{\partial{W_i}} $$ $$ \frac{\partial{L}}{\partial{b_i}} = \sum_{\text{batch}} \partial{H_t} \odot \frac{\partial{H_t}}{\partial{C_t}} \odot \frac{\partial{C_t}}{\partial{I_t}} \odot \frac{\partial{I_t}}{\partial{b_i}} $$

Candidate

$$ \frac{\partial{L}}{\partial{W_c}} = \partial{H_t} \odot \frac{\partial{H_t}}{\partial{C_t}} \odot \frac{\partial{C_t}}{\partial{\tilde{C}_t}} \odot \frac{\partial{\tilde{C}_t}}{\partial{W_c}} $$ $$ \frac{\partial{L}}{\partial{b_c}} = \sum_{\text{batch}} \partial{H_t} \odot \frac{\partial{H_t}}{\partial{C_t}} \odot \frac{\partial{C_t}}{\partial{\tilde{C}_t}} \odot \frac{\partial{\tilde{C}_t}}{\partial{b_c}} $$

Output Gate

$$ \frac{\partial{L}}{\partial{W_o}} = \partial{H_t} \odot \frac{\partial{H_t}}{\partial{O_t}} \odot \frac{\partial{O_t}}{\partial{W_o}} $$ $$ \frac{\partial{L}}{\partial{b_o}} = \sum_{\text{batch}} \partial{H_t} \odot \frac{\partial{H_t}}{\partial{O_t}} \odot \frac{\partial{O_t}}{\partial{b_o}} $$

You’ll notice that there are several terms that are used many times like the following.

$$ \frac{\partial{H_t}}{\partial{C_t}}, \frac{\partial{C_t}}{\partial{F_t}}, \frac{\partial{C_t}}{\partial{I_t}}, \frac{\partial{C_t}}{\partial{\tilde{C}_t}}, \frac{\partial{H_t}}{\partial{O_t}} $$

To optimize our code implementation, we want to re-use as much terms as possible.

struct LSTMUnitGrads {  
	Matrix dC_prev;  
	Matrix dH_prev;  
	Matrix dX_t;  
};

class LSTMUnit {
	// ... Other methods
	LSTMUnitGrads backward(const Matrix& dH_t, const Matrix& dC_next) {  
	  
		// dHt_Ct = O_t \odot this->C.tanhDerivative()  
		Matrix dHt_Ct = this->C.tanhDerivative();  
		dHt_Ct.elementMultiply(this->output_gate);  
	  
		// dH_t \odot dHt_Ct + dC_next
		Matrix dCt = dH_t;  
		dCt.elementMultiply(dHt_Ct);
		
		// 2. Add the error coming from the future time step.
		// Because we add dC_next here, the Forget Gate, Input Gate, and Candidate
		// below automatically get the total combined blame.
		dCt.add(dC_next);  

		Matrix stacked_H_x_T = this->stacked_H_x.transpose();
	  
		// 1. Forget Gate
		// dCt \odot C_{t-1}
		Matrix dFt = dCt; 
		dFt.elementMultiply(this->C_prev);  
	  
		// dFt \odot F_t(1 - F_t)  
		Matrix dZ_f = dFt;  
		dZ_f.elementMultiply(this->forget_gate.sigmoidDerivative());  
	  
		Matrix dL_dWf = dZ_f.multiply(stacked_H_x_T);  
		Matrix dB_f = dZ_f.sumColumns();  
	  
		// 2. Input Gate
		// dCt \odot \tilde{C}_t
		Matrix dIt = dCt;  
		dIt.elementMultiply(this->candidate);  
	  
		// dIt \odot I_t(1 - I_t)  
		Matrix dZ_i = dIt;  
		dZ_i.elementMultiply(this->input_gate.sigmoidDerivative());  
	  
		Matrix dL_dWi = dZ_i.multiply(stacked_H_x_T);  
		Matrix dB_i = dZ_i.sumColumns();  
	  
		// 3. Candidate
		// dCt \odot I_t
		Matrix dCn = dCt;  
		dCn.elementMultiply(this->input_gate);  
	  
		// dCn \odot (1 - \tilde{C}_t^2)  
		Matrix dZ_cn = dCn;  
		dZ_cn.elementMultiply(this->candidate.tanhDerivativeFromActivated());  
	  
		Matrix dL_dWcn = dZ_cn.multiply(stacked_H_x_T);  
		Matrix dB_cn = dZ_cn.sumColumns();  
	  
		// 4. Output Gate
		// dH_t \odot tanh(C_t)
		Matrix dOt = this->C;  
		dOt.applyTanh();  
		dOt.elementMultiply(dH_t);  
	  
		// dOt \odot O_t(1 - O_t)  
		Matrix dZ_o = this->output_gate.sigmoidDerivative();  
		dZ_o.elementMultiply(dOt);  
	  
		Matrix dL_dWo = dZ_o.multiply(stacked_H_x_T);  
		Matrix dB_o = dZ_o.sumColumns();  
	  
		// 5. Pass the blame
		Matrix dC_prev = dCt;  
		dC_prev.elementMultiply(this->forget_gate);  
	  
		Matrix err_forget_gate = this->W_f.transpose().multiply(dZ_f);  
		Matrix err_input_gate = this->W_i.transpose().multiply(dZ_i);  
		Matrix err_candidate = this->W_c.transpose().multiply(dZ_cn);  
		Matrix err_output_gate = this->W_o.transpose().multiply(dZ_o);  
	  
		Matrix total_stacked_err = err_forget_gate;  
		total_stacked_err.add(err_input_gate);  
		total_stacked_err.add(err_candidate);  
		total_stacked_err.add(err_output_gate);  
	  
		Matrix dH_prev = total_stacked_err.sliceRows(0, this->hidden_size);  
		Matrix dX_t = total_stacked_err.sliceRows(this->hidden_size, this->hidden_size + this->input_size);  
	  
		return {dC_prev, dH_prev, dX_t};  
	}
};

Backpropagation Through Time (BPTT)

I find it easier to understand if we can visualize. Below is an example diagram of the forward pass of a Many-to-One LSTM architecture.

Now let’s see how the backward pass.

We will update our LSTM forward and backward pass implementation later to handle sequences.

Model’s Prediction

The LSTM unit itself does not compute the final prediction $\hat{y}$. It’s only job is to extract patterns from the sequence and output the Hidden State $H_t$.

To generate a prediction, we must route the Hidden State through a linear layer.

$$ \hat{y} = \text{Activation}(W_y \cdot H_t + b_y) $$

The activation function we use here entirely depends on what our model is trying to solve. For this blog, let’s make our model do a binary classification, so let’s use the Sigmoid function as our activation.

$$ \hat{y} = \sigma(W_y \cdot H_t + b_y) $$

Loss Function

Before we can train our model, we need to measure its mistake (Loss function). What loss function to use depends on what our model wants to predict. Since our model’s task is binary classification, let’s use the Binary Cross-Entropy Loss (BCE).

Let:

  • $y$: The target (true label).
  • $\hat{y}$: The model’s prediction.
$$ L = -[y \odot \text{ln}(\hat{y}) + (1 – y) \odot \text{ln}(1 – \hat{y})] $$

Our goal is to minimize the loss function. Backpropagation is basically looking at the loss function $L$ then trace backward to find which variables, and how much we need to adjust them to minimize the loss function.

We also need to get the gradients for the prediction parameters.

$W_y$

$$ \frac{\partial{L}}{\partial{W_y}} = \frac{\partial{L}}{\partial{\hat{y}}} \odot \frac{\partial{\hat{y}}}{\partial{W_y}} $$ $$ \frac{\partial{L}}{\partial{\hat{y}}} = – [y (\frac{1}{\hat{y}}) + (1 – y)(\frac{1}{1 – \hat{y}})(-1)] = -[\frac{y(1 – \hat{y}) – \hat{y}(1 – y)}{\hat{y}(1-\hat{y})}] $$ $$ \frac{\partial{\hat{y}}}{\partial{W_y}} = \hat{y}(1 – \hat{y}) \cdot H_t^T $$ $$ \frac{\partial{L}}{\partial{W_y}} = -[\frac{y(1 – \hat{y}) – \hat{y}(1 – y)}{\hat{y}(1-\hat{y})}] \cdot [\hat{y}(1 – \hat{y})] \cdot H_t^T $$ $$ \frac{\partial{L}}{\partial{W_y}} = -[y – y\hat{y} – \hat{y} + y\hat{y}] \cdot H_t^T = (\hat{y} – y) \cdot H_t^T $$

$b_y$

$$ \frac{\partial{L}}{\partial{b_y}} = \frac{\partial{L}}{\partial{\hat{y}}} \odot \frac{\partial{\hat{y}}}{\partial{b_y}} $$ $$ \frac{\partial{\hat{y}}}{\partial{b_y}} = \hat{y}(1 – \hat{y}) $$ $$ \frac{\partial{L}}{\partial{b_y}} = -[\frac{y(1 – \hat{y}) – \hat{y}(1 – y)}{\hat{y}(1-\hat{y})}] \cdot \hat{y}(1 – \hat{y}) $$

Remember that we have to reverse the broadcasting for the bias, so the final equation is:

$$ \frac{\partial{L}}{\partial{b_y}} = \sum_{\text{batch}}{\hat{y} – y} $$

Passing the Blame

Our prediction layer’s incoming data is $H_t$, which was the output of our LSTM unit. Our prediction layer must figure out how much of the final mistake was caused by receiving a bad $H_t$, and pass that error down to the LSTM.

$$ \frac{\partial{L}}{\partial{H_t}} = \frac{\partial{\hat{y}}}{\partial{H_t}} \cdot \frac{\partial{L}}{\partial{\hat{y}}} $$ $$ \frac{\partial{L}}{\partial{H_t}} = W_y^T \cdot (\hat{y}-y) $$

Now that we have everything we need. Here’s the C++ implementation of a LSTM Network.

Full C++ Implementation

#include <vector>
#include <cmath>
#include <stdexcept>
#include <iostream>
#include <random>
#include <iomanip>

class Matrix {
public:
    int rows;
    int cols;
    std::vector<double> data;

    Matrix(int r, int c) : rows(r), cols(c) {
        data.resize(r * c, 0.0);
    }

    double get(int r, int c) const {
        return data[ (r * cols) + c ];
    }

    void set(int r, int c, double value) {
        data[ (r * cols) + c ] = value;
    }

    Matrix multiply(const Matrix&B) const {
        // Safety check: The inner dimensions must match
        if (this->cols != B.rows) {
            throw std::invalid_argument("Incompatible matrices size!");
        }

        // Create the output matrix (with other dimensions).
        Matrix C(this->rows, B.cols);

        // 1. Iterate through A's rows.
        for ( size_t i = 0; i < this->rows; ++i ) {
            // 2. Iterate through B's columns.
            for ( size_t j = 0; j < B.cols; ++j ) {
                double sum = 0.0;

                // 3. Compute the dot products along the shared inner dimension.
                for ( size_t k = 0; k < this->cols; ++k ) {
                    sum += this->get(i, k) * B.get(k, j);
                }

                // Store the final computed value.
                C.set(i, j, sum);
            }
        }

        return C;
    }

    Matrix concatenate(const Matrix&B) const {
        // Safe check: Vertical stacking requires identical column size.
        if ( this->cols != B.cols ) {
            throw std::invalid_argument("Incompatible matrices size!");
        }

        Matrix C( this->rows + B.rows, this->cols);

        C.data = this->data;

        C.data.insert(C.data.end(), B.data.begin(), B.data.end());

        return C;
    }

    void add(const Matrix& B) {
        if ( this->rows != B.rows ) {
            throw std::invalid_argument("Row dimensions must match!");
        }

        if ( B.cols == 1 ) {
            for ( size_t i = 0; i < this->rows; ++i ) {
                for ( size_t j = 0; j < this->cols; ++j ) {
                    this->set(i, j, this->get(i, j) + B.get(i, 0) );
                }
            }
        }
        else if ( this->cols == B.cols ) {
            for ( size_t i = 0; i < this->data.size(); ++i ) {
                this->data[i] += B.data[i];
            }
        }
        else {
            throw std::invalid_argument("Incompatible matrices size!");
        }
    }

    void elementMultiply(const Matrix& B) {
        if ( this->rows != B.rows || this->cols != B.cols ) {
            throw std::invalid_argument("Incompatible matrices size!");
        }

        for ( size_t i = 0; i < this->data.size(); ++i ) {
            this->data[i] *= B.data[i];
        }
    }

    void applySigmoid() {
        for ( size_t i = 0; i < this->data.size(); ++i ) {
            this->data[i] = 1.0 / (1.0 + std::exp(-this->data[i]));
        }
    }

    void applyTanh() {
        for ( size_t i = 0; i < this->data.size(); ++i ) {
            this->data[i] = std::tanh(this->data[i]);
        }
    }

    Matrix tanhDerivative() const {
        Matrix result(this->rows, this->cols);

        for ( size_t i = 0; i < this->data.size(); ++i ) {
            double tanh_val = std::tanh(this->data[i]);
            result.data[i] = 1.0 - (tanh_val * tanh_val);
        }

        return result;
    }

    Matrix tanhDerivativeFromActivated() const {
        Matrix result(this->rows, this->cols);
        for ( size_t i = 0; i < this->data.size(); ++i ) {
            result.data[i] = 1.0 - (this->data[i] * this->data[i]);
        }
        return result;
    }

    // We assume that `applySigmoid()` was already invoked during the forward pass.
    Matrix sigmoidDerivative() const {
        Matrix result(this->rows, this->cols);

        for ( size_t i = 0; i < this->data.size(); ++i ) {
            result.data[i] = this->data[i] * (1.0 - this->data[i]);
        }

        return result;
    }

    Matrix transpose() const {
        Matrix result( this->cols, this->rows );

        for ( size_t i = 0; i < this->rows; ++i ) {
            for ( size_t j = 0; j < this->cols; ++j ) {
                result.set(j, i, this->get(i, j));
            }
        }

        return result;
    }

    Matrix sumColumns() const {
        Matrix result( this->rows, 1 );

        for ( size_t i = 0; i < this->rows; ++i ) {
            double sum = 0.0;

            for ( size_t j = 0; j < this->cols; ++j ) {
                sum += this->get(i, j);
            }

            result.set(i, 0, sum);
        }

        return result;
    }

    Matrix sliceRows( int start_row, int end_row ) const {
        int new_row_count = end_row - start_row;

        Matrix result(new_row_count, this->cols);

        for ( size_t i = 0; i < new_row_count; ++i ) {
            for ( size_t j = 0; j < this->cols; ++j ) {
                result.set(i, j, this->get(start_row + i, j) );
            }
        }

        return result;
    }

    void randomize(double min_val = -0.5, double max_val = 0.5) {
        static std::mt19937 gen(42); // Fixed seed for consistent results
        std::uniform_real_distribution<double> dist(min_val, max_val);

        for (size_t i = 0; i < data.size(); ++i) {
            data[i] = dist(gen);
        }
    }

    void subtractScaled(const Matrix& grad, double learning_rate) {
        if (this->rows != grad.rows || this->cols != grad.cols) {
            throw std::invalid_argument("Incompatible matrices size!");
        }

        for (size_t i = 0; i < this->data.size(); ++i) {
            this->data[i] -= learning_rate * grad.data[i];
        }
    }

    Matrix subtract(const Matrix& B) const {
        if (this->rows != B.rows || this->cols != B.cols) {
            throw std::invalid_argument("Incompatible matrices size!");
        }

        Matrix result(this->rows, this->cols);

        for (size_t i = 0; i < this->data.size(); ++i) {
            result.data[i] = this->data[i] - B.data[i];
        }

        return result;
    }
};

struct LSTMTimeStepCache {
    Matrix C_prev; // Previous TimeStep Long Term memory.
    Matrix stack_H_prev_x; // [H_{t-1}, x].
    Matrix F; // Forget gate
    Matrix I; // Input gate
    Matrix Cn; // Candidate
    Matrix O; // Output gate
    Matrix C; // Current timestep Long Term Memory.
    Matrix H; // Current timestep Short Term Memory.

    LSTMTimeStepCache(int input_size, int hidden_size, int batch_size = 1)
        : C_prev(hidden_size, batch_size),
          stack_H_prev_x(hidden_size + input_size, batch_size),
          F(hidden_size, batch_size),
          I(hidden_size, batch_size),
          Cn(hidden_size, batch_size),
          O(hidden_size, batch_size),
          C(hidden_size, batch_size),
          H(hidden_size, batch_size) {}
};

struct LSTMGrads {
    std::vector<Matrix> dX_sequence;
    Matrix dW_f, db_f;
    Matrix dW_i, db_i;
    Matrix dW_c, db_c;
    Matrix dW_o, db_o;
};

class LSTMSequence {
public:
    int hidden_size;
    int input_size;
    int batch_size;

    // Cell State (Long-Term memory)
    Matrix C;
    // Hidden State (Short-Term memory)
    Matrix H;

    Matrix forget_gate;
    Matrix W_f;
    Matrix b_f;

    Matrix input_gate;
    Matrix W_i;
    Matrix b_i;

    Matrix candidate;
    Matrix W_c;
    Matrix b_c;

    Matrix output_gate;
    Matrix W_o;
    Matrix b_o;

    std::vector<LSTMTimeStepCache> sequence_cache;

    // Constructor to set sizes.
    LSTMSequence(int input_size, int hidden_size, int batch_size = 1)
        : hidden_size(hidden_size),
          input_size(input_size),
          batch_size(batch_size),
          C(hidden_size, batch_size),
          H(hidden_size, batch_size),
          W_f(hidden_size, hidden_size + input_size),
          b_f(hidden_size, 1),
          W_i(hidden_size, hidden_size + input_size),
          b_i(hidden_size, 1),
          W_c(hidden_size, hidden_size + input_size),
          b_c(hidden_size, 1),
          W_o(hidden_size, hidden_size + input_size),
          b_o(hidden_size, 1),
          forget_gate(hidden_size, batch_size),
          input_gate(hidden_size, batch_size),
          candidate(hidden_size, batch_size),
          output_gate(hidden_size, batch_size) {

        // If we start with zeros and we don't randomize the weights, then it will not learn anything from training.
        this->W_f.randomize();
        this->W_i.randomize();
        this->W_c.randomize();
        this->W_o.randomize();
    }

    std::vector<Matrix> forward(const std::vector<Matrix>& x_sequence) {
        this->H = Matrix(hidden_size, batch_size);
        this->C = Matrix(hidden_size, batch_size);
        sequence_cache.clear();

        std::vector<Matrix> H_sequence;

        // We are now accepting the whole input sequence, not just a single input at a time.
        for ( const auto& x_t : x_sequence ) {
            LSTMTimeStepCache step_cache(input_size, hidden_size, batch_size);

            step_cache.C_prev = this->C;

            // 1. Stack the hidden state and input [H, x]
            step_cache.stack_H_prev_x = this->H.concatenate(x_t); // (hidden_size + input_size, batch_size)

            // 2. Compute the forget gate.
            forget_gate = this->W_f.multiply(step_cache.stack_H_prev_x); // (hidden_size, batch_size)
            forget_gate.add(b_f); // (hidden_size, batch_size)
            forget_gate.applySigmoid(); // (hidden_size, batch_size)

            step_cache.F = forget_gate;

            // 3. Compute the input gate.
            input_gate = this->W_i.multiply(step_cache.stack_H_prev_x); // (hidden_size, batch_size)
            input_gate.add(b_i); // (hidden_size, batch_size)
            input_gate.applySigmoid(); // (hidden_size, batch_size)

            step_cache.I = input_gate;

            // 4. Calculate the candidate.
            candidate = this->W_c.multiply(step_cache.stack_H_prev_x); // (hidden_size, batch_size)
            candidate.add(b_c); // (hidden_size, batch_size)
            candidate.applyTanh(); // (hidden_size, batch_size)

            step_cache.Cn = candidate;

            // 5. Calculate the output gate.
            output_gate = this->W_o.multiply(step_cache.stack_H_prev_x); // (hidden_size, batch_size)
            output_gate.add(b_o); // (hidden_size, batch_size)
            output_gate.applySigmoid(); // (hidden_size, batch_size)

            step_cache.O = output_gate;

            // 6. Calculate the new cell state (long-term memory).
            this->C.elementMultiply(forget_gate); // (hidden_size, batch_size)
            Matrix temp_input_gate = this->input_gate;
            temp_input_gate.elementMultiply(candidate); // (hidden_size, batch_size)
            this->C.add(temp_input_gate); // (hidden_size, batch_size)

            step_cache.C = this->C;

            // 7. Calculate the hidden state (short-term memory).
            this->H = this->C; // (hidden_size, batch_size)
            this->H.applyTanh(); // (hidden_size, batch_size)
            this->H.elementMultiply(output_gate); // (hidden_size, batch_size)

            step_cache.H = this->H;

            sequence_cache.push_back(step_cache);
            H_sequence.push_back(this->H);
        }

        // Remember that H is not only passed to the next LSTM, it's also passed as an output for other architecture
        // example: Many-to-Many.
        return H_sequence;
    }

    LSTMGrads backward(const std::vector<Matrix>& dH_sequence) {

        // Initialize accumulated weight gradients with zeros
        LSTMGrads total_grads = {
            std::vector<Matrix>(dH_sequence.size(), Matrix(input_size, this->batch_size)),
            Matrix(W_f.rows, W_f.cols), Matrix(b_f.rows, b_f.cols),
            Matrix(W_i.rows, W_i.cols), Matrix(b_i.rows, b_i.cols),
            Matrix(W_c.rows, W_c.cols), Matrix(b_c.rows, b_c.cols),
            Matrix(W_o.rows, W_o.cols), Matrix(b_o.rows, b_o.cols)
        };

        Matrix dH_next(hidden_size, this->batch_size);
        Matrix dC_next(hidden_size, this->batch_size);

        // BPTT
        for ( int t = dH_sequence.size() - 1; t >= 0; --t ) {
            LSTMTimeStepCache& cache = this->sequence_cache[t];

            // Combine gradient from loss at step t and recurrent gradient from t+1
            Matrix dH_t = dH_sequence[t];
            dH_t.add(dH_next);

            // dHt_Ct = O_t \odot this->C.tanhDerivative().
            Matrix dHt_Ct = cache.C.tanhDerivative();
            dHt_Ct.elementMultiply(cache.O);

            // dL \odot dHt_Ct
            Matrix dCt = dH_t;
            dCt.elementMultiply(dHt_Ct);

            dCt.add(dC_next);

            // Forget Gate.

            // dCt \odot dCt_dFt
            Matrix dFt = dCt;
            dFt.elementMultiply(cache.C_prev);

            // F_t \odot (1 - F_t)
            Matrix dZ_f = dFt;
            dZ_f.elementMultiply(cache.F.sigmoidDerivative());

            // Cache [H_{t-1}, x].T
            Matrix stack_H_prev_x_T = cache.stack_H_prev_x.transpose();

            Matrix dL_dWf = dZ_f.multiply(stack_H_prev_x_T);
            Matrix db_f = dZ_f.sumColumns();

            // Input Gate.

            // dCt \odot dCt_dIt
            Matrix dIt = dCt;
            dIt.elementMultiply(cache.Cn);

            // I_t \odot (1 - I_t)
            Matrix dZ_i = dIt;
            dZ_i.elementMultiply(cache.I.sigmoidDerivative());

            Matrix dL_dWi = dZ_i.multiply(stack_H_prev_x_T);
            Matrix db_i = dZ_i.sumColumns();

            // Candidate.

            // dCt \odot dCt_dCn
            Matrix dCn = dCt;
            dCn.elementMultiply(cache.I);

            // dCn \odot cache.Cn.tanhDerivativeFromActivated()
            Matrix dZ_cn = dCn;
            dZ_cn.elementMultiply(cache.Cn.tanhDerivativeFromActivated());

            Matrix dL_dWcn = dZ_cn.multiply(stack_H_prev_x_T);
            Matrix db_cn = dZ_cn.sumColumns();

            // Output Gate.

            // dL \odot dHt_dOt
            Matrix dOt = cache.C;
            dOt.applyTanh();
            dOt.elementMultiply(dH_t);

            // dL \odot dHt_dOt
            Matrix dZ_o = cache.O.sigmoidDerivative();
            dZ_o.elementMultiply(dOt);

            Matrix dL_dWo = dZ_o.multiply(stack_H_prev_x_T);
            Matrix db_o = dZ_o.sumColumns();

            // Accumulate weight gradients across all timesteps
            total_grads.dW_f.add(dL_dWf);
            total_grads.db_f.add(db_f);

            total_grads.dW_i.add(dL_dWi);
            total_grads.db_i.add(db_i);

            total_grads.dW_c.add(dL_dWcn);
            total_grads.db_c.add(db_cn);

            total_grads.dW_o.add(dL_dWo);
            total_grads.db_o.add(db_o);

            // Pass the blame.

            dC_next = dCt;
            dC_next.elementMultiply(cache.F);

            Matrix err_forget_gate = this->W_f.transpose().multiply(dZ_f);
            Matrix err_input_gate = this->W_i.transpose().multiply(dZ_i);
            Matrix err_candidate = this->W_c.transpose().multiply(dZ_cn);
            Matrix err_output_gate = this->W_o.transpose().multiply(dZ_o);

            Matrix total_stacked_err = err_forget_gate;
            total_stacked_err.add(err_input_gate);
            total_stacked_err.add(err_candidate);
            total_stacked_err.add(err_output_gate);

            dH_next = total_stacked_err.sliceRows(0, this->hidden_size);

            Matrix dX_t = total_stacked_err.sliceRows(this->hidden_size, this->hidden_size + this->input_size);
            total_grads.dX_sequence[t] = dX_t;
        }

        return total_grads;
    }

    void updateWeights(const LSTMGrads& grads, double learning_rate) {
        W_f.subtractScaled(grads.dW_f, learning_rate);
        b_f.subtractScaled(grads.db_f, learning_rate);

        W_i.subtractScaled(grads.dW_i, learning_rate);
        b_i.subtractScaled(grads.db_i, learning_rate);

        W_c.subtractScaled(grads.dW_c, learning_rate);
        b_c.subtractScaled(grads.db_c, learning_rate);

        W_o.subtractScaled(grads.dW_o, learning_rate);
        b_o.subtractScaled(grads.db_o, learning_rate);
    }
};

class LSTMModel {
public:
    int input_size;
    int hidden_size;
    int output_size;
    int batch_size;

    LSTMSequence lstm;
    Matrix W_y;
    Matrix b_y;

    LSTMModel(int input_size, int hidden_size, int output_size, int batch_size = 1)
        : input_size(input_size),
          hidden_size(hidden_size),
          output_size(output_size),
          batch_size(batch_size),
          lstm(input_size, hidden_size, batch_size),
          W_y(output_size, hidden_size),
          b_y(output_size, 1) {

        W_y.randomize();
    }

    // Many-to-One Prediction: Returns a single prediction Matrix for the whole sequence
    Matrix predict(const std::vector<Matrix>& x_sequence) {
        std::vector<Matrix> H_sequence = lstm.forward(x_sequence);

        // Only use the final hidden state at the end of the sequence.
        const Matrix& H_final = H_sequence.back();

        Matrix pred = W_y.multiply(H_final);
        pred.add(b_y);
        pred.applySigmoid();

        return pred;
    }

    // Many-to-One Training: Accepts a sequence of inputs and a SINGLE target Matrix y_target
    void train(const std::vector<Matrix>& x_sequence,
               const Matrix& y_target,
               int epochs,
               double learning_rate) {

        for (int epoch = 0; epoch <= epochs; ++epoch) {

            // 1. Forward pass through LSTM across all time steps
            std::vector<Matrix> H_sequence = lstm.forward(x_sequence);
            const Matrix& H_final = H_sequence.back();

            // 2. Output layer forward pass ONLY on the final time step.
            Matrix pred = W_y.multiply(H_final);
            pred.add(b_y);
            pred.applySigmoid();

            // 3. Binary Cross-Entropy Loss on the final prediction.
            double loss = 0.0;

            for (size_t i = 0; i < pred.data.size(); ++i) {
                double y = y_target.data[i];
                double y_pred = pred.data[i];

                loss += -(y * std::log(y_pred + 1e-8) + (1.0 - y) * std::log(1.0 - y_pred + 1e-8));
            }

            loss /= pred.data.size();

            // 4. Output layer gradients.
            Matrix dZ_y = pred.subtract(y_target);
            Matrix dW_y = dZ_y.multiply(H_final.transpose());
            Matrix db_y = dZ_y.sumColumns();

            // 5. Build dH_sequence: Zeros for all steps except the final step (Many-to-One).
            std::vector<Matrix> dH_sequence(x_sequence.size(), Matrix(hidden_size, batch_size));
            dH_sequence.back() = W_y.transpose().multiply(dZ_y);

            // 6. Backward pass through LSTM (BPTT).
            LSTMGrads lstm_grads = lstm.backward(dH_sequence);

            // 7. Update weights and biases.
            lstm.updateWeights(lstm_grads, learning_rate);
            W_y.subtractScaled(dW_y, learning_rate);
            b_y.subtractScaled(db_y, learning_rate);

            if (epoch % 100 == 0) {
                std::cout << "Epoch " << epoch << " | Loss: " << loss << "\n";
            }
        }
    }
};

int main() {
    // Hyperparameters
    int input_size = 2;
    int hidden_size = 4;
    int output_size = 1;
    int batch_size = 2; // Training 2 sequences in parallel!

    LSTMModel model(input_size, hidden_size, output_size, batch_size);

    // Create a 3-step sequence (t = 0, t = 1, t = 2) for a batch of 2 examples:
    // - Batch Column 0: Starts with [1.0, 0.0] at t=0 -> Target label is 1.0
    // - Batch Column 1: Starts with [0.0, 1.0] at t=0 -> Target label is 0.0
    // Steps t=1 and t=2 are identical noise for both examples, forcing the LSTM
    // to rely on its Long-Term Cell State (C_t) from t=0 to solve the task!
    std::vector<Matrix> x_sequence(3, Matrix(input_size, batch_size));

    // Time step 0 (The decisive signal)
    x_sequence[0].set(0, 0, 1.0); x_sequence[0].set(0, 1, 0.0);
    x_sequence[0].set(1, 0, 0.0); x_sequence[0].set(1, 1, 1.0);

    // Time step 1 (Identical distraction/noise for both batch items)
    x_sequence[1].set(0, 0, 0.5); x_sequence[1].set(0, 1, 0.5);
    x_sequence[1].set(1, 0, 0.5); x_sequence[1].set(1, 1, 0.5);

    // Time step 2 (Identical distraction/noise for both batch items)
    x_sequence[2].set(0, 0, 0.2); x_sequence[2].set(0, 1, 0.2);
    x_sequence[2].set(1, 0, 0.8); x_sequence[2].set(1, 1, 0.8);

    // Target labels for the end of the sequence: [1.0, 0.0]
    Matrix y_target(output_size, batch_size);
    y_target.set(0, 0, 1.0); // Target for Batch Column 0
    y_target.set(0, 1, 0.0); // Target for Batch Column 1

    std::cout << "--- Training Many-to-One LSTM ---\n";
    model.train(x_sequence, y_target, 1000, 0.5);

    // Verify final predictions
    Matrix final_pred = model.predict(x_sequence);
    std::cout << "\n--- Final Predictions ---\n";
    std::cout << "Sample 0 (Target 1.0): " << final_pred.get(0, 0) << "\n";
    std::cout << "Sample 1 (Target 0.0): " << final_pred.get(0, 1) << "\n";

    return 0;
}

Closing

We’ve tackled a lot in this post! We even touch the surface of optimizing for our hardware. But please be aware that the C++ implementation above is not optimized. My intention this time is to have a solid foundation and intuition of how LSTM works. We’ll get to a point where we start to optimize models for faster inference (that’s my goal!).

I hope you enjoyed and learned as much as I did!