Search code examples
halide

How to define generic reductions using any binary Operator example OR or AND, custom function?


I believe Halide currently supports sum,minimum,maximum and product which work with RDom. I would like to write a function which does reductions over custom binary operations For Eg. 'AND (&&)', 'OR (||)', '(&)', '(|)' etc. How can I do this in Halide ?

Here are my thoughts on this problem: Suppose we have a uint8_t input and to perform a reduction using (|),

RDom rw(0,width); rh(0,height);
Func f,g;
f(y) = cast<uint8_t>(0);
f(y) = f(y) | input(rw,y);
g(x) = cast<uint8_t>(0);
g(x) = g(x) | f(rh);

It would be nice to have a Halide function which can perform generic reduction by means of specifying a reduction function (two inputs)

Thanks in advance for your reply.


Solution

  • The helpers sum, product, etc are not actually built-ins. They are just helpers written in the Halide front-end language itself, so you can define more if you like, or make a generic that takes a binary operator. I would start by looking at https://github.com/halide/Halide/blob/master/src/InlineReductions.cpp

    The bulk of the magic is just the automatic capturing of free variables, the rest is just like the code you wrote.