Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[mob] Switch to custom plugin for face embedding

Neeraj Gupta1033f26a8140
diff --git a/mobile/lib/services/machine_learning/face_ml/face_embedding/face_embedding_service.dart b/mobile/lib/services/machine_learning/face_ml/face_embedding/face_embedding_service.dart
index 9dd1ec2b08..26e593f945 100644
--- a/mobile/lib/services/machine_learning/face_ml/face_embedding/face_embedding_service.dart
+++ b/mobile/lib/services/machine_learning/face_ml/face_embedding/face_embedding_service.dart
@@ -1,6 +1,7 @@
import 'dart:typed_data' show Float32List;
import 'package:logging/logging.dart';
+import "package:onnx_dart/onnx_dart.dart";
import 'package:onnxruntime/onnxruntime.dart';
import "package:photos/services/machine_learning/ml_model.dart";
import "package:photos/utils/ml_util.dart";
@@ -10,6 +11,7 @@ class MobileFaceNetInterpreterRunException implements Exception {}
/// This class is responsible for running the face embedding model (MobileFaceNet) on ONNX runtime, and can be accessed through the singleton instance [FaceEmbeddingService.instance].
class FaceEmbeddingService extends MlModel {
static const kRemoteBucketModelPath = "mobilefacenet_opset15.onnx";
+ static const String _modelName = "MobileFaceNet";
@override
String get modelRemotePath => kModelBucketEndpoint + kRemoteBucketModelPath;
@@ -19,7 +21,7 @@ class FaceEmbeddingService extends MlModel {
static final _logger = Logger('FaceEmbeddingService');
@override
- String get modelName => "MobileFaceNet";
+ String get modelName => _modelName;
static const int kInputSize = 112;
static const int kEmbeddingSize = 192;
@@ -33,35 +35,75 @@ class FaceEmbeddingService extends MlModel {
static Future<List<List<double>>> predict(
Float32List input,
- int sessionAddress,
- ) async {
- assert(sessionAddress != 0 && sessionAddress != -1);
+ int sessionAddress, {
+ bool useEntePlugin = false,
+ }) async {
+ if (!useEntePlugin) {
+ assert(sessionAddress != 0 && sessionAddress != -1);
+ }
try {
- final stopwatch = Stopwatch()..start();
- _logger.info('MobileFaceNet interpreter.run is called');
- final runOptions = OrtRunOptions();
- final int numberOfFaces = input.length ~/ (kInputSize * kInputSize * 3);
- final inputOrt = OrtValueTensor.createTensorWithDataList(
- input,
- [numberOfFaces, kInputSize, kInputSize, kNumChannels],
- );
- final inputs = {'img_inputs': inputOrt};
- final session = OrtSession.fromAddress(sessionAddress);
- final List<OrtValue?> outputs = session.run(runOptions, inputs);
- final embeddings = outputs[0]?.value as List<List<double>>;
-
- for (final embedding in embeddings) {
- normalizeEmbedding(embedding);
+ if (useEntePlugin) {
+ return await _runEntePlugin(input);
+ } else {
+ return _runFFIBasedPredict(input, sessionAddress);
}
- stopwatch.stop();
- _logger.info(
- 'MobileFaceNet interpreter.run is finished, in ${stopwatch.elapsedMilliseconds}ms',
- );
-
- return embeddings;
} catch (e) {
- _logger.info('MobileFaceNet Error while running inference: $e');
+ _logger.info(
+ 'MobileFaceNet (entePlugin: $useEntePlugin)Error while running inference: $e');
throw MobileFaceNetInterpreterRunException();
}
}
+
+ static List<List<double>> _runFFIBasedPredict(
+ Float32List input,
+ int sessionAddress,
+ ) {
+ final stopwatch = Stopwatch()..start();
+ _logger.info('MobileFaceNet interpreter.run is called');
+ final runOptions = OrtRunOptions();
+ final int numberOfFaces = input.length ~/ (kInputSize * kInputSize * 3);
+ final inputOrt = OrtValueTensor.createTensorWithDataList(
+ input,
+ [numberOfFaces, kInputSize, kInputSize, kNumChannels],
+ );
+ final inputs = {'img_inputs': inputOrt};
+ final session = OrtSession.fromAddress(sessionAddress);
+ final List<OrtValue?> outputs = session.run(runOptions, inputs);
+ final embeddings = outputs[0]?.value as List<List<double>>;
+
+ for (final embedding in embeddings) {
+ normalizeEmbedding(embedding);
+ }
+ stopwatch.stop();
+ _logger.info(
+ 'MobileFaceNetFFI interpreter.run is finished, in ${stopwatch.elapsedMilliseconds}ms',
+ );
+
+ return embeddings;
+ }
+
+ static Future<List<List<double>>> _runEntePlugin(
+ Float32List inputImageList,
+ ) async {
+ final stopwatch = Stopwatch()..start();
+ final OnnxDart plugin = OnnxDart();
+ final int numberOfFaces =
+ inputImageList.length ~/ (kInputSize * kInputSize * 3);
+ final result = await plugin.predict(
+ inputImageList,
+ _modelName,
+ );
+ final List<List<double>> embeddings = [];
+ for (int i = 0; i < numberOfFaces; i++) {
+ embeddings
+ .add(result!.sublist(i * kEmbeddingSize, (i + 1) * kEmbeddingSize));
+ }
+ for (final embedding in embeddings) {
+ normalizeEmbedding(embedding);
+ }
+ _logger.info(
+ 'MobileFaceNetEntePlugin interpreter.run is finished, in ${stopwatch.elapsedMilliseconds}ms',
+ );
+ return embeddings;
+ }
}
diff --git a/mobile/lib/services/machine_learning/face_ml/face_recognition_service.dart b/mobile/lib/services/machine_learning/face_ml/face_recognition_service.dart
index 281292b6ff..b8bc29e1d5 100644
--- a/mobile/lib/services/machine_learning/face_ml/face_recognition_service.dart
+++ b/mobile/lib/services/machine_learning/face_ml/face_recognition_service.dart
@@ -1,5 +1,6 @@
import "dart:async" show unawaited;
import "dart:developer" as dev show log;
+import "dart:io";
import "dart:typed_data" show ByteData, Float32List;
import "dart:ui" show Image;
@@ -237,7 +238,7 @@ class FaceRecognitionService {
image,
imageByteData,
interpreterAddress,
- useEntePlugin: true,
+ useEntePlugin: Platform.isAndroid,
);
// Add detected faces to the faceResults
@@ -300,8 +301,11 @@ class FaceRecognitionService {
) async {
try {
// Get the embedding of the faces
- final List<List<double>> embeddings =
- await FaceEmbeddingService.predict(facesList, interpreterAddress);
+ final List<List<double>> embeddings = await FaceEmbeddingService.predict(
+ facesList,
+ interpreterAddress,
+ useEntePlugin: Platform.isAndroid,
+ );
// Store the results
if (embeddings.length != faceResults.length) {
diff --git a/mobile/plugins/onnx_dart/android/src/main/kotlin/io/ente/photos/onnx_dart/OnnxDartPlugin.kt b/mobile/plugins/onnx_dart/android/src/main/kotlin/io/ente/photos/onnx_dart/OnnxDartPlugin.kt
index 5ed553ed6d..ad6419c8b3 100644
--- a/mobile/plugins/onnx_dart/android/src/main/kotlin/io/ente/photos/onnx_dart/OnnxDartPlugin.kt
+++ b/mobile/plugins/onnx_dart/android/src/main/kotlin/io/ente/photos/onnx_dart/OnnxDartPlugin.kt
@@ -39,6 +39,7 @@ class OnnxDartPlugin: FlutterPlugin, MethodCallHandler {
}
companion object {
const val DEFAULT_SESSION_COUNT = 1
+ const val FACENET_SINGLE_INPUT_SIZE = 112*112*3
}
@@ -162,14 +163,33 @@ class OnnxDartPlugin: FlutterPlugin, MethodCallHandler {
try {
val env = OrtEnvironment.getEnvironment()
val inputTensorShape = longArrayOf(1, 3, 640, 640)
+ if (modelType == ModelType.MobileFaceNet) {
+ inputTensorShape[0] = inputData.size.toLong()/ FACENET_SINGLE_INPUT_SIZE
+ inputTensorShape[1] = 112
+ inputTensorShape[2] = 112
+ inputTensorShape[3] = 3
+ }
val inputTensor = OnnxTensor.createTensor(env, FloatBuffer.wrap(inputData), inputTensorShape)
- val inputs = mapOf("input" to inputTensor)
+ val inputs = mutableMapOf<String, OnnxTensor>()
+ if (modelType == ModelType.MobileFaceNet) {
+ inputs["img_inputs"] = inputTensor
+ } else {
+ inputs["input"] = inputTensor
+ }
val outputs = session.run(inputs)
Log.d(TAG, "Output shape: ${outputs.size()}")
- val outputTensor = (outputs[0].value as Array<Array<FloatArray>>).get(0)
- val flatList = outputTensor.flattenToFloatArray()
- withContext(Dispatchers.Main) {
- result.success(flatList)
+ if (modelType == ModelType.MobileFaceNet) {
+ val outputTensor = (outputs[0].value as Array<FloatArray>)
+ val flatList = outputTensor.flattenToFloatArray()
+ withContext(Dispatchers.Main) {
+ result.success(flatList)
+ }
+ } else {
+ val outputTensor = (outputs[0].value as Array<Array<FloatArray>>).get(0)
+ val flatList = outputTensor.flattenToFloatArray()
+ withContext(Dispatchers.Main) {
+ result.success(flatList)
+ }
}
outputs.close()
inputTensor.close()