Efficient softmax approximation for GPUs

Edouard Grave, Armand Joulin, Moustapha Cissé, David Grangier, Hervé Jégou

Introduction

This paper considers strategies to learn parametric models for language modeling with very large vocabularies. This problem is key to natural language processing, with applications in machine translation (Schwenk et al., 2012; Sutskever et al., 2014; Vaswani et al., 2013) or automatic speech recognition (Graves et al., 2013; Hinton et al., 2012). In particular, Neural Network Language Models (NNLMs) have received a renewed interest in recent years, by achieving state of the art performance on standard benchmarks (Jozefowicz et al., 2016; Mikolov et al., 2010). These approaches are more computationally intensive but generalize better than traditional non-parametric models (Bahl et al., 1983; Kneser & Ney, 1995).

Statistical language models assign a probability to words given their history (Bahl et al., 1983). They are evaluated by objective criteria such as perplexity (ppl), which directly measures the ability of the system to determine proper probabilities for all the words. This potentially makes parametric models prohibitively slow to train on corpora with very large vocabulary. For instance, the vocabulary of the One Billion Word benchmark (Chelba et al., 2013) contains around 800800K words. In standard NNLMs, such as feedforward networks (Bengio et al., 2003a) or recurrent networks (Mikolov et al., 2010), computing this probability over the whole vocabulary is the bottleneck. Many solutions have been proposed to reduce the complexity of this expensive step (Bengio et al., 2003b; Goodman, 2001a; Gutmann & Hyvärinen, 2010). We distinguish (i) the methods that consider the original distribution and aim at providing approximations of the probabilities, or of a subset of them (Bengio et al., 2003b; Ji et al., 2015), from (ii) the approaches that compute exact probabilities for an approximate model yielding a lower computational time, such as the popular hierarchical softmax (Goodman, 2001a; Mnih & Hinton, 2009; Morin & Bengio, 2005).

Our approach, called adaptive softmax, belongs to the second category. More specifically, it is inspired by the hierarchical softmax and its subsequent variants. In contrast to previous works and motivated by the trend that GPUs are comparatively more and more performant than CPUs, our design is oriented towards efficient processing on GPUs. In this context, our paper makes the following points:

We define a strategy to produce an approximate hierarchical model. It departs from previous ones in that it explicitly takes into account the computation time of matrix-matrix multiplications on modern architectures, which is not trivially linear in the dimensions of the matrices.

We conduct an empirical analysis of this model on recent GPUs. This leads us to define a realistic computation time model that is incorporated in the proposed optimization;

Our approach provides a significant acceleration factor compared to the regular softmax, i.e., 2×2\times to 10×10\times speed-ups. Equivalently we improve the accuracy under computational constraints. Importantly, on the largest corpus, this higher efficiency empirically comes at no cost in accuracy for a given amount of training data, in contrast to concurrent approaches improving the efficiency.

This paper is organized as follows. Section 2 briefly reviews the related work and Section 3 provides some background on the language modeling task that we consider. Section 4 describes our proposal, which is subsequently evaluated in Section 5 on typical benchmarks of the language modeling literature, including Text8, Europarl and One Billion Word datasets.

Related work

Many methods have been proposed to approximate the softmax efficiently (Bengio et al., 2003b; Goodman, 2001a; Gutmann & Hyvärinen, 2010; Morin & Bengio, 2005). We briefly describe the most popular ones below and point the reader to Chen et al. (2015) for a comparative study. For the sake of completeness, we refer the reader to other strategies that can speed-up the training of language models in complementary manners (Mikolov et al., 2011b).

The Hierarchical Softmax (HSM) is an approximation of the softmax function introduced by Goodman (2001a). This approach is generally used with a two-level tree (Goodman, 2001a; Mikolov et al., 2011c) but has also been extended to deeper hierarchies (Morin & Bengio, 2005; Mnih & Hinton, 2009). In general, the hierarchy structure is built on word similarities (Brown et al., 1992; Le et al., 2011; Mikolov et al., 2013) or frequency binning (Mikolov et al., 2011c). In particular, Mikolov et al. (2013) proposes an optimal hierarchy by constructing a Huffman coding based on frequency. However this coding scheme does not take into account the theoretical complexity reduction offered by matrix-matrix multiplication and distributed computation, in particular with modern GPUs.

