替代错误:“参数0的尺寸无效”

问题描述 投票:1回答:1

将下面的示例转换为gfor循环。我遇到类型为“参数0的无效维”的错误,下面是完整的错误消息。但是,发生错误,然后函数运行,然后出现相同的错误。此模式重复。我很困惑,想知道这个错误是否与系统有关。

完整错误消息:

 Error in random_shuffle(theta, 5, 1) : 
 ArrayFire Exception (Invalid input size:203):
In function af_err af_assign_seq(af_array *, const af_array, const unsigned int, const af_seq *, const af_array)
In file src/api/c/assign.cpp:168
Invalid dimension for argument 0
Expected: (outDims.ndims() >= inDims.ndims())

第二个问题,使用gfor循环时,种子无法通过输入参数进行更改。

#include "RcppArrayFire.h"

using namespace Rcpp;
using namespace RcppArrayFire;

// [[Rcpp::export]]
af::array random_shuffle(const RcppArrayFire::typed_array<f64> theta, int counts, int seed){

  const int theta_size = theta.dims()[0];
  af::array out(counts, theta_size, f64);
  af::array seed_seq = af::seq(seed, seed+counts);

// for(int f = 0; f < counts; f++){
gfor ( af::seq f, counts-1 ){

  af::randomEngine engine;
  engine.setSeed(af::sum<double>(seed_seq(f)));

  af::array index_shuffle(1, u16);

  af::array temp_rand(1, f64);
  af::array temp_end(1, f64);

  af::array shuffled = theta;

// implementation of the Knuth-Fisher-Yates shuffle algo
  for(int i = theta_size-1; i > 1; i --){

    index_shuffle = af::round(af::randu(1, u16, engine)/(65536/(i+1)));
    temp_rand = shuffled(index_shuffle);
    temp_end = shuffled(i);
    shuffled(index_shuffle) = temp_end;
    shuffled(i) = temp_rand;
    }

  out(f, af::span) = shuffled;
  }
  return out;
}


/*** R
theta <- 10:20
random_shuffle(theta, 5, 1)
random_shuffle(theta, 5, 2)
*/
c++ rcpp arrayfire
1个回答
1
投票

您为什么要并行使用多个RNG引擎?确实没有必要这样做。通常,仅使用全局RNG引擎就足够了。只设置一次该引擎的种子也应该足够。您可以使用RcppArrayFire::arrayfire_set_seed从R中进行此操作。此外,在gfor循环中生成随机数不能像人们期望的那样工作,请参阅http://arrayfire.org/docs/page_gfor.htm

无论如何,我不是编写高效GPU算法的专家,这就是为什么我喜欢使用ArrayFire之类的库中实现的方法的原因。不幸的是,ArrayFire没有随机播放算法,但是相应的问题有一个nice implementation,可以针对您的情况进行多次随机播放:

// [[Rcpp::depends(RcppArrayFire)]]
#include "RcppArrayFire.h"

// [[Rcpp::export]]
af::array random_shuffle(const RcppArrayFire::typed_array<f64> theta, int counts, int seed) {
    int len = theta.dims(0);
    af::setSeed(seed);
    af::array tmp = af::randu(counts, len, 1);
    af::array val, idx;
    af::sort(val, idx, tmp, 1);
    af::array shuffled = theta(idx);
    return af::moddims(shuffled, counts, len);
}

顺便说一句,根据以后的用法,将不同的样本排列在列而不是行中可能更有意义,因为R和AF都使用列主布局。

© www.soinside.com 2019 - 2024. All rights reserved.