libtorch:如何基于 data_ptr 创建一个 gpu 张量?

libtorch : How to create a gpu tensor base on data_ptr?

在 data_ptr 的基础上创建一个 gpu 张量?

  int main{
        auto ten=torch::randn({3,10},torch::kCuda);
        auto p=ten.data_ptr<float>();//I believe "p" is a gpu pointer?
        auto ten2=torch::from_blob(p,{3,10});//ten2's device=cpu,that's the problem
        cout<<ten2;//then I got error:"interrupted by signal 11 SIGSEGV"
    }

有什么建议吗?

我相信你应该声明 ten2 的设备是 GPU,像这样:

  int main{
    auto ten=torch::randn({3,10},torch::kCUDA);
    auto p=ten.data_ptr<float>();//I believe "p" is a gpu pointer?
    auto options = torch::TensorOptions().device(torch::kCUDA);
    auto ten2=torch::from_blob(p,{3,10}, options);
    cout<<ten2;
}

附带说明一下,使用 from_blob 时要小心,生成的张量不会取得底层内存的所有权。因此,如果 ten 超出范围,它将释放它的内存,这也是 ten2 的基础数据。如果您知道 ten 将在 ten2 之前超出范围,您应该调用 clone :

auto ten2=torch::from_blob(p,{3,10}, options).clone();