libtorch:如何在data_ptr的基础上创建gpu张量



基于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();

最新更新