// Compute smoothed soft Dice loss over a row and its probability-space gradient. Use targets and predictions in [0,1]. use graph_io; pub fn fd_dice_fit(rows: i64, width: i64) { println!("module {"); fd_line(" func.func @main(%prediction: tensor, %target: tensor) -> (tensor, tensor) {", rows, width); fd_line(" %v0 = stablehlo.constant dense<0.00000000000000000e+00> : tensor", rows, width); fd_line(" %v1 = stablehlo.constant dense<2.00000000000000000e+00> : tensor", rows, width); fd_line(" %v2 = stablehlo.multiply %prediction, %target : tensor", rows, width); println!(" %v3 = stablehlo.constant dense<0.00000000000000000e+00> : tensor"); fd_line(" %v4 = stablehlo.reduce(%v2 init: %v3) applies stablehlo.add across dimensions = [1] : (tensor, tensor) -> tensor", rows, width); fd_line(" %v5 = stablehlo.broadcast_in_dim %v4, dims = [0] : (tensor) -> tensor", rows, width); fd_line(" %v6 = stablehlo.multiply %v1, %v5 : tensor", rows, width); fd_line(" %v7 = stablehlo.constant dense<1.00000000000000000e+00> : tensor", rows, width); fd_line(" %v8 = stablehlo.add %v6, %v7 : tensor", rows, width); // top = 2*rsum(prediction*target)+1 fd_line(" %v9 = stablehlo.add %prediction, %target : tensor", rows, width); fd_line(" %v10 = stablehlo.reduce(%v9 init: %v3) applies stablehlo.add across dimensions = [1] : (tensor, tensor) -> tensor", rows, width); fd_line(" %v11 = stablehlo.broadcast_in_dim %v10, dims = [0] : (tensor) -> tensor", rows, width); fd_line(" %v12 = stablehlo.add %v11, %v7 : tensor", rows, width); // bottom = rsum(prediction+target)+1 fd_line(" %v13 = stablehlo.divide %v8, %v12 : tensor", rows, width); fd_line(" %v14 = stablehlo.subtract %v7, %v13 : tensor", rows, width); // loss = 1-top/bottom fd_line(" %v15 = stablehlo.multiply %v1, %target : tensor", rows, width); fd_line(" %v16 = stablehlo.multiply %v15, %v12 : tensor", rows, width); fd_line(" %v17 = stablehlo.subtract %v8, %v16 : tensor", rows, width); fd_line(" %v18 = stablehlo.multiply %v12, %v12 : tensor", rows, width); fd_line(" %v19 = stablehlo.divide %v17, %v18 : tensor", rows, width); // grad = (top-2*target*bottom)/(bottom*bottom) fd_line(" return %v14, %v19 : tensor, tensor", rows, width); println!(" }"); println!("}"); }