Создать быструю контрольную сумму для большого массива чисел без использования каких-либо библиотек? - PullRequest
3 голосов
/ 15 мая 2011

В C (точнее, C для CUDA), каков наилучший способ вычисления контрольной суммы большого массива чисел с плавающей запятой (скажем, двадцать тысяч значений), который легко распечатать с помощью printf без использования каких-либо библиотек? 1001 *

Я мог бы просто сложить все значения с плавающей точностью, но я боюсь, что ошибки округления или насыщения, или значения nan / inf, сделают некоторые изменения не обнаруживаемыми.

Это используется для сравнения значений переменной между запусками одного и того же двоичного файла на одном и том же оборудовании GPU, и это используется только для отладки, а не для обеспечения безопасности.

Чтобы быть еще более понятным, было бы хорошо, если бы все цифры контрольной суммы изменялись (с высокой вероятностью), когда любое из значений с плавающей запятой в массиве изменяется, так что контрольные суммы легко сравнивать визуально.

Ответы [ 6 ]

1 голос
/ 20 мая 2011

Возможно, это слишком велико для ответа stackoverflow, но вот файл crc.cu, который я взломал из вывода pycrc .Он включает несколько приемов, уже упомянутых в других ответах.Я больше всего доверяю версии crc, но версии add и xor удобны, когда массивы должны быть заполнены нулями.

    /*  The MIT License
    Copyright (c) <year> <copyright holders>

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.  */

/*
 * (formerly) file crc.h
 * Functions and types for CRC checks.
 *
 * Generated on Sun May 15 16:28:36 2011,
 * by pycrc v0.7.7, http://www.tty1.net/pycrc/
 * using the configuration:
 *    Width        = 32
 *    Poly         = 0x04c11db7
 *    XorIn        = 0xffffffff
 *    ReflectIn    = True
 *    XorOut       = 0xffffffff
 *    ReflectOut   = True
 *    Algorithm    = table-driven
 *
 * , and then hacked by Drew Wagner to work in CUDA.
 * NOTE: Note, most of this code was generated by the MIT license
 * version of the pycrc.  Accordingly, this derivative work is also
 * licensed under the MIT license.  This license applies ONLY to this file!
 *
 *****************************************************************************/
#ifndef __CRC_CU__
#define __CRC_CU__

/**
 * The definition of the used algorithm.
 *****************************************************************************/
#define CRC_ALGO_TABLE_DRIVEN 1


/**
 * The type of the CRC values.
 *
 * This type must be big enough to contain at least 32 bits.
 *****************************************************************************/
typedef uint32_t crc_t;


/**
 * Calculate the initial crc value.
 *
 * \return     The initial crc value.
 *****************************************************************************/
__device__ crc_t crc_init(void)
{
    return 0xffffffff;
}

/**
 * Calculate the final crc value.
 *
 * \param crc  The current crc value.
 * \return     The final crc value.
 *****************************************************************************/
__device__ crc_t crc_finalize(crc_t crc)
{
    return crc ^ 0xffffffff;
}

/**
 * (formally) file crc.c
 * Functions and types for CRC checks.
 *
 * Generated on Sun May 15 16:28:42 2011,
 * by pycrc v0.7.7, http://www.tty1.net/pycrc/
 * using the configuration:
 *    Width        = 32
 *    Poly         = 0x04c11db7
 *    XorIn        = 0xffffffff
 *    ReflectIn    = True
 *    XorOut       = 0xffffffff
 *    ReflectOut   = True
 *    Algorithm    = table-driven
 *****************************************************************************/

/**
 * Static table used for the table_driven implementation.
 *****************************************************************************/
__device__ static const crc_t crc_table[16] = {
    0x00000000, 0x1db71064, 0x3b6e20c8, 0x26d930ac,
    0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c,
    0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c,
    0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c
};

/**
 * Reflect all bits of a \a data word of \a data_len bytes.
 *
 * \param data         The data word to be reflected.
 * \param data_len     The width of \a data expressed in number of bits.
 * \return             The reflected data.
 *****************************************************************************/
__device__ crc_t crc_reflect(crc_t data, size_t data_len)
{
    unsigned int i;
    crc_t ret;

    ret = data & 0x01;
    for (i = 1; i < data_len; i++) {
        data >>= 1;
        ret = (ret << 1) | (data & 0x01);
    }
    return ret;
}

/**
 * Update the crc value with new data.
 *
 * \param crc      The current crc value.
 * \param data     Pointer to a buffer of \a data_len bytes.
 * \param data_len Number of bytes in the \a data buffer.
 * \return         The updated crc value.
 *****************************************************************************/
__device__ crc_t crc_update(crc_t crc, const unsigned char *data, size_t data_len)
{
    unsigned int tbl_idx;

    while (data_len--) {
        tbl_idx = crc ^ (*data >> (0 * 4));
        crc = crc_table[tbl_idx & 0x0f] ^ (crc >> 4);
        tbl_idx = crc ^ (*data >> (1 * 4));
        crc = crc_table[tbl_idx & 0x0f] ^ (crc >> 4);

        data++;
    }
    return crc & 0xffffffff;
}

// Note 1: The xor and add versions below will return 0x00000000 if the vector, or array,
// is all zeros.  This can be convenient, but they will NOT detect if zero values move
// around.  This invariance to changes in order is especially true for the add version.

// Note 2:  Calling these introduces thread synchronization!  Be wary of heisenbugs!

// Note 3: The CRC version is the most principled, but is also slowest, and makes zeros arrays less obvious.

__device__ uint32_t vector_checksum_xor(const float* array, int m, uint32_t prevValue=0x00000000)
{
    __syncthreads();
    if(threadIdx.x==0 && blockIdx.x==0)
    {
        uint32_t sum = prevValue;
        uint32_t * array_ptr = (uint32_t*) array;
        for(int i=0; i<m; i++)
            if(array_ptr[i]!=0x00000000)
                sum ^= array_ptr[i];
        return sum;
    } else { return 0xffffffff;}
    __syncthreads();
}
// Coded for m x n column major arrays with column stride lda
__device__ uint32_t array_checksum_xor(const float* A, int m, int n, int lda, uint32_t prevValue=0x00000000)
{
    uint32_t sum = prevValue;
    __syncthreads();
    if(threadIdx.x==0 && blockIdx.x==0)
    {
        for(int i=0; i<n; i++)
            sum = vector_checksum_xor(&A[i*lda], m, sum);
        return sum;
    } else { return 0xffffffff;}
    __syncthreads();
}
__device__ uint32_t vector_checksum_sum(const float* array, int m, uint32_t prevValue=0x00000000)
{
    __syncthreads();
    if(threadIdx.x==0 && blockIdx.x==0)
    {
        uint32_t sum = prevValue;
        uint32_t * array_ptr = (uint32_t*) array;
        for(int i=0; i<m; i++)
            if(array_ptr[i]!=0x00000000)
                sum += array_ptr[i];
        return sum;
    } else { return 0xffffffff;}
    __syncthreads();
}
// Coded for m x n column major arrays with column stride lda
__device__ uint32_t array_checksum_sum(const float* A, int m, int n, int lda, uint32_t prevValue=0x00000000)
{
    uint32_t sum = prevValue;
    __syncthreads();
    if(threadIdx.x==0 && blockIdx.x==0)
    {
        for(int i=0; i<n; i++)
        {
            sum = vector_checksum_sum(&A[i*lda], m, sum);
        }
        return sum;
    } else { return 0xffffffff;}
    __syncthreads();
}
__device__ uint32_t vector_checksum_crc(const float* array, int m, uint32_t sum=0xffffffff)
{
    __syncthreads();
    if(threadIdx.x==0 && blockIdx.x==0)
    {
        const unsigned char * array_ptr = (const unsigned char*) array;
        sum = crc_update(sum, array_ptr, m*sizeof(float));
        sum = crc_finalize(sum);
        return sum;
    } else { return 0xffffffff;}
    __syncthreads();
}
// Coded for m x n column major arrays with column stride lda
__device__ uint32_t array_checksum_crc(const float* A, int m, int n, int lda, uint32_t sum=0xffffffff)
{
    __syncthreads();
    if(threadIdx.x==0 && blockIdx.x==0)
    {
        for(int i=0; i<n; i++)
        {
            const unsigned char * array_ptr = (const unsigned char*) A;
            sum = crc_update(sum, array_ptr, m*sizeof(float));
        }
        sum = crc_finalize(sum);
        return sum;
    } else { return 0xffffffff;}
    __syncthreads();
}

#endif
1 голос
/ 15 мая 2011

Если вы используете числа с плавающей запятой IEEE-754, вы можете привести числа с плавающей точкой к указателю, который затем интерпретируется как указатель типа unsigned int, и суммировать их таким образом, чтобы избежать проблем с округлением с плавающей запятой. Вы в основном в этот момент создаете контрольную сумму для реальных битов, представляющих числа с плавающей запятой, а не сами значения с плавающей запятой.

Так, например:

float array[20] = { /* initialized to some values */ };
unsigned int total = 0;

for (int i=0; i < 20; i++)
{
    float* temp_float_ptr = &array[i];
    unsigned int* temp_uint_ptr = (unsigned int*)temp_float_ptr;
    total += (*temp_uint_ptr);
}

Редактировать: Как уже упоминалось в комментариях, это никак не создает безопасную контрольную сумму ... это очень простая форма суммирования чеков, но, надеюсь, она будет работать для ваших целей отладки.

1 голос
/ 15 мая 2011

Это как раз то, для чего предназначены циклические проверки избыточности. Boost имеет библиотеку CRC , и в Интернете существуют десятки реализаций исходного кода. Вероятно, лучше использовать 16-битную CRC, потому что результат будет легким. Но вам может потребоваться 32-битный CRC, если вы параноидально относитесь к ложным срабатываниям.

0 голосов
/ 18 мая 2011

Если вы хотите вычислить контрольную сумму на GPU, используйте встроенные функции __int_as_float () и __float_as_int () для обработки значений типа float-as-ints. Библиотека Thrust, включенная в CUDA 4.0, упрощает вычисление этой контрольной суммы - вот пример minmax Thrust, портированный для выполнения того, что вы ищете.

#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
#include <thrust/transform_reduce.h>
#include <thrust/functional.h>
#include <thrust/extrema.h>


// sumAsInt contains a float, but implements a binary
// operator that adds them as if they were ints.
template <typename T>
struct sumAsInt
{
    T val;
};

// sumAsInt_unary_op is a functor that initializes a sumAsInt
// with a given value T.
template <typename T>
struct sumAsInt_unary_op : public thrust::unary_function<T,T>
{
    __host__ __device__
        sumAsInt<T> operator()(const T& x) const {
            sumAsInt<T> result;
            result.val = x;
            return result;
        }
};

// sumAsInt_binary_op is a functor that accepts two sumAsInt 
// structs and returns a new sumAsInt that contains the
// sum of the two floats, as if they were integers.
template <typename T>
struct sumAsInt_binary_op : public thrust::binary_function<T,T,T>
{
    __host__ __device__
        sumAsInt<T> operator()(const sumAsInt<T>& x, const sumAsInt<T>& y) const {
            sumAsInt<T> result;
            result.val = __int_as_float(__float_as_int(x.val)+__float_as_int(y.val));
            return result;
        }
};


int main(void)
{
    // initialize host array
    float x[7] = {-1, 2, 7, -3, -4, 5};

    int sum = 0;
    for ( int i = 0; i < sizeof(x)/sizeof(x[0]); i++ ) {
        sum += *((int *) (&x[i]));
    }
    printf( "CPU sum: %d\n", sum );

    // transfer to device
    thrust::device_vector<float> d_x(x, x + 7);

    // setup arguments
    sumAsInt_unary_op<float>  unary_op;
    sumAsInt_binary_op<float> binary_op;
    sumAsInt<float> init = unary_op(0.0f/*d_x[0]*/);  // initialize with first element

    // compute sum-as-int
    sumAsInt<float> result = thrust::transform_reduce(d_x.begin(), d_x.end(), unary_op, init, binary_op);

    printf( "GPU sum: %d\n", *((int *) (&result.val)) );

//    std::cout << result.val << std::endl;

    return 0;
}
0 голосов
/ 16 мая 2011

Надлежащая библиотека CRC, вероятно, является вашей лучшей ставкой, но только для потенциального интереса: вместо того, чтобы XOR биты в ваших значениях, вы можете использовать каждый байт (то есть *(uint8_t*)& реинтерпретация) для индексации в таблицу, скажем, 32- битовые случайные числа, затем XOR эти записи таблицы вместе. Это означает, что один бит изменения значения случайным образом переворачивает биты на выходе. Если нежелательно иметь столько таблиц поиска, сколько может быть байтов, вы можете получить разумные результаты, выполнив круговое смещение битов в уже использованной таблице. Концептуально это намного проще, чем математические алгоритмы хеширования ...

0 голосов
/ 15 мая 2011

РЕДАКТИРОВАНИЕ:
Я считаю, что лучший ответ - это сочетание ответов ТониКа и Джейсона.Используйте 32-битный CRC в буфере после приведения float* к uint32_t*.Получите определение uint32, если его предоставляет ваш компилятор, или введите его самостоятельно, основываясь на вашей платформе (обычно это unsigned long на 32-битных машинах, unsigned int на 64-битных машинах). Вот хорошее объяснение и реализация CRC 1005*

...