Stable softmax for sparse matrices
\newcommand{\lgc}[1]{{\color{my-light-green} #1}}\newcommand{\gc}[1]{{\color{my-green} #1}}\newcommand{\lrc}[1]{{\color{my-light-red} #1}}\newcommand{\rc}[1]{{\color{my-red} #1}}\newcommand{\lbc}[1]{{\color{my-light-blue} #1}}\newcommand{\bc}[1]{{\color{my-blue} #1}}\newcommand{\kc}[1]{{\color{my-gray} #1}}\newcommand{\loc}[1]{{\color{my-light-orange} #1}}\newcommand{\oc}[1]{{\color{my-orange} #1}}\newcommand{\a}[0]{\mathbf a}\newcommand{\A}[0]{\mathbf A}\newcommand{\b}[0]{\mathbf b}\newcommand{\B}[0]{\mathbf B}\newcommand{\c}[0]{\mathbf c}\newcommand{\C}[0]{\mathbf C}\newcommand{\d}[0]{\mathbf d}\newcommand{\D}[0]{\mathbf D}\newcommand{\E}[0]{\mathbf E}\newcommand{\I}[0]{\mathbf I}\newcommand{\L}[0]{\mathbf L}\newcommand{\m}[0]{\mathbf m}\newcommand{\M}[0]{\mathbf M}\newcommand{\r}[0]{\mathbf r}\newcommand{\s}[0]{\mathbf s}\newcommand{\t}[0]{\mathbf t}\newcommand{\S}[0]{\mathbf S}\newcommand{\x}[0]{\mathbf x}\newcommand{\z}[0]{\mathbf z}\newcommand{\v}[0]{\mathbf v}\newcommand{\y}[0]{\mathbf y}\newcommand{\k}[0]{\mathbf k}\newcommand{\bp}[0]{\mathbf p}\newcommand{\P}[0]{\mathbf P}\newcommand{\q}[0]{\mathbf q}\newcommand{\Q}[0]{\mathbf Q}\newcommand{\r}[0]{\mathbf r}\newcommand{\R}[0]{\mathbf R}\newcommand{\Sig}[0]{\mathbf \Sigma}\newcommand{\t}[0]{\mathbf t}\newcommand{\T}[0]{\mathbf T}\newcommand{\e}[0]{\mathbf e}\newcommand{\X}[0]{\mathbf X}\newcommand{\u}[0]{\mathbf u}\newcommand{\U}[0]{\mathbf U}\newcommand{\v}[0]{\mathbf v}\newcommand{\V}[0]{\mathbf V}\newcommand{\w}[0]{\mathbf w}\newcommand{\W}[0]{\mathbf W}\newcommand{\Y}[0]{\mathbf Y}\newcommand{\z}[0]{\mathbf z}\newcommand{\Z}[0]{\mathbf Z}\newcommand{\p}[0]{\,\text{.}}\newcommand{\tab}[0]{\hspace{0.7cm}}\newcommand{\sp}[0]{^{\small\prime}}\newcommand{\mR}[0]{{\mathbb R}}\newcommand{\mC}[0]{{\mathbb C}}\newcommand{\mN}[0]{{\mathbb N}}\newcommand{\mZ}[0]{{\mathbb Z}}\newcommand{\deg}[0]{{^\circ}}
- 7 July 2019
- code on github
I this post, I'll introduce a trick for computing the row-wise softmax over sparse matrices. I expect this could be useful in building self-attention models with sparse attention, like a sparse transformer, or a graph attention network.
Sparsity is an important topic in machine learning. When we build a model, the simplest approach is usually to make no assumptions about its internal structure, and to connect every possible input to every possible output, perhaps with some intermediate representations. This is, for instance, how we ended up with the fully connected network (or multilayer perceptron) as one of the first neural network architectures.
When that fails to work, a good way to add some domain knowledge to the network is to remove some of these connections. For instance, in image analysis, we know that when we build up low-level representations, we can just look at local information in the input, so instead of connecting everything with everything, we take a local neighborhood of pixels, and connect it to one hidden unit in the next layer.
In a phrase, we add sparsity to strengthen the inductive bias.
Now, more than 20 years since the first convnet, we are in the age self-attention: we represent units (words, pixels, graph nodes) with a vector instead of a single value, and we let some function determine how much attention should pay to when building up its new representation vector for the next layer. Again, potentially everything connected with everything, although the weights are now derived through attention rather than learned.
So when the self-attention models fail to work, or fail to scale, we ask the same question. Can we add some sparsity to the model, based on what we know of the domain, to strengthen the inductive bias. Some recent examples are the sparse transformer by Child et al. from OpenAI labs, and the graph attention network, by Veličković et al. In both models, self-attention is used, but only particular units are allowed to attend to one another. Under graph attention, the input graph controls the allowed connections, and in the sparse transformer, a domain-specific connectivity pattern is introduced.
The problem
To build a sparse self attention, and to do so efficiently, we want to store the attention weights in a sparse matrix . It’s no use building a sparse model if we have to store a dense matrix full of zeros to store all the attention weights from inputs to outputs.
The trouble with storing this matrix sparsely is that we need to compute a row-wise softmax. The weights in each row need to sum to one, so that the new representation for a particular unit becomes a weighted mean of all previous representations.
All this brings us to the topic of this post: How do we compute a row-wise softmax on a sparse matrix efficiently and stably. Efficient, in this context, means using the basic primitives available for sparse matrices, so that we can rely on existing optimizations for sparse matrix multiplication. Stable means that we can compute the softmax accurately for a wide range of values, without rounding errors exploding into infinity, zero or NaN.
Currently, the standard approach in GATs is to rely on dense matrices, which makes the memory requirements quadratic in the number of nodes in the input. The sparse transformer uses custom CUDA kernels, that seem to rely on the attention matrix being block-sparse rather than fully sparse.
We’ll look at three approaches towards implementing a fully sparse softmax using only basic matrix primitives which we’ll call the naive, the -norm and the iterative approach. As far as I know the latter two are original methods, but I’m happy to be corrected if somebody’s already though of this in some other context.
notation and terminology
A sparse matrix is a matrix for which most elements have the same value (usually ), so that it becomes more efficient to store only the elements that deviate from this value. We will call these the explicit elements, and the rest the implicit elements.
A sparse matrix witk explicit elements is defined by three components: a integer matrix containing the indices of the explicit elements. A length real valued vector containing the values of the explicit elements, and an integer pair determining the size of the matrix. We will omit the size, to clarify our notation.
We’ll use to refer to a sparse matrix as a function of its component parts.
1. The naive approach
The row-wise softmax for matrix is defined as
That is, we exp all the values in the matrix, perform a row-wise sum, and then divide element-wise by the resulting vector (broadcasting along the rows).
Note that we want the result of this operation, , to be sparse with implicit zero elements. To achieve this, the input should not have implicit zero elements, but implicit elements.
A row-wise sum is easy enough to implement using matrix multiplication, all you need is:
where is a length vector filled with ones. This gives us the following straightforward algorithm: (\begin{aligned} & {\bf E} \leftarrow \text{exp}({\bf A}) \\ & {\bf s} \leftarrow {\bf E} \cdot \bf{1}^m \\ & \bar {\bf A} \leftarrow \frac{{\bf E}}{{\bf s} \cdot {{\bf 1}^n} ^T}\\ \end{aligned}) Where the division in the last line is element-wise.
To see how this algorithm fares, we generate random sparse matrices of size , with 6000 explicit elements drawn from a normal distribution for increasing . We softmax the matrix by the algorithm above and plot the proportion, out of 40 repeats, of results containing at least one NaN.
If you’ve ever implemented softmax, this result should come as no surprise. The problem comes from the exponentiation: after this, the values in the matrix have such wildly different scales that, unless they fit a very narrow range, it’s likely that either some will overflow to positive infinity (ultimately leading to NaN) or, if they’re all negative, the whole sum will underflow to zero (leading to NaN again in the division).
There is a standard solution, closely related to the famous logsumexp trick. We simply subtract a large value from all elements in row of .
Working out of the exp, we see that we get a multiplier on both sides of the divisor, so the formulation is equivalent:
The trick is to choose large enough that any values that would normally overflow, can now be computed. Any values that are much smaller than this will underflow to zero, but they would not have contributed to the sum anyway. The only danger is that we choose so big that _all_ values underflow, and we end up dividing by zero. The foolproof solution is take the maximum of the values over which we're softmaxing:
But that’s also where the problem arises for our use case. For this to work, we need to compute the row-wise maximum of . This is a tricky operation. To work out the row-wise maxima of , we need to group by their rows, and then compute the maxima over each group. Since each group will have a different size, this is tough to parallelize. Can we simplify this using the basic primitives available for sparse matrices?
How do we efficiently compute the row-wise maximum of a sparse matrix, when all we can do is matrix multiply, and element-wise operations?
2. The -norm approach
We will start by using the following identity:
That is, the -norm of approaches the maximum element of , as goes to infinity. To see why, consider what happens to the values of under application of a convex function:
The is increased, proportionally, by more than . In the limit, the contribution of any element other than the maximum disappears from the sum, and all we are doing is exponentiating by and then reversing that exponentiation.
Of course, we can’t exponentiate by infinity to compute the max, but maybe a large value is already enough to give us a reasonable . After all, we don’t need the exact maximum, we just need a close enough value to prevent overflows.
This gives us the following algorithm (with larger than 1 but not too large): (\begin{aligned} &{\bf b} \leftarrow \text{pow}({\bf A}, \rc{p}) \cdot {\bf 1}^m \\ &{\bf b} \leftarrow \text{pow}({\bf b}, 1/\rc{p}) \\ & {\bf \bc{E}} \leftarrow \text{exp}({\bf A} - {\bf b}) \\ & {\bf \gc{s}} \leftarrow {\bf \bc{E}} \cdot \bf{1}^m \\ & \bar {\bf A} \leftarrow \frac{{\bf \bc{E}}}{{\bf \gc{s}} \cdot {{\bf 1}^n} ^T} \\ \end{aligned})
Let’s see how this method does.
Error bars in line plots indicate standard deviation over 40 repeats. The second plot shows the deviation from summing to 1 (maximum over all rows in the matrix).
As we can see, we have avoided the problem of the NaNs. Even for matrices with pretty large random values, we get no NaNs. Unfortunately, the second row in the plot shows that the method fails a second basic test: the rows in the result should sum to one (this is the whole point of the softmax operation). When we compute the row sums of the result, and check how far they deviate from 1, we see that the -norm method begins to fail much earlier than the naive approach. Changing the value of the exponent has little effect.
The problem is that the -norm approximation tends to overestimate the max. In the limit, the non-max terms don’t contribute to the sum anymore, but before we reach the limit, they still contribute, giving us only an upper bound for the max. And if we use a value larger than the max for our , we end up pushing all values towards zero. The problem is not severe enough to cause NaNs, but the rounding errors ultimately make the result less useful than the naive approach.
3. The iterative approach
In short, it turns out we do need quite a precise approximation for the maximum if we want to compute the row-wise softmax with a greater degree of accuracy and stability.
Let be a vector containing only nonnegative values. Consider the following iteration:
Under this iteration, is always a probability vector (its elements sum to one). This ensures that so long as the iteration itself is stable, the vector itself should never blow up. Moreover, it turns out that this iteration converges to the one-hot vector for the the maximum element of the original . To see why, consider what happens after two iterations:
That is, after iterations, we have computed with .
As goes to infinity, this converges to a one-hot vector for the maximum of the initial (scroll down for a proof).
This approach works with any exponent . The bigger the value, the fewer iterations we need to converge, but the more likely we are to overflow in a single iteration.
If we compute this one-hot vector, multiply it by the original values of and sum, we get the maximum of .
To use this method for a row-wise softmax, we need to make all values positive first. We have two options.
- Take the softplus() over all all values.
- Subtract the minimum of the whole matrix from all values.
Both of these options are standard dense-matrix operations that we can apply directly to the elements of . The first option seems to work best in our experiments.
This brings us to the following algorithm to compute a row-wise max for a sparse matrix.
The function works in the same way as pytorch's index_select(). It selects the elements of vector by the indices in integer vector , resulting in a vector with the same length as , containing elements of , possibly multiple times.
After computing the maxima, the softmax can be computed in the same manner as in the -norm approach.
Note that the matrix must be coalesced for this method to work. It is common to allow indices to be present multiple times, adding up the corresponding values. In this case, the maximum of a row may be split among multiple values in the value vector, which causes the method to fail.
We can now show all approaches together. We’ll add 2 additional metrics:
- The RMSE of the non-zero values compared to computation of the softmax on a dense version of the matrix.
- The mean absolute error of just the estimated row-wise max (only for the -norm and iterative approaches).
We run the iterative approach for 20 iterations, with exponents 2 and 1.1.
The iterative approach seems to do the trick. It avoids NaNs, and the rows sum to one for greater variances than either the naive or the -norm approaches. We can expect reasonable stability up to a variance of 40. Even better stability may be possible by reducing further, and increasing the number of iterations, but if gets too close to 1, stability will suffer again.
Conclusion
Is this useful? Iterative approaches are expensive in deep learning systems (every iteration is stored in the computation graph), and there are other approaches that may work, depending on the situation: for shallow models, careful initialization may be enough for the naive approach to work, and batch normalization in between layers can probably ameliorate the problem as well.
There may even be a way to compute the row-wise max more directly (perhaps with a custom CUDA kernel). Nevertheless, this approach uses only existing API calls, which means it can be implemented in a decoupled way (for instance, the implementation is the same for GPU and CPU computation).
Whether this allows us to build deeper GATs and sparse transformers, and whether these allow for better performance than was previously possible is left to be seen. I may investigate in a future blog post.
Finally, we should note that most of these issues arise from the default use of the softmax function to parametrize a categorical distribution. Other approaches exist that may be just as practical and much more stable. Simply taking the absolute values of the inputs and normalizing may work just as well. The softmax approach seems to be inspired by statistical mechanics with little requirement for numerical precision. This is very similar to the sigmoid activation, which was ultimately replaced by the more linear ReLU, at least for internal activations. Perhaps a similar approach is called for when it comes to the softmax activation.
Appendix: proof of convergence
Lemma. Let . Assume that has maximal elements; that is, there are elements such that . Then
Proof. Let . Then
Let . Then