tensor-compiler / taco

The Tensor Algebra Compiler (taco) computes sparse tensor expressions on CPUs and GPUs
http://tensor-compiler.org
Other
1.24k stars 186 forks source link

Conjugate Gradient #91

Open sueda opened 7 years ago

sueda commented 7 years ago

I'm trying to write CG with taco, but I'm having difficulties. Here is my starter code, which doesn't compile yet.

void conjgrad(taco::Tensor<double> &A, taco::Tensor<double> &b, taco::Tensor<double> &x)
{
    taco::Format  dv({taco::Dense});
    int n = b.getDimensions()[0];

    taco::Tensor<double> r({n}, dv);
    taco::Tensor<double> p({n}, dv);
    taco::Tensor<double> Ap({n}, dv);

    double rsold, rsnew, alpha;
    taco::IndexVar i, j;

    r(i) = b(i) - A(i,j) * x(j); // A can't be const!
    p = r;
    rsold = r(i) * r(i);

    int itermax = n;
    double thresh = 1e-10;
    for(int iter = 0; iter < itermax; ++iter) {
        Ap(i) = A(i,j) * p(j);
        alpha = rsold / (p(i) * Ap(i));
        x(i) = x(i) + alpha * p(i);
        r(i) = r(i) - alpha * Ap(i);
        rsnew = r(i) * r(i);
        if(sqrt(rsnew) < thresh) {
            break;
        }
        p(i) = r(i) + (rsnew / rsold) * p(i);
        rsold = rsnew;
    }
}

Here are some comments/issues.

stephenchouca commented 7 years ago

Thanks for your feedback! 57661f4 and eedb9db should address your first and fourth points respectively. With regards to your last point, the Tensor class does in fact have a getFormat method that returns the format of the tensor, so you can write something like

taco::Tensor<double> r({n}, b.getFormat());