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

标签 c++ libtorch

基于 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/

相关文章:

c++ - Pytorch Torch.Cholesky忽略异常

pytorch - LibTorch,将 deeplabv3_resnet101 转换为 c++

visual-studio - 在 Windows 上的 C++ 应用程序中使用 PyTorch 模型

c++ - torch C++ : Getting the value of a int tensor by using *. 数据<int>()

c++ - 在 C++ 中覆盖 Cast 运算符

c++ - 使用 (void*) 作为标识符的一种类型

c++ - G++ 错误 ELF CLASS 错误

c++ - 为动态数据结构预分配内存

c++ - 让 Sprite 沿着一个角度行走

c++ - Visual Studio 中的 Libtorch 运算符/语法错误