Skip to content

Commit ff7ee24

Browse files
YUNQIUGUOskottmckayrachguoEmma1807
authored
Updated phi-3 mobile android example (#420)
* updated phi-3 mobile android example * add model downloading step from url * remove generated files * fix the update * update * minor update * Update mobile/examples/phi-3/android/.gitignore Co-authored-by: Scott McKay <[email protected]> * Update mobile/examples/phi-3/android/.gitignore Co-authored-by: Scott McKay <[email protected]> * Update mobile/examples/phi-3/android/README.md Co-authored-by: Scott McKay <[email protected]> * Update mobile/examples/phi-3/android/app/src/main/cpp/native-lib.cpp Co-authored-by: Scott McKay <[email protected]> * Update mobile/examples/phi-3/android/app/src/main/java/ai/onnxruntime/genai/demo/GenAIWrapper.java Co-authored-by: Scott McKay <[email protected]> * Update mobile/examples/phi-3/android/app/src/main/java/ai/onnxruntime/genai/demo/GenAIWrapper.java Co-authored-by: Scott McKay <[email protected]> * Update mobile/examples/phi-3/android/app/src/main/java/ai/onnxruntime/genai/demo/GenAIWrapper.java Co-authored-by: Scott McKay <[email protected]> * apply pr suggestions * minor update * apply pr suggestions * update and fix --------- Co-authored-by: Scott McKay <[email protected]> Co-authored-by: rachguo <[email protected]> Co-authored-by: Emma <[email protected]>
1 parent 8fcc97e commit ff7ee24

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

60 files changed

+1633
-0
lines changed

Diff for: mobile/examples/phi-3/android/.gitignore

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
*.iml
2+
.gradle
3+
.idea
4+
.DS_Store
5+
build
6+
/captures
7+
.externalNativeBuild
8+
.cxx
9+
local.properties
10+

Diff for: mobile/examples/phi-3/android/README.md

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# ONNX Runtime Mobile Phi-3 Android sample application with ORT GenAI library support
2+
3+
## Overview
4+
5+
This is a basic [Phi-3](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct-onnx) example application for [ONNX Runtime](https://github.com/microsoft/onnxruntime) on Android with [Ort-GenAI](https://github.com/microsoft/onnxruntime-genai) support for running generative AI models. This app demonstrates the usage of phi-3 model in a simple question answering chatbot mode.
6+
7+
### Model
8+
The model used here is from the source: [HuggingFace](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct-onnx#phi-3-mini-4k-instruct-onnx-models)
9+
and optimized for int4 CPU and Mobile usage.
10+
11+
### Requirements
12+
- Android Studio Giraffe | 2022.3.1 or later (installed on Mac/Windows/Linux)
13+
- Android SDK 29+
14+
- Android NDK r22+
15+
- An Android device or an Android Emulator
16+
17+
## Build And Run
18+
19+
### Step 1: Clone the ONNX runtime mobile examples source code
20+
21+
Clone this repository to get the sample application.
22+
23+
`[email protected]:microsoft/onnxruntime-inference-examples.git`
24+
25+
### [Optional] Step 2: Prepare the model
26+
27+
The current set up supports downloading Phi-3-mini model directly from Huggingface repo to the android device folder. However, it takes time since the model data is >2.5G.
28+
29+
You can also follow this link to download **Phi-3-mini**: https://huggingface.co/microsoft/Phi-3-mini-4k-instruct-onnx/tree/main/cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4
30+
and manually copy to the android device file directory following the below instructions:
31+
32+
#### Steps for manual copying models to android device directory:
33+
From Android Studio:
34+
- create (if necessary) and run your emulator/device
35+
- make sure it has at least 8GB of internal storage
36+
- debug/run the app so it's deployed to the device and creates it's `files` directory
37+
- expected to be `/data/data/ai.onnxruntime.genai.demo/files`
38+
- this is the path returned by `getFilesDir()`
39+
- Open Device Explorer in Android Studio
40+
- Navigate to `/data/data/ai.onnxruntime.genai.demo/files`
41+
- adjust as needed if the value returned by getFilesDir() differs for your emulator or device
42+
- copy the whole [phi-3](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct-onnx/tree/main/cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4) model folder to the `files` directory
43+
44+
### Step 3: Connect Android Device and Run the app
45+
Connect your Android Device to your computer or select the Android Emulator in Android Studio Device manager.
46+
47+
Then select `Run -> Run app` and this will prompt the app to be built and installed on your device or emulator.
48+
49+
Now you can try giving some sample prompt questions and test the chatbot android app by clicking the ">" action button.
50+
51+
#
52+
Here are some sample example screenshots of the app.
53+
54+
<img width=20% src="images/Local_LLM_1.jpg" alt="App Screenshot 1" />
55+
56+
<img width=20% src="images/Local_LLM_2.jpg" alt="App Screenshot 2" />
57+
58+
<img width=20% src="images/Local_LLM_3.jpg" alt="App Screenshot 3" />
59+

Diff for: mobile/examples/phi-3/android/app/.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
/build

Diff for: mobile/examples/phi-3/android/app/build.gradle.kts

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
plugins {
2+
id("com.android.application")
3+
}
4+
5+
android {
6+
namespace = "ai.onnxruntime.genai.demo"
7+
compileSdk = 33
8+
9+
defaultConfig {
10+
applicationId = "ai.onnxruntime.genai.demo"
11+
minSdk = 27
12+
targetSdk = 33
13+
versionCode = 1
14+
versionName = "1.0"
15+
16+
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
17+
externalNativeBuild {
18+
cmake {
19+
cppFlags += "-std=c++17"
20+
}
21+
}
22+
23+
ndk {
24+
//noinspection ChromeOsAbiSupport
25+
abiFilters += listOf("arm64-v8a", "x86_64")
26+
}
27+
}
28+
29+
buildTypes {
30+
release {
31+
isMinifyEnabled = false
32+
proguardFiles(
33+
getDefaultProguardFile("proguard-android-optimize.txt"),
34+
"proguard-rules.pro"
35+
)
36+
}
37+
}
38+
39+
compileOptions {
40+
sourceCompatibility = JavaVersion.VERSION_1_8
41+
targetCompatibility = JavaVersion.VERSION_1_8
42+
}
43+
44+
externalNativeBuild {
45+
cmake {
46+
path = file("src/main/cpp/CMakeLists.txt")
47+
version = "3.22.1"
48+
}
49+
}
50+
buildFeatures {
51+
viewBinding = true
52+
}
53+
}
54+
55+
dependencies {
56+
57+
implementation("androidx.appcompat:appcompat:1.6.1")
58+
implementation("com.google.android.material:material:1.9.0")
59+
implementation("androidx.constraintlayout:constraintlayout:2.1.4")
60+
testImplementation("junit:junit:4.13.2")
61+
androidTestImplementation("androidx.test.ext:junit:1.1.5")
62+
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
63+
}

Diff for: mobile/examples/phi-3/android/app/proguard-rules.pro

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Add project specific ProGuard rules here.
2+
# You can control the set of applied configuration files using the
3+
# proguardFiles setting in build.gradle.
4+
#
5+
# For more details, see
6+
# http://developer.android.com/guide/developing/tools/proguard.html
7+
8+
# If your project uses WebView with JS, uncomment the following
9+
# and specify the fully qualified class name to the JavaScript interface
10+
# class:
11+
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12+
# public *;
13+
#}
14+
15+
# Uncomment this to preserve the line number information for
16+
# debugging stack traces.
17+
#-keepattributes SourceFile,LineNumberTable
18+
19+
# If you keep the line number information, uncomment this to
20+
# hide the original source file name.
21+
#-renamesourcefileattribute SourceFile
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package ai.onnxruntime.genai.demo;
2+
3+
import android.content.Context;
4+
5+
import androidx.test.platform.app.InstrumentationRegistry;
6+
import androidx.test.ext.junit.runners.AndroidJUnit4;
7+
8+
import org.junit.Test;
9+
import org.junit.runner.RunWith;
10+
11+
import static org.junit.Assert.*;
12+
13+
/**
14+
* Instrumented test, which will execute on an Android device.
15+
*
16+
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
17+
*/
18+
@RunWith(AndroidJUnit4.class)
19+
public class ExampleInstrumentedTest {
20+
@Test
21+
public void useAppContext() {
22+
// Context of the app under test.
23+
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
24+
assertEquals("ai.onnxruntime.genai.demo", appContext.getPackageName());
25+
}
26+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
3+
xmlns:tools="http://schemas.android.com/tools">
4+
5+
<uses-permission android:name="android.permission.INTERNET" />
6+
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
7+
8+
<application
9+
android:allowBackup="true"
10+
android:dataExtractionRules="@xml/data_extraction_rules"
11+
android:fullBackupContent="@xml/backup_rules"
12+
android:icon="@mipmap/ic_launcher"
13+
android:label="@string/app_name"
14+
android:roundIcon="@mipmap/ic_launcher_round"
15+
android:supportsRtl="true"
16+
android:theme="@style/Theme.ORTGenAIDemo"
17+
tools:targetApi="31">
18+
<activity
19+
android:name=".MainActivity"
20+
android:exported="true">
21+
<intent-filter>
22+
<action android:name="android.intent.action.MAIN" />
23+
24+
<category android:name="android.intent.category.LAUNCHER" />
25+
</intent-filter>
26+
</activity>
27+
</application>
28+
29+
</manifest>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# For more information about using CMake with Android Studio, read the
2+
# documentation: https://d.android.com/studio/projects/add-native-code.html.
3+
# For more examples on how to use CMake, see https://github.com/android/ndk-samples.
4+
5+
# Sets the minimum CMake version required for this project.
6+
cmake_minimum_required(VERSION 3.22.1)
7+
8+
# Declares the project name. The project name can be accessed via ${ PROJECT_NAME},
9+
# Since this is the top level CMakeLists.txt, the project name is also accessible
10+
# with ${CMAKE_PROJECT_NAME} (both CMake variables are in-sync within the top level
11+
# build script scope).
12+
project("genai")
13+
14+
#set(APP_LIB_DIR ${PROJECT_SOURCE_DIR}/../../../libs)
15+
16+
# Creates and names a library, sets it as either STATIC
17+
# or SHARED, and provides the relative paths to its source code.
18+
# You can define multiple libraries, and CMake builds them for you.
19+
# Gradle automatically packages shared libraries with your APK.
20+
#
21+
# In this top level CMakeLists.txt, ${CMAKE_PROJECT_NAME} is used to define
22+
# the target library name; in the sub-module's CMakeLists.txt, ${PROJECT_NAME}
23+
# is preferred for the same purpose.
24+
#
25+
# In order to load a library into your app from Java/Kotlin, you must call
26+
# System.loadLibrary() and pass the name of the library defined here;
27+
# for GameActivity/NativeActivity derived applications, the same library name must be
28+
# used in the AndroidManifest.xml file.
29+
add_library(${CMAKE_PROJECT_NAME} SHARED
30+
# List C/C++ source files with relative paths to this CMakeLists.txt.
31+
native-lib.cpp)
32+
33+
target_link_directories(${CMAKE_PROJECT_NAME} PRIVATE ${PROJECT_SOURCE_DIR}/../jniLibs/${CMAKE_ANDROID_ARCH_ABI})
34+
35+
# Specifies libraries CMake should link to your target library. You
36+
# can link libraries from various origins, such as libraries defined in this
37+
# build script, prebuilt third-party libraries, or Android system libraries.
38+
target_link_libraries(${CMAKE_PROJECT_NAME}
39+
# List libraries link to the target library
40+
onnxruntime-genai
41+
onnxruntime
42+
android
43+
log)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
**Note:**
2+
3+
4+
`ort_genai_c.h` file is copied from ORT GenAI package so it matches GenAI libraries.
5+
We copy it here because Android Studio code completion doesn't work nicely with the C++ code if the file is not in this directory.

0 commit comments

Comments
 (0)