Skip to content

armgit / ente

Public Imported from GitHub
0

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

Add CLIP text tokenizer parity test and warmup

laurenspriemae7e12f37cff
diff --git a/mobile/apps/photos/integration_test/clip_text_tokenizer_parity_test.dart b/mobile/apps/photos/integration_test/clip_text_tokenizer_parity_test.dart
new file mode 100644
index 0000000000..6816739dc6
--- /dev/null
+++ b/mobile/apps/photos/integration_test/clip_text_tokenizer_parity_test.dart
@@ -0,0 +1,65 @@
+import "dart:io";
+
+import "package:flutter_test/flutter_test.dart";
+import "package:integration_test/integration_test.dart";
+import "package:photos/services/machine_learning/semantic_search/clip/clip_text_tokenizer.dart";
+import "package:photos/src/rust/api/ml_indexing_api.dart" as rust_ml;
+import "package:photos/src/rust/frb_generated.dart";
+
+const _kClipBpeMergeLineCount = 49152 - 256 - 2;
+
+void main() {
+ IntegrationTestWidgetsFlutterBinding.ensureInitialized();
+
+ setUpAll(() async {
+ await EntePhotosRust.init();
+ });
+
+ test("Rust CLIP tokenizer matches Dart tokenizer", () async {
+ final tempDir = await Directory.systemTemp.createTemp(
+ "clip_tokenizer_parity_",
+ );
+ addTearDown(() async {
+ if (tempDir.existsSync()) {
+ await tempDir.delete(recursive: true);
+ }
+ });
+
+ final vocabPath = "${tempDir.path}/bpe_simple_vocab_16e6.txt";
+ await File(vocabPath)
+ .writeAsString(_buildSyntheticClipVocab(), flush: true);
+ await ClipTextTokenizer.instance.init(vocabPath);
+
+ const queries = <String>[
+ "hello world",
+ "can't won't i'd we're",
+ "multiple spaces\\tand\\nlines",
+ "&amp;lt;html&amp;gt; entities &amp;amp; symbols",
+ "<|startoftext|> should be tokenized literally",
+ "numbers 1234567890 and punctuation !!! ???",
+ "long query long query long query long query long query long query long query long query long query long query",
+ ];
+
+ for (final query in queries) {
+ final dartTokens = await ClipTextTokenizer.instance.tokenize(query);
+ final rustTokens = await rust_ml.tokenizeClipTextRust(
+ text: query,
+ vocabPath: vocabPath,
+ );
+ expect(
+ rustTokens.toList(growable: false),
+ dartTokens,
+ reason: "Tokenizer mismatch for query: '$query'",
+ );
+ expect(rustTokens.length, ClipTextTokenizer.totalTokens);
+ }
+ });
+}
+
+String _buildSyntheticClipVocab() {
+ final buffer = StringBuffer("#version: 0.2");
+ for (int i = 0; i < _kClipBpeMergeLineCount; i++) {
+ buffer.write("\na b");
+ }
+ return buffer.toString();
+}
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart b/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart
index ef11aa4e0e..ababaed1bc 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart
@@ -25,6 +25,7 @@ class MLComputer extends SuperIsolate {
bool _isClipTokenizerInitialized = false;
String? _clipTextModelPath;
String? _clipTextVocabPath;
+ Future<void>? _clipTextWarmupFuture;
@override
bool get isDartUiIsolate => false;
@@ -113,6 +114,21 @@ class MLComputer extends SuperIsolate {
}
}
+ Future<void> warmUpClipTextEncoder() {
+ _clipTextWarmupFuture ??= _warmUpClipTextEncoderInternal();
+ return _clipTextWarmupFuture!;
+ }
+
+ Future<void> _warmUpClipTextEncoderInternal() async {
+ try {
+ await runClipText("warm up text encoder");
+ } catch (e, s) {
+ _clipTextWarmupFuture = null;
+ _logger.warning("Clip text warmup failed in MLComputer", e, s);
+ rethrow;
+ }
+ }
+
Future<void> _ensureLoadedClipTextModel(bool useRustMl) async {
return _initModelLock.synchronized(() async {
try {
diff --git a/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart b/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart
index 9a4c6be837..62d8370cbd 100644
--- a/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart
@@ -330,7 +330,7 @@ class SemanticSearchService {
_logger.info("Initializing ClipText");
try {
if (delay) await Future.delayed(const Duration(seconds: 5));
- await MLComputer.instance.runClipText("warm up text encoder");
+ await MLComputer.instance.warmUpClipTextEncoder();
_textModelIsLoaded = true;
} catch (e, s) {
_logger.severe("Clip text loading failed", e, s);
diff --git a/mobile/apps/photos/rust/src/api/ml_indexing_api.rs b/mobile/apps/photos/rust/src/api/ml_indexing_api.rs
index 335750535a..60a83f9a51 100644
--- a/mobile/apps/photos/rust/src/api/ml_indexing_api.rs
+++ b/mobile/apps/photos/rust/src/api/ml_indexing_api.rs
@@ -1,6 +1,6 @@
use crate::image::decode::decode_image_from_path;
use crate::ml::{
- clip::{image::run_clip_image, text::run_clip_text_query},
+ clip::{image::run_clip_image, text::run_clip_text_query, tokenizer::tokenize_clip_text},
error::{MlError, MlResult},
face::{align::run_face_alignment, detect::run_face_detection, embed::run_face_embedding},
runtime::{self, ExecutionProviderPolicy, MlRuntimeConfig, ModelPaths},
@@ -121,6 +121,10 @@ pub fn run_clip_text_rust(req: RunClipTextRequest) -> Result<RunClipTextResult,
run_clip_text_rust_inner(req).map_err(|e| e.to_string())
}
+pub fn tokenize_clip_text_rust(text: String, vocab_path: String) -> Result<Vec<i32>, String> {
+ tokenize_clip_text_rust_inner(&text, &vocab_path).map_err(|e| e.to_string())
+}
+
fn analyze_image_rust_inner(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageResult> {
validate_request_model_paths(&req)?;
@@ -209,6 +213,15 @@ fn run_clip_text_rust_inner(req: RunClipTextRequest) -> MlResult<RunClipTextResu
})
}
+fn tokenize_clip_text_rust_inner(text: &str, vocab_path: &str) -> MlResult<Vec<i32>> {
+ if vocab_path.trim().is_empty() {
+ return Err(MlError::InvalidRequest(
+ "missing model path: clipTextVocabPath".to_string(),
+ ));
+ }
+ tokenize_clip_text(text, vocab_path)
+}
+
fn validate_request_model_paths(req: &AnalyzeImageRequest) -> MlResult<()> {
let mut missing = Vec::new();
if req.run_faces {
diff --git a/mobile/apps/photos/rust/src/ml/clip/tokenizer.rs b/mobile/apps/photos/rust/src/ml/clip/tokenizer.rs
index 1d52f8ae37..a32fdf21dd 100644
--- a/mobile/apps/photos/rust/src/ml/clip/tokenizer.rs
+++ b/mobile/apps/photos/rust/src/ml/clip/tokenizer.rs
@@ -15,7 +15,10 @@ const BPE_MERGES_END_EXCLUSIVE: usize = 49152 - 256 - 2 + 1;
static TOKEN_PATTERN: Lazy<Regex> = Lazy::new(|| {
Regex::new(
- r"(?i)<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[a-zA-Z]+|[0-9]+|[^\s\p{L}\p{N}]+",
+ // Keep this expression behaviorally aligned with Dart's RegExp in
+ // clip_text_tokenizer.dart. Dart does not support \p{L}/\p{N} here,
+ // so those sequences are treated literally.
+ r"(?i)<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[a-zA-Z]+|[0-9]+|[^\sp{L}p{N}]+",
)
.expect("valid clip tokenizer regex")
});