// Threshold small gradient coordinates and reconstruct retained signs with their mean absolute magnitude. Supply a nonnegative per-row threshold. use graph_io; pub fn fd_ternary_compress(rows: i64, width: i64) { println!("module {"); fd_line(" func.func @main(%grad: tensor, %threshold: tensor) -> (tensor, tensor, tensor) {", rows, width); fd_line(" %v0 = stablehlo.constant dense<0.00000000000000000e+00> : tensor", rows, width); fd_line(" %v1 = stablehlo.abs %grad : tensor", rows, width); fd_line(" %v2 = stablehlo.compare GT, %v1, %threshold, FLOAT : (tensor, tensor) -> tensor", rows, width); // keep = abs(grad)>threshold fd_line(" %v3 = stablehlo.constant dense<1.00000000000000000e+00> : tensor", rows, width); fd_line(" %v4 = stablehlo.select %v2, %v3, %v0 : tensor, tensor", rows, width); // mask = choose(keep,1,0) fd_line(" %v5 = stablehlo.multiply %v1, %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.reduce(%v4 init: %v6) 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.maximum %v10, %v3 : tensor", rows, width); fd_line(" %v12 = stablehlo.divide %v8, %v11 : tensor", rows, width); // scale = rsum(abs(grad)*mask)/maximum(rsum(mask),1) fd_line(" %v13 = stablehlo.sign %grad : tensor", rows, width); fd_line(" %v14 = stablehlo.multiply %v13, %v4 : tensor", rows, width); // code = sign(grad)*mask fd_line(" %v15 = stablehlo.multiply %v12, %v14 : tensor", rows, width); // decoded = scale*code fd_line(" return %v14, %v15, %v12 : tensor, tensor, tensor", rows, width); println!(" }"); println!("}"); }