fn

margin_ranking_loss

Tensor
margin_ranking_loss(x1: Tensor, x2: Tensor, y: Tensor, margin: float = 0.0, reduction: str = 'mean')
source

Pairwise ranking hinge loss.

Trains a scoring function so that for each pair (x1,x2)(x_1, x_2) the signed score gap y(x1x2)y\,(x_1 - x_2) exceeds the margin. Used for learning-to-rank (search, recommendation), Bradley-Terry style preference modelling, and reward-model training for RLHF — wherever the supervision signal is a pairwise preference rather than a target value.

Parameters

x1Tensor
Scores for the first item of each pair, any shape.
x2Tensor
Scores for the second item, same shape as x1.
yTensor
Pairwise preference label ±1\pm 1: +1+1 if x1x_1 should rank higher, 1-1 otherwise.
marginfloat= 0.0
Required minimum score gap (default 0.0).
reductionstr= 'mean'
"mean" (default), "sum", or "none".

Returns

Tensor

Scalar or per-pair tensor.

Notes

Per-pair loss:

Li=max ⁣(0,  yi(x1(i)x2(i))+margin)L_i = \max\!\big(0,\; -y_i\,(x_1^{(i)} - x_2^{(i)}) + \text{margin}\big)

Pairs already satisfying the margin (y(x1x2)marginy(x_1 - x_2) \ge \text{margin}) contribute zero loss and zero gradient — the hinge structure naturally focuses learning on the violating pairs, akin to a pairwise SVM.

Examples

>>> import lucid
>>> from lucid.nn.functional import margin_ranking_loss
>>> s1 = lucid.tensor([2.0, 0.5])
>>> s2 = lucid.tensor([1.0, 1.0])
>>> y = lucid.tensor([1.0, 1.0])
>>> margin_ranking_loss(s1, s2, y, margin=1.0)
Tensor(0.75)