重新播种cuRAND主机API

时间:2017-02-06 16:15:21

标签: random cuda

是否可以重新播种cuRAND主机API RNG?

我发现如果我使用相同的种子创建,分配和生成主机API RNG的两个独立实例,它们会产生与预期完全相同的数字序列。

但是,如果我创建一个实例,分配,播种并生成一系列数字,然后再次使用相同的种子调用curandSetPseudoRandomGeneratorSeed(),生成新的数字,它们是不同的序列。我希望它们能够再次重置为相同的序列。

1 个答案:

答案 0 :(得分:2)

重置种子不会重置序列。尝试使用curandSetGeneratorOffset()

这是一个有用的示例(源自主机API示例here):

$ cat t85.cu
/* * This program uses the host CURAND API to generate 100 * pseudorandom floats. */
#include <stdio.h>
#include <stdlib.h>
#include <cuda.h>
#include <curand.h>
#define CUDA_CALL(x) do { if((x)!=cudaSuccess) { \
 printf("Error at %s:%d\n",__FILE__,__LINE__);\
 return EXIT_FAILURE;}} while(0)
#define CURAND_CALL(x) do { if((x)!=CURAND_STATUS_SUCCESS) { \
 printf("Error at %s:%d\n",__FILE__,__LINE__);\
 return EXIT_FAILURE;}} while(0)
int main(int argc, char *argv[]) {
  size_t n = 10;
  size_t i;
  curandGenerator_t gen;
  float *devData, *hostData; /* Allocate n floats on host */
  hostData = (float *)calloc(n, sizeof(float)); /* Allocate n floats on device */
  CUDA_CALL(cudaMalloc((void **)&devData, n*sizeof(float))); /* Create pseudo-random number generator */
  CURAND_CALL(curandCreateGenerator(&gen, CURAND_RNG_PSEUDO_DEFAULT)); /* Set seed */
  CURAND_CALL(curandSetPseudoRandomGeneratorSeed(gen, 1234ULL)); /* Generate n floats on device */
  CURAND_CALL(curandGenerateUniform(gen, devData, n)); /* Copy device memory to host */
  CUDA_CALL(cudaMemcpy(hostData, devData, n * sizeof(float), cudaMemcpyDeviceToHost)); /* Show result */
  for(i = 0; i < n; i++) { printf("%1.4f ", hostData[i]); }
  printf("\n");
  CURAND_CALL(curandSetGeneratorOffset(gen, 0)); /* Copy device memory to host */
  CURAND_CALL(curandGenerateUniform(gen, devData, n)); /* Copy device memory to host */
  CUDA_CALL(cudaMemcpy(hostData, devData, n * sizeof(float), cudaMemcpyDeviceToHost)); /* Show result */
  for(i = 0; i < n; i++) { printf("%1.4f ", hostData[i]); }
  printf("\n");

   /* Cleanup */
  CURAND_CALL(curandDestroyGenerator(gen));
  CUDA_CALL(cudaFree(devData));
  free(hostData);
  return EXIT_SUCCESS;
}
$ nvcc -arch=sm_61 -o t85 t85.cu -lcurand
$ ./t85
0.1455 0.8202 0.5504 0.2948 0.9147 0.8690 0.3219 0.7829 0.0113 0.2855
0.1455 0.8202 0.5504 0.2948 0.9147 0.8690 0.3219 0.7829 0.0113 0.2855
$