💚 End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Move CLIP text tokenization into Rust path
laurenspriem431f59c19e71
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart b/mobile/apps/photos/lib/services/machine_learning/ml_computer.dartindex eb64009134..ef11aa4e0e 100644--- a/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart+++ b/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart@@ -24,6 +24,7 @@ class MLComputer extends SuperIsolate {final _initModelLock = Lock();bool _isClipTokenizerInitialized = false;String? _clipTextModelPath;+ String? _clipTextVocabPath;@overridebool get isDartUiIsolate => false;@@ -80,16 +81,23 @@ class MLComputer extends SuperIsolate {final useRustMl = _shouldUseRustMl;await _ensureLoadedClipTextModel(useRustMl);final modelPath = _clipTextModelPath;+ final vocabPath = _clipTextVocabPath;if (useRustMl && (modelPath == null || modelPath.trim().isEmpty)) {throw Exception("RustMLMissingModelPath: Missing required model path: clipTextModelPath",);}+ if (useRustMl && (vocabPath == null || vocabPath.trim().isEmpty)) {+ throw Exception(+ "RustMLMissingModelPath: Missing required model path: clipTextVocabPath",+ );+ }final textEmbedding = await runInIsolate(IsolateOperation.runClipText, {"text": query,"useRustMl": useRustMl,if (useRustMl) ...{"clipTextModelPath": modelPath,+ "clipTextVocabPath": vocabPath,"preferCoreml": Platform.isIOS,"preferNnapi": Platform.isAndroid,"preferXnnpack": Platform.isAndroid,@@ -108,26 +116,32 @@ class MLComputer extends SuperIsolate {Future<void> _ensureLoadedClipTextModel(bool useRustMl) async {return _initModelLock.synchronized(() async {try {- if (_isClipTokenizerInitialized &&- _clipTextModelPath != null &&- (useRustMl || ClipTextEncoder.instance.isInitialized)) {+ if (_clipTextVocabPath == null) {+ final tokenizerRemotePath = ClipTextEncoder.instance.vocabRemotePath;+ _clipTextVocabPath = await RemoteAssetsService.instance+ .getAssetPath(tokenizerRemotePath);+ }++ if (useRustMl &&+ _clipTextVocabPath != null &&+ _clipTextModelPath != null) {return;}- // Initialize ClipText tokenizer- if (!_isClipTokenizerInitialized) {- final String tokenizerRemotePath =- ClipTextEncoder.instance.vocabRemotePath;- final String tokenizerVocabPath = await RemoteAssetsService.instance- .getAssetPath(tokenizerRemotePath);+ if (!useRustMl &&+ _isClipTokenizerInitialized &&+ ClipTextEncoder.instance.isInitialized) {+ return;+ }++ if (!useRustMl && !_isClipTokenizerInitialized) {await runInIsolate(IsolateOperation.initializeClipTokenizer,- {'vocabPath': tokenizerVocabPath},+ {'vocabPath': _clipTextVocabPath!},);_isClipTokenizerInitialized = true;}- // Load ClipText modelfinal String? downloadedModelPath =await ClipTextEncoder.instance.downloadModelSafe();if (downloadedModelPath == null) {diff --git a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dartindex d84c8f910b..aaa21d6a90 100644--- a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart+++ b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart@@ -1,4 +1,4 @@-import 'dart:typed_data' show Float32List, Int32List, Uint8List;+import 'dart:typed_data' show Float32List, Uint8List;import "package:flutter_rust_bridge/flutter_rust_bridge.dart" show Uint64List;import "package:ml_linalg/linalg.dart";@@ -219,11 +219,18 @@ Future<dynamic> isolateFunction();}- final tokenIds = await ClipTextTokenizer.instance.tokenize(text);+ final clipTextVocabPath = args["clipTextVocabPath"] as String?;+ if (clipTextVocabPath == null || clipTextVocabPath.trim().isEmpty) {+ throw Exception(+ "RustMLMissingModelPath: Missing required model path: clipTextVocabPath",+ );+ }+final result = await rust_ml.runClipTextRust(req: rust_ml.RunClipTextRequest(- tokenIds: Int32List.fromList(tokenIds),+ text: text,modelPath: clipTextModelPath,+ vocabPath: clipTextVocabPath,providerPolicy: rust_ml.RustExecutionProviderPolicy(preferCoreml: args["preferCoreml"] as bool? ?? true,preferNnapi: args["preferNnapi"] as bool? ?? true,diff --git a/mobile/apps/photos/rust/Cargo.lock b/mobile/apps/photos/rust/Cargo.lockindex 7ed8a498f9..c6617baab0 100644--- a/mobile/apps/photos/rust/Cargo.lock+++ b/mobile/apps/photos/rust/Cargo.lock@@ -645,6 +645,7 @@ dependencies = ["ente_media_inspector","fast_image_resize","flutter_rust_bridge",+ "html-escape","image","imageproc","kamadak-exif",@@ -653,6 +654,7 @@ dependencies = ["ndarray 0.16.1","once_cell","ort",+ "regex","thiserror 2.0.18","usearch",]@@ -1008,6 +1010,15 @@ version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"+[[package]]+name = "html-escape"+version = "0.2.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6d1ad449764d627e22bfd7cd5e8868264fc9236e07c752972b4080cd351cb476"+dependencies = [+ "utf8-width",+]+[[package]]name = "image"version = "0.25.9"@@ -2310,6 +2321,12 @@ dependencies = ["cxx-build",]+[[package]]+name = "utf8-width"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1292c0d970b54115d14f2492fe0170adf21d68a1de108eebc51c1df4f346a091"+[[package]]name = "v_frame"version = "0.3.9"diff --git a/mobile/apps/photos/rust/Cargo.toml b/mobile/apps/photos/rust/Cargo.tomlindex d8a81bb0bd..7e333d68e2 100644--- a/mobile/apps/photos/rust/Cargo.toml+++ b/mobile/apps/photos/rust/Cargo.toml@@ -20,6 +20,8 @@ libheic-rs = { git = "https://github.com/laurens-pilot/libheic-rs.git", tag = "vnalgebra = "0.33.2"ndarray = "0.16.1"once_cell = "1.20.2"+regex = "1.11.1"+html-escape = "0.2.13"thiserror = "2.0.11"[target.'cfg(target_os = "ios")'.dependencies]diff --git a/mobile/apps/photos/rust/src/api/ml_indexing_api.rs b/mobile/apps/photos/rust/src/api/ml_indexing_api.rsindex 05ad7f8b2d..335750535a 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},+ clip::{image::run_clip_image, text::run_clip_text_query},error::{MlError, MlResult},face::{align::run_face_alignment, detect::run_face_detection, embed::run_face_embedding},runtime::{self, ExecutionProviderPolicy, MlRuntimeConfig, ModelPaths},@@ -94,8 +94,9 @@ pub struct AnalyzeImageResult {#[derive(Clone, Debug)]pub struct RunClipTextRequest {- pub token_ids: Vec<i32>,+ pub text: String,pub model_path: String,+ pub vocab_path: String,pub provider_policy: RustExecutionProviderPolicy,}@@ -169,8 +170,9 @@ fn analyze_image_rust_inner(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageRefn run_clip_text_rust_inner(req: RunClipTextRequest) -> MlResult<RunClipTextResult> {let RunClipTextRequest {- token_ids,+ text,model_path,+ vocab_path,provider_policy,} = req;@@ -179,6 +181,11 @@ fn run_clip_text_rust_inner(req: RunClipTextRequest) -> MlResult<RunClipTextResu"missing model path: clipTextModelPath".to_string(),));}+ if vocab_path.trim().is_empty() {+ return Err(MlError::InvalidRequest(+ "missing model path: clipTextVocabPath".to_string(),+ ));+ }let runtime_config = MlRuntimeConfig {model_paths: ModelPaths {@@ -191,7 +198,7 @@ fn run_clip_text_rust_inner(req: RunClipTextRequest) -> MlResult<RunClipTextResu};runtime::with_runtime_mut(&runtime_config, move |runtime| {- let clip = run_clip_text(runtime, &token_ids)?;+ let clip = run_clip_text_query(runtime, &text, &vocab_path)?;Ok(RunClipTextResult {embedding: clip.embeddingdiff --git a/mobile/apps/photos/rust/src/ml/clip/mod.rs b/mobile/apps/photos/rust/src/ml/clip/mod.rsindex ab1ed42573..c539df6d30 100644--- a/mobile/apps/photos/rust/src/ml/clip/mod.rs+++ b/mobile/apps/photos/rust/src/ml/clip/mod.rs@@ -1,2 +1,3 @@pub mod image;pub mod text;+pub mod tokenizer;diff --git a/mobile/apps/photos/rust/src/ml/clip/text.rs b/mobile/apps/photos/rust/src/ml/clip/text.rsindex a9d929543c..2c942df165 100644--- a/mobile/apps/photos/rust/src/ml/clip/text.rs+++ b/mobile/apps/photos/rust/src/ml/clip/text.rs@@ -1,4 +1,5 @@use crate::ml::{+ clip::tokenizer,error::{MlError, MlResult},onnx,runtime::MlRuntime,@@ -43,6 +44,15 @@ pub fn run_clip_text(runtime: &mut MlRuntime, token_ids: &[i32]) -> MlResult<CliOk(ClipResult { embedding })}+pub fn run_clip_text_query(+ runtime: &mut MlRuntime,+ query: &str,+ vocab_path: &str,+) -> MlResult<ClipResult> {+ let token_ids = tokenizer::tokenize_clip_text(query, vocab_path)?;+ run_clip_text(runtime, &token_ids)+}+fn normalize_embedding(embedding: &mut [f32]) {let mut norm = 0.0f32;for value in embedding.iter() {diff --git a/mobile/apps/photos/rust/src/ml/clip/tokenizer.rs b/mobile/apps/photos/rust/src/ml/clip/tokenizer.rsnew file mode 100644index 0000000000..1d52f8ae37--- /dev/null+++ b/mobile/apps/photos/rust/src/ml/clip/tokenizer.rs@@ -0,0 +1,322 @@+use std::{+ collections::{HashMap, HashSet},+ fs,+ sync::Mutex,+};++use html_escape::decode_html_entities;+use once_cell::sync::Lazy;+use regex::Regex;++use crate::ml::error::{MlError, MlResult};++const CLIP_TEXT_TOKEN_COUNT: usize = 77;+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}]+",+ )+ .expect("valid clip tokenizer regex")+});++static WHITESPACE_PATTERN: Lazy<Regex> =+ Lazy::new(|| Regex::new(r"\s+").expect("valid whitespace regex"));++struct TokenizerState {+ vocab_path: String,+ tokenizer: ClipTextTokenizer,+}++static TOKENIZER_STATE: Lazy<Mutex<Option<TokenizerState>>> = Lazy::new(|| Mutex::new(None));++pub fn tokenize_clip_text(text: &str, vocab_path: &str) -> MlResult<Vec<i32>> {+ let mut state = match TOKENIZER_STATE.lock() {+ Ok(guard) => guard,+ Err(poisoned) => {+ let mut guard = poisoned.into_inner();+ *guard = None;+ guard+ }+ };++ let needs_reload = match state.as_ref() {+ Some(existing) => existing.vocab_path != vocab_path,+ None => true,+ };++ if needs_reload {+ let tokenizer = ClipTextTokenizer::from_vocab_path(vocab_path)?;+ *state = Some(TokenizerState {+ vocab_path: vocab_path.to_string(),+ tokenizer,+ });+ }++ let tokenizer = state+ .as_mut()+ .ok_or_else(|| MlError::Runtime("clip tokenizer state unavailable".to_string()))?;+ tokenizer.tokenizer.tokenize(text)+}++struct ClipTextTokenizer {+ byte_encoder: HashMap<u8, String>,+ encoder: HashMap<String, i32>,+ bpe_ranks: HashMap<(String, String), usize>,+ cache: HashMap<String, String>,+ sot: i32,+ eot: i32,+}++impl ClipTextTokenizer {+ fn from_vocab_path(vocab_path: &str) -> MlResult<Self> {+ let vocabulary = fs::read_to_string(vocab_path)+ .map_err(|e| MlError::Runtime(format!("failed to read clip vocab file: {e}")))?;+ Self::from_vocabulary(&vocabulary)+ }++ fn from_vocabulary(vocabulary: &str) -> MlResult<Self> {+ let (byte_encoder, byte_encoder_values) = bytes_to_unicode()?;++ let split = vocabulary.split('\n').collect::<Vec<_>>();+ let merges_end = split.len().min(BPE_MERGES_END_EXCLUSIVE);+ let merges_slice = if split.len() > 1 {+ &split[1..merges_end]+ } else {+ &[][..]+ };++ let mut merges = Vec::<(String, String)>::new();+ for merge in merges_slice {+ let mut parts = merge.split_whitespace();+ let Some(first) = parts.next() else {+ continue;+ };+ let Some(second) = parts.next() else {+ continue;+ };+ merges.push((first.to_string(), second.to_string()));+ }++ let mut vocab = byte_encoder_values;+ let with_suffix = vocab+ .iter()+ .map(|value| format!("{value}</w>"))+ .collect::<Vec<_>>();+ vocab.extend(with_suffix);+ for (first, second) in &merges {+ vocab.push(format!("{first}{second}"));+ }+ vocab.push("<|startoftext|>".to_string());+ vocab.push("<|endoftext|>".to_string());++ let encoder = vocab+ .into_iter()+ .enumerate()+ .map(|(index, token)| (token, index as i32))+ .collect::<HashMap<_, _>>();++ let mut bpe_ranks = HashMap::with_capacity(merges.len());+ for (index, merge) in merges.into_iter().enumerate() {+ bpe_ranks.insert(merge, index);+ }++ let sot = *encoder+ .get("<|startoftext|>")+ .ok_or_else(|| MlError::Runtime("missing start token in vocab".to_string()))?;+ let eot = *encoder+ .get("<|endoftext|>")+ .ok_or_else(|| MlError::Runtime("missing end token in vocab".to_string()))?;++ let cache = HashMap::from([+ ("<|startoftext|>".to_string(), "<|startoftext|>".to_string()),+ ("<|endoftext|>".to_string(), "<|endoftext|>".to_string()),+ ]);++ Ok(Self {+ byte_encoder,+ encoder,+ bpe_ranks,+ cache,+ sot,+ eot,+ })+ }++ fn tokenize(&mut self, text: &str) -> MlResult<Vec<i32>> {+ let encoded = self.encode(text)?;+ let max_text_tokens = CLIP_TEXT_TOKEN_COUNT - 2;+ let truncated_len = encoded.len().min(max_text_tokens);++ let mut tokens = Vec::with_capacity(CLIP_TEXT_TOKEN_COUNT);+ tokens.push(self.sot);+ tokens.extend_from_slice(&encoded[..truncated_len]);+ tokens.push(self.eot);+ while tokens.len() < CLIP_TEXT_TOKEN_COUNT {+ tokens.push(0);+ }+ Ok(tokens)+ }++ fn encode(&mut self, text: &str) -> MlResult<Vec<i32>> {+ let mut bpe_tokens = Vec::<i32>::new();+ let clean_text = whitespace_clean(&basic_clean(text)).to_lowercase();+ for matched in TOKEN_PATTERN.find_iter(&clean_text) {+ let mut token = String::new();+ for byte in matched.as_str().as_bytes() {+ let value = self.byte_encoder.get(byte).ok_or_else(|| {+ MlError::Runtime(format!("missing byte encoding for byte {byte}"))+ })?;+ token.push_str(value);+ }++ let bpe = self.bpe(&token);+ for bpe_token in bpe.split(' ') {+ let token_id = self.encoder.get(bpe_token).ok_or_else(|| {+ MlError::Runtime(format!("missing BPE token in encoder: {bpe_token}"))+ })?;+ bpe_tokens.push(*token_id);+ }+ }+ Ok(bpe_tokens)+ }++ fn bpe(&mut self, token: &str) -> String {+ if let Some(cached) = self.cache.get(token) {+ return cached.clone();+ }++ let mut word = token.chars().map(|ch| ch.to_string()).collect::<Vec<_>>();+ if word.is_empty() {+ return String::new();+ }+ let last = word.len() - 1;+ word[last] = format!("{}{}", word[last], "</w>");++ let mut pairs = get_pairs(&word);+ if pairs.is_empty() {+ return format!("{token}</w>");+ }++ loop {+ let mut bigram = pairs[0].clone();+ for pair in &pairs {+ let rank1 = self.bpe_ranks.get(pair).copied().unwrap_or(usize::MAX);+ let rank2 = self.bpe_ranks.get(&bigram).copied().unwrap_or(usize::MAX);+ if rank1 < rank2 {+ bigram = pair.clone();+ }+ }++ if !self.bpe_ranks.contains_key(&bigram) {+ break;+ }++ let first = &bigram.0;+ let second = &bigram.1;+ let mut new_word = Vec::<String>::new();+ let mut i = 0usize;+ while i < word.len() {+ let j = index_of(&word[i..], first);+ let Some(j) = j else {+ new_word.extend(word[i..].iter().cloned());+ break;+ };++ new_word.extend(word[i..(i + j)].iter().cloned());+ i += j;++ if word[i] == *first && i < word.len() - 1 && word[i + 1] == *second {+ new_word.push(format!("{first}{second}"));+ i += 2;+ } else {+ new_word.push(word[i].clone());+ i += 1;+ }+ }++ word = new_word;+ if word.len() == 1 {+ break;+ }+ pairs = get_pairs(&word);+ }++ let word_str = word.join(" ");+ self.cache.insert(token.to_string(), word_str.clone());+ word_str+ }+}++fn basic_clean(text: &str) -> String {+ let decoded_once = decode_html_entities(text).to_string();+ let decoded_twice = decode_html_entities(&decoded_once).to_string();+ decoded_twice.trim().to_string()+}++fn whitespace_clean(text: &str) -> String {+ let replaced = WHITESPACE_PATTERN.replace_all(text, " ");+ replaced.trim().to_string()+}++fn get_pairs(word: &[String]) -> Vec<(String, String)> {+ if word.len() < 2 {+ return Vec::new();+ }+ let mut seen = HashSet::<(String, String)>::new();+ let mut pairs = Vec::<(String, String)>::new();+ let mut previous = word[0].clone();+ for current in word.iter().skip(1) {+ let pair = (previous.clone(), current.clone());+ if seen.insert(pair.clone()) {+ pairs.push(pair);+ }+ previous = current.clone();+ }+ pairs+}++fn index_of(values: &[String], needle: &str) -> Option<usize> {+ values.iter().position(|value| value == needle)+}++fn bytes_to_unicode() -> MlResult<(HashMap<u8, String>, Vec<String>)> {+ let mut bs = Vec::<u32>::new();+ for code in b'!'..=b'~' {+ bs.push(code as u32);+ }+ for code in ('¡' as u32)..=('¬' as u32) {+ bs.push(code);+ }+ for code in ('®' as u32)..=('ÿ' as u32) {+ bs.push(code);+ }++ let mut cs = bs.clone();+ let mut n = 0u32;+ for b in 0u32..256u32 {+ if !bs.contains(&b) {+ bs.push(b);+ cs.push(256 + n);+ n += 1;+ }+ }++ let mut ds = Vec::<String>::with_capacity(cs.len());+ for code in cs {+ let ch = char::from_u32(code).ok_or_else(|| {+ MlError::Runtime(format!(+ "invalid unicode scalar generated for byte map: {code}"+ ))+ })?;+ ds.push(ch.to_string());+ }++ let mut byte_encoder = HashMap::<u8, String>::new();+ for (index, byte_value) in bs.iter().enumerate() {+ let key = *byte_value as u8;+ byte_encoder.insert(key, ds[index].clone());+ }++ Ok((byte_encoder, ds))+}