pytorch/android
H1Gdev 6edd49a8e8 [Android]Removed dependency with AppCompat. (#58527)
Summary:
I build using [Bazel](https://bazel.build/).

When I use `pytorch_android` in latest Android app, I get the following error due to dependencies:

```
$ bazel build //app/src/main:app
WARNING: API level 30 specified by android_ndk_repository 'androidndk' is not available. Using latest known API level 29
INFO: Analyzed target //app/src/main:app (0 packages loaded, 0 targets configured).
INFO: Found 1 target...
ERROR: /home/H1Gdev/android-bazel-app/app/src/main/BUILD.bazel:3:15: Merging manifest for //app/src/main:app failed: (Exit 1): ResourceProcessorBusyBox failed: error executing command bazel-out/k8-opt-exec-2B5CBBC6/bin/external/bazel_tools/src/tools/android/java/com/google/devtools/build/android/ResourceProcessorBusyBox --tool MERGE_MANIFEST -- --manifest ... (remaining 11 argument(s) skipped)

Use --sandbox_debug to see verbose messages from the sandbox ResourceProcessorBusyBox failed: error executing command bazel-out/k8-opt-exec-2B5CBBC6/bin/external/bazel_tools/src/tools/android/java/com/google/devtools/build/android/ResourceProcessorBusyBox --tool MERGE_MANIFEST -- --manifest ... (remaining 11 argument(s) skipped)

Use --sandbox_debug to see verbose messages from the sandbox
Error: /home/H1Gdev/.cache/bazel/_bazel_H1Gdev/29e18157a4334967491de4cc9a879dc0/sandbox/linux-sandbox/914/execroot/__main__/app/src/main/AndroidManifest.xml:19:18-86 Error:
	Attribute application@appComponentFactory value=(androidx.core.app.CoreComponentFactory) from [maven//:androidx_core_core] AndroidManifest.xml:19:18-86
	is also present at [maven//:com_android_support_support_compat] AndroidManifest.xml:19:18-91 value=(android.support.v4.app.CoreComponentFactory).
	Suggestion: add 'tools:replace="android:appComponentFactory"' to <application> element at AndroidManifest.xml:5:5-19:19 to override.
May 19, 2021 10:45:03 AM com.google.devtools.build.android.ManifestMergerAction main
SEVERE: Error during merging manifests
com.google.devtools.build.android.AndroidManifestProcessor$ManifestProcessingException: Manifest merger failed : Attribute application@appComponentFactory value=(androidx.core.app.CoreComponentFactory) from [maven//:androidx_core_core] AndroidManifest.xml:19:18-86
	is also present at [maven//:com_android_support_support_compat] AndroidManifest.xml:19:18-91 value=(android.support.v4.app.CoreComponentFactory).
	Suggestion: add 'tools:replace="android:appComponentFactory"' to <application> element at AndroidManifest.xml:5:5-19:19 to override.
	at com.google.devtools.build.android.AndroidManifestProcessor.mergeManifest(AndroidManifestProcessor.java:186)
	at com.google.devtools.build.android.ManifestMergerAction.main(ManifestMergerAction.java:217)
	at com.google.devtools.build.android.ResourceProcessorBusyBox$Tool$5.call(ResourceProcessorBusyBox.java:93)
	at com.google.devtools.build.android.ResourceProcessorBusyBox.processRequest(ResourceProcessorBusyBox.java:233)
	at com.google.devtools.build.android.ResourceProcessorBusyBox.main(ResourceProcessorBusyBox.java:177)

Warning:
See http://g.co/androidstudio/manifest-merger for more information about the manifest merger.
Target //app/src/main:app failed to build
Use --verbose_failures to see the command lines of failed build steps.
INFO: Elapsed time: 2.221s, Critical Path: 1.79s
INFO: 2 processes: 2 internal.
FAILED: Build did NOT complete successfully
```

This is due to conflict between `AndroidX` and `Support Library` on which `pytorch_android_torch` depends.
(In the case of `Gradle`, it is avoided by `android.useAndroidX`.)

I created [Android application](https://github.com/H1Gdev/android-bazel-app) for comparison.

At first, I updated `AppCompat` from `Support Library` to `AndroidX`, but `pytorch_android` and `pytorch_android_torchvision` didn't seem to need any dependencies, so I removed dependencies.

Pull Request resolved: https://github.com/pytorch/pytorch/pull/58527

Reviewed By: xta0

Differential Revision: D28585234

Pulled By: IvanKobzarev

fbshipit-source-id: 78aa6b1525543594ae951a6234dd88a3fdbfc062
2021-05-20 15:49:19 -07:00
..
gradle [andoid] publishing to maven central (#53568) 2021-03-10 10:42:23 -08:00
libs Revert D27469727: [pytorch][PR] [android] fbjni from prefab dependency 0.2.2 2021-03-31 17:21:30 -07:00
pytorch_android [Android]Removed dependency with AppCompat. (#58527) 2021-05-20 15:49:19 -07:00
pytorch_android_torchvision [Android]Removed dependency with AppCompat. (#58527) 2021-05-20 15:49:19 -07:00
test_app AutoNonVariableTypeMode->InferenceMode in OSS. (#56421) 2021-04-19 18:07:41 -07:00
.gitignore Build pytorch_android using Gradle wrapper. (#51067) 2021-02-09 03:09:08 -08:00
build_test_app_custom.sh [pytorch][ci] add custom selective build flow for android build (#40199) 2020-07-02 21:11:01 -07:00
build_test_app.sh [pytorch] consolidate android gradle build scripts (#39999) 2020-06-15 23:55:21 -07:00
build.gradle [Android]Removed dependency with AppCompat. (#58527) 2021-05-20 15:49:19 -07:00
common.sh Build pytorch_android using Gradle wrapper. (#51067) 2021-02-09 03:09:08 -08:00
gradle.properties [android] bump nigtlies version to 1.9.0 (#55076) 2021-03-31 14:37:59 -07:00
gradlew Build pytorch_android using Gradle wrapper. (#51067) 2021-02-09 03:09:08 -08:00
gradlew.bat Build pytorch_android using Gradle wrapper. (#51067) 2021-02-09 03:09:08 -08:00
README.md [Android]Removed dependency with AppCompat. (#58527) 2021-05-20 15:49:19 -07:00
run_tests.sh [pytorch] consolidate android gradle build scripts (#39999) 2020-06-15 23:55:21 -07:00
settings.gradle [lint] Apply whitespace linter to all gradle files 2020-12-22 17:01:51 -08:00

Android

Demo applications and tutorials

Demo applications with code walk-through can be find in this github repo.

Publishing

Release

Release artifacts are published to jcenter:

repositories {
    jcenter()
}

dependencies {
    implementation 'org.pytorch:pytorch_android:1.6.0'
    implementation 'org.pytorch:pytorch_android_torchvision:1.6.0'
}
Nightly

Nightly(snapshots) builds are published every night from master branch to nexus sonatype snapshots repository

To use them repository must be specified explicitly:

repositories {
    maven {
        url "https://oss.sonatype.org/content/repositories/snapshots"
    }
}

dependencies {
    ...
    implementation 'org.pytorch:pytorch_android:1.9.0-SNAPSHOT'
    implementation 'org.pytorch:pytorch_android_torchvision:1.9.0-SNAPSHOT'
    ...
}

The current nightly(snapshots) version is the value of VERSION_NAME in gradle.properties in current folder, at this moment it is 1.8.0-SNAPSHOT.

Building PyTorch Android from Source

In some cases you might want to use a local build of pytorch android, for example you may build custom libtorch binary with another set of operators or to make local changes.

For this you can use ./scripts/build_pytorch_android.sh script.

git clone https://github.com/pytorch/pytorch.git
cd pytorch
git submodule update --init --recursive
sh ./scripts/build_pytorch_android.sh

The workflow contains several steps:

1. Build libtorch for android for all 4 android abis (armeabi-v7a, arm64-v8a, x86, x86_64)

2. Create symbolic links to the results of those builds: android/pytorch_android/src/main/jniLibs/${abi} to the directory with output libraries android/pytorch_android/src/main/cpp/libtorch_include/${abi} to the directory with headers. These directories are used to build libpytorch.so library that will be loaded on android device.

3. And finally run gradle in android/pytorch_android directory with task assembleRelease

Script requires that Android SDK, Android NDK and gradle are installed. They are specified as environment variables:

ANDROID_HOME - path to Android SDK

ANDROID_NDK - path to Android NDK

GRADLE_HOME - path to gradle

After successful build you should see the result as aar file:

$ find pytorch_android/build/ -type f -name *aar
pytorch_android/build/outputs/aar/pytorch_android.aar
pytorch_android_torchvision/build/outputs/aar/pytorch_android.aar

It can be used directly in android projects, as a gradle dependency:

allprojects {
    repositories {
        flatDir {
            dirs 'libs'
        }
    }
}

dependencies {
    implementation(name:'pytorch_android', ext:'aar')
    implementation(name:'pytorch_android_torchvision', ext:'aar')
    ...
    implementation 'com.facebook.soloader:nativeloader:0.8.0'
    implementation 'com.facebook.fbjni:fbjni-java-only:0.0.3'
}

We also have to add all transitive dependencies of our aars. As pytorch_android depends on 'com.facebook.soloader:nativeloader:0.8.0' and 'com.facebook.fbjni:fbjni-java-only:0.0.3', we need to add them. (In case of using maven dependencies they are added automatically from pom.xml).

You can check out test app example that uses aars directly.

Linking to prebuilt libtorch library from gradle dependency

In some cases, you may want to use libtorch from your android native build. You can do it without building libtorch android, using native libraries from PyTorch android gradle dependency. For that, you will need to add the next lines to your gradle build.

android {
...
    configurations {
       extractForNativeBuild
    }
...
    compileOptions {
        externalNativeBuild {
            cmake {
                arguments "-DANDROID_STL=c++_shared"
            }
        }
    }
...
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
}

dependencies {
    extractForNativeBuild('org.pytorch:pytorch_android:1.6.0')
}

task extractAARForNativeBuild {
    doLast {
        configurations.extractForNativeBuild.files.each {
            def file = it.absoluteFile
            copy {
                from zipTree(file)
                into "$buildDir/$file.name"
                include "headers/**"
                include "jni/**"
            }
        }
    }
}

tasks.whenTaskAdded { task ->
  if (task.name.contains('externalNativeBuild')) {
    task.dependsOn(extractAARForNativeBuild)
  }
}

pytorch_android aar contains headers to link in headers folder and native libraries in jni/$ANDROID_ABI/. As PyTorch native libraries use ANDROID_STL - we should use ANDROID_STL=c++_shared to have only one loaded binary of STL.

The added task will unpack them to gradle build directory.

In your native build you can link to them adding these lines to your CMakeLists.txt:

# Relative path of gradle build directory to CMakeLists.txt
set(build_DIR ${CMAKE_SOURCE_DIR}/build)

file(GLOB PYTORCH_INCLUDE_DIRS "${build_DIR}/pytorch_android*.aar/headers")
file(GLOB PYTORCH_LINK_DIRS "${build_DIR}/pytorch_android*.aar/jni/${ANDROID_ABI}")

set(BUILD_SUBDIR ${ANDROID_ABI})
target_include_directories(${PROJECT_NAME} PRIVATE
  ${PYTORCH_INCLUDE_DIRS}
)

find_library(PYTORCH_LIBRARY pytorch_jni
  PATHS ${PYTORCH_LINK_DIRS}
  NO_CMAKE_FIND_ROOT_PATH)

find_library(FBJNI_LIBRARY fbjni
  PATHS ${PYTORCH_LINK_DIRS}
  NO_CMAKE_FIND_ROOT_PATH)

target_link_libraries(${PROJECT_NAME}
  ${PYTORCH_LIBRARY})
  ${FBJNI_LIBRARY})

If your CMakeLists.txt file is located in the same directory as your build.gradle, set(build_DIR ${CMAKE_SOURCE_DIR}/build) should work for you. But if you have another location of it, you may need to change it.

After that, you can use libtorch C++ API from your native code.

#include <string>
#include <ATen/NativeFunctions.h>
#include <torch/script.h>
namespace pytorch_testapp_jni {
namespace {
    struct JITCallGuard {
      c10::InferenceMode guard;
      torch::jit::GraphOptimizerEnabledGuard no_optimizer_guard{false};
    };
}

void loadAndForwardModel(const std::string& modelPath) {
  JITCallGuard guard;
  torch::jit::Module module = torch::jit::load(modelPath);
  module.eval();
  torch::Tensor t = torch::randn({1, 3, 224, 224});
  c10::IValue t_out = module.forward({t});
}
}

To load torchscript model for mobile we need some special setup which is placed in struct JITCallGuard in this example. It may change in future, you can track the latest changes keeping an eye in our pytorch android jni code

Example of linking to libtorch from aar

PyTorch Android API Javadoc

You can find more details about the PyTorch Android API in the Javadoc.