// Compute the clipped PPO surrogate and clipping fraction using sampled-token log probabilities. Supply a fixed positive clip radius in each row. use graph_io; pub fn fd_policy_ratio(rows: i64, width: i64) { println!("module {"); fd_line(" func.func @main(%new_logp: tensor, %old_logp: tensor, %advantage: tensor, %radius: tensor) -> (tensor, tensor) {", rows, width); fd_line(" %v0 = stablehlo.constant dense<0.00000000000000000e+00> : tensor", rows, width); fd_line(" %v1 = stablehlo.subtract %new_logp, %old_logp : tensor", rows, width); fd_line(" %v2 = stablehlo.exponential %v1 : tensor", rows, width); // ratio = exp(new_logp-old_logp) fd_line(" %v3 = stablehlo.constant dense<1.00000000000000000e+00> : tensor", rows, width); fd_line(" %v4 = stablehlo.subtract %v3, %radius : tensor", rows, width); fd_line(" %v5 = stablehlo.add %v3, %radius : tensor", rows, width); fd_line(" %v6 = stablehlo.maximum %v2, %v4 : tensor", rows, width); fd_line(" %v7 = stablehlo.minimum %v6, %v5 : tensor", rows, width); // limited = clip(ratio,1-radius,1+radius) fd_line(" %v8 = stablehlo.multiply %v2, %advantage : tensor", rows, width); fd_line(" %v9 = stablehlo.multiply %v7, %advantage : tensor", rows, width); fd_line(" %v10 = stablehlo.minimum %v8, %v9 : tensor", rows, width); println!(" %v11 = stablehlo.constant dense<0.00000000000000000e+00> : tensor"); fd_line(" %v12 = stablehlo.reduce(%v10 init: %v11) applies stablehlo.add across dimensions = [1] : (tensor, tensor) -> tensor", rows, width); fd_line(" %v13 = stablehlo.broadcast_in_dim %v12, dims = [0] : (tensor) -> tensor", rows, width); fd_line(" %v14 = stablehlo.constant dense : tensor", rows, width); fd_line(" %v15 = stablehlo.divide %v13, %v14 : tensor", rows, width); fd_line(" %v16 = stablehlo.negate %v15 : tensor", rows, width); // loss = -mean(minimum(ratio*advantage,limited*advantage)) fd_line(" %v17 = stablehlo.subtract %v2, %v3 : tensor", rows, width); fd_line(" %v18 = stablehlo.abs %v17 : tensor", rows, width); fd_line(" %v19 = stablehlo.compare GT, %v18, %radius, FLOAT : (tensor, tensor) -> tensor", rows, width); fd_line(" %v20 = stablehlo.select %v19, %v3, %v0 : tensor, tensor", rows, width); fd_line(" %v21 = stablehlo.reduce(%v20 init: %v11) applies stablehlo.add across dimensions = [1] : (tensor, tensor) -> tensor", rows, width); fd_line(" %v22 = stablehlo.broadcast_in_dim %v21, dims = [0] : (tensor) -> tensor", rows, width); fd_line(" %v23 = stablehlo.divide %v22, %v14 : tensor", rows, width); // fraction = mean(choose(abs(ratio-1)>radius,1,0)) fd_line(" return %v16, %v23 : tensor, tensor", rows, width); println!(" }"); println!("}"); }