簡體   English   中英

使用CUDA縮放矩陣的行

[英]Scaling the rows of a matrix with CUDA

在GPU上的一些計算中,我需要縮放矩陣中的行,以便給定行中的所有元素總和為1。

| a1,1 a1,2 ... a1,N |    | alpha1*a1,1 alpha1*a1,2 ... alpha1*a1,N |
| a2,1 a2,2 ... a2,N | => | alpha2*a2,1 alpha2*a2,2 ... alpha2*a2,N |
| .            .   |    | .                                .    |
| aN,1 aN,2 ... aN,N |    | alphaN*aN,1 alphaN*aN,2 ... alphaN*aN,N |

哪里

alphai =  1.0/(ai,1 + ai,2 + ... + ai,N)

我需要alpha的矢量和縮放矩陣,我想在盡可能少的blas調用中執行此操作。 該代碼將在nvidia CUDA硬件上運行。 有誰知道有任何聰明的方法來做到這一點?

Cublas 5.0引入了類似blas的例程,稱為cublas(Type)dgmm,它是矩陣乘以對角矩陣(由向量表示)的乘法。

左側選項(將縮放行)或右側選項將縮放列。

有關詳細信息,請參閱CUBLAS 5.0文檔。

所以在你的問題中,你需要創建一個包含GPU上所有alpha的向量,並使用帶左選項的cublasdgmm。

我想用一個例子來更新上面的答案,考慮使用CUDA Thrust的thrust::transformcuBLAScublas<t>dgmm 我正在跳過縮放因子alpha的計算,因為已經處理過了

使用CUDA減少矩陣行

使用CUDA減少矩陣列

以下是一個完整的例子:

#include <thrust/device_vector.h>
#include <thrust/reduce.h>
#include <thrust/random.h>
#include <thrust/sort.h>
#include <thrust/unique.h>
#include <thrust/equal.h>

#include <cublas_v2.h>

#include "Utilities.cuh"
#include "TimingGPU.cuh"

/**************************************************************/
/* CONVERT LINEAR INDEX TO ROW INDEX - NEEDED FOR APPROACH #1 */
/**************************************************************/
template <typename T>
struct linear_index_to_row_index : public thrust::unary_function<T,T> {

    T Ncols; // --- Number of columns

    __host__ __device__ linear_index_to_row_index(T Ncols) : Ncols(Ncols) {}

    __host__ __device__ T operator()(T i) { return i / Ncols; }
};

/***********************/
/* RECIPROCAL OPERATOR */
/***********************/
struct Inv: public thrust::unary_function<float, float>
{
    __host__ __device__ float operator()(float x)
    {
        return 1.0f / x;
    }
};

/********/
/* MAIN */
/********/
int main()
{
    /**************************/
    /* SETTING UP THE PROBLEM */
    /**************************/

    const int Nrows = 10;           // --- Number of rows
    const int Ncols =  3;           // --- Number of columns  

    // --- Random uniform integer distribution between 0 and 100
    thrust::default_random_engine rng;
    thrust::uniform_int_distribution<int> dist1(0, 100);

    // --- Random uniform integer distribution between 1 and 4
    thrust::uniform_int_distribution<int> dist2(1, 4);

    // --- Matrix allocation and initialization
    thrust::device_vector<float> d_matrix(Nrows * Ncols);
    for (size_t i = 0; i < d_matrix.size(); i++) d_matrix[i] = (float)dist1(rng);

    // --- Normalization vector allocation and initialization
    thrust::device_vector<float> d_normalization(Nrows);
    for (size_t i = 0; i < d_normalization.size(); i++) d_normalization[i] = (float)dist2(rng);

    printf("\n\nOriginal matrix\n");
    for(int i = 0; i < Nrows; i++) {
        std::cout << "[ ";
        for(int j = 0; j < Ncols; j++)
            std::cout << d_matrix[i * Ncols + j] << " ";
        std::cout << "]\n";
    }

    printf("\n\nNormlization vector\n");
    for(int i = 0; i < Nrows; i++) std::cout << d_normalization[i] << "\n";

    TimingGPU timerGPU;

    /*********************************/
    /* ROW NORMALIZATION WITH THRUST */
    /*********************************/

    thrust::device_vector<float> d_matrix2(d_matrix);

    timerGPU.StartCounter();
    thrust::transform(d_matrix2.begin(), d_matrix2.end(),
                      thrust::make_permutation_iterator(
                                d_normalization.begin(),
                                thrust::make_transform_iterator(thrust::make_counting_iterator(0), linear_index_to_row_index<int>(Ncols))),
                      d_matrix2.begin(),
                      thrust::divides<float>());
    std::cout << "Timing - Thrust = " << timerGPU.GetCounter() << "\n";

    printf("\n\nNormalized matrix - Thrust case\n");
    for(int i = 0; i < Nrows; i++) {
        std::cout << "[ ";
        for(int j = 0; j < Ncols; j++)
            std::cout << d_matrix2[i * Ncols + j] << " ";
        std::cout << "]\n";
    }

    /*********************************/
    /* ROW NORMALIZATION WITH CUBLAS */
    /*********************************/
    d_matrix2 = d_matrix;

    cublasHandle_t handle;
    cublasSafeCall(cublasCreate(&handle));

    timerGPU.StartCounter();
    thrust::transform(d_normalization.begin(), d_normalization.end(), d_normalization.begin(), Inv());
    cublasSafeCall(cublasSdgmm(handle, CUBLAS_SIDE_RIGHT, Ncols, Nrows, thrust::raw_pointer_cast(&d_matrix2[0]), Ncols, 
                   thrust::raw_pointer_cast(&d_normalization[0]), 1, thrust::raw_pointer_cast(&d_matrix2[0]), Ncols));
    std::cout << "Timing - cuBLAS = " << timerGPU.GetCounter() << "\n";

    printf("\n\nNormalized matrix - cuBLAS case\n");
    for(int i = 0; i < Nrows; i++) {
        std::cout << "[ ";
        for(int j = 0; j < Ncols; j++)
            std::cout << d_matrix2[i * Ncols + j] << " ";
        std::cout << "]\n";
    }

    return 0;
}

Utilities.cuUtilities.cuh文件在此處保留, 此處省略。 TimingGPU.cuTimingGPU.cuh這里維護,也被省略。

我在Kepler K20c上測試了上面的代碼,結果如下:

                 Thrust      cuBLAS
2500 x 1250      0.20ms      0.25ms
5000 x 2500      0.77ms      0.83ms

cuBLAS時間,我不包括cublasCreate時間。 即便如此,CUDA Thrust版本似乎更方便。

如果你使用BLAS gemv和單位向量,結果將是你需要的縮放因子(1 / alpha)倒數的向量。 這是容易的部分。

逐行應用因子有點困難,因為標准BLAS沒有像您可以使用的Hadamard產品運算符那樣的東西。 另外因為你提到BLAS,我認為你正在為你的矩陣使用列主要訂單存儲,這對於行式操作來說並不是那么簡單。 真正緩慢的方法是使用一個音調對每行上的BLAS scal進行調整,但是每行需要一次BLAS調用, 並且由於對合並和L1緩存一致性的影響調整的內存訪問將會降低性能。

我的建議是使用你自己的內核進行第二次操作。 它不一定非常復雜,也許只有這樣:

template<typename T>
__global__ void rowscale(T * X, const int M, const int N, const int LDA,
                             const T * ralpha)
{
    for(int row=threadIdx.x; row<M; row+=gridDim.x) {
        const T rscale = 1./ralpha[row]; 
        for(int col=blockIdx.x; col<N; col+=blockDim.x) 
            X[row+col*LDA] *= rscale;
    }
}

只有一堆塊逐列地逐行排列,隨着它們的進行縮放。 應適用於任何大小的列主要有序矩陣。 內存訪問應該合並,但根據您對性能的擔憂程度,您可以嘗試一些優化。 它至少給出了如何做的一般概念。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM