// Train an embedding direction against a target row. A squared-norm epsilon stabilizes empty signal. use graph_io; pub fn fd_cosine_fit(rows: i64, width: i64) { println!("module {"); fd_line(" func.func @main(%x: tensor, %target: tensor) -> (tensor, tensor) {", rows, width); fd_line(" %v0 = stablehlo.constant dense<0.00000000000000000e+00> : tensor", rows, width); fd_line(" %v1 = stablehlo.multiply %x, %x : tensor", rows, width); println!(" %v2 = stablehlo.constant dense<0.00000000000000000e+00> : tensor"); fd_line(" %v3 = stablehlo.reduce(%v1 init: %v2) applies stablehlo.add across dimensions = [1] : (tensor, tensor) -> tensor", rows, width); fd_line(" %v4 = stablehlo.broadcast_in_dim %v3, dims = [0] : (tensor) -> tensor", rows, width); fd_line(" %v5 = stablehlo.constant dense<9.99999999999999955e-07> : tensor", rows, width); fd_line(" %v6 = stablehlo.add %v4, %v5 : tensor", rows, width); fd_line(" %v7 = stablehlo.sqrt %v6 : tensor", rows, width); // xn = sqrt(rsum(x*x)+1e-6) fd_line(" %v8 = stablehlo.multiply %target, %target : tensor", rows, width); fd_line(" %v9 = stablehlo.reduce(%v8 init: %v2) applies stablehlo.add across dimensions = [1] : (tensor, tensor) -> tensor", rows, width); fd_line(" %v10 = stablehlo.broadcast_in_dim %v9, dims = [0] : (tensor) -> tensor", rows, width); fd_line(" %v11 = stablehlo.add %v10, %v5 : tensor", rows, width); fd_line(" %v12 = stablehlo.sqrt %v11 : tensor", rows, width); // tn = sqrt(rsum(target*target)+1e-6) fd_line(" %v13 = stablehlo.multiply %x, %target : tensor", rows, width); fd_line(" %v14 = stablehlo.reduce(%v13 init: %v2) applies stablehlo.add across dimensions = [1] : (tensor, tensor) -> tensor", rows, width); fd_line(" %v15 = stablehlo.broadcast_in_dim %v14, dims = [0] : (tensor) -> tensor", rows, width); fd_line(" %v16 = stablehlo.multiply %v7, %v12 : tensor", rows, width); fd_line(" %v17 = stablehlo.divide %v15, %v16 : tensor", rows, width); // score = rsum(x*target)/(xn*tn) fd_line(" %v18 = stablehlo.constant dense<1.00000000000000000e+00> : tensor", rows, width); fd_line(" %v19 = stablehlo.subtract %v18, %v17 : tensor", rows, width); // loss = 1-score fd_line(" %v20 = stablehlo.multiply %v17, %x : tensor", rows, width); fd_line(" %v21 = stablehlo.multiply %v7, %v7 : tensor", rows, width); fd_line(" %v22 = stablehlo.divide %v20, %v21 : tensor", rows, width); fd_line(" %v23 = stablehlo.divide %target, %v16 : tensor", rows, width); fd_line(" %v24 = stablehlo.subtract %v22, %v23 : tensor", rows, width); // grad = score*x/(xn*xn)-target/(xn*tn) fd_line(" return %v19, %v24 : tensor, tensor", rows, width); println!(" }"); println!("}"); }