Halide: Reduction over a domain for the specific values

余生颓废 提交于 2019-12-12 04:35:25

问题


I got a func f(x, y, z) in which the values is either 1 and 0, and I need to get the the first 100 coordinates of the values which equals to 1, to reduction/update them to 0.

This is very simple to realize in c and other languages, However, I've been trying to solve it with Halide for a couple of days. Is there any Function or Algorithm that I can use to solve it in Halide Generators?


回答1:


The question amounts to "How do I implement stream compaction in Halide?" There is much written on parallel stream compaction and it is somewhat non-trivial to do well. See this Stack Overflow answer on doing it in cuda for some discussion and references: CUDA stream compaction algorithm

An quick implementation of simple stream compaction in Halide using a prefix sum looks like so:

#include "Halide.h"
#include <iostream>

using namespace Halide;

static void print_1d(const Buffer<int32_t> &result) {
    std::cout << "{ ";
    const char *prefix = "";
    for (int i = 0; i < result.dim(0).extent(); i++) {
        std::cout << prefix << result(i);
        prefix = ", ";
    }
    std::cout << "}\n";

}

int main(int argc, char **argv) {
    uint8_t vals[] = {0, 10, 99, 76, 5, 200, 88, 15};
    Buffer<uint8_t> in(vals);

    Var x;
    Func prefix_sum;

    RDom range(1, in.dim(0).extent() - 1);
    prefix_sum(x) = (int32_t)0;
    prefix_sum(range) = select(in(range - 1) > 42, prefix_sum(range - 1) + 1, prefix_sum(range - 1));

    RDom in_range(0, in.dim(0).extent());
    Func compacted_indices;
    compacted_indices(x) = -1;
    compacted_indices(clamp(prefix_sum(in_range), 0, in.dim(0).extent() - 1)) = select(in(in_range) > 42, in_range, - 1);

    Buffer<int32_t> sum = prefix_sum.realize(8);
    Buffer<int32_t> indices = compacted_indices.realize(8);

    print_1d(sum);
    print_1d(indices);

    return 0;
}


来源:https://stackoverflow.com/questions/46725426/halide-reduction-over-a-domain-for-the-specific-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!