iTranslated by AI
Intuition behind the Johnson–Lindenstrauss Lemma: A Key Lemma for LLM Performance, with Mathematical Insights into Attention
Introduction
This is an article for Day 17 of the AI Voice Creation Technology Research Group Advent Calendar 2024.
(Apologies that this theme is unrelated to speech synthesis...)
One of my favorite YouTubers is "3Blue1BrownJapan," and in one of their videos, they mentioned an interesting lemma, so I would like to write about it this time.
The relevant video is "But what is a GPT? Visual intro to Transformers | Chapter 5, Deep Learning."
In the latter half of this video, they touch upon a lemma called the "Johnson–Lindenstrauss lemma" and perform an interesting experiment with it.
In this post, I would like to provide a brief explanation of the "Johnson–Lindenstrauss lemma" and share my own thoughts on how it relates to current LLMs.
References
About the Johnson–Lindenstrauss lemma
Books:
Hands-On Unsupervised Learning Using Python: How to Build Applied Machine Learning Solutions from Unlabeled Data
(The Johnson–Lindenstrauss lemma isn't explained extensively, but I thought its mention in the book was valuable. There is a brief explanation of how to implement it.)
Videos:
"But what is a GPT? Visual intro to Transformers | Chapter 5, Deep Learning"
Web pages:
Johnson–Lindenstrauss lemma: Wikipedia
johnson-lindenstrauss lemma preserves angles: mathoverflow
About Theorems and Lemmas
Books:
How to Read Mathematical Books (数学書の読みかた)
About Attention
Books:
Introduction to Large Language Models (大規模言語モデル入門)
What are Lemmas and Theorems?
First, you might wonder: what exactly is a lemma (Lemma)?
A lemma represents a mathematical proposition.
A proposition refers to a claim whose truth or falsehood can be logically determined.
In other words, from this perspective alone, a lemma and a theorem (Theorem) are the same.
However, there are differences in the roles and purposes of lemmas and theorems.
A lemma is primarily an auxiliary proposition used to help prove other propositions.
In other words, when a lemma appears, it means it will be used to derive an important theorem later on.
On the other hand, a theorem is a central proposition in mathematical research or applications, possessing significant importance or generality. Theorems hold higher importance in theory and application compared to lemmas.
Since this article deals with the "Johnson–Lindenstrauss lemma," it falls into the category of a lemma.
Written this way, it might seem like a proposition of low importance, but that is not the case.
Some propositions proven as lemmas were later discovered to be extremely important, and such lemmas are often referred to by specific names.
The "Johnson–Lindenstrauss lemma" is one such extremely important proposition that, despite being a lemma, rivals theorems in both mathematical and practical significance.
Johnson–Lindenstrauss lemma
First, I will provide the definition as it appears on Wikipedia.
In short, the Johnson–Lindenstrauss lemma is a mathematical theorem that guarantees that a set of points in a high-dimensional space can be embedded into a lower-dimensional space while almost preserving the distances between them.
Let's examine the formula.
Therefore,
The expression above indicates that the relative error of the squared distance between two points before and after dimensionality reduction by the mapping
What does "distance not changing" mean?
The idea that the distance between two points doesn't change is counter-intuitive. For example, I previously wrote an article about Principal Component Analysis (PCA).

As shown in the figure in that article (though it's a 2D diagram here), when reducing dimensions, the distance between points usually becomes shorter. This "shortening of distance between points" means that information is being lost.
It is intuitive that reducing dimensions leads to a loss of information.
However, the Johnson–Lindenstrauss lemma states that in a high-dimensional space, even if dimensions are reduced, the distance between two points is preserved within a relative error of
This is why the Johnson–Lindenstrauss lemma is counter-intuitive and interesting.
If distance doesn't change, it means classification and learning are possible
The fact that distance is preserved means that the difficulty of distinguishing between points of different classes does not change significantly before and after dimensionality reduction.
For example, consider a machine learning model like SVM (Support Vector Machine). SVM performs classification by drawing a separating hyperplane that maximizes the margin between classes.
The Johnson–Lindenstrauss lemma shows that the distance between any two points is relatively preserved before and after dimensionality reduction. Therefore, when considering SVM, it can be said that the difficulty of drawing a separating hyperplane that maximizes the margin between classes does not change much before and after dimensionality reduction.
Distance not changing = Angle not changing
Johnson–Lindenstrauss lemma shows that in a high-dimensional space, there exists a mapping
The fact that the distance between any two points is preserved implies that when you pick any three points, the lengths of the three sides of the triangle formed by those three points remain almost unchanged before and after dimensionality reduction.
According to the law of cosines, "the lengths of the three sides remaining almost the same" indicates that the interior angles of the triangle formed by those three points do not change before and after dimensionality reduction.
Details can be found below:
In short, the Johnson–Lindenstrauss lemma shows that in a high-dimensional space, there exists a mapping
Angle not changing = Basis vectors are preserved
The Johnson–Lindenstrauss lemma shows that in a high-dimensional space, there exists a mapping
This implies that the basis vectors in the high-dimensional space should also be preserved (within the relative error
Specifically, for 10 million-dimensional basis vectors, if we limit them to length 1, there should be 10 million vectors. These basis vectors should be orthogonal to each other.
The Johnson–Lindenstrauss lemma demonstrates that even if we reduce the dimensions to a lower-dimensional space (e.g., 100,000 dimensions) using an appropriate mapping
Experiment
Now, let's conduct an experiment. This experiment is similar to the one performed in the video I referenced.
(I am using the code and concepts presented in the video.)
Please refer to the video for more details.
In the video, 10,000 random 100-dimensional vectors are prepared to show that the angles between these vectors mostly fall within the range of 89 to 91 degrees.
Actual code
You can find the actual code below (please try running it if you are interested).
The code itself is based on the snippets shown in the video. Additionally, I have modified it to use Google Colab's GPU for acceleration.
The execution results below can be obtained by running the above code to completion.
Execution results
First, the histogram below shows the angles between pairs from 10,000 randomly created 100-dimensional vectors before optimization. (The number of pairs is 99,990,000.)

If all 10,000 vectors were orthogonal in the 100-dimensional space, we could say that the structure of the 10,000-dimensional basis vectors was preserved even after reducing the dimensionality to 100.
The histogram after performing 250 optimization iterations is shown below:

As seen above, almost all vector pairs fall within the range of 89 to 91 degrees. The specific breakdown is as follows:
Total data count: 99,990,000
Number of data points in the range of 89 to 91 degrees: 98,294,342
Percentage: 98.30%
Therefore, for more than 98% of all pairs, the angle formed by the vectors is within the range of 89 to 91 degrees.
From the above, it can be seen that the structure of the 10,000-dimensional basis vectors is preserved in the 100-dimensional space.
Importance of the angles being quasi-orthogonal
In the discussion so far, it has been established that in the Johnson–Lindenstrauss lemma, high-dimensional basis vectors maintain their structure in a quasi-orthogonal form even after dimensionality reduction.
What does it mean for angles to be orthogonal?
Let's consider a 2D plane.

The horizontal axis represents gender, where going to the right indicates male and left indicates female.
The vertical axis represents age, where up indicates adult and down indicates child.
When words like (man, woman, boy, girl) are embedded in such a plane, the result is expected to look like the following image.

In other words, when words are represented as vectors, the axes of that plane represent the meanings that constitute the words (i.e., gender and age).
Furthermore, if we add a third axis orthogonal to these two axes representing the "degree of family," we can also represent words such as "father" and "mother."
In this way, when representing words as vectors, they can be expressed as a single point in a vector space that can express as many meanings as the total number of dimensions.
This is possible because all axes (basis vectors) are orthogonal to each other.
If we consider a vector that is not orthogonal to any of the basis vectors, that vector can be expressed as a linear combination of the basis vectors (linearly dependent), meaning it cannot possess concepts beyond the meanings already held by the basis vectors.
What it means for the structure to be preserved with quasi-orthogonal basis vectors
NNs perform inner product calculations between data and parameters
Now, let's consider why it is beneficial for these basis vectors to maintain their structure in a quasi-orthogonal manner.
For instance, a fully connected layer involves linear operations like the following:
Here,
Also, ignoring bias, we consider
Focusing on the
We can see that this is expressed by an inner product.
The above was considered for a fully connected layer (the linear transformation part), but the same applies to convolutions in a CNN.
Convolution can be expressed by the following equation:
For simplicity, assuming a single channel:
-
is the value at positionZ_{i,j} of the output feature map (before activation function input)(i,j) -
is the value at positionX_{i,j} of the input feature map (size(i,j) )H \times W -
is the value at positionW_{i,j} of the convolution kernel (size(i,j) )M \times N
Although the 2D representation makes it less obvious, the above expression is also an inner product of
(Note: In this article, "inner product" refers to the Euclidean inner product (the general dot product learned in high school).)
Inner Product Determines Similarity
The inner product is expressed in the following form, where
The inner product discussed in the previous section is mainly in the form
And if it is an inner product, the form
What is important here is
Specifically, the inner product has the following properties:
- When two vectors point in the same direction (
), the inner product takes its maximum value\theta = 0^\circ .\|\mathbf{a}\| \|\mathbf{b}\| - In this case, the two vectors are conceptually close.
- When two vectors point in opposite directions (
), the inner product takes its minimum value\theta = 180^\circ .-\|\mathbf{a}\| \|\mathbf{b}\| - In this case, the two vectors are conceptually opposites.
- When two vectors are orthogonal (
), the inner product is 0.\theta = 90^\circ - In this case, the two vectors are completely unrelated, regardless of the concept.
As a result, the inner product can be seen as an indicator whose value changes depending on whether the directions of the two vectors are similar.
Therefore, whether the directions of two vectors are similar can be determined by the value of
Strictly speaking, the inner product also includes the magnitude (norm) of the vectors, so a large inner product doesn't necessarily mean two vectors are similar, but a similar interpretation can be made broadly.
Revisiting: Quasi-orthogonality = Gaining Expressive Power Beyond Dimensions
Now, let's return to the Johnson–Lindenstrauss lemma.
The Johnson–Lindenstrauss lemma claims that when dimensionality reduction is performed using an appropriate mapping
In the "Experiment" in the previous section, it was shown that in a 100-dimensional vector space, 98.3% of the pairs among 10,000 vectors were quasi-orthogonal.
If the quasi-orthogonal angle is
(This is because
In other words, for quasi-orthogonal vectors, the result of calculating their inner product is expected to be a value close to 0, since the product of the norms is multiplied by a value of around 0.01.
To summarize the discussion:
In a 100-dimensional vector space, most of the 10,000 vectors can be said to be quasi-orthogonal to each other.
When they are quasi-orthogonal, the result of the inner product is close to 0, which means that approximately 10,000 independent representations can be embedded within the 100-dimensional space.
This provides an intuitive explanation for how more than 100 semantic concepts can be given to a 100-dimensional space, by showing that additional quasi-orthogonal vectors can be prepared for all axes of the space.
What about LLMs?
Having explained the Johnson–Lindenstrauss lemma and the importance of preserving quasi-orthogonal angles in CNNs and fully connected layers (which perform inner product calculations), let's look at how this applies to LLMs.
LLMs utilize a structure called the Transformer.
Broadly speaking, a Transformer consists of Self-Attention and fully connected layers. Since fully connected layers were discussed above, I will focus on explaining Self-Attention here.
What is Self-Attention?
Presenting the Formula
Self-Attention is expressed as follows:
For
If we let
then,
the following relationships hold:
Here,
Explanation of Each Part
Since
In that case, I will explain the following Self-Attention in this order:
-
calculates the inner product (similarity) of the input tokensQK^\top -
is a parameter that standardizes the result after the inner product calculation of\sqrt{m} -dimensional tokensm - Normalization by
\text{softmax} - Performing matrix multiplication between the similarity map and
. This corresponds to a global convolution.V
Calculating the Similarity Map
First, let's consider:
calculates the inner product (similarity) of the input tokens QK^\top
Since
Therefore,
In other words,
This shows that the inner product between the
As mentioned before, the inner product represents similarity.
As follows, for the two vectors
- When pointing in the same direction (
), the inner product takes the maximum value\theta = 0^\circ .\|q_{i}\| \|k_{j}\| - When pointing in opposite directions (
), the inner product takes the minimum value\theta = 180^\circ .-\|q_{i}\| \|k_{j}\| - When orthogonal (
), the inner product is 0.\theta = 90^\circ
Therefore,
Standardization
Next, let's consider
The reason for this division is the same as standardization. Let's explain below.
For example, when considering
Next, when calculating the inner product, we take the sum over
When taking the sum of
Therefore,
Because of this,
It can be seen that this has the effect of scaling the values down to the product of the variances of each feature. Conversely, if this scaling is not performed, the variance increases by a factor of the dimensionality
In the calculation of Attention, if this scaling is not done, the large number of terms being added during the inner product calculation when the dimensionality is high will cause the values to become very large, making the Softmax calculation unstable.
By dividing by
Normalization by Softmax
Next, let's consider
Here, we ultimately want to create a similarity map.
In
Softmax transforms elements in the row or column direction such that all elements are 0 or greater and their sum is 1. In other words, values can be evaluated as probabilities.
Since
Therefore, focusing on a specific row, it converts the values into a probability representation while maintaining the magnitude relationship of the inner products.
Focusing on a certain row
Where,
In short,
Global Convolution between the Similarity Map and V
Finally,
We consider the above formula.
Here, we calculate the matrix product of the similarity map created so far and the values
Let me explain in detail.
First, the final equation can be written as:
Where,
Focusing on row
Here,
In other words, focusing on a specific token
For example, if a specific token
By repeating this, Transformers can process sentences as each token gradually embeds the concepts of the entire sentence into its vector.
LLMs and the Johnson–Lindenstrauss Lemma
By now, through the explanation of the Johnson–Lindenstrauss lemma and the fact that CNNs and fully connected layers perform inner product calculations, I hope you have understood the importance of angles being preserved in a quasi-orthogonal manner.
Considering the above, while it is still a hypothesis, it suggests that in LLMs, entirely unrelated concepts can be processed in a quasi-orthogonal form, potentially exceeding the actual number of dimensions the LLM possesses.
If You Want to Know More
The behavior of neural networks in relation to the Johnson–Lindenstrauss lemma is already being researched.
For example, the article above mentions:
This study hypothesizes that the cause of polysemy lies in "feature superposition." In other words, because language models try to learn as many features as possible within a limited number of dimensions, individual neurons end up taking on multiple meanings. In fact, visualizing the internal representations of language models confirms that a single axis direction can hold multiple meanings.
This "single axis direction holding multiple meanings" is exactly what suggests that neural networks represent more features than their dimensions by utilizing quasi-orthogonality.
For more details, please visit the following page:
This is the project page for the paper "Toy Models of Superposition." This paper mentions that the sparsity of features in neural networks is what enables superposition without performance degradation, and they demonstrate this through experiments.
If you are interested, please take a look.
Summary
Thank you for reading this far. Although I am still a student of these topics, I have outputted my current understanding before I forget it.
I hope this helps in your understanding.
Discussion