// Normalize retrieval embeddings to near-unit length and differentiate a row objective through the normalization. use graph_io; pub fn fd_unit_embeddings(rows: i64, width: i64) { println!("module {"); fd_line(" func.func @main(%x: tensor, %upstream: tensor) -> (tensor, tensor) {", rows, width); fd_line(" %v0 = stablehlo.constant dense<0.00000000000000000e+00> : tensor", rows, width); fd_line(" %v1 = stablehlo.constant dense<1.00000000000000000e+00> : tensor", rows, width); fd_line(" %v2 = stablehlo.multiply %x, %x : 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.constant dense<9.99999999999999955e-07> : tensor", rows, width); fd_line(" %v7 = stablehlo.add %v5, %v6 : tensor", rows, width); fd_line(" %v8 = stablehlo.sqrt %v7 : tensor", rows, width); fd_line(" %v9 = stablehlo.divide %v1, %v8 : tensor", rows, width); // inv = 1/sqrt(rsum(x*x)+1e-6) fd_line(" %v10 = stablehlo.multiply %x, %v9 : tensor", rows, width); // unit = x*inv fd_line(" %v11 = stablehlo.multiply %v10, %upstream : tensor", rows, width); fd_line(" %v12 = stablehlo.reduce(%v11 init: %v3) 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.multiply %v10, %v13 : tensor", rows, width); fd_line(" %v15 = stablehlo.subtract %upstream, %v14 : tensor", rows, width); fd_line(" %v16 = stablehlo.multiply %v9, %v15 : tensor", rows, width); // dx = inv*(upstream-unit*rsum(unit*upstream)) fd_line(" return %v10, %v16 : tensor, tensor", rows, width); println!(" }"); println!("}"); }