Differentiable Ranks and Sorting using Optimal Transport
Marco Cuturi, Olivier Teboul, Jean-Philippe Vert
Introduction
On (not) learning with sorting and ranking. Operators and play an important role across statistics and machine learning. For instance, is the main workhorse behind order statistics , but also appears prominently in -NN rules, in which is applied on a vector of distances to select the closest neighbors to a query point. Ranking is also used to assess the performance of an algorithm: either at test time, such as and top- classification accuracies and NDCG metrics when learning-to-rank , or at train time, by selecting pairs and triplets of points of interest. The sorting operator is of no less importance, and can be used to handle outliers in robust statistics, as in trimmed and least-quantile regression or median-of-means estimators . Yet, and although examples of using and abound in ML, neither nor are actively used in end-to-end learning approaches: while is not differentiable everywhere, is outright pathological, since it is piecewise constant and has therefore a Jacobian that is almost everywhere zero.
Outline. We recall first the link between the and operators and OT between 1D measures, to define then generalized Kantorovich rank and sort operators in §2. We turn them into differentiable operators using entropic regularization, and discuss in §3 the several parameters that can shape this smoothness. Using these smooth operators, we propose in §4 alternatives to cross-entropy and least-quantile losses to learn classifiers and regression functions.
Ranking and Sorting as an Optimal Transport Problem
The fact that solving the OT problem between two discrete univariate measures boils down to sorting is well known [33, §2]. The usual narrative states that the Wasserstein distance between two univariate measures reduces to comparing their quantile functions, which can be obtained by inverting CDFs, which are themselves computed by considering the sorted values of the supports of these measures. This downstream connection from OT to quantiles, CDFs and finally sorting has been exploited in several works, notably because the price for sorting is far cheaper than the order one has to pay to solve generic OT problems. This is evidenced by the recent surge in interest for sliced Wasserstein distances . We propose in this section to go instead upstream, that is to redefine ranking and sorting functions as byproducts of the resolution of an optimal assignment problem between measures supported on the reals. We then propose in Def.1 generalized rank and sort operators using the Kantorovich formulation of OT.
We make in what follows the additional assumption that is convex. A fundamental result [33, Theorem 2.9] states that in that case (see also for the more involved case where is concave) can be computed in closed form using the quantile functions of :
Therefore, to compute OT between and , one only needs to integrate the difference in their quantile functions, which can be done by inverting the empirical distribution functions for , which itself only requires sorting the entries in and to obtain their sorting permutations and . Additionally, Eq. (2) allows us not only to recover the value of as defined in Eq. (1), but it can also be used to recover the corresponding optimal solution in operations, using the permutations and to build a so-called north-west corner solution [28, §3.4.2]:
Let and be sorting permutations for and . Define to be the north-west corner solution using permuted weights . Then is optimal for (1).
Such a permuted north-western corner solution is illustrated in Figure 1(b). It is indeed easy to check that in that case runs from the top-left (north-west) to the bottom right corner. In the simple case where and , the solution is a permutation matrix divided by , namely a matrix equal to everywhere except for its entries indexed by which are all equal to . That solution is a vertex of the Birkhoff polytope, namely, an optimal assignment which to the -th value in associates the -th value in ; informally, this solution assigns the -th smallest entry in to the -th smallest entry in .
Generalizing sorting, CDFs and quantiles using optimal transport. From now on in this paper, we make the crucial assumption that is already sorted, that is, . is therefore the identity permutation. When in addition , the -th value in is simply assigned to the -th value in . Conversely, and as illustrated in Figure 1(a), the rank value in is assigned to the -th value . Because of this, and can be rewritten using the optimal assignment matrix :
These identities stem from the fact that is a permutation matrix, which can be applied to the vector to recover the rank of each entry in , or transposed and applied to to recover the sorted values of . The former expression can be equivalently interpreted as times the CDF of evaluated elementwise to , the latter as the quantiles of at levels . The identities in Prop. 2 are valid when the input measures are uniform and of the same size. The first contribution of this paper is to consider more general scenarios, in which , the size of , can be smaller than , and where weights need not be uniform. This is a major departure from previous references , which all require pairwise comparisons between the entries in . We show in our applications that can be as small as 3 when trying to recover a quantile, as in Figs. 1, 3.
The K-ranking operator computes convex combinations of rank values (as described in the entries ) while the K-sorting operator computes convex combinations of values contained in directly. Note that we consider here convex combinations (weighted averages) of these ranks/values, according to the Euclidean geometry. Extending more generally these combinations to Fréchet means using alternative geometries (KL, hyperbolic, etc) on these ranks/values is left for future work. Because these quantities are only defined pointwisely (we output vectors and not functions) and depend on the ordering of , we drop our reference to measure in notations.
The K-rank vector map outputs a vector of size containing a continuous rank for each entry for (these entries can be alternatively interpreted as times a “synthetic” CDF value in $\overline{\mathbf{b}}_{j}y_{j}x_{i}\widetilde{S}m\mathbf{x}\xi\upsilonx_{i}y_{j}$, and then use the monotonicity given by the third identity of Prop. 2.
Computations and Non-differentiability The generalized ranking and sorting operators presented in Def. 1 are interesting in their own right, but have very little practical appeal. For one, their computation relies on solving an OT problem at a cost of and remains therefore far more costly than regular sorting, even when is very small. Furthermore, these operators remain fundamentally not differentiable. This can be hinted by the simple fact that it is difficult to guarantee in general that a solution to (1) is unique. Most importantly, the Jacobian is, very much like , null almost everywhere. This can be visualized by looking at Figure 1(b) to notice that an infinitesimal change in would not change (notice however that an infinitesimal change in weights would; that Jacobian would involve North-west corner type mass transfers). All of these pathologies — computational cost, non-uniqueness of optimal solution and non-differentiability — can be avoided by using regularized OT .
The Sinkhorn Ranking and Sorting Operators
Both K-rank and K-sort operators are expressed using the optimal solution to the linear program in (1). However, is not differentiable w.r.t inputs nor parameters [2, §5]. We propose instead to rely on a differentiable variant of the OT problem that uses entropic regularization , as detailed in [28, §4]. This differentiability is reflected in the fact that the optimal regularized transport plan is a dense matrix (yielding more arrows in Fig. 1(c)), which ensures differentiability everywhere w.r.t. both and .
Consider first a regularization strength to define the solution to the regularized OT problem:
Given a regularization strength , run Alg.1 to define
Sensitivity to . Parameter plays the same role as other temperature parameters in previously proposed smoothed sorting operators : the smaller is, the closer the Sinkhorn operator’s output is to the original vectors of ranks and sorted values; The bigger , the closer to matrix , and therefore all entries of collapse to the average of , while all entries of collapse to the weigted average (using ) of , as illustrated in Fig. 2. Although choosing a small value for might seem natural, in the sense that approximate more faithfully , one should not forget that this would result in recovering the deficiencies of in terms of differentiability. When learning with such operators, it may therefore be desirable to use a value for that is large enough to ensure has non-null entries. We usually set or when lie in as in Fig. 2. We have kept fixed throughout Alg. 1, but we do notice some speedups using scheduling as advocated by .
Numerical Stability. When using small regularization strengths, we recommend to cast Sinkhorn iterations in the log-domain by considering the following stabilized iterations for each pair of vectors , resulting in the following updates (with and initialized to and ),
where is the soft-minimum operator applied linewise to a matrix to output a vector, namely for , and is such that . The rationale behind the substractions/additions of and above is that once a Sinkhorn iteration is carried out, the terms inside the parenthesis above are normalized, in the sense that once divided by , their exponentials sum to one (they can be used to recover a coupling). Therefore, they must be negative, which improves the stability of summing exponentials [28, §4.4].
The choices that we have made are summarized in Alg. 2, but we believe there are opportunities to perfect them depending on the task.
Learning with Smoothed Ranks and Sorts
We propose a differentiable variant of the 0/1 and more generally top losses that bypasses combinatorial consideration nor builds upon non-differentiable surrogates . Ignoring the degenerate case in which is not unique, given a query , stating that the the label has been selected is equivalent to stating that the entry indexed at of the vector of ranks is . Given a labelled pair , the 0/1 loss of the classifier for that pair is therefore,
where is the heaviside function: if and for . More generally, if for some labelled input , the entry is bigger than , then that labelled example has a top- error of . Conversely, if is smaller than , then the top- error is . The top- error can be therefore formulated as in (6), where the argument within the Heaviside function is replaced by .
We propose the simple family of ReLU losses , and have focused our experiments on the case . We train a vanilla CNN (4 Conv2D with 2 max-pooling layers, ReLU activation, 2 fully connected layers, batchnorm on each) and a Resnet18 on CIFAR-10 and CIFAR-100. Fig. 4 and 5 report test-set classification accuracies / epochs. We used , , a squared distance cost and a stepsize of with the ADAM optimizer.
Learning CNNs by sorting handwritten numbers. We use the MNIST experiment setup in , in which a CNN is given numbers between between 0 and 9999 given as 4 concatenated MNIST images. The labels are the ranks (within pairs) of each of these numbers. We use the code kindly made available by the authors. We use epochs, and confirm experimentally that S-sort performs on par with their neural-sort function. We set .
For each quantile/dataset pair, we report the original (not-regularized) quantile of the errors evaluated on the entire training set, on an entire held-out test set, and the MSE on the test set of the function that is recovered. We notice that our algorithm reaches overall better quantile errors on the training set—this is our main goal—but comparable test/MSE errors.
Conclusion. We have proposed in this paper differentiable proxies to the ranking and sorting operations. These proxies build upon the existing connection between sorting and the computation of OT in 1D. By generalizing sorting using OT, and then introducing a regularized form that can be solved using Sinkhorn iterations, we recover the simple benefit that all of its steps can be easily automatically differentiated. We have shown that, with a focus on numerical stability, one can use there operators in various settings, including smooth extensions of test-time metrics that rely on sort, and which can be now used as training losses. For instance, we have used the Sinkhorn sort operator to provide a smooth approximation of quantiles to solve least-quantile regression problems, and the Sinkhorn rank operator to formulate an alternative to the cross-entropy that can mimic the loss in multiclass classification. This smooth approximation to the rank, and the resulting gradient flow that we obtain is strongly reminiscent of rank based dynamics, in which players in a given game produce an effort (a gradient) that is a direct function of their rank (or standing) within the game, as introduced by . Our use of the Sinkhorn algorithm can therefore be interpreted as a smooth mechanism to enact such dynamics. Several open questions remain: although the choice of a cost function , target vector and squashing function (used to form vector in Alg. 1, using Eq. 4) have in principle no influence on the vector of Sinkhorn ranks or sorted values in the limit when goes to (they all converge to and ), these choices strongly shape the differentiability of and when . Our empirical findings suggest that whitening and squashing all entries within $\varepsilon$ at each iteration.