gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:46:07 28 4
gpt4 key购买 nike

基于 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 时要小心,生成的张量不会取得底层内存的所有权。因此,如果 ten2 超出范围,它将释放它的内存,这也是 ten2 的基础数据。如果您知道 ten2 将在 ten2 之前超出范围,您应该调用 clone :

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

关于c++ - libtorch : How to create a gpu tensor base on data_ptr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65424643/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com