Torch::nn in iOS C++ is unavailable

I started from the HelloWorld example on iOS and everything worked until i tried to add nn functionality like

auto loss = torch::nn::MSELoss(); // Error: No member named 'nn' in namespace 'torch'

Is there a way to include torch::nn and torch::nn::functional API in iOS?

Hi @dnnagy the APIs under nn namespace are being used to support eager mode in Python. Since we’re using torchscript on mobile, we didn’t compile that part of code in our binary. However, I think you can manually enable it by changing the NO_API value to OFF in the root CMakeLists.txt and rebuild the libraries. However, I personally haven’t tried, so not sure if they’ll work or not.

Hi @xta0, I realize this conversation is a little old, but am having a similar issue. I tried your suggestion of changing the NO_API value to OFF but when i do I the build fails with the following:

#> BUILD_PYTORCH_MOBILE=1 IOS_PLATFORM=SIMULATOR ./scripts/build_ios.sh

pytorch/csrc/api/src/nn/module.cpp:5:10: fatal error: 'torch/csrc/autograd/generated/VariableType.h' file not found
#include <torch/csrc/autograd/generated/VariableType.h>

Seems someone has had and resolved this issue… here but the resolution was unclear.

Technically I only need torch::nn::functional::pad() might there be a way to include just this limited requirement?

@xta0 I was able to build torchlib with NO_API value to OFF, I also had to set BUILD_MOBILE_AUTOGRAD to ON to resolve the missing VariableTypes.h issue above.

However, the nn namespace still does not appear to be included

I had a very similar issue. I wanted to do something like this on iOS Libtorch-Lite:

auto inputTensor = torch::nn::functional::pad(inputTensor, padOptions);

So just copied constant_pad_nd from https://github.com/pytorch/pytorch/blob/1317dbf17660232d16d40efcbb134d3540446008/aten/src/ATen/native/PadNd.cpp#L29 and adjusted the at:: namespace.

This avoids the hassle compiling your custom iOS build.