π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Fix Android custom model generation budgets
Prateek Sunal40f51dd3c49e
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/llm/InferenceRsProvider.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/llm/InferenceRsProvider.ktindex 5cd10efce8..8d6ab49971 100644--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/llm/InferenceRsProvider.kt+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/llm/InferenceRsProvider.kt@@ -37,13 +37,19 @@ class InferenceRsProvider(private val modelDir: File,private val ioDispatcher: kotlinx.coroutines.CoroutineDispatcher = Dispatchers.IO) : LlmProvider {+ private data class LoadedModelKey(+ val id: String,+ val requestedContextLength: Int?+ )+private val httpClient = OkHttpClient()private val downloadCancelled = AtomicBoolean(false)@Volatile private var downloadCall: Call? = null@Volatile private var modelHandle: ModelHandle? = null@Volatile private var contextHandle: ContextHandle? = null- @Volatile private var currentModelId: String? = null+ @Volatile private var currentModelKey: LoadedModelKey? = null+ @Volatile private var currentContextLength: Int? = null@Volatile private var currentJobId: Long? = nullprivate var backendInitialized = false@@ -56,12 +62,13 @@ class InferenceRsProvider(onProgress: (DownloadProgress) -> Unit) {withContext(ioDispatcher) {+ val modelKey = LoadedModelKey(target.id, target.contextLength)if (!backendInitialized) {initBackend()backendInitialized = true}- if (currentModelId == target.id && contextHandle != null && modelHandle != null) {+ if (currentModelKey == modelKey && contextHandle != null && modelHandle != null) {return@withContext}@@ -71,35 +78,54 @@ class InferenceRsProvider(val mmprojFile = mmprojPathFor(target)val mmprojUrl = target.mmprojUrl- val downloads = mutableListOf<DownloadTarget>()- if (!modelFile.exists()) {- downloads.add(DownloadTarget("Model", target.url, modelFile))- }- if (mmprojFile != null && !mmprojUrl.isNullOrBlank() && !mmprojFile.exists()) {- downloads.add(DownloadTarget("Mmproj", mmprojUrl, mmprojFile))+ val expectedTargets = mutableListOf<DownloadTarget>()+ expectedTargets.add(DownloadTarget("Model", target.url, modelFile))+ if (mmprojFile != null && !mmprojUrl.isNullOrBlank()) {+ expectedTargets.add(DownloadTarget("Mmproj", mmprojUrl, mmprojFile))}+ val downloads = expectedTargets.filterNot { it.destination.exists() }+if (downloads.isNotEmpty()) {downloadCancelled.set(false)- onProgress(DownloadProgress(0, "Starting download..."))modelFile.parentFile?.mkdirs()mmprojFile?.parentFile?.mkdirs()- val lengths = downloads.map { fetchContentLength(it.url) }+ val lengths = expectedTargets.map { download ->+ download.destination.length().takeIf { it > 0 } ?: fetchContentLength(download.url)+ }val totalBytes = lengths.filterNotNull().sum()val hasTotal = lengths.all { it != null } && totalBytes > 0- var downloadedSoFar = 0L+ var downloadedSoFar = expectedTargets.zip(lengths).sumOf { (download, total) ->+ existingDownloadBytes(download.destination).coerceAtMost(total ?: existingDownloadBytes(download.destination))+ }++ if (hasTotal && downloadedSoFar > 0) {+ val initialPercent = ((downloadedSoFar * 100) / totalBytes).toInt().coerceIn(0, 99)+ onProgress(+ DownloadProgress(+ initialPercent,+ "Downloading... ${formatBytes(downloadedSoFar)} / ${formatBytes(totalBytes)}"+ )+ )+ } else {+ onProgress(DownloadProgress(0, "Starting download..."))+ }- downloads.forEachIndexed { index, download ->- val fileTotal = lengths[index]+ downloads.forEach { download ->+ val expectedIndex = expectedTargets.indexOfFirst { it.destination == download.destination }+ val fileTotal = lengths.getOrNull(expectedIndex)+ val existingBytesForFile = existingDownloadBytes(download.destination)+ // downloadedSoFar already includes any resumed bytes for this file.+ val bytesBeforeFile = downloadedSoFar - existingBytesForFiledownloadFile(download.url, download.destination) { downloaded, total ->- val overallDownloaded = downloadedSoFar + downloaded+ val overallDownloaded = bytesBeforeFile + downloadedval percent = if (hasTotal) {((overallDownloaded * 100) / totalBytes).toInt()} else {- val step = 100f / downloads.size+ val step = 100f / expectedTargets.sizeval filePercent = total?.let { downloaded.toFloat() / it } ?: 0f- ((index * step) + (filePercent * step)).toInt()+ ((expectedIndex.coerceAtLeast(0) * step) + (filePercent * step)).toInt()}val status = if (hasTotal) {"Downloading... ${formatBytes(overallDownloaded)} / ${formatBytes(totalBytes)}"@@ -108,7 +134,7 @@ class InferenceRsProvider(}onProgress(DownloadProgress(percent.coerceIn(0, 99), status))}- downloadedSoFar += fileTotal ?: download.destination.length()+ downloadedSoFar = bytesBeforeFile + (fileTotal ?: existingDownloadBytes(download.destination))}}@@ -123,7 +149,7 @@ class InferenceRsProvider(messages: List<LlmMessage>,imageFiles: List<File>,temperature: Float,- maxTokens: Int,+ maxTokens: Int?,onToken: (String) -> Unit): GenerationSummary = withContext(ioDispatcher) {val context = contextHandle ?: throw IllegalStateException("Model context not loaded")@@ -186,6 +212,15 @@ class InferenceRsProvider(if (sizes.isEmpty()) null else sizes.sum()}+ override fun loadedContextLength(target: LlmModelTarget): Int? {+ val modelKey = LoadedModelKey(target.id, target.contextLength)+ return if (currentModelKey == modelKey && contextHandle != null && modelHandle != null) {+ currentContextLength+ } else {+ null+ }+ }+override fun stopGeneration() {val jobId = currentJobIdif (jobId != null) {@@ -198,7 +233,7 @@ class InferenceRsProvider(override fun resetContext() {val model = modelHandle ?: returnval contextParams = ContextParams(- contextSize = null,+ contextSize = currentContextLength,nThreads = null,nBatch = null)@@ -224,12 +259,13 @@ class InferenceRsProvider(contextHandle = nullmodelHandle?.destroy()modelHandle = null- currentModelId = null+ currentModelKey = null+ currentContextLength = null}private fun loadWithFallbacks(target: LlmModelTarget, modelFile: File) {- val desiredCtx = target.contextLength ?: 4096- val contexts = listOf(desiredCtx, 4096, 2048, 1024).distinct().filter { it > 0 }+ val desiredCtx = target.contextLength ?: 12000+ val contexts = listOf(desiredCtx, 12000, 8192, 4096, 2048, 1024).distinct().filter { it > 0 }val threads = max(1, Runtime.getRuntime().availableProcessors() - 1)val batch = 512@@ -252,7 +288,8 @@ class InferenceRsProvider(nBatch = batch)contextHandle = createContext(model, contextParams)- currentModelId = target.id+ currentModelKey = LoadedModelKey(target.id, target.contextLength)+ currentContextLength = ctxreturn} catch (err: Throwable) {lastError = err@@ -380,9 +417,15 @@ class InferenceRsProvider(return pathForUrl(target, url, fallback = "mmproj.gguf")}+ private fun existingDownloadBytes(dest: File): Long {+ if (dest.exists()) return dest.length()+ val tmp = File(dest.absolutePath + ".tmp")+ return tmp.length().takeIf { tmp.exists() && it > 0 } ?: 0L+ }+private fun pathForUrl(target: LlmModelTarget, url: String, fallback: String): File {val baseDir = File(modelDir, "models")- val filename = url.substringAfterLast('/').ifBlank { fallback }+ val filename = filenameForUrl(url, fallback)return if (target.id.startsWith("custom:")) {val customDir = File(baseDir, "custom")File(customDir, "${hash(url)}_$filename")@@ -391,6 +434,11 @@ class InferenceRsProvider(}}+ private fun filenameForUrl(url: String, fallback: String): String {+ val withoutQuery = url.substringBefore('?').substringBefore('#')+ return withoutQuery.substringAfterLast('/').ifBlank { fallback }+ }+private fun looksLikeGguf(file: File): Boolean {if (!file.exists() || file.length() < 4) return falseval header = ByteArray(4)diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/llm/LlmProvider.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/llm/LlmProvider.ktindex c23b54343f..04010d3022 100644--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/llm/LlmProvider.kt+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/llm/LlmProvider.kt@@ -45,12 +45,13 @@ interface LlmProvider {messages: List<LlmMessage>,imageFiles: List<File>,temperature: Float,- maxTokens: Int,+ maxTokens: Int?,onToken: (String) -> Unit): GenerationSummaryfun isModelDownloaded(target: LlmModelTarget): Booleansuspend fun estimateModelDownloadSize(target: LlmModelTarget): Long?+ fun loadedContextLength(target: LlmModelTarget): Int?fun stopGeneration()fun resetContext()diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.ktindex d3d881fe23..95211734f3 100644--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.kt+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.kt@@ -30,6 +30,7 @@ import kotlinx.coroutines.launchimport kotlinx.coroutines.withContextimport kotlin.math.absimport kotlin.math.max+import kotlin.math.mininternal class ChatStoreActions(private val state: MutableStateFlow<AppState>,@@ -450,23 +451,6 @@ internal class ChatStoreActions(val settings = state.value.modelSettingsval target = modelSettingsActions.resolveTarget(settings)val prompt = buildPrompt(userMessage.text, userMessage.attachments)- val historySelection = buildHistorySelection(- sessionId = sessionId,- promptText = prompt.text,- promptImageCount = prompt.imageFiles.size,- currentMessageId = userMessage.id,- target = target- )-- if (historySelection.wasTrimmed && overflowBypassMessageId != userMessage.id) {- pendingOverflow = PendingOverflow(sessionId, userMessage.id)- showOverflowDialog(historySelection, target)- return- }-- overflowBypassMessageId = null- pendingOverflow = null- clearOverflowDialog()val generationToken = nextGenerationToken()streamingParentId = userMessage.id@@ -487,19 +471,19 @@ internal class ChatStoreActions(generationJob = scope.launch {val isActive = { isGenerationActive(generationToken, sessionId) }+ val progressTracker = DownloadProgressTracker()try {llmProvider.ensureModelReady(target) { progress ->if (!isActive()) return@ensureModelReady- val downloading = (progress.percent in 0..99) || progress.status.contains("Loading", ignoreCase = true)- val finished = progress.status.contains("Ready", ignoreCase = true)+ val resolvedProgress = progressTracker.resolve(progress)state.update { appState ->appState.copy(chat = appState.chat.copy(- isDownloading = downloading && !finished,- downloadPercent = progress.percent.takeIf { it >= 0 },- downloadStatus = progress.status,- isModelDownloaded = if (finished) true else appState.chat.isModelDownloaded,- modelDownloadSizeBytes = if (finished) null else appState.chat.modelDownloadSizeBytes+ isDownloading = resolvedProgress.isDownloading,+ downloadPercent = resolvedProgress.percent,+ downloadStatus = resolvedProgress.status,+ isModelDownloaded = if (resolvedProgress.isFinished) true else appState.chat.isModelDownloaded,+ modelDownloadSizeBytes = if (resolvedProgress.isFinished) null else appState.chat.modelDownloadSizeBytes))}@@ -536,6 +520,44 @@ internal class ChatStoreActions(if (!isActive()) return@launch+ state.update { appState ->+ appState.copy(chat = appState.chat.copy(isModelDownloaded = true))+ }++ val generationLimits = resolveGenerationLimits(target)+ val historySelection = buildHistorySelection(+ sessionId = sessionId,+ promptText = prompt.text,+ promptImageCount = prompt.imageFiles.size,+ currentMessageId = userMessage.id,+ limits = generationLimits+ )++ if (historySelection.wasTrimmed && overflowBypassMessageId != userMessage.id) {+ overflowBypassMessageId = null+ pendingOverflow = PendingOverflow(sessionId, userMessage.id)+ streamingParentId = null+ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ isGenerating = false,+ isDownloading = false,+ streamingResponse = "",+ streamingParentId = null,+ downloadPercent = null,+ downloadStatus = null+ )+ )+ }+ showOverflowDialog(historySelection, generationLimits)+ rebuildChatState(sessionId)+ return@launch+ }++ overflowBypassMessageId = null+ pendingOverflow = null+ clearOverflowDialog()+val history = historySelection.messagesval systemPrompt = buildSystemPrompt()val systemMessage = LlmMessage(@@ -557,7 +579,7 @@ internal class ChatStoreActions(messages = llmMessages,imageFiles = prompt.imageFiles,temperature = modelSettingsActions.resolveTemperature(settings),- maxTokens = target.maxTokens ?: 1024+ maxTokens = generationLimits.maxOutput) { token ->buffer.append(token)tokenCount += estimateTokens(token)@@ -1002,6 +1024,11 @@ internal class ChatStoreActions(val wasTrimmed: Boolean)+ private data class GenerationLimits(+ val contextLength: Int,+ val maxOutput: Int+ )+private data class PendingOverflow(val sessionId: String,val messageId: String@@ -1043,13 +1070,11 @@ internal class ChatStoreActions(promptText: String,promptImageCount: Int,currentMessageId: String,- target: LlmModelTarget+ limits: GenerationLimits): HistorySelection {val path = buildSelectedPath(sessionId)val historyMessages = path.takeWhile { it.id != currentMessageId }- val contextSize = target.contextLength ?: 4096- val maxOutput = target.maxTokens ?: 1024- val inputBudget = max(0, contextSize - maxOutput - OVERFLOW_SAFETY_TOKENS)+ val inputBudget = max(0, limits.contextLength - limits.maxOutput - OVERFLOW_SAFETY_TOKENS)val systemPrompt = buildSystemPrompt()val systemTokens = estimateTokens(systemPrompt)val promptTokens = estimatePromptTokens(promptText, promptImageCount)@@ -1082,15 +1107,29 @@ internal class ChatStoreActions(return HistorySelection(selected.reversed(), inputTokens, inputBudget, inputTokens > inputBudget)}- private fun showOverflowDialog(selection: HistorySelection, target: LlmModelTarget) {+ private fun resolveGenerationLimits(target: LlmModelTarget): GenerationLimits {+ val contextLength = llmProvider.loadedContextLength(target)+ ?: target.contextLength+ ?: DEFAULT_CONTEXT_LENGTH+ val maxOutput = resolveMaxOutputTokens(target.maxTokens, contextLength)+ return GenerationLimits(contextLength = contextLength, maxOutput = maxOutput)+ }++ private fun resolveMaxOutputTokens(configuredMaxTokens: Int?, contextLength: Int): Int {+ val maxAllowed = max(1, contextLength - OVERFLOW_SAFETY_TOKENS)+ val implicitMax = min(DEFAULT_GENERATION_MAX_TOKENS, max(1, contextLength / 2))+ return (configuredMaxTokens ?: implicitMax).coerceIn(1, maxAllowed)+ }++ private fun showOverflowDialog(selection: HistorySelection, limits: GenerationLimits) {state.update { appState ->appState.copy(chat = appState.chat.copy(overflowDialog = io.ente.ensu.domain.state.OverflowDialogState(inputTokens = selection.inputTokens,inputBudget = selection.inputBudget,- contextLength = target.contextLength ?: 4096,- maxOutput = target.maxTokens ?: 1024+ contextLength = limits.contextLength,+ maxOutput = limits.maxOutput)))@@ -1186,6 +1225,8 @@ internal class ChatStoreActions(}companion object {+ private const val DEFAULT_CONTEXT_LENGTH = 12_000+ private const val DEFAULT_GENERATION_MAX_TOKENS = 8_192private const val MEDIA_MARKER = "<__media__>"private const val OVERFLOW_SAFETY_TOKENS = 128private const val IMAGE_TOKEN_ESTIMATE = 768diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/DownloadProgressTracker.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/DownloadProgressTracker.ktnew file mode 100644index 0000000000..df5db7ea58--- /dev/null+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/DownloadProgressTracker.kt@@ -0,0 +1,54 @@+package io.ente.ensu.domain.store++import io.ente.ensu.domain.llm.DownloadProgress++internal data class ResolvedDownloadProgress(+ val percent: Int?,+ val status: String,+ val isDownloading: Boolean,+ val isFinished: Boolean+)++internal class DownloadProgressTracker(+ initialPercent: Int? = 0,+ initialStatus: String? = "Starting download..."+) {+ private var lastVisiblePercent: Int? = initialPercent+ private var lastVisibleStatus: String? = initialStatus++ fun resolve(progress: DownloadProgress): ResolvedDownloadProgress {+ val isLoading = progress.status.contains("Loading", ignoreCase = true)+ val isFinished = progress.status.contains("Ready", ignoreCase = true)+ val rawPercent = progress.percent.takeIf { it >= 0 }+ val previousPercent = lastVisiblePercent+ val previousStatus = lastVisibleStatus++ val resolvedPercent = when {+ isFinished -> 100+ rawPercent == null -> previousPercent+ previousPercent == null -> rawPercent+ rawPercent >= previousPercent -> rawPercent+ else -> previousPercent+ }+ val regressed = rawPercent != null &&+ previousPercent != null &&+ rawPercent < previousPercent+ val resolvedStatus = when {+ isFinished || isLoading -> progress.status+ regressed -> previousStatus ?: progress.status+ else -> progress.status+ }++ if (!isFinished) {+ lastVisiblePercent = resolvedPercent+ lastVisibleStatus = resolvedStatus+ }++ return ResolvedDownloadProgress(+ percent = resolvedPercent,+ status = resolvedStatus,+ isDownloading = ((progress.percent in 0..99) || isLoading) && !isFinished,+ isFinished = isFinished+ )+ }+}