Skip to content

armgit / ente

Public Imported from GitHub
0

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

[mob][photos] Load models in isolate

laurenspriemcfd5c22649a0
diff --git a/mobile/lib/services/machine_learning/ml_isolate.dart b/mobile/lib/services/machine_learning/ml_isolate.dart
index 01a36a768f..3172006812 100644
--- a/mobile/lib/services/machine_learning/ml_isolate.dart
+++ b/mobile/lib/services/machine_learning/ml_isolate.dart
@@ -1,5 +1,4 @@
import "dart:async";
-import "dart:io" show Platform;
import "dart:isolate";
import "package:dart_ui_isolate/dart_ui_isolate.dart";
@@ -8,10 +7,10 @@ import "package:logging/logging.dart";
import "package:photos/core/error-reporting/super_logging.dart";
import 'package:photos/services/machine_learning/face_ml/face_detection/face_detection_service.dart';
import 'package:photos/services/machine_learning/face_ml/face_embedding/face_embedding_service.dart';
+import "package:photos/services/machine_learning/ml_model.dart";
+import "package:photos/services/machine_learning/ml_models_overview.dart";
import 'package:photos/services/machine_learning/ml_result.dart';
import "package:photos/services/machine_learning/semantic_search/clip/clip_image_encoder.dart";
-import "package:photos/services/machine_learning/semantic_search/clip/clip_text_encoder.dart";
-import "package:photos/services/remote_assets_service.dart";
import "package:photos/utils/ml_util.dart";
import "package:synchronized/synchronized.dart";
@@ -90,10 +89,17 @@ class MLIsolate {
sendPort.send(result.toJsonString());
break;
case MLOperation.loadModels:
- await FaceDetectionService.instance.loadModel(useEntePlugin: true);
- await FaceEmbeddingService.instance.loadModel(useEntePlugin: true);
- await ClipImageEncoder.instance.loadModel(useEntePlugin: true);
- sendPort.send(true);
+ final modelNames = args['modelNames'] as List<String>;
+ final modelPaths = args['modelPaths'] as List<String>;
+ final addresses = <int>[];
+ for (int i = 0; i < modelNames.length; i++) {
+ final int address = await MlModel.loadModel(
+ modelNames[i],
+ modelPaths[i],
+ );
+ addresses.add(address);
+ }
+ sendPort.send(List.from(addresses, growable: false));
break;
}
} catch (e, s) {
@@ -188,10 +194,10 @@ class MLIsolate {
"runFaces": instruction.shouldRunFaces,
"runClip": instruction.shouldRunClip,
"faceDetectionAddress":
- FaceDetectionService.instance.sessionAddress,
+ FaceDetectionService.instance.ffiSessionAddress,
"faceEmbeddingAddress":
- FaceEmbeddingService.instance.sessionAddress,
- "clipImageAddress": ClipImageEncoder.instance.sessionAddress,
+ FaceEmbeddingService.instance.ffiSessionAddress,
+ "clipImageAddress": ClipImageEncoder.instance.ffiSessionAddress,
}
),
) as String?;
@@ -225,11 +231,47 @@ class MLIsolate {
return result;
}
- Future<void> loadModels() async {
+ Future<void> loadModels({
+ required bool loadFaces,
+ required bool loadClip,
+ }) async {
+ if (!loadFaces && !loadClip) return;
+ final List<MLModels> models = [];
+ final List<String> modelNames = [];
+ final List<String> modelPaths = [];
+ if (loadFaces) {
+ models.addAll([MLModels.faceDetection, MLModels.faceEmbedding]);
+ final faceDetection =
+ await FaceDetectionService.instance.getModelNameAndPath();
+ modelNames.add(faceDetection.$1);
+ modelPaths.add(faceDetection.$2);
+ final faceEmbedding =
+ await FaceEmbeddingService.instance.getModelNameAndPath();
+ modelNames.add(faceEmbedding.$1);
+ modelPaths.add(faceEmbedding.$2);
+ }
+ if (loadClip) {
+ models.add(MLModels.clipImageEncoder);
+ final clipImage = await ClipImageEncoder.instance.getModelNameAndPath();
+ modelNames.add(clipImage.$1);
+ modelPaths.add(clipImage.$2);
+ }
+
try {
- await _runInIsolate(
- (MLOperation.loadModels, {}),
- );
+ final addresses = await _runInIsolate(
+ (
+ MLOperation.loadModels,
+ {
+ "modelNames": modelNames,
+ "modelPaths": modelPaths,
+ }
+ ),
+ ) as List<int>;
+ for (int i = 0; i < models.length; i++) {
+ final model = models[i].model;
+ final address = addresses[i];
+ model.storeSessionAddress(address);
+ }
} catch (e, s) {
_logger.severe("Could not load models in isolate", e, s);
rethrow;
diff --git a/mobile/lib/services/machine_learning/ml_model.dart b/mobile/lib/services/machine_learning/ml_model.dart
index 2b973afa7c..5eab535206 100644
--- a/mobile/lib/services/machine_learning/ml_model.dart
+++ b/mobile/lib/services/machine_learning/ml_model.dart
@@ -1,6 +1,5 @@
-import "dart:io" show File;
+import "dart:io" show File, Platform;
-import "package:computer/computer.dart";
import "package:logging/logging.dart";
import "package:onnx_dart/onnx_dart.dart";
import "package:onnxruntime/onnxruntime.dart";
@@ -8,6 +7,7 @@ import "package:photos/services/machine_learning/onnx_env.dart";
import "package:photos/services/remote_assets_service.dart";
abstract class MlModel {
+ static final Logger isolateLogger = Logger("MlModelInIsolate");
Logger get logger;
String get kModelBucketEndpoint => "https://models.ente.io/";
@@ -16,92 +16,100 @@ abstract class MlModel {
String get modelName;
+ bool get isInitialized =>
+ Platform.isAndroid ? isNativePluginInitialized : isFfiInitialized;
+ int get sessionAddress =>
+ Platform.isAndroid ? nativePluginSessionIndex : ffiSessionAddress;
+
// isInitialized is used to check if the model is loaded by the ffi based
// plugin
- bool isInitialized = false;
+ bool isFfiInitialized = false;
+ int ffiSessionAddress = -1;
bool isNativePluginInitialized = false;
- int sessionAddress = 0;
+ int nativePluginSessionIndex = -1;
+
+ Future<(String, String)> getModelNameAndPath() async {
+ final path =
+ await RemoteAssetsService.instance.getAssetPath(modelRemotePath);
+ return (modelName, path);
+ }
- final computer = Computer.shared();
+ void storeSessionAddress(int address) {
+ if (Platform.isAndroid) {
+ nativePluginSessionIndex = address;
+ isNativePluginInitialized = true;
+ } else {
+ ffiSessionAddress = address;
+ isFfiInitialized = true;
+ }
+ }
// Initializes the model.
// If `useEntePlugin` is set to true, the custom plugin is used for initialization.
// Note: The custom plugin requires a dedicated isolate for loading the model to ensure thread safety and performance isolation.
// In contrast, the current FFI-based plugin leverages the session memory address for session management, which does not require a dedicated isolate.
- Future<void> loadModel({bool useEntePlugin = false}) async {
- final model = await RemoteAssetsService.instance.getAsset(modelRemotePath);
- if (useEntePlugin) {
- await _loadModelWithEntePlugin(modelName, model.path);
+ static Future<int> loadModel(
+ String modelName,
+ String modelPath,
+ ) async {
+ if (Platform.isAndroid) {
+ return await _loadModelWithEntePlugin(modelName, modelPath);
} else {
- await _loadModelWithFFI(modelName, model.path);
+ return await _loadModelWithFFI(modelName, modelPath);
}
}
- Future<void> _loadModelWithEntePlugin(
+ static Future<int> _loadModelWithEntePlugin(
String modelName,
String modelPath,
) async {
- if (!isNativePluginInitialized) {
- final startTime = DateTime.now();
- logger.info('Initializing $modelName with EntePlugin');
- final OnnxDart plugin = OnnxDart();
- final bool? initResult = await plugin.init(modelName, modelPath);
- isNativePluginInitialized = initResult ?? false;
- if (isNativePluginInitialized) {
- final endTime = DateTime.now();
- logger.info(
- "$modelName loaded via EntePlugin ${(endTime.millisecondsSinceEpoch - startTime.millisecondsSinceEpoch).toString()}ms",
- );
- } else {
- logger.severe("Failed to initialize $modelName with EntePlugin.");
- }
- } else {
- logger.info("$modelName already initialized with Ente Plugin.");
+ final startTime = DateTime.now();
+ isolateLogger.info('Initializing $modelName with EntePlugin');
+ final OnnxDart plugin = OnnxDart();
+ final bool? initResult = await plugin.init(modelName, modelPath);
+ if (initResult == null || !initResult) {
+ isolateLogger.severe("Failed to initialize $modelName with EntePlugin.");
+ throw Exception("Failed to initialize $modelName with EntePlugin.");
}
+ final endTime = DateTime.now();
+ isolateLogger.info(
+ "$modelName loaded via EntePlugin in ${endTime.difference(startTime).inMilliseconds}ms",
+ );
+ return 0;
}
- Future<void> _loadModelWithFFI(String modelName, String modelPath) async {
- if (!isInitialized) {
- logger.info('Initializing $modelName with FFI');
+ static Future<int> _loadModelWithFFI(
+ String modelName,
+ String modelPath,
+ ) async {
+ isolateLogger.info('Initializing $modelName with FFI');
+ try {
final startTime = DateTime.now();
- sessionAddress = await computer.compute(
- _loadModel,
- param: {
- "modelPath": modelPath,
- },
- );
- isInitialized = true;
+ final sessionOptions = OrtSessionOptions()
+ ..setInterOpNumThreads(1)
+ ..setIntraOpNumThreads(1)
+ ..setSessionGraphOptimizationLevel(
+ GraphOptimizationLevel.ortEnableAll,
+ );
+ final session = OrtSession.fromFile(File(modelPath), sessionOptions);
final endTime = DateTime.now();
- logger.info(
- "$modelName loaded with FFI, took: ${(endTime.millisecondsSinceEpoch - startTime.millisecondsSinceEpoch).toString()}ms",
+ isolateLogger.info(
+ "$modelName loaded with FFI, took: ${endTime.difference(startTime).inMilliseconds}ms",
);
- } else {
- logger.info("$modelName already initialized with FFI.");
+ return session.address;
+ } catch (e) {
+ rethrow;
}
}
// TODO: add release method for native plugin
Future<void> release() async {
- if (isInitialized) {
- await computer.compute(_releaseModel, param: {'address': sessionAddress});
+ if (isFfiInitialized) {
+ await _releaseModel({'address': ffiSessionAddress});
await ONNXEnv.instance.releaseONNX(modelName);
- isInitialized = false;
- sessionAddress = 0;
- }
- }
-
- static Future<int> _loadModel(Map args) async {
- final sessionOptions = OrtSessionOptions()
- ..setInterOpNumThreads(1)
- ..setIntraOpNumThreads(1)
- ..setSessionGraphOptimizationLevel(GraphOptimizationLevel.ortEnableAll);
- try {
- final session =
- OrtSession.fromFile(File(args["modelPath"]), sessionOptions);
- return session.address;
- } catch (e) {
- rethrow;
+ isFfiInitialized = false;
+ ffiSessionAddress = 0;
}
}
diff --git a/mobile/lib/services/machine_learning/ml_models_overview.dart b/mobile/lib/services/machine_learning/ml_models_overview.dart
new file mode 100644
index 0000000000..039628c142
--- /dev/null
+++ b/mobile/lib/services/machine_learning/ml_models_overview.dart
@@ -0,0 +1,27 @@
+import "package:photos/services/machine_learning/face_ml/face_detection/face_detection_service.dart";
+import "package:photos/services/machine_learning/face_ml/face_embedding/face_embedding_service.dart";
+import "package:photos/services/machine_learning/ml_model.dart";
+import "package:photos/services/machine_learning/semantic_search/clip/clip_image_encoder.dart";
+import "package:photos/services/machine_learning/semantic_search/clip/clip_text_encoder.dart";
+
+enum MLModels {
+ faceDetection,
+ faceEmbedding,
+ clipImageEncoder,
+ clipTextEncoder,
+}
+
+extension MLModelsExtension on MLModels {
+ MlModel get model {
+ switch (this) {
+ case MLModels.faceDetection:
+ return FaceDetectionService.instance;
+ case MLModels.faceEmbedding:
+ return FaceEmbeddingService.instance;
+ case MLModels.clipImageEncoder:
+ return ClipImageEncoder.instance;
+ case MLModels.clipTextEncoder:
+ return ClipTextEncoder.instance;
+ }
+ }
+}
diff --git a/mobile/lib/services/machine_learning/ml_service.dart b/mobile/lib/services/machine_learning/ml_service.dart
index e254794dcc..98089b6b6a 100644
--- a/mobile/lib/services/machine_learning/ml_service.dart
+++ b/mobile/lib/services/machine_learning/ml_service.dart
@@ -1,5 +1,4 @@
import "dart:async";
-import "dart:io" show Platform;
import "dart:math" show min;
import "dart:typed_data" show Uint8List;
@@ -47,8 +46,6 @@ class MLService {
final _initModelLock = Lock();
bool _isInitialized = false;
- bool _isModelsInitialized = false;
- bool _isModelsInitUsingEntePlugin = false;
late String client;
@@ -56,7 +53,7 @@ class MLService {
bool get showClusteringIsHappening => _showClusteringIsHappening;
- bool get allModelsLoaded => _isModelsInitialized;
+ bool modelsAreLoading = false;
bool debugIndexingDisabled = false;
bool _showClusteringIsHappening = false;
@@ -181,7 +178,7 @@ class MLService {
_logger.info("indexAllImages() was paused, stopping");
break outerLoop;
}
- await _ensureReadyForInference();
+ await _ensureLoadedModels(instruction);
futures.add(processImage(instruction));
}
final awaitedFutures = await Future.wait(futures);
@@ -504,47 +501,6 @@ class MLService {
return actuallyRanML;
}
- Future<void> _initModelsUsingFfiBasedPlugin() async {
- return _initModelLock.synchronized(() async {
- if (_isModelsInitialized) return;
- _logger.info('initModels called');
- try {
- await FaceDetectionService.instance.loadModel();
- } catch (e, s) {
- _logger.severe("Could not initialize yolo onnx", e, s);
- }
- try {
- await FaceEmbeddingService.instance.loadModel();
- } catch (e, s) {
- _logger.severe("Could not initialize mobilefacenet", e, s);
- }
- try {
- await ClipImageEncoder.instance.loadModel();
- } catch (e, s) {
- _logger.severe("Could not initialize clip image", e, s);
- }
- _isModelsInitialized = true;
- _logger.info('initModels done');
- _logStatus();
- });
- }
-
- Future<void> _initModelUsingEntePlugin() async {
- return _initModelLock.synchronized(() async {
- if (_isModelsInitUsingEntePlugin) return;
- _logger.info('initModelUsingEntePlugin called');
-
- try {
- await MLIsolate.instance.loadModels();
- _isModelsInitUsingEntePlugin = true;
- } catch (e, s) {
- _logger.severe("Could not initialize clip image", e, s);
- }
- _logger.info('initModelUsingEntePlugin done');
- _logStatus();
- });
- }
-
Future<void> _releaseModels() async {
return _initModelLock.synchronized(() async {
_logger.info("dispose called");
@@ -570,13 +526,29 @@ class MLService {
});
}
- Future<void> _ensureReadyForInference() async {
- await _initModelsUsingFfiBasedPlugin();
- if (Platform.isAndroid) {
- await _initModelUsingEntePlugin();
- } else {
- await _initModelsUsingFfiBasedPlugin();
- }
+ Future<void> _ensureLoadedModels(FileMLInstruction instruction) async {
+ return _initModelLock.synchronized(() async {
+ final faceDetectionLoaded = FaceDetectionService.instance.isInitialized;
+ final faceEmbeddingLoaded = FaceEmbeddingService.instance.isInitialized;
+ final facesModelsLoaded = faceDetectionLoaded && faceEmbeddingLoaded;
+ final clipModelsLoaded = ClipImageEncoder.instance.isInitialized;
+
+ final shouldLoadFaces = instruction.shouldRunFaces && !facesModelsLoaded;
+ final shouldLoadClip = instruction.shouldRunClip && !clipModelsLoaded;
+ if (!shouldLoadFaces && !shouldLoadClip) {
+ return;
+ }
+
+ modelsAreLoading = true;
+ _logger.info(
+ 'Loading models. faces: $shouldLoadFaces, clip: $shouldLoadClip',
+ );
+ await MLIsolate.instance
+ .loadModels(loadFaces: shouldLoadFaces, loadClip: shouldLoadClip);
+ _logger.info('Models loaded');
+ _logStatus();
+ modelsAreLoading = false;
+ });
}
bool _cannotRunMLFunction({String function = ""}) {
diff --git a/mobile/lib/ui/settings/machine_learning_settings_page.dart b/mobile/lib/ui/settings/machine_learning_settings_page.dart
index 6fb617160a..798486b4b5 100644
--- a/mobile/lib/ui/settings/machine_learning_settings_page.dart
+++ b/mobile/lib/ui/settings/machine_learning_settings_page.dart
@@ -138,9 +138,9 @@ class _MachineLearningSettingsPageState
height: 12,
),
hasEnabled
- ? MLService.instance.allModelsLoaded
- ? const MLStatusWidget()
- : const ModelLoadingState()
+ ? MLService.instance.modelsAreLoading
+ ? const ModelLoadingState()
+ : const MLStatusWidget()
: const SizedBox.shrink(),
],
);