// Score a preferred/rejected response pair against a reference policy. Return the DPO loss and gradient to the policy log-ratio. use graph_io; pub fn fd_preference_dpo(rows: i64, width: i64) { println!("module {"); fd_line(" func.func @main(%policy_win: tensor, %policy_lose: tensor, %ref_win: tensor, %ref_lose: tensor, %beta: tensor) -> (tensor, tensor) {", rows, width); fd_line(" %v0 = stablehlo.constant dense<0.00000000000000000e+00> : tensor", rows, width); fd_line(" %v1 = stablehlo.subtract %policy_win, %policy_lose : tensor", rows, width); fd_line(" %v2 = stablehlo.subtract %ref_win, %ref_lose : tensor", rows, width); fd_line(" %v3 = stablehlo.subtract %v1, %v2 : tensor", rows, width); fd_line(" %v4 = stablehlo.multiply %beta, %v3 : tensor", rows, width); // margin = beta*((policy_win-policy_lose)-(ref_win-ref_lose)) fd_line(" %v5 = stablehlo.negate %v4 : tensor", rows, width); fd_line(" %v6 = stablehlo.maximum %v5, %v0 : tensor", rows, width); fd_line(" %v7 = stablehlo.abs %v4 : tensor", rows, width); fd_line(" %v8 = stablehlo.negate %v7 : tensor", rows, width); fd_line(" %v9 = stablehlo.exponential %v8 : tensor", rows, width); fd_line(" %v10 = stablehlo.log_plus_one %v9 : tensor", rows, width); fd_line(" %v11 = stablehlo.add %v6, %v10 : tensor", rows, width); // loss = maximum(-margin,0)+log1p(exp(-abs(margin))) fd_line(" %v12 = stablehlo.negate %beta : tensor", rows, width); fd_line(" %v13 = stablehlo.logistic %v5 : tensor", rows, width); fd_line(" %v14 = stablehlo.multiply %v12, %v13 : tensor", rows, width); // grad = -beta*sig(-margin) fd_line(" return %v11, %v14 : tensor, tensor", rows, width); println!(" }"); println!("}"); }