Friday, October 26, 2018

Build AI Camera App (Caffe2)

AI Camera app from Facebook is an example app that shows how to build Caffe2 on Android platform. Unfortunately, you will find that it does not work with the latest Android Studio. Here is how to get it to work.

One of the main reasons that it does not build is because starting with NDK r18b, GCC has been removed. The easiest way to get it working is to download older version, say r17c, and edit local.properties file and change ndk.dir to r17c folder.

Other than that, a couple of minor changes. In gradle.build file, update gradle version to 3.2.1 as below:

classpath 'com.android.tools.build:gradle:3.0.1'
classpath 'com.android.tools.build:gradle:3.2.1'


Lastly, edit gradle/wrapper/gradle-wrapper.properties file and change gradle tool version to 4.6 as below:

distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip


After all these changes, the app should successfully build! Happy hacking!

Build Caffe2 using Android NDK

Starting with Google's Android NDK r18b, gcc has been removed (history). That is, only one has to use clang as the toolchain. This may cause some problems if you do not set its toolchain as clang.

In fact, when you try to build Caffe2 for Android with android-ndk, it will fail, complaining

GCC is no longer supported.  See
  https://android.googlesource.com/platform/ndk/+/master/docs/ClangMigration.md.

The solution is to simply edit pytorch/scripts/build_android.sh file, replacing gcc to clang for ANDROID_TOOLCHAIN variable, as shown below:

CMAKE_ARGS+=("-DANDROID_TOOLCHAIN=gcc")
CMAKE_ARGS+=("-DANDROID_TOOLCHAIN=clang")

Happy hacking!

Building Caffe2 and Pytorch for Ubuntu 18.04 LTS

I am trying to export my pytorch model to Android devices. It seems that using onnx and caffe2 is the easiest way to do so. Here, I will describe the steps to build and install pytorch & caffe2 for Ubuntu 18.04 LTS.

Basically, one has to follow the instructions here, but I had some problems building. The easiest way to build is to disable all unnecessary features. For example, since I am only going to port it to caffe2 and do not intend to use GPU for running pytorch model (at least for this python environment), I can set some flags:
$ export NO_CUDA=1
$ export NO_DISTRIBUTED=1

Also, I will build pytorch and caffe2 together. Hence, I set the flag
$ export FULL_CAFFE2=1

With these environment variables set, I successfully built and installed caffe2 and pytorch from the source, following the official instruction.

Happy hacking!