java support linux x86

pull/12721/head
yeyunpeng 4 years ago committed by yeyunpeng2020
parent c5310da824
commit 62f0676805

File diff suppressed because it is too large Load Diff

@ -5,17 +5,26 @@ if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_L
message(FATAL_ERROR "GCC version ${CMAKE_CXX_COMPILER_VERSION} must not be less than 7.3.0") message(FATAL_ERROR "GCC version ${CMAKE_CXX_COMPILER_VERSION} must not be less than 7.3.0")
endif() endif()
# Add directory to include search path
include_directories(${CMAKE_CURRENT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_SOURCE_DIR})
file(GLOB_RECURSE QUICK_START_CXX ${CMAKE_CURRENT_SOURCE_DIR}/*.cc)
add_library(mindspore-lite STATIC IMPORTED) # Add directory to linker search path
set_target_properties(mindspore-lite PROPERTIES IMPORTED_LOCATION link_directories(${CMAKE_CURRENT_SOURCE_DIR}/lib)
${CMAKE_CURRENT_SOURCE_DIR}/lib/libmindspore-lite.a)
file(GLOB_RECURSE QUICK_START_CXX ${CMAKE_CURRENT_SOURCE_DIR}/*.cc)
add_executable(mindspore_quick_start_cpp ${QUICK_START_CXX}) add_executable(mindspore_quick_start_cpp ${QUICK_START_CXX})
target_link_libraries( target_link_libraries(
mindspore_quick_start_cpp mindspore_quick_start_cpp
-Wl,--whole-archive mindspore-lite -Wl,--no-whole-archive -Wl,--whole-archive mindspore-lite -Wl,--no-whole-archive
pthread pthread
) )
# Due to the increased compilation options for stack protection,
# it is necessary to target link ssp library when Use the static library in Windows.
if(WIN32)
target_link_libraries(
mindspore_quick_start_cpp
ssp
)
endif()

@ -0,0 +1,26 @@
@rem Copyright 2020 Huawei Technologies Co., Ltd
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem http://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem ============================================================================
@echo off
@title mindspore_lite_quick_start_cpp_demo_build
SET BASEPATH=%CD%
IF NOT EXIST "%BASEPATH%/build" (
md build
)
cd %BASEPATH%/build
cmake -G "CodeBlocks - MinGW Makefiles" %BASEPATH%
cmake --build .

@ -22,7 +22,7 @@ get_version() {
VERSION_STR=${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_REVISION} VERSION_STR=${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_REVISION}
} }
get_version get_version
MODEL_DOWNLOAD_URL="https://download.mindspore.cn/model_zoo/official/lite/mobilenetv2_openimage_lite/1.1/mobilenetv2.ms" MODEL_DOWNLOAD_URL="https://download.mindspore.cn/model_zoo/official/lite/mobilenetv2_imagenet/mobilenetv2.ms"
MINDSPORE_LITE_DOWNLOAD_URL="https://ms-release.obs.cn-north-4.myhuaweicloud.com/${VERSION_STR}/MindSpore/lite/release/linux/mindspore-lite-${VERSION_STR}-inference-linux-x64.tar.gz" MINDSPORE_LITE_DOWNLOAD_URL="https://ms-release.obs.cn-north-4.myhuaweicloud.com/${VERSION_STR}/MindSpore/lite/release/linux/mindspore-lite-${VERSION_STR}-inference-linux-x64.tar.gz"
mkdir -p build mkdir -p build

@ -25,16 +25,16 @@
#include "include/lite_session.h" #include "include/lite_session.h"
std::string RealPath(const char *path) { std::string RealPath(const char *path) {
size_t PATH_MAX = 4096; size_t max = 4096;
if (path == nullptr) { if (path == nullptr) {
std::cerr << "path is nullptr" << std::endl; std::cerr << "path is nullptr" << std::endl;
return ""; return "";
} }
if ((strlen(path)) >= PATH_MAX) { if ((strlen(path)) >= max) {
std::cerr << "path is too long" << std::endl; std::cerr << "path is too long" << std::endl;
return ""; return "";
} }
auto resolved_path = std::make_unique<char[]>(PATH_MAX); auto resolved_path = std::make_unique<char[]>(max);
if (resolved_path == nullptr) { if (resolved_path == nullptr) {
std::cerr << "new resolved_path failed" << std::endl; std::cerr << "new resolved_path failed" << std::endl;
return ""; return "";

@ -0,0 +1,55 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mindspore.lite.demo</groupId>
<artifactId>quick_start_java</artifactId>
<version>1.0</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.mindspore.lite</groupId>
<artifactId>mindspore-lite-java</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/mindspore-lite-java.jar</systemPath>
</dependency>
</dependencies>
<build>
<finalName>${project.name}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>com.mindspore.lite.demo.Main</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assemble</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,150 @@
package com.mindspore.lite.demo;
import com.mindspore.lite.LiteSession;
import com.mindspore.lite.MSTensor;
import com.mindspore.lite.Model;
import com.mindspore.lite.DataType;
import com.mindspore.lite.Version;
import com.mindspore.lite.config.MSConfig;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.Random;
public class Main {
private static Model model;
private static LiteSession session;
public static float[] generateArray(int len) {
Random rand = new Random();
float[] arr = new float[len];
for (int i = 0; i < arr.length; i++) {
arr[i] = rand.nextFloat();
}
return arr;
}
private static ByteBuffer floatArrayToByteBuffer(float[] floats) {
if (floats == null) {
return null;
}
ByteBuffer buffer = ByteBuffer.allocateDirect(floats.length * Float.BYTES);
buffer.order(ByteOrder.LITTLE_ENDIAN);
FloatBuffer floatBuffer = buffer.asFloatBuffer();
floatBuffer.put(floats);
return buffer;
}
private static boolean compile() {
MSConfig msConfig = new MSConfig(DeviceType.DT_CPU, 2);
boolean ret = msConfig.init();
if (!ret) {
System.err.println("Init context failed");
return false;
}
// Create the MindSpore lite session.
session = new LiteSession();
ret = session.init(msConfig);
msConfig.free();
if (!ret) {
System.err.println("Create session failed");
model.free();
return false;
}
// Compile graph.
ret = session.compileGraph(model);
if (!ret) {
System.err.println("Compile graph failed");
model.free();
return false;
}
return true;
}
private static boolean run() {
MSTensor inputTensor = session.getInputsByTensorName("2031_2030_1_construct_wrapper:x");
if (inputTensor.getDataType() != DataType.kNumberTypeFloat32) {
System.err.println("Input tensor shape do not float, the data type is " + inputTensor.getDataType());
return false;
}
// Generator Random Data.
int elementNums = inputTensor.elementsNum();
float[] randomData = generateArray(elementNums);
ByteBuffer inputData = floatArrayToByteBuffer(randomData);
// Set Input Data.
inputTensor.setData(inputData);
// Run Inference.
boolean ret = session.runGraph();
if (!ret) {
System.err.println("MindSpore Lite run failed.");
return false;
}
// Get Output Tensor Data.
MSTensor outTensor = session.getOutputByTensorName("Default/head-MobileNetV2Head/Softmax-op204");
// Print out Tensor Data.
StringBuilder msgSb = new StringBuilder();
msgSb.append("out tensor shape: [");
int[] shape = outTensor.getShape();
for (int dim : shape) {
msgSb.append(dim).append(",");
}
msgSb.append("]");
if (outTensor.getDataType() != DataType.kNumberTypeFloat32) {
System.err.println("output tensor shape do not float, the data type is " + outTensor.getDataType());
return false;
}
float[] result = outTensor.getFloatData();
if (result == null) {
System.err.println("decodeBytes return null");
return false;
}
msgSb.append(" and out data:");
for (int i = 0; i < 10 && i < outTensor.elementsNum(); i++) {
msgSb.append(" ").append(result[i]);
}
System.out.println(msgSb.toString());
return true;
}
private static void freeBuffer() {
session.free();
model.free();
}
public static void main(String[] args) {
System.out.println(Version.version());
if (args.length < 1) {
System.err.println("The model path parameter must be passed.");
return;
}
String modelPath = args[0];
model = new Model();
boolean ret = model.loadModel(modelPath);
if (!ret) {
System.err.println("Load model failed, model path is " + modelPath);
return;
}
ret = compile();
if (!ret) {
System.err.println("MindSpore Lite compile failed.");
return;
}
ret = run();
if (!ret) {
System.err.println("MindSpore Lite run failed.");
freeBuffer();
return;
}
freeBuffer();
}
}

@ -25,7 +25,7 @@ get_version() {
VERSION_STR=${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_REVISION} VERSION_STR=${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_REVISION}
} }
get_version get_version
MODEL_DOWNLOAD_URL="https://download.mindspore.cn/model_zoo/official/lite/mobilenetv2_openimage_lite/1.1/mobilenetv2.ms" MODEL_DOWNLOAD_URL="https://download.mindspore.cn/model_zoo/official/lite/mobilenetv2_imagenet/mobilenetv2.ms"
MINDSPORE_LITE_DOWNLOAD_URL="https://ms-release.obs.cn-north-4.myhuaweicloud.com/${VERSION_STR}/MindSpore/lite/release/android/mindspore-lite-${VERSION_STR}-inference-android.tar.gz" MINDSPORE_LITE_DOWNLOAD_URL="https://ms-release.obs.cn-north-4.myhuaweicloud.com/${VERSION_STR}/MindSpore/lite/release/android/mindspore-lite-${VERSION_STR}-inference-android.tar.gz"
mkdir -p build mkdir -p build

@ -167,7 +167,7 @@ int GetInputsAndSetData(mindspore::session::LiteSession *session) {
} }
int GetInputsByTensorNameAndSetData(mindspore::session::LiteSession *session) { int GetInputsByTensorNameAndSetData(mindspore::session::LiteSession *session) {
auto in_tensor = session->GetInputsByTensorName("2029_2028_1_construct_wrapper:x"); auto in_tensor = session->GetInputsByTensorName("2031_2030_1_construct_wrapper:x");
if (in_tensor == nullptr) { if (in_tensor == nullptr) {
std::cerr << "Input tensor is nullptr" << std::endl; std::cerr << "Input tensor is nullptr" << std::endl;
return -1; return -1;
@ -183,7 +183,7 @@ int GetInputsByTensorNameAndSetData(mindspore::session::LiteSession *session) {
void GetOutputsByNodeName(mindspore::session::LiteSession *session) { void GetOutputsByNodeName(mindspore::session::LiteSession *session) {
// model has a output node named output_node_name_0. // model has a output node named output_node_name_0.
auto output_vec = session->GetOutputsByNodeName("Default/Sigmoid-op204"); auto output_vec = session->GetOutputsByNodeName("Default/head-MobileNetV2Head/Softmax-op204");
// output node named output_node_name_0 has only one output tensor. // output node named output_node_name_0 has only one output tensor.
auto out_tensor = output_vec.front(); auto out_tensor = output_vec.front();
if (out_tensor == nullptr) { if (out_tensor == nullptr) {

@ -0,0 +1,45 @@
plugins {
id 'com.android.application'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.2"
defaultConfig {
applicationId "com.mindspore.lite.demo"
minSdkVersion 19
targetSdkVersion 30
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
aaptOptions {
noCompress = ['.so', '.ms', '.bin', '.jpg']
}
}
repositories {
flatDir {
dirs 'libs'
}
}
apply from: 'download.gradle'
dependencies {
implementation fileTree(dir: "libs", include: ['*.aar', '*.jar'])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
}

@ -0,0 +1,112 @@
/**
* To download necessary library from HuaWei server.
* Including mindspore-lite .so file, minddata-lite .so file and model file.
* The libraries can be downloaded manually.
*/
def targetModelFile = "src/main/assets/mobilenetv2.ms"
def modelDownloadUrl = "https://download.mindspore.cn/model_zoo/official/lite/mobilenetv2_imagenet/mobilenetv2.ms"
def mindsporeLite_Version = "mindspore-lite-1.1.0-inference-android"
def mindsporeLite_Version_AAR = "mindspore-lite-maven-1.1.0"
def mindsporeLiteDownloadUrl = "https://ms-release.obs.cn-north-4.myhuaweicloud.com/1.1.0/MindSpore/lite/release/android/${mindsporeLite_Version}.tar.gz"
def targetRoot = "libs/"
def mindSporeLibrary = "${targetRoot}${mindsporeLite_Version}.tar.gz"
def mindSporeLibraryAAR = "${targetRoot}${mindsporeLite_Version}/${mindsporeLite_Version_AAR}.zip"
def cleantargetMindSporeInclude = "${targetRoot}${mindsporeLite_Version}"
def cleantargetMindSporeIncludeAAR = "${targetRoot}mindspore"
task downloadModelFile(type: DownloadUrlTask) {
doFirst {
println "Downloading ${modelDownloadUrl}"
}
sourceUrl = "${modelDownloadUrl}"
target = file("${targetModelFile}")
}
task downloadMindSporeLibrary(type: DownloadUrlTask) {
doFirst {
println "Downloading ${mindsporeLiteDownloadUrl}"
}
sourceUrl = "${mindsporeLiteDownloadUrl}"
target = file("${mindSporeLibrary}")
}
task unzipMindSporeInclude(type: Copy, dependsOn: ['downloadMindSporeLibrary']) {
doFirst {
println "Unzipping ${mindSporeLibrary}"
}
from tarTree(resources.gzip("${mindSporeLibrary}"))
into "${targetRoot}"
}
task unzipMindSporeIncludeAAR(type: Copy, dependsOn: ['unzipMindSporeInclude']) {
doFirst {
println "Unzipping ${mindSporeLibraryAAR}"
}
from zipTree("${mindSporeLibraryAAR}")
into "${targetRoot}"
}
task copyAARToRoot(type: Copy, dependsOn: ['unzipMindSporeIncludeAAR']) {
from('libs/mindspore/mindspore-lite/1.1.0/mindspore-lite-1.1.0.aar')
into "${targetRoot}"
}
task cleanUnusedmindsporeFiles(type: Delete, dependsOn: ['copyAARToRoot']) {
delete fileTree("${targetRoot}").matching {
include "*.tar.gz"
}
}
task cleanUnuseFiles(type: Delete, dependsOn: ['cleanUnusedmindsporeFiles']) {
delete("${cleantargetMindSporeInclude}")
}
task cleanUnuseFileAAR(type: Delete, dependsOn: ['cleanUnuseFiles']) {
delete("${cleantargetMindSporeIncludeAAR}")
}
if (file("libs/mindspore-lite-1.1.0.aar").exists()) {
downloadMindSporeLibrary.enabled = false
unzipMindSporeInclude.enabled = false
unzipMindSporeIncludeAAR.enabled = false
cleanUnuseFiles.enabled = false
cleanUnuseFileAAR.enabled = false
cleanUnusedmindsporeFiles.enabled = false
copyAARToRoot.enabled = false
}
if (file("src/main/assets/mobilenetv2.ms").exists()) {
downloadModelFile.enabled = false
}
preBuild.dependsOn downloadModelFile
preBuild.dependsOn downloadMindSporeLibrary
preBuild.dependsOn unzipMindSporeInclude
preBuild.dependsOn unzipMindSporeIncludeAAR
preBuild.dependsOn copyAARToRoot
preBuild.dependsOn cleanUnusedmindsporeFiles
preBuild.dependsOn cleanUnuseFiles
preBuild.dependsOn cleanUnuseFileAAR
class DownloadUrlTask extends DefaultTask {
@Input
String sourceUrl
@OutputFile
File target
@TaskAction
void download() {
ant.get(src: sourceUrl, dest: target)
}
}

@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mindspore.lite.demo">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Runtime">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

@ -0,0 +1,24 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:4.1.2"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

@ -0,0 +1,2 @@
include ':app'
rootProject.name = "Runtime"

@ -9,17 +9,6 @@ android {
targetSdkVersion 30 targetSdkVersion 30
versionCode 1 versionCode 1
versionName project.hasProperty("LITE_VERSION") ? LITE_VERSION : "" versionName project.hasProperty("LITE_VERSION") ? LITE_VERSION : ""
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
cppFlags "-std=c++17"
}
}
ndk {
abiFilters 'arm64-v8a'
abiFilters 'armeabi-v7a'
}
} }
buildTypes { buildTypes {
@ -45,7 +34,6 @@ android {
dependencies { dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"]) implementation fileTree(dir: "libs", include: ["*.jar"])
testImplementation 'junit:junit:4.12'
} }
publishing { publishing {

@ -0,0 +1,9 @@
plugins {
id 'java'
}
archivesBaseName = 'mindspore-lite-java-common'
repositories {
mavenCentral()
}

@ -16,8 +16,6 @@
package com.mindspore.lite; package com.mindspore.lite;
import android.util.Log;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
public class MSTensor { public class MSTensor {

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save