// Normalize attention scores along each row and compute the softmax vector-Jacobian product. use graph_io; pub fn fd_softmax_backward(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); println!(" %v1 = stablehlo.constant dense<-3.40282346000000007e+38> : tensor"); fd_line(" %v2 = stablehlo.reduce(%x init: %v1) applies stablehlo.maximum across dimensions = [1] : (tensor, tensor) -> tensor", rows, width); fd_line(" %v3 = stablehlo.broadcast_in_dim %v2, dims = [0] : (tensor) -> tensor", rows, width); fd_line(" %v4 = stablehlo.subtract %x, %v3 : tensor", rows, width); fd_line(" %v5 = stablehlo.exponential %v4 : tensor", rows, width); println!(" %v6 = stablehlo.constant dense<0.00000000000000000e+00> : tensor"); fd_line(" %v7 = stablehlo.reduce(%v5 init: %v6) applies stablehlo.add across dimensions = [1] : (tensor, tensor) -> tensor", rows, width); fd_line(" %v8 = stablehlo.broadcast_in_dim %v7, dims = [0] : (tensor) -> tensor", rows, width); fd_line(" %v9 = stablehlo.log %v8 : tensor", rows, width); fd_line(" %v10 = stablehlo.subtract %v4, %v9 : tensor", rows, width); fd_line(" %v11 = stablehlo.exponential %v10 : tensor", rows, width); // p = exp(logsoft(x)) fd_line(" %v12 = stablehlo.multiply %upstream, %v11 : tensor", rows, width); fd_line(" %v13 = stablehlo.reduce(%v12 init: %v6) applies stablehlo.add across dimensions = [1] : (tensor, tensor) -> tensor", rows, width); fd_line(" %v14 = stablehlo.broadcast_in_dim %v13, dims = [0] : (tensor) -> tensor", rows, width); fd_line(" %v15 = stablehlo.subtract %upstream, %v14 : tensor", rows, width); fd_line(" %v16 = stablehlo.multiply %v11, %v15 : tensor", rows, width); // dx = p*(upstream-rsum(upstream*p)) fd_line(" return %v11, %v16 : tensor, tensor", rows, width); println!(" }"); println!("}"); }