Compute the KTO loss for unpaired feedback

MediumAlignmentPro

Why it matters KTO lets teams align on production thumbs-up and thumbs-down logs without paired data.

KTO learns from single thumbs-up or thumbs-down examples instead of pairs.

Write kto_loss(pi_logp, ref_logp, desirable, z_ref, beta=0.1, lam_d=1.0, lam_u=1.0). r = pi_logp - ref_logp. For desirable examples v = lam_d * sigmoid(beta * (r - z_ref)); for undesirable v = lam_u * sigmoid(beta * (z_ref - r)). Loss per example is lam - v with lam = lam_d or lam_u. Return the mean.

Signaturedef kto_loss(pi_logp, ref_logp, desirable, z_ref, beta=0.1, lam_d=1.0, lam_u=1.0)

Example

with r = 0 and z_ref = 0, every example has v = 0.5 * lam, so with default weights the loss is 0.5.

Understand the idea

KTO trains from single examples marked good or bad, without needing pairs. For each example, r = pi_logp - ref_logp says how much more likely the policy makes it than the reference. Good examples are rewarded for pushing r above a reference point z_ref, bad examples for pushing it below. A sigmoid turns that gap into a value v between 0 and 1, and the loss is lam - v. Worked example: beta 0.1, z_ref 0, default weights. A desirable example with r = 10: v = sigmoid(0.1 * 10) = sigmoid(1) = 0.731, loss 0.269. An undesirable example with r = 10: v = sigmoid(0.1 * (0 - 10)) = sigmoid(-1) = 0.269, loss 0.731, a large loss because the model made a bad answer more likely. Mean = 0.5. Rule: r = pi_logp - ref_logp; desirable: v = lam_d * sigmoid(beta (r - z_ref)), loss = lam_d - v; undesirable: v = lam_u * sigmoid(beta (z_ref - r)), loss = lam_u - v; return the mean. The direction flips for bad examples. Used in: aligning models from thumbs up and thumbs down feedback.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplekto_loss([0, 0], [0, 0], [True, False], 0.0)
  • Sample 2: mixedkto_loss([-1, -2, -0.5], [-1.5, -1.0, -0.5], [True, False, True], 0.2, 0.5)