// Clip a gradient relative to the parameter-row norm. Supply a positive clipping factor fixed within the row. use graph_io; pub fn fd_adaptive_clip(rows: i64, width: i64) { println!("module {"); fd_line(" func.func @main(%weight: tensor, %grad: tensor, %factor: tensor) -> (tensor, tensor) {", rows, width); fd_line(" %v0 = stablehlo.constant dense<0.00000000000000000e+00> : tensor", rows, width); fd_line(" %v1 = stablehlo.multiply %weight, %weight : 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); fd_line(" %v6 = stablehlo.constant dense<1.00000000000000002e-03> : tensor", rows, width); fd_line(" %v7 = stablehlo.maximum %v5, %v6 : tensor", rows, width); // wn = maximum(sqrt(rsum(weight*weight)),1e-3) fd_line(" %v8 = stablehlo.multiply %grad, %grad : 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.sqrt %v10 : tensor", rows, width); // gn = sqrt(rsum(grad*grad)) fd_line(" %v12 = stablehlo.constant dense<1.00000000000000000e+00> : tensor", rows, width); fd_line(" %v13 = stablehlo.multiply %factor, %v7 : tensor", rows, width); fd_line(" %v14 = stablehlo.constant dense<9.99999999999999955e-07> : tensor", rows, width); fd_line(" %v15 = stablehlo.maximum %v11, %v14 : tensor", rows, width); fd_line(" %v16 = stablehlo.divide %v13, %v15 : tensor", rows, width); fd_line(" %v17 = stablehlo.minimum %v12, %v16 : tensor", rows, width); // scale = minimum(1,factor*wn/maximum(gn,1e-6)) fd_line(" %v18 = stablehlo.multiply %grad, %v17 : tensor", rows, width); // clipped = grad*scale fd_line(" return %v18, %v17 : tensor, tensor", rows, width); println!(" }"); println!("}"); }