【问题标题】:How to give a batch of frames to the model in pytorch c++ api?如何在pytorch c++ api中为模型提供一批帧?
【发布时间】:2019-07-06 23:43:27
【问题描述】:

在 PyTorch C++ Frontend api 的帮助下,我编写了一个代码来在 C++ 中加载 pytorch 模型。我想通过使用module->forward(batch_frames) 为 C++ 中的预训练模型提供一批帧。但它可以通过单个输入转发。
如何给模型提供一批输入?

我要给批处理的部分代码如下所示:

 cv::Mat frame;
 vector<torch::jit::IValue> frame_batch;

 // do some pre-processes on each frame and then add it to the frame_batch

 //forward through the batch frames
 torch::Tensor output = module->forward(frame_batch).toTensor();

【问题讨论】:

  • 你有什么解决办法吗?我在discuss.pytorch.org/t/… 也问过同样的问题
  • 还没有!我以为问题会通过更新 libtorch 来解决,但什么也没发生。感谢您分享您的问题。 @马库斯
  • 我的问题在上面的链接中得到了回答。

标签: c++ pytorch torch


【解决方案1】:

最后,我在 c++ 中使用了一个函数来连接图像并制作一批图像。然后将批次转换为 torch::tensor 并使用批次输入模型。部分代码如下:

// cat 2 or more images to make a batch
cv::Mat batch_image;
cv::vconcat(image_2, images_1, batch_image);

// do some pre-process on image
auto input_tensor_batch = torch::from_blob(batch_image.data, {size_of_batch, image_height, image_width, 3});
input_tensor_batch = input_tensor_batch.permute({0, 3, 1, 2});

//forward through the batch frames
 torch::Tensor output = module->forward({input_tensor_batch}).toTensor();

注意将 { } 放在前向传递函数中!

【讨论】:

  • 如果您还可以添加 vconcat 实际上是 opencv 中的 ``` cv::vconcat``` 会更好。
  • 已编辑!谢谢@Rika。
【解决方案2】:

您可以使用多种方式在 libtorch 中创建一批张量。
以下是其中一种方式:
使用 Torch::TensorList:
由于torch::TensorListArrayRef,因此您不能直接向其添加任何张量,因此首先创建一个张量向量,然后使用该向量创建您的TensorList

// two already processed tensor!
auto tensor1 = torch::randn({ 1, 3, 32, 32 });
auto tensor2 = torch::randn({ 1, 3, 32, 32 });
// using a tensor list
std::vector<torch::Tensor> tensor_vec{ tensor1, tensor2 };
torch::TensorList tensor_list{ tensor_vec};

auto batch_of_tensors = torch::cat(tensor_lst);
auto out = module->forward({batch_of_tensors}).toTensor();

或者你可以这样做:

auto batch_of_tensors = torch::cat({ tensor_vec});

auto batch_of_tensors = torch::cat({ tensor1, tensor2});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-12
    • 2019-08-14
    • 2018-08-23
    • 2023-04-07
    • 1970-01-01
    • 2022-07-21
    • 2014-09-15
    • 2016-01-29
    相关资源
    最近更新 更多