首页 > 解决方案 > 使用 2D std::vector 对 SYCL 进行矩阵乘法

问题描述

我是 SYCL 和 C++ 的新手。这是我使用 2D 进行简单矩阵乘法的内核std::vector


void MatrixMulParallel(queue& q, 
    const std::vector<std::vector<double>>& a_host,
    const std::vector<std::vector<double>>& b_host,
    std::vector<std::vector<double>>& c_gpu) {
    /*
        To Multiply: C[M][P] = A[M][N] * B[N][P]
    */
    PROFILE_FUNCTION();
    try {
        size_t M = a_host.size();
        size_t N = a_host[0].size();
        size_t P = b_host[0].size();
        // Create device buffers for A, B, C
        buffer a(a_host.data(), range<2>{M, N});
        buffer b(b_host.data(), range<2>{N, P});
        buffer c(c_gpu.data(), range<2>{M, P});

        PROFILE_SCOPE("Starting Multiply on GPU");
        std::cout << "GPU::Multiplying A and B into C.\n";
        auto e = q.submit([&](handler& h) {

            auto A = a.get_access<access::mode::read>(h);
            auto B = b.get_access<access::mode::read>(h);
            auto C = c.get_access<access::mode::write>(h);

            h.parallel_for(range<2>{M, P}, [=](id<2> index) {
                // index[0] allows accessing ROW index, index[1] is column index
                
                int row = index[0];
                int col = index[1];
                auto sum = 0.0;
                for (int i = 0; i < N; i++)
                    sum += A[row][i] * B[i][col]; // Error #1
                C[index] = sum; // Error #2
                });
            });
        e.wait();
    }
    catch (sycl::exception const& e) {
        std::cout << "An exception is caught while multiplying matrices.\n";
        terminate();
    }
}

我收到两个错误,如下所示:

  1. 错误 #1:invalid operands to binary expression ('const std::vector<double, std::allocator<double>>' and 'const std::vector<double, std::allocator<double>>')
  2. 错误 #2:no viable overloaded '='

我尝试查找类似于 的错误invalid operands for binary expression (...),但它们似乎都不能帮助调试我的具体情况。也许是因为这对初学者不友好。

从我目前的理解来看,a_host.data()显示了一个返回类型std::vector<double>(不应该是std::vector< std::vector<double> >吗?)。

我尝试过使用std::array静态已知的尺寸,它可以工作。

如何使用 2D 完成这项工作std::vector

任何帮助,将不胜感激。

标签: c++vectorsyclintel-oneapidpc++

解决方案


更一般地说,在进行 HPC 时避免使用非紧凑的数据结构。与连续数组元素相比,它对内存层次结构不太友好,而且初始化很复杂。改用类似于md_span和的东西md_array(基本上是类固醇上的Fortran数组:-))。


推荐阅读