Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.6k views
in Technique[技术] by (71.8m points)

Sum of array in Halide

I've started learning Halide. Suppose I wanted to calculate the sum of elements in an array. Why is the following code snippet failing?

constexpr int N = 10;
ImageParam array(Float(32), 1);
Var x;
Func fsum("sum");
RDom i(1, N);
fsum(x) = 0.0f;
fsum(0) = array(0);
fsum(i) = array(i) + fsum(i-1); 
Buffer<float> buffer(N);
for (int i = 0; i < N; ++i) buffer(i) = rand() / 100.0f;
array.set(buffer);
Buffer<float> output = fsum.realize(1);

The runtime error is:

libc++abi: terminating with uncaught exception of type Halide::RuntimeError: Error: Input buffer p0 is accessed at 10, which is beyond the max (9) in dimension 0

UPDATE: I've updated the indices according to the accepted answer and put some code to check the reproducibility.

    constexpr int N = 10;
    ImageParam array(Float(32), 1);   
    Var x;
    Func fsum("sum");
    RDom i(1, N-1);
    fsum(x) = 0.0f;
    fsum(0) = array(0);
    fsum(i) = array(i) + fsum(i-1); 
    Buffer<float> buffer(N);
    float cppsum = 0.0f;
    for (int k = 0; k < N; ++k) {
        buffer(k) = (float) k;
        cppsum += k; 
    }    
    array.set(buffer);
    Buffer<float> hsum = fsum.realize(1);
    std::cout << "Halide sum: " << hsum(0) << std::endl;
    std::cout << "C++ sum: " << cppsum << std::endl;
    //fsum.compile_to_lowered_stmt("hsum.html", {}, HTML);

Halide sum is 0. C++ sum is 45. I wanted to check the resulting code, but if the last line is commented out I get a

libc++abi: terminating with uncaught exception of type Halide::CompileError: Error: Generated code refers to image parameter p0, which was not found in the argument list. Argument list specified:> Parameters referenced in generated code: p0> Abort trap: 6

What am I doing wrong?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The error is telling you that your code reads out of bounds in the input array. This is because the RDom i goes from 1 to N+1 (RDom ranges in Halide are expressed as min, extent not min, max, so they go from min to min+extent). You probably mean RDom i(1,N-1).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...