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