Unverified Commit 793b647c authored by bmanga's avatar bmanga Committed by GitHub
Browse files

Add hello world example for C++ torchvision (#2003)

* Add hello world example for C++ torchvision

* README updates and mention the hello_world example
parent 91b44590
......@@ -82,8 +82,10 @@ Once installed, the library can be accessed in cmake (after properly configuring
find_package(TorchVision REQUIRED)
target_link_libraries(my-target PUBLIC TorchVision::TorchVision)
The ``TorchVision`` package will also automatically look for the ``Torch`` and ``pybind11`` packages and add them as dependencies to ``my-target``,
so make sure that they are also available to cmake via the ``CMAKE_PREFIX_PATH``.
The ``TorchVision`` package will also automatically look for the ``Torch`` package and add it as a dependency to ``my-target``,
so make sure that it is also available to cmake via the ``CMAKE_PREFIX_PATH``.
For an example setup, take a look at ``examples/cpp/hello_world``.
Documentation
=============
......
cmake_minimum_required(VERSION 3.10)
project(hello-world)
# The first thing do is to tell cmake to find the TorchVision library.
# The package pulls in all the necessary torch libraries,
# so there is no need to also add `find_package(Torch)` here.
find_package(TorchVision REQUIRED)
add_executable(hello-world main.cpp)
# We now need to link the TorchVision library to our executable.
# We can do that by using the TorchVision::TorchVision target,
# which also adds all the necessary torch dependencies.
target_link_libraries(hello-world TorchVision::TorchVision)
Hello World!
============
This is a minimal example of getting TorchVision to work in C++ with CMake.
In order to successfully compile this example, make sure you have both ``LibTorch`` and
``TorchVision`` installed.
Once both dependencies are sorted, we can start the CMake fun:
1) Create a ``build`` directory inside the current one.
2) from within the ``build`` directory, run the following commands:
- | ``cmake -DCMAKE_PREFIX_PATH="<PATH_TO_LIBTORCH>;<PATH_TO_TORCHVISION>" ..``
| where ``<PATH_TO_LIBTORCH>`` and ``<PATH_TO_TORCHVISION>`` are the paths to the libtorch and torchvision installations.
- ``cmake --build .``
| That's it!
| You should now have a ``hello-world`` executable in your ``build`` folder.
Running it will output a (fairly long) tensor of random values to your terminal.
\ No newline at end of file
#include <iostream>
#include <torchvision/models/resnet.h>
int main()
{
auto model = vision::models::ResNet18();
model->eval();
// Create a random input tensor and run it through the model.
auto in = torch::rand({1, 3, 10, 10});
auto out = model->forward(in);
std::cout << out;
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment