// Scale each parameter row by a LARS trust ratio before an SGD step. Zero norms fall back to unit scaling. use graph_io; pub fn fd_lars_step(rows: i64, width: i64) { println!("module {"); fd_line(" func.func @main(%weight: tensor, %grad: tensor, %lr: tensor, %decay: tensor) -> (tensor, tensor) {", rows, width); fd_line(" %v0 = stablehlo.constant dense<0.00000000000000000e+00> : tensor", rows, width); fd_line(" %v1 = stablehlo.multiply %decay, %weight : tensor", rows, width); fd_line(" %v2 = stablehlo.add %grad, %v1 : tensor", rows, width); // g = grad+decay*weight fd_line(" %v3 = stablehlo.multiply %weight, %weight : tensor", rows, width); println!(" %v4 = stablehlo.constant dense<0.00000000000000000e+00> : tensor"); fd_line(" %v5 = stablehlo.reduce(%v3 init: %v4) applies stablehlo.add across dimensions = [1] : (tensor, tensor) -> tensor", rows, width); fd_line(" %v6 = stablehlo.broadcast_in_dim %v5, dims = [0] : (tensor) -> tensor", rows, width); fd_line(" %v7 = stablehlo.sqrt %v6 : tensor", rows, width); // wn = sqrt(rsum(weight*weight)) fd_line(" %v8 = stablehlo.multiply %v2, %v2 : tensor", rows, width); fd_line(" %v9 = stablehlo.reduce(%v8 init: %v4) 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(g*g)) fd_line(" %v12 = stablehlo.multiply %v7, %v11 : tensor", rows, width); fd_line(" %v13 = stablehlo.compare GT, %v12, %v0, FLOAT : (tensor, tensor) -> tensor", rows, width); fd_line(" %v14 = stablehlo.constant dense<1.00000000000000002e-03> : tensor", rows, width); fd_line(" %v15 = stablehlo.multiply %v14, %v7 : tensor", rows, width); fd_line(" %v16 = stablehlo.constant dense<9.99999999999999945e-21> : tensor", rows, width); fd_line(" %v17 = stablehlo.maximum %v11, %v16 : tensor", rows, width); fd_line(" %v18 = stablehlo.divide %v15, %v17 : tensor", rows, width); fd_line(" %v19 = stablehlo.constant dense<1.00000000000000000e+00> : tensor", rows, width); fd_line(" %v20 = stablehlo.select %v13, %v18, %v19 : tensor, tensor", rows, width); // trust = choose(wn*gn>0,0.001*wn/maximum(gn,1e-20),1) fd_line(" %v21 = stablehlo.multiply %lr, %v20 : tensor", rows, width); fd_line(" %v22 = stablehlo.multiply %v21, %v2 : tensor", rows, width); fd_line(" %v23 = stablehlo.subtract %weight, %v22 : tensor", rows, width); // updated = weight-lr*trust*g fd_line(" return %v23, %v20 : tensor, tensor", rows, width); println!(" }"); println!("}"); }