Similar to our work, Zweig & Makarychev (2013) constructs their hierarchy in order to explicitly reduce the computational complexity. They also solve the assignment problem with dynamic programming. However, they only consider hierarchies where words are kept in the leaves of the tree, leading to a significant drop of performance (reported to be around 5−10%5-10\%), forcing them to also optimize for word similarity. In our case, allowing classes to be stored in the internal node of the tree leads to almost no drop of performance. Also, they assume a linear computational time for the vector-matrix operation which significantly limits the use of their approach on distributed system such as GPU.

The idea of keeping a short-list of the most frequent words has been explored before (Le et al., 2011; Schwenk, 2007). In particular, Le et al. (2011) combines a short-list with a hierachical softmax based on word representation. In contrast, the word hierarchy that we introduce in Section 4 explicitly aims at reducing the complexity.

Our work also shares similarities with the d-softmax introduced by Chen et al. (2015). They assign capacity to words according to their frequency to speed up the training. Less frequent words have smaller classifiers than frequent ones. Unlike our method, their formulation requires accessing the whole vocabulary to evaluate the probability of a word.

Sampling based approximation.

Sampling based approaches have been successfully applied to approximate the softmax function over large dictionaries in different domains, such as language modeling (Jozefowicz et al., 2016), machine translation (Jean et al., 2015) and computer vision (Joulin et al., 2015). In particular, importance sampling (Bengio & Senécal, 2008; Bengio et al., 2003b) selects a subset of negative targets to approximate the softmax normalization. Different schemes have been proposed for sampling, such as the unigram and bigram distribution (Bengio et al., 2003b) or more recently, a power-raised distribution of the unigram (Ji et al., 2015; Mikolov et al., 2013). While this approach often leads to significant speed-up at train time, it still requires to evaluate the full softmax at test time.

Self-normalized approaches.

Self-normalized approaches aim at learning naturally normalized classifier, to avoid computing the softmax normalization. Popular methods are Noise Contrastive Estimation (Gutmann & Hyvärinen, 2010; Mnih & Teh, 2012; Vaswani et al., 2013) or a penalization on the normalization function (Andreas & Klein, 2014; Devlin et al., 2014). Noise Contrastive Estimation (Gutmann & Hyvärinen, 2010) replaces the softmax by a binary classifier distinguishing the original distribution form a noisy one. While the original formulation still requires to compute the softmax normalization, Mnih & Teh (2012) shows that good performance can be achieved even without it.

Finally, Vincent et al. (2015) have also proposed an efficient way to train model with high dimensional output space. Their approach is exact and leads to a promising speed-up but it cannot be directly applied to the softmax function, limiting its potential application to language modeling.

Preliminaries on language modeling

The goal of language modeling is to learn a probability distribution over a sequence of words from a given dictionary V\mathcal{V}. The joint distribution is defined as a product of conditional distribution of tokens given their past (Bahl et al., 1983). More precisely, the probability of a sequence of TT words w1,…,wT∈VTw_{1},\dots,w_{T}\in\mathcal{V}^{T} is given as

This problem is traditionally addressed with non-parameteric models based on counting statistics (Goodman, 2001b). In particular, smoothed N-gram models (Bahl et al., 1983; Katz, 1987; Kneser & Ney, 1995) achieve good performance in practice (Mikolov et al., 2011a), especially when they are associated with cache models (Kuhn & De Mori, 1990). More recently, parametric models based on neural networks have gained popularity for language modeling (Bengio et al., 2003a; Jozefowicz et al., 2016; Mikolov et al., 2010). They are mostly either feedforward networks (Bengio et al., 2003a) or recurrent networks (Mikolov et al., 2010).

In a standard feedforward network for language modeling, we fix a window of length NN and predict the next words according to the words appearing in this window. In the simplest case, this probability is represented by a 2-layer neural network acting on an input xt∈VNx_{t}\in\mathcal{V}^{N}, defined as the concatenation of the one-hot representation of the NN previous words, wt−N+1,…,wtw_{t-N+1},\dots,w_{t}. The state hth_{t} of the hidden layer and subsequently the vector of scores yty_{t} associated with the next token wt+1w_{t+1} are computed as

