// Normalize only unmasked attention scores and propagate through allowed positions. Fully masked rows return zeros. Use a binary mask. use graph_io; pub fn fd_masked_attention(rows: i64, width: i64) { println!("module {"); fd_line(" func.func @main(%x: tensor, %mask: tensor, %upstream: tensor) -> (tensor, tensor) {", rows, width); fd_line(" %v0 = stablehlo.constant dense<0.00000000000000000e+00> : tensor", rows, width); fd_line(" %v1 = stablehlo.compare GT, %mask, %v0, FLOAT : (tensor, tensor) -> tensor", rows, width); // visible = mask>0 fd_line(" %v2 = stablehlo.constant dense<3.40282339999999992e+38> : tensor", rows, width); fd_line(" %v3 = stablehlo.negate %v2 : tensor", rows, width); fd_line(" %v4 = stablehlo.select %v1, %x, %v3 : tensor, tensor", rows, width); println!(" %v5 = stablehlo.constant dense<-3.40282346000000007e+38> : tensor"); fd_line(" %v6 = stablehlo.reduce(%v4 init: %v5) applies stablehlo.maximum across dimensions = [1] : (tensor, tensor) -> tensor", rows, width); fd_line(" %v7 = stablehlo.broadcast_in_dim %v6, dims = [0] : (tensor) -> tensor", rows, width); // m = rmax(choose(visible,x,-3.4028234e38)) fd_line(" %v8 = stablehlo.subtract %x, %v7 : tensor", rows, width); fd_line(" %v9 = stablehlo.constant dense<9.00000000000000000e+01> : tensor", rows, width); fd_line(" %v10 = stablehlo.negate %v9 : tensor", rows, width); fd_line(" %v11 = stablehlo.select %v1, %v8, %v10 : tensor, tensor", rows, width); fd_line(" %v12 = stablehlo.exponential %v11 : tensor", rows, width); fd_line(" %v13 = stablehlo.multiply %v12, %mask : tensor", rows, width); // z = exp(choose(visible,x-m,-90))*mask println!(" %v14 = stablehlo.constant dense<0.00000000000000000e+00> : tensor"); fd_line(" %v15 = stablehlo.reduce(%v13 init: %v14) applies stablehlo.add across dimensions = [1] : (tensor, tensor) -> tensor", rows, width); fd_line(" %v16 = stablehlo.broadcast_in_dim %v15, dims = [0] : (tensor) -> tensor", rows, width); fd_line(" %v17 = stablehlo.constant dense<1.00000000000000008e-30> : tensor", rows, width); fd_line(" %v18 = stablehlo.maximum %v16, %v17 : tensor", rows, width); fd_line(" %v19 = stablehlo.divide %v13, %v18 : tensor", rows, width); // p = z/maximum(rsum(z),1e-30) fd_line(" %v20 = stablehlo.multiply %upstream, %v19 : tensor", rows, width); fd_line(" %v21 = stablehlo.reduce(%v20 init: %v14) applies stablehlo.add across dimensions = [1] : (tensor, tensor) -> tensor", rows, width); fd_line(" %v22 = stablehlo.broadcast_in_dim %v21, dims = [0] : (tensor) -> tensor", rows, width); fd_line(" %v23 = stablehlo.subtract %upstream, %v22 : tensor", rows, width); fd_line(" %v24 = stablehlo.multiply %v19, %v23 : tensor", rows, width); // dx = p*(upstream-rsum(upstream*p)) fd_line(" return %v19, %v24 : tensor, tensor", rows, width); println!(" }"); println!("}"); }