A Matryoshka model is trained so that the first coordinates of its embedding are themselves a good embedding for several . The recipe is simple: compute the contrastive loss at every nested size and sum. Implement it in PyTorch.
truncate_normalize(E, k)
k columns of E (shape (B, d)), L2-normalized along dim 1 with F.normalize.infonce_loss(Q, P, tau=0.05)
Qn @ Pn.T / tau on normalized rows, targets arange(B), F.cross_entropy.mrl_loss(Q, P, dims, tau=0.05)
k in dims of infonce_loss(truncate_normalize(Q, k), truncate_normalize(P, k), tau). dims are increasing and the last one may equal d.mrl_gradient_profile(Q, P, dims, tau=0.05)
Q with requires_grad=True, compute mrl_loss, backpropagate, and return the L2 norm of the gradient restricted to each block of coordinates [0:dims[0]], [dims[0]:dims[1]], ..., [dims[-2]:dims[-1]], as a list of floats rounded to 4 decimals. Coordinates beyond dims[-1] are ignored.F.normalize(E[:, :k], dim=1) handles the truncation and the re-normalization.torch.autograd.grad or .backward() on a cloned leaf keeps the original tensor untouched.