where σ\sigma is a non linearity, e.g., the pointwise sigmoid function σ(z)=1/(1+exp⁡(−z))\sigma(z)=1/(1+\exp(-z)), and ff is the softmax function discussed in section 3.3. This model is parameterized by the weight matrices PP, AA and BB and is routinely learned with an optimization scheme such as stochastic gradient descent or Adagrad (Duchi et al., 2011).

2 Recurrent network.

A Recurrent network (Elman, 1990) extends a feedforward network in that the current state of the hidden layer also depends on its previous state. The hidden state hth_{t} is updated according to the equation

where RR is a weight matrix and xtx_{t} is the one-hot representation of the current word wtw_{t}. Computing the exact gradient for this model is challenging but it is possible to compute an efficient and stable approximation of it, using a truncated back-propagation through time (Werbos, 1990; Williams & Peng, 1990) and norm clipping (Mikolov et al., 2010).

Since the model introduced by Elman (1990), many extensions have been proposed, such as Longer Short Term Memory (LSTM) (Hochreiter & Schmidhuber, 1997), Gated recurrent units (Chung et al., 2014) or structurally constrained network (Mikolov et al., 2014). These models have been successfully used in the context of language modeling (Jozefowicz et al., 2016; Mikolov et al., 2010; Mikolov & Zweig, 2012). In this work, we focus on the standard word level LSTM architecture since it has obtained state of the art performance on the challenging One Billion Word Benchmark (Jozefowicz et al., 2016).

3 Class-based hierarchical softmax.

In neural language modeling, predicting the probability of the next word requires computing scores for every word in the vocabulary and to normalize them to form a probability distribution. This is typically achieved by applying a softmax function to the unnormalized score zwz_{w} associated with each word ww, where the softmax function is defined as

For a vocabulary comprising k=∣V∣k=|\mathcal{V}| words, this function requires O(k)\mathcal{O}(k) operations once the scores are computed. In the case of neural networks, the overall complexity is O(dk)\mathcal{O}(dk), where dd is the size of the last hidden layer. When the vocabulary is large, this step is computationally expensive and often dominates the computation of the whole model (Jozefowicz et al., 2016; Mikolov et al., 2014), as discussed in introduction and related work. A simple approach (Goodman, 2001a) to reduce this computational cost is to assign each word ww of the vocabulary to a unique class C(w)\mathcal{C}(w) and to factorize the probability distribution over words as

where p1p_{1} and p2p_{2} are obtained using the softmax function (Eq. 4). If each class contains k\sqrt{k} words, the computational cost is reduced from O(dk)\mathcal{O}(dk) to O(dk)\mathcal{O}(d\sqrt{k}).

Our approach: the adaptive softmax

In this section, we propose the adaptive softmax, a simple speedup technique for the computation of probability distributions over words. The adaptive softmax is inspired by the class-based hierarchical softmax, where the word classes are built to minimize the computation time. Our method is designed to be efficient for GPUs, which are commonly used to train neural networks. For the sake of clarity, we first present the intuition behind our method in the simple case where we simply split our dictionary in two distinct clusters, before analyzing a more general case.

The bottleneck of the model described in the previous section is the matrix multiplication between the matrix representing the hidden states (of size B×dB\times d, where BB denotes the batch size), and the matrix of word representations, of size d×kd\times k. For a fixed size dd of the hidden layer, we denote by g(k,B)g(k,B) the computation time of this multiplication (using an efficient implementation such as cuBLAS), and simplify the notation wherever some parameters are fixed. Figure 1 reports empirical timings as a function of kk for typical parameters of BB and dd for two GPU models, namely K40 and M40. We observe that the computation time g(k)g(k) is constant for low values of kk, until a certain inflection point k0≈50k_{0}\approx 50, and then becomes affine for values k>k0k>k_{0}. This suggests a computational model of the form

While this is a very crude model of computation, it allows to explain empirical observations well.

2 Intuition: the two-clusters case

In natural languages, the distribution of the words notoriously follows a Zipf law (Zipf, 1949). Most of the probability mass is covered by a small fraction of the dictionary, e.g., 87%87\% of the document is covered by only 20%20\% of the vocabulary in the Penn TreeBank. Similar to the frequency binning hierarchical softmax (Mikolov et al., 2011c), this information can be exploited to reduce the computation time.

We observe empirically that putting all the clusters in the leaves of the tree leads to a significant drop of performance (around 5−10%5-10\% performance drop, Mikolov et al., 2011c; Zweig & Makarychev, 2013). The reason is that the probability of every word ww belonging to a cluster cc is multiplied by the probability of its class, i.e., it is equal to P(c ∣ h)P(w ∣ c, h)P(c~{}|~{}h)P(w~{}|~{}c,~{}h), while attaching a frequent word directly to the root associates it directly to the probability P(w ∣ h)P(w~{}|~{}h) making its inference sharper. For this reason, unless there is a significant difference in computation time, we favor using a short-list, over the standard 2-level hierarchical softmax.

Minimizing the computation time.

Adapting the classifier capacity for each cluster.

3 General case

We add the constraint kB≥k0B0kB\geq k_{0}B_{0} to ensure that there is no penalty induced by the constant part of the computational model of Equation 7, the previous equation simplifies as

Let us discuss this equation, by first considering that the cardinalities of the sub-vocabularies are fixed. The right-most term is the only one that depends on the word probabilities. For two distinct clusters Vi\mathcal{V}_{i} and Vj\mathcal{V}_{j}, we can re-write pjkjp_{j}k_{j} as (pi+j−pi)kj(p_{i+j}-p_{i})k_{j}, where pi+j=pi+pjp_{i+j}=p_{i}+p_{j}, so that

Without loss of generality, we assume that ki>kjk_{i}>k_{j}. The quantities pi+jp_{i+j}, kik_{i} and kjk_{j} being fixed, the second term of the right-hand side of this equation is constant, and the best strategy is trivially to minimize the probability of the largest cluster Vi\mathcal{V}_{i}. In other terms, an optimal solution for Equation 10 requires that the most frequent words are assigned to the smallest cluster. This remark is true for any tuple (i,j)(i,j), and we easily see that this point also holds for the head cluster. As a consequence, for a fixed number of clusters of given sizes, the best strategy is to assign the words by decreasing probabilities to clusters of increasing size. Note, this analysis remains valid as long as the gg is monotonically increasing in kk.

We now assume that the number of clusters is fixed. Following our analysis above, the optimization solely depends on the cardinalities kik_{i} for all clusters, which perfectly determines how to split the list of words ordered by frequency. We solve this problem by dynamic programming.

Finding the number of clusters.

The only remaining free variable in our optimization is JJ, since the other parameters are then determined by the aforementioned optimizations. We plot in Figure 4 the optimal computation time, as a function of the number of clusters JJ, according to our model. We observe that a small number of clusters, between 1010 and 1515 gives the best computation time. Moreover, we observe that using more than 5 clusters does not lead to significant gains in computational time (a couple of milliseconds at best). In practice, we thus decide to use a small number of clusters (between 2 and 5), as it usually lead to slightly better perplexity, and we empirically determine the best speed/perplexity compromise on training data. As shown later by our experiments, using a small number of clusters allows to obtain comparable perplexity as the exact softmax on large corpora.

Experiments

This section provides a set of experiments aiming at analyzing the trade-off between actual computation time and effectiveness of several strategies, in particular the approach presented in the previous section. First we describe our evaluation protocol, then we evaluate some of the properties of our model and finally we compare it on standard benchmark against standard baselines.

We evaluate our method on standard datasets, and use the perplexity (ppl) as an evaluation metric, as the function of the training time or of the number of training data (epochs). The datasets have varying vocabulary sizes, in different languages, which allows us to better understand the strengths and weaknesses of the different approaches.

Text8http://mattmahoney.net/dc/textdata is a standard compression dataset containing a pre-processed version of the first 100100 million characters from Wikipedia in English. It has been recently used for language modeling (Mikolov et al., 2014) and has a vocabulary of 4444k words.

Europarlhttp://www.statmt.org/europarl/ is a machine translation corpus, containing 20 languages (Koehn, 2005). For most languages, there are 10M–60M tokens and the vocabulary is in between 44k and 250k words.

One Billion Word https://code.google.com/archive/p/1-billion-word-language-modeling-benchmark/ is a massive corpus introduced by Chelba et al. (2013). It contains 0.80.8B tokens and a vocabulary comprising almost 800k words.

Implementation details.

We use an LSTM with one layer in all our experiments. On Text8 and Europarl, the models have d=512d=512 hidden units and are regularized with weight decay (λ=10−6\lambda=10^{-6}). On the One Billion Word benchmark, we use d=2048d=2048 hidden units and no regularization. The dimension of the input word embeddings is set to 256256, so that large models fit in GPU memory. For the backpropagation through time, we unroll the models for 20 steps. We use Adagrad (Duchi et al., 2011), with a step size of 0.1 and 5 epochs, and we clip the norm of the gradients to 1. The batch size BB is set to 128, except on the Finnish portion of Europarl where BB=64 due to memory constraints. All the experiments were run on the same GPU with the Maxwell architecture.

Baselines.

Our method is compared to: (1) the full softmax, (2) the hierarchical softmax with frequency binning (HSM freq) and similarity-based binning (HSM sim), (3) importance sampling (Bengio et al., 2003b; Bengio & Senécal, 2008) and (4) the differentiated softmax (Chen et al., 2015). For HSM, we tried different strategies for the binning. We observe that using the square root function on the count before computing the word bins is the most efficient for frequency binning. For the similarity-based binning, we used the Brown clustering algorithm (Brown et al., 1992) to determine the word classes. For the negative sampling method, we used a number of samples equal to 20%20\% of the size of the vocabulary (Chen et al., 2015). For the differentiated softmax (D-softmax), we used the same partitions for the vocabulary as for our approach. We tried two version of the differentiated softmax. The first is the one described by Chen et al. (2015), where each word cluster uses a disjoint subset of the hidden representation. We also present an improved version, referred to as D-softmax [*], which uses our choice to have the whole hidden representation mapped to the different word clusters using projection matrices of different sizes.

Comparison with the state of the art.

Table 1 reports the results that we achieve on Text8. On this small vocabulary, approximate methods are comparatively less interesting. Our approach is the only one to approach the result of the full soft-max (below by 3 points of perplexity), while being the fastest. Our improved variant D-softmax [*] of the work by Chen et al. (2015) obtains similar results but is slower by a factor ×1.8\times 1.8.

On Europarl, we first present the convergence properties of our approach compared to other approximate strategies in Figure 5 show the perplexity (ppl) as a function of training time. Our approach significantly outperforms all competitors by a large margin. For reference, we also show the performance (D-softmax [*]) obtained by improving the D-softmax, to make it more comparable to our method. Our method is 2×2\times to 3×3\times faster than this improved competitor, which demonstrates how critical is our optimization strategy. Similar conclusions are drawn from Table 3 for other languages from the Europal corpus.

Table 2 gives the test perplexity on One Billion Word benchmark: Our method achieves a perplexity of 43.943.9 after five epochs, taking less than three days to train on a single GPU. In comparison, only Jozefowicz et al. (2016) achieves a lower perplexity, but with a model 8×8\times bigger than ours and trained over 3232 GPUs during 33 weeks. We also note that for models of similar size, we achieve similar perplexity than the method introduced by Jozefowicz et al. (2016). As far as we know, ours the first method to achieve a perplexity lower than 50 on a single GPU.

Conclusion

In this paper, we have proposed a simple yet efficient approximation of the softmax classifier. To our knowledge, it is the first speed optimizing approximation that obtains performance on par with the exact model. This is achieved by explicitly taking into account the computation time of matrix-multiplication on parallel systems and combining it with a few important observations, namely keeping a short-list of frequent words in the root node (Schwenk, 2007) and reducing the capacity of rare words (Chen et al., 2015). In all our experiments on GPU, our method consistently maintains a low perplexity while enjoying a speed-up going from 2×2\times to 10×10\times compared to the exact model. This type of speed-up allows to deal with extremely large corpora in reasonable time and without the need of a large number of GPUs. We believe our approach to be general enough to be applied to other parallel computing architectures and other losses, as well as to other domains where the distributions of the class are unbalanced.

The authors would like to thank Jeff Johnson for his help with GPU benchmarking as well as Tomas Mikolov, Rob Fergus and Jeff Johnson for insightful discussions.

References