Bounds samples to 0 if the warp image indices are out of the (-1, image_size) bound. The resulting dimension is given by 'result_dims'.
| 193 | // bound. |
| 194 | // The resulting dimension is given by 'result_dims'. |
| 195 | XlaOp BoundSamples(XlaOpKernelContext* ctx, XlaOp warp, |
| 196 | xla::PrimitiveType warp_type, TensorShape warp_shape, |
| 197 | std::vector<int64> result_dims, |
| 198 | std::vector<int64> broadcasted_dims, int64 last_warp_dim, |
| 199 | xla::Shape data_shape, XlaOp sample) { |
| 200 | auto is_gt_minus_one = |
| 201 | xla::Gt(warp, |
| 202 | xla::ConvertElementType( |
| 203 | xla::ConstantR1<float>(ctx->builder(), {-1, -1}), warp_type), |
| 204 | /*broadcast_dimensions=*/{warp_shape.dims() - 1}); |
| 205 | auto is_lt_image_size = xla::Lt( |
| 206 | warp, |
| 207 | xla::ConvertElementType( |
| 208 | xla::ConstantR1<float>( |
| 209 | ctx->builder(), |
| 210 | {/*width=*/static_cast<float>(data_shape.dimensions(2)), |
| 211 | /*height=*/static_cast<float>(data_shape.dimensions(1))}), |
| 212 | warp_type), |
| 213 | /*broadcast_dimensions=*/{warp_shape.dims() - 1}); |
| 214 | |
| 215 | auto is_in_bound_padded_x_y = xla::And(is_gt_minus_one, is_lt_image_size); |
| 216 | // Reduce along last dimension. The resulting dimension is: |
| 217 | // [batch, dim_0, ...dim_n]. |
| 218 | auto is_in_bound = xla::Reduce( |
| 219 | is_in_bound_padded_x_y, xla::ConstantR0<bool>(ctx->builder(), true), |
| 220 | xla::CreateScalarAndComputation(xla::PrimitiveType::PRED, ctx->builder()), |
| 221 | {last_warp_dim}); |
| 222 | |
| 223 | // Broadcast 'is_in_bound' to the same dimension as 'result_dims'. |
| 224 | auto broadcasted_is_in_bound = |
| 225 | xla::BroadcastInDim(is_in_bound, result_dims, broadcasted_dims); |
| 226 | |
| 227 | // Set out of bound samples to zero. |
| 228 | auto zeros = |
| 229 | xla::Broadcast(xla::Zero(ctx->builder(), warp_type), result_dims); |
| 230 | return xla::Select(broadcasted_is_in_bound, sample, zeros); |
| 231 | } |
| 232 | |
| 233 | // Build computation the backprop into input 'data'. |
| 234 | // Where input: |
no test coverage detected