PyTorch C++ ---C++17重编libtorch

libtorch (PyTorch C++)根据系统(Win/Mac/Linux)和GPU/CUDA(version) 选择install 之后就可通过Cmake find_package 直接使用,但是默认编译libtorch 为 C++14,如果和其他 C++17 编译得到的库共同链接到项目,就可能产生一系列问题:如下图,原因是先链接 C++14 编译的torch,会将编译设为 C++14,再去链接C++17的库,就无法识别C17加入标准库的内容,编译报错。实际上先链接C++17 的其他库,再链接 torch 可解决这个问题。但是想从根源解决链接问题需要手动使用C++17重编torch.

/data/code/ml-platform-thirdparty/seastar/include/seastar/util/std-compat.hh:154:23: error: ‘optional’ in namespace ‘std’ does not name a template type
 using optional = std::optional<T>;
                       ^~~~~~~~

C++17 编译 libtorch 步骤:

CentOS 7 build
  1. 安装 devtoolset-9,并设置CC、CXX变量
    a. sudo yum install centos-release-scl
    b. sudo yum-config-manager --enable rhel-server-rhscl-9-rpms
    c. sudo yum install devtoolset-9
  2. 替换所有CMakeLists.txt、*.cmake 中的 CXX_STANDARD 14 为 17
  3. 修改 caffe2/onnx/helper.h 中的 MakeTensor 接口,去掉最后一个参数的引用,
否则会出现 undefined reference
  4. cmake .. -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo \
                       -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
                       -DCMAKE_INSTALL_PREFIX=/data/code/ml-platform-thirdparty/libtorch \
                       -DUSE_NCCL=OFF -DONNX_ML=OFF -DUSE_DISTRIBUTED=OFF
  5. ninja
以下是使用C++libtorch实现类似于pytorch的ImageFolder方法的示例代码: ``` #include <torch/torch.h> #include <opencv2/opencv.hpp> class ImageFolderDataset : public torch::data::datasets::Dataset<ImageFolderDataset> { public: ImageFolderDataset(const std::string& root_dir, const std::string& extensions = ".jpg") : root_dir_(root_dir), extensions_(extensions) { // find all image files in the root directory for (auto& dir_entry : std::filesystem::directory_iterator(root_dir)) { auto path = dir_entry.path(); if (std::filesystem::is_regular_file(path) && is_image_file(path)) { image_paths_.push_back(path); } } } // get the i-th example in the dataset torch::data::Example<> get(size_t index) override { // load the image and convert to tensor auto image = cv::imread(image_paths_[index].string()); cv::cvtColor(image, image, cv::COLOR_BGR2RGB); // convert from BGR to RGB torch::Tensor tensor_image = torch::from_blob(image.data, { image.rows, image.cols, 3 }, torch::kByte).permute({ 2, 0, 1 }).toType(torch::kFloat) / 255.0; // get the label from the directory name auto label_path = image_paths_[index].parent_path(); int label = std::distance(std::filesystem::directory_iterator(root_dir_), std::find_if(std::filesystem::directory_iterator(root_dir_), std::filesystem::directory_iterator(), [&label_path](const auto& dir_entry) { return dir_entry.path() == label_path; })); return { tensor_image.clone(), torch::tensor(label) }; } // return the number of examples in the dataset torch::optional<size_t> size() const override { return image_paths_.size(); } private: std::vector<std::filesystem::path> image_paths_; std::string root_dir_; std::string extensions_; bool is_image_file(const std::filesystem::path& path) const { auto extension = path.extension().string(); return extensions_.empty() || std::find(extensions_.begin(), extensions_.end(), extension) != extensions_.end(); } }; int main() { // create the dataset and dataloader std::string root_dir = "/path/to/dataset"; ImageFolderDataset dataset(root_dir); auto data_loader = torch::data::make_data_loader<torch::data::samplers::SequentialSampler>(dataset, torch::data::DataLoaderOptions().batch_size(32)); // train the model using the dataset // ... } ``` 在上面的代码中,`ImageFolderDataset`类继承了`torch::data::datasets::Dataset`,并实现了`get()`和`size()`方法,以便能够使用`torch::data::make_data_loader()`函数创建一个数据加载器。在`get()`方法中,我们加载了图像并将其转换为张量,并从目录名称中获取标签。在`size()`方法中,我们返回数据集中的示例数。 注意,这里我们使用了OpenCV库来加载和处理图像。如果您想使用其他库,可以相应地修改代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值