// Apply row RMS normalization with per-feature gain and return the input gradient and per-row gain contribution. use graph_io; pub fn fd_rmsnorm_backward(rows: i64, width: i64) { println!("module {"); fd_line(" func.func @main(%x: tensor, %gain: tensor, %upstream: tensor) -> (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 : tensor", rows, width); fd_line(" %v7 = stablehlo.divide %v5, %v6 : tensor", rows, width); fd_line(" %v8 = stablehlo.constant dense<1.00000000000000008e-05> : tensor", rows, width); fd_line(" %v9 = stablehlo.add %v7, %v8 : tensor", rows, width); fd_line(" %v10 = stablehlo.sqrt %v9 : tensor", rows, width); fd_line(" %v11 = stablehlo.divide %v1, %v10 : tensor", rows, width); // inv = 1/sqrt(mean(x*x)+1e-5) fd_line(" %v12 = stablehlo.multiply %x, %v11 : tensor", rows, width); // u = x*inv fd_line(" %v13 = stablehlo.multiply %gain, %v12 : tensor", rows, width); // y = gain*u fd_line(" %v14 = stablehlo.multiply %upstream, %gain : tensor", rows, width); // g = upstream*gain fd_line(" %v15 = stablehlo.multiply %v14, %v12 : tensor", rows, width); fd_line(" %v16 = stablehlo.reduce(%v15 init: %v3) applies stablehlo.add across dimensions = [1] : (tensor, tensor) -> tensor", rows, width); fd_line(" %v17 = stablehlo.broadcast_in_dim %v16, dims = [0] : (tensor) -> tensor", rows, width); fd_line(" %v18 = stablehlo.divide %v17, %v6 : tensor", rows, width); fd_line(" %v19 = stablehlo.multiply %v12, %v18 : tensor", rows, width); fd_line(" %v20 = stablehlo.subtract %v14, %v19 : tensor", rows, width); fd_line(" %v21 = stablehlo.multiply %v11, %v20 : tensor", rows, width); // dx = inv*(g-u*mean(g*u)) fd_line(" %v22 = stablehlo.multiply %upstream, %v12 : tensor", rows, width); // dg = upstream*u fd_line(" return %v13, %v21, %v22 : tensor, tensor, tensor", rows, width); println!(" }"); println!("}"); }