Search code examples
halide

Halide: How to deal with Expr evaluated as nan or inf?


I have a 1D Func over which I'd like to perform the following: take the sum of a kernel of n values, and divide it by the sum of the kernel shifted by 1. Here's the code I have so far:

Var x("x");

Func result("result");
RDom r(0, kernel_size);

Expr sum1 = sum(vec_func(x+r));
Expr sum2 = sum(vec_func(x+r+1));           
Expr quotient = sum1 / sum2;

result(x) = quotient;

This is an example of the type of calculation which might result in a NaN or Inf. Ideally I would be able to deal with this in Halide using something like this:

Expr safe_calc = select(isnan(quotient) || isinf(quotient), 0, quotient);
result(x) = quotient;

Does such a method exist in Halide?


Solution

  • Expr Halide::is_nan(Expr) exists right now, but we are missing is_finite. (Added as https://github.com/halide/Halide/issues/2497)

    However: be aware that Halide does floating point math in accordance with -ffast-math rules, which means it is allowed to optimize the code in ways that assume NaN/Inf values can't happen. If it's possible to structure your code in a way to ensure such values aren't possible, you should do so.