pycuda似乎是不确定的

时间:2012-10-07 12:02:40

标签: cuda pycuda

我和cuda有一个奇怪的问题,

在下面的代码段中,

#include <stdio.h>

#define OUTPUT_SIZE         26

typedef $PRECISION REAL;

extern "C"    
{
    __global__ void test_coeff ( REAL* results )
    {
        int id      = blockDim.x * blockIdx.x + threadIdx.x;

        int out_index  = OUTPUT_SIZE * id;
        for (int i=0; i<OUTPUT_SIZE; i++)
        {               
            results[out_index+i]=id;
            printf("q");
        }
    }
}

当我编译并运行代码(通过pycuda)时,它按预期工作。当我删除printf时,结果很奇怪 - 大部分数组都是正确填充的,但有些似乎是完全随机的。

这是完整的python代码:

import numpy as np
import string

#pycuda stuff
import pycuda.driver as drv
import pycuda.autoinit

from pycuda.compiler import SourceModule

class MC:

    cudacodetemplate = """
    #include <stdio.h>

    #define OUTPUT_SIZE         26

    typedef $PRECISION REAL;

    extern "C"    
    {
        __global__ void test_coeff ( REAL* results )
        {
            int id      = blockDim.x * blockIdx.x + threadIdx.x;

            int out_index  = OUTPUT_SIZE * id;
            for (int i=0; i<OUTPUT_SIZE; i++)
            {               
                results[out_index+i]=id;
                //printf("q");
            }
        }
    }
    """

    def __init__(self, size, prec = np.float32):
        #800 meg should be enough . . .
        drv.limit.MALLOC_HEAP_SIZE = 1024*1024*800

        self.size       = size
        self.prec       = prec
        template        = string.Template(MC.cudacodetemplate)
        self.cudacode   = template.substitute( PRECISION = 'float' if prec==np.float32 else 'double')

        #self.module     = pycuda.compiler.SourceModule(self.cudacode, no_extern_c=True, options=['--ptxas-options=-v'])
        self.module     = SourceModule(self.cudacode, no_extern_c=True)

    def test(self, out_size):
        #try to precalc the co-efficients for just the elements of the vector that changes
        test  = np.zeros( ( 128, out_size*(2**self.size) ), dtype=self.prec )
        test2 = np.zeros( ( 128, out_size*(2**self.size) ), dtype=self.prec )

        test_coeff =  self.module.get_function ('test_coeff')
        test_coeff( drv.Out(test), block=(2**self.size,1,1), grid=( 128, 1 ) )
        test_coeff( drv.Out(test2), block=(2**self.size,1,1), grid=( 128, 1 ) )
        error = (test-test2)
        return error

if __name__ == '__main__':
    p1  = MC ( 5, np.float64 )
    err = p1.test(26)
    print err.max()
    print err.min()

基本上,使用内核中的printf,错误为0 - 没有它会打印一些随机错误(在我的机器上大约2452(最大)和-2583(小时))

我不知道为什么。

我使用geforce 570在pycuda 2012.2(Windows 7 64位)上运行cuda 4.2。

感谢。

1 个答案:

答案 0 :(得分:1)

这很可能是由于编译器优化造成的。您将内存块OUTPUT_SIZE的长度设置为id的循环常量值。根据我的经验,编译器会将其优化为memcpy或whathaveyou ,除非循环中还有其他内容 - 即你的print语句。此外,如果您不使用该内存块,编译器可能会优化整个循环。尝试摆弄优化级别,看看你是否有不同的结果。