 __global__ void NAME(curandStateMtgp32 *state, int size, float *result, ARG1, ARG2)  \
 {                                                                                    \
   int idx = blockIdx.x * BLOCK_SIZE + threadIdx.x;                                   \
-  for (int i = idx; i < size; i += BLOCK_SIZE * MAX_NUM_BLOCKS) {                    \
+  int rounded_size = DIVUP(size, BLOCK_SIZE) * BLOCK_SIZE;                           \
+  for (int i = idx; i < rounded_size; i += BLOCK_SIZE * MAX_NUM_BLOCKS) {            \
     float x = CURAND_FUNC(&state[blockIdx.x]);                                       \
-    x = TRANSFORM;                                                                   \
-    result[i] = x;                                                                   \
+    if (i < size) {                                                                  \
+      x = TRANSFORM;                                                                 \
+      result[i] = x;                                                                 \
+    }                                                                                \
   }                                                                                  \
 }
 

__global__ void NAME(curandStateMtgp32 *state, int size, float *result, ARG1)  \
{                                                                              \
  int idx = blockIdx.x * BLOCK_SIZE + threadIdx.x;                             \
  for (int i = idx; i < size; i += BLOCK_SIZE * MAX_NUM_BLOCKS) {              \
    float x = CURAND_FUNC(&state[blockIdx.x]);                                 \
    x = TRANSFORM;                                                             \
    result[i] = x;                                                             \
  }                                                                            \
}


/* Creates a new generator state given the seed. */
__host__ void createGeneratorState(Generator* gen, unsigned long seed)
{
  if (curandMakeMTGP32Constants(mtgp32dc_params_fast_11213, gen->kernel_params) != CURAND_STATUS_SUCCESS)
  {
    THError("Creating MTGP constants failed.");
  }
  if (curandMakeMTGP32KernelState(gen->gen_states, mtgp32dc_params_fast_11213,
                                  gen->kernel_params, MAX_NUM_BLOCKS, seed) != CURAND_STATUS_SUCCESS)
  {
