// Clip each gradient row to a supplied positive L2 bound. Repeat the same bound across features in a row. use graph_io; pub fn fd_clip_row_grad(rows: i64, width: i64) { println!("module {"); fd_line(" func.func @main(%grad: tensor, %bound: tensor) -> (tensor, tensor) {", rows, width); fd_line(" %v0 = stablehlo.constant dense<0.00000000000000000e+00> : tensor", rows, width); fd_line(" %v1 = stablehlo.multiply %grad, %grad : 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.sqrt %v4 : tensor", rows, width); // norm = sqrt(rsum(grad*grad)) fd_line(" %v6 = stablehlo.constant dense<1.00000000000000000e+00> : tensor", rows, width); fd_line(" %v7 = stablehlo.constant dense<9.99999999999999945e-21> : tensor", rows, width); fd_line(" %v8 = stablehlo.maximum %v5, %v7 : tensor", rows, width); fd_line(" %v9 = stablehlo.divide %bound, %v8 : tensor", rows, width); fd_line(" %v10 = stablehlo.minimum %v6, %v9 : tensor", rows, width); // ratio = minimum(1,bound/maximum(norm,1e-20)) fd_line(" %v11 = stablehlo.multiply %grad, %v10 : tensor", rows, width); // clipped = grad*ratio fd_line(" return %v11, %v5 : tensor, tensor", rows, width); println!(" }"); println!("}"); }