Skip to content
fn

margin_ranking_loss

→Tensor
margin_ranking_loss(input1: Tensor, input2: Tensor, target: Tensor, margin: float = 0.0, size_average: bool | None = None, reduce: bool | None = None, reduction: Reduction = 'mean')

Pairwise ranking hinge loss.

Trains a scoring function so that for each pair (x1,x2)(x_1, x_2) the signed score gap y (x1−x2)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

input1Tensor
Scores for the first item of each pair, any shape.
input2Tensor
Scores for the second item, same shape as input1.
targetTensor
Pairwise preference label ±1\pm 1: +1+1 if input1input1 should rank higher, −1-1 otherwise. The three tensors have one rank and broadcastable shapes; otherwise ValueError is raised.
marginfloat= 0.0
Required minimum score gap (default 0.0).
reductionstr= 'mean'
"mean" (default), "sum", or "none".
size_averagestr= 'mean'
"mean" (default), "sum", or "none".
reducestr= '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(x1−x2)≥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)

Used by 2