From ed54423630f25d4151262214dcdd16812c748f2e Mon Sep 17 00:00:00 2001 From: Bobby Bones Date: Tue, 1 Dec 2026 11:18:05 -0500 Subject: [PATCH] feat: bundled INT8 dual-tower encoder, zero-permission OCR & :models_pack --- .github/workflows/ci.yml | 12 +- .gitignore | 1 + README.md | 13 +- app/build.gradle.kts | 25 +- .../recall/engine/BitmapOcrExtractor.kt | 407 ++++++++++++++++++ .../recall/engine/FreeSchedEngine.kt | 120 ++++-- .../recall/engine/Int8DualTowerEncoder.kt | 188 ++++++++ .../recall/engine/ModelPackLoader.kt | 156 +++++++ .../recall/imports/ImportManager.kt | 32 ++ .../recall/store/RecallDatabase.kt | 14 +- .../freesilicon/recall/ui/RecallViewModel.kt | 18 +- .../recall/ui/screens/BenchmarkScreen.kt | 2 +- .../recall/Int8EncoderAndOcrTest.kt | 209 +++++++++ build.gradle.kts | 1 + models_pack/build.gradle.kts | 10 + .../main/assets/recall_models/manifest.json | 23 + scripts/clean-room-audit.sh | 2 +- scripts/export-int8-models.py | 164 +++++++ settings.gradle.kts | 2 +- 19 files changed, 1348 insertions(+), 51 deletions(-) create mode 100644 app/src/main/java/org/freesilicon/recall/engine/BitmapOcrExtractor.kt create mode 100644 app/src/main/java/org/freesilicon/recall/engine/Int8DualTowerEncoder.kt create mode 100644 app/src/main/java/org/freesilicon/recall/engine/ModelPackLoader.kt create mode 100644 app/src/test/java/org/freesilicon/recall/Int8EncoderAndOcrTest.kt create mode 100644 models_pack/build.gradle.kts create mode 100644 models_pack/src/main/assets/recall_models/manifest.json create mode 100755 scripts/export-int8-models.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b6e42ae..a5a4ab4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -50,11 +50,19 @@ jobs: - name: Build pinned FreeSched 16 KiB AAR run: ./scripts/build-freesched-aar.sh - - name: Run unit tests & assembleDebug - run: ./gradlew --no-daemon testDebugUnitTest assembleDebug + - name: Run unit tests, assembleDebug & bundleDebug (with :models_pack) + run: ./gradlew --no-daemon testDebugUnitTest assembleDebug bundleDebug - name: Verify zero platform permissions in merged manifest & APK run: ./scripts/check-zero-permissions.sh app/build/outputs/apk/debug/app-debug.apk - name: Verify 16 KiB PT_LOAD 0x4000 & zipalign -P 16 on APK run: ./scripts/check-16k-alignment.sh app/build/outputs/apk/debug/app-debug.apk + + - name: Verify INT8 model packs in AAB (:models_pack) and debug APK + run: | + set -euo pipefail + unzip -l app/build/outputs/bundle/debug/app-debug.aab | grep -q "models_pack/assets/recall_models/dual_tower_int8.rcl1" + unzip -l app/build/outputs/bundle/debug/app-debug.aab | grep -q "models_pack/assets/recall_models/ocr_glyphs_int8.rcl1" + unzip -l app/build/outputs/apk/debug/app-debug.apk | grep -q "recall_models/dual_tower_int8.rcl1" + unzip -l app/build/outputs/apk/debug/app-debug.apk | grep -q "recall_models/ocr_glyphs_int8.rcl1" diff --git a/.gitignore b/.gitignore index 44f5b2b..9995b05 100644 --- a/.gitignore +++ b/.gitignore @@ -21,6 +21,7 @@ local.properties app/libs/*.aar app/libs/*.jar gradle/wrapper/gradle-wrapper.jar +models_pack/src/main/assets/recall_models/*.rcl1 # Compose Preview outputs build/compose-preview/ diff --git a/README.md b/README.md index 7622bef..b88ecb8 100644 --- a/README.md +++ b/README.md @@ -15,11 +15,12 @@ Recall (`org.freesilicon.recall`) indexes and searches your screenshots locally ## Architecture 1. **Import & Dedupe (`ImportManager`, `Sha256Hasher`)** — Streams incoming URIs through SHA-256 deduplication and reserves a monotonic `import_generation` in SQLite. -2. **FreeSched Hardware Telemetry (`FreeSchedEngine`)** — Discovers NNAPI accelerators (`google-edgetpu`, `qti-htp`/`qti-dsp`, `mtk-neuron`/`mtk-mdla`) via `freesilicon/freesched` and reports honest active-backend telemetry (falling back to Vulkan GPU / CPU without faking NPU acceleration). -3. **Hybrid Store (`RecallDatabase`)** — Combines SQLite `fts5` (`bm25`) lexical search with quantized 512-d INT8 cosine similarity and normalized OCR bounding boxes. -4. **3-Screen Jetpack Compose UI** — +2. **Bundled INT8 Encoders & Zero-Permission OCR (`Int8DualTowerEncoder`, `BitmapOcrExtractor`, `:models_pack`)** — Play Asset Delivery install-time pack (`dual_tower_int8.rcl1` + `ocr_glyphs_int8.rcl1`, deterministically generated at build time by `scripts/export-int8-models.py`) provides 512-d INT8 dual-tower embeddings and light/dark-aware on-device OCR with normalized bounding boxes. +3. **FreeSched Hardware Telemetry & 8-Image Calibration (`FreeSchedEngine`)** — Discovers NNAPI accelerators (`google-edgetpu`, `qti-htp`/`qti-dsp`, `mtk-neuron`/`mtk-mdla`) via `freesilicon/freesched` and runs an apples-to-apples 8-image 2-layer FFN calibration (`64 -> 128 -> 64`) on CPU vs FreeSched AHB+NNAPI without faking NPU speedup on fallback. +4. **Hybrid Store (`RecallDatabase`)** — Combines SQLite `fts5` (`bm25`) lexical search with quantized 512-d INT8 cosine similarity and normalized OCR bounding boxes. +5. **3-Screen Jetpack Compose UI** — - **Search Home:** Instant semantic + OCR search, matched snippet pills, masonry grid, and `+ Import` sheet. - - **Indexing & Benchmark Card:** Live batch telemetry + 1-tap dark-mode PNG **Hardware Card** exporter (zero personal screenshots included). + - **Indexing & Benchmark Card:** Live batch telemetry, 8-image calibration comparison, and 1-tap PNG **Hardware Card** exporter (zero personal screenshots included). - **Result Detail & Crop Jump:** Pinch/pan zoom focused on matched OCR bounding boxes, `Copy`, `Share`, `Redact` (v1.1 hook), and atomic `Delete`. ## Build & Verify @@ -28,8 +29,8 @@ Recall (`org.freesilicon.recall`) indexes and searches your screenshots locally # 1. Sync pinned freesilicon/freesched (c795eed1) & build its 16 KiB arm64-v8a AAR ./scripts/build-freesched-aar.sh -# 2. Run JVM + Robolectric unit tests & assemble debug APK -./gradlew testDebugUnitTest assembleDebug +# 2. Run JVM + Robolectric unit tests, assemble debug APK & Play Asset Delivery AAB +./gradlew testDebugUnitTest assembleDebug bundleDebug # 3. Verify zero platform permissions, 16 KiB ELF alignment, and clean-room boundaries ./scripts/check-zero-permissions.sh diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 940afb8..ba3cac5 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -14,9 +14,29 @@ val ensureFreeSchedAar by tasks.registering(Exec::class) { commandLine("bash", "scripts/build-freesched-aar.sh") } +val exportInt8Models by tasks.registering(Exec::class) { + workingDir = rootProject.projectDir + commandLine("python3", "scripts/export-int8-models.py") + inputs.file(rootProject.file("scripts/export-int8-models.py")) + outputs.files( + rootProject.file("models_pack/src/main/assets/recall_models/dual_tower_int8.rcl1"), + rootProject.file("models_pack/src/main/assets/recall_models/ocr_glyphs_int8.rcl1"), + ) +} + android { namespace = "org.freesilicon.recall" compileSdk = 35 + assetPacks += listOf(":models_pack") + + sourceSets { + getByName("debug") { + resources.srcDir(rootProject.file("models_pack/src/main/assets")) + } + getByName("test") { + resources.srcDir(rootProject.file("models_pack/src/main/assets")) + } + } defaultConfig { applicationId = "org.freesilicon.recall" @@ -78,7 +98,10 @@ android { } tasks.named("preBuild").configure { - dependsOn(ensureFreeSchedAar) + dependsOn(ensureFreeSchedAar, exportInt8Models) +} +tasks.matching { it.name.contains("AssetPack", ignoreCase = true) }.configureEach { + dependsOn(exportInt8Models) } // Fail build if any unexpected uses-permission slips into the merged debug/release manifest. diff --git a/app/src/main/java/org/freesilicon/recall/engine/BitmapOcrExtractor.kt b/app/src/main/java/org/freesilicon/recall/engine/BitmapOcrExtractor.kt new file mode 100644 index 0000000..872b20b --- /dev/null +++ b/app/src/main/java/org/freesilicon/recall/engine/BitmapOcrExtractor.kt @@ -0,0 +1,407 @@ +package org.freesilicon.recall.engine + +import android.graphics.Bitmap +import org.freesilicon.recall.model.OcrBox +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.min +import kotlin.math.roundToInt +import kotlin.math.sqrt + +/** + * Zero-permission, clean-room on-device OCR extractor backed by `ocr_glyphs_int8.rcl1`. + * + * Pipeline: + * 1. Grayscale conversion + border-aware Otsu binarization (supports both light & dark UI screenshots). + * 2. Horizontal projection line segmentation. + * 3. Vertical projection character segmentation + word gap grouping. + * 4. 8x12 INT8 template cosine matching against bundled `OcrGlyphPack`. + * + * Returns extracted full text and normalized `[0, 1]` bounding boxes per word. + * Never fabricates text or boxes on blank/uniform images. + */ +class BitmapOcrExtractor( + private val glyphPack: OcrGlyphPack?, +) : OcrExtractor { + + override fun extract(bitmap: Bitmap?, displayName: String): OcrExtractionResult { + val pack = glyphPack ?: return OcrExtractionResult("", emptyList()) + if (bitmap == null || bitmap.width < MIN_BITMAP_DIM || bitmap.height < MIN_BITMAP_DIM) { + return OcrExtractionResult("", emptyList()) + } + + // Bound working resolution so large screenshots stay fast and memory-bounded. + val scale = computeDownscale(bitmap.width, bitmap.height) + val w = (bitmap.width / scale).coerceAtLeast(1) + val h = (bitmap.height / scale).coerceAtLeast(1) + if (w < MIN_BITMAP_DIM || h < MIN_BITMAP_DIM) { + return OcrExtractionResult("", emptyList()) + } + + val pixels = IntArray(w * h) + if (scale == 1) { + bitmap.getPixels(pixels, 0, w, 0, 0, w, h) + } else { + val scaled = Bitmap.createScaledBitmap(bitmap, w, h, true) + scaled.getPixels(pixels, 0, w, 0, 0, w, h) + if (scaled !== bitmap) scaled.recycle() + } + + val gray = IntArray(w * h) + val hist = IntArray(256) + var minLum = 255 + var maxLum = 0 + for (i in pixels.indices) { + val p = pixels[i] + val r = (p ushr 16) and 0xFF + val g = (p ushr 8) and 0xFF + val b = p and 0xFF + val lum = (77 * r + 150 * g + 29 * b) ushr 8 + gray[i] = lum + hist[lum]++ + if (lum < minLum) minLum = lum + if (lum > maxLum) maxLum = lum + } + + // Blank or ultra-low-contrast image: do not fabricate OCR boxes. + if (maxLum - minLum < MIN_CONTRAST) { + return OcrExtractionResult("", emptyList()) + } + + val threshold = otsuThreshold(hist, w * h) + val borderMean = estimateBorderLuminance(gray, w, h) + // If border is bright (light theme), dark pixels are ink; if border is dark, bright pixels are ink. + val inkIsDark = borderMean >= threshold + + val ink = BooleanArray(w * h) + var inkCount = 0 + for (i in gray.indices) { + val isInk = if (inkIsDark) gray[i] < threshold else gray[i] > threshold + ink[i] = isInk + if (isInk) inkCount++ + } + + val inkRatio = inkCount.toFloat() / (w * h).toFloat() + if (inkRatio < 0.0004f || inkRatio > 0.65f) { + return OcrExtractionResult("", emptyList()) + } + + val lineBands = segmentHorizontalLines(ink, w, h) + if (lineBands.isEmpty()) { + return OcrExtractionResult("", emptyList()) + } + + val boxes = ArrayList() + val lineTexts = ArrayList() + + for (band in lineBands.take(MAX_LINES)) { + val lineWords = extractLineWords(ink, w, h, band.first, band.second, pack) + if (lineWords.isNotEmpty()) { + val joined = lineWords.joinToString(" ") { it.text } + if (joined.isNotBlank()) { + lineTexts.add(joined) + for (wordBox in lineWords) { + if (boxes.size < MAX_BOXES) boxes.add(wordBox) + } + } + } + } + + return OcrExtractionResult( + fullText = lineTexts.joinToString("\n"), + boxes = boxes, + ) + } + + private fun extractLineWords( + ink: BooleanArray, + w: Int, + h: Int, + y0: Int, + y1: Int, + pack: OcrGlyphPack, + ): List { + val lineH = (y1 - y0 + 1) + if (lineH < MIN_LINE_HEIGHT) return emptyList() + + // Vertical projection of ink columns within [y0..y1] + val colCounts = IntArray(w) + for (y in y0..y1) { + val rowOff = y * w + for (x in 0 until w) { + if (ink[rowOff + x]) colCounts[x]++ + } + } + + val rawCols = ArrayList() + var x = 0 + while (x < w) { + while (x < w && colCounts[x] == 0) x++ + if (x >= w) break + val start = x + while (x < w && colCounts[x] > 0) x++ + val end = x - 1 + val cw = end - start + 1 + if (cw >= MIN_GLYPH_WIDTH && cw <= lineH * 3) { + rawCols.add(start..end) + } + } + if (rawCols.isEmpty()) return emptyList() + + val widths = rawCols.map { it.last - it.first + 1 }.sorted() + val medianW = widths[widths.size / 2].coerceAtLeast(3) + val spaceThreshold = max((medianW * 0.90f).roundToInt(), (lineH * 0.60f).roundToInt()).coerceAtLeast(4) + + val words = ArrayList() + val curText = StringBuilder() + var wordLeft = -1 + var wordRight = -1 + var wordTop = y1 + var wordBottom = y0 + var prevEnd = -1 + var scoreSum = 0f + var charCount = 0 + + fun flushWord() { + if (curText.isNotEmpty() && wordLeft >= 0 && wordRight >= wordLeft) { + val meanScore = if (charCount > 0) scoreSum / charCount else 0f + if (curText.length >= 2 || meanScore >= HIGH_CONF_SINGLE_CHAR) { + words.add( + OcrBox( + text = curText.toString(), + left = (wordLeft.toFloat() / w.toFloat()).coerceIn(0f, 1f), + top = (wordTop.toFloat() / h.toFloat()).coerceIn(0f, 1f), + right = ((wordRight + 1).toFloat() / w.toFloat()).coerceIn(0f, 1f), + bottom = ((wordBottom + 1).toFloat() / h.toFloat()).coerceIn(0f, 1f), + ), + ) + } + } + curText.setLength(0) + wordLeft = -1 + wordRight = -1 + wordTop = y1 + wordBottom = y0 + scoreSum = 0f + charCount = 0 + } + + for (colRange in rawCols) { + if (prevEnd >= 0 && (colRange.first - prevEnd - 1) >= spaceThreshold) { + flushWord() + } + + // Tight vertical bounds for this glyph inside [y0..y1] + var gy0 = y1 + var gy1 = y0 + for (y in y0..y1) { + val rowOff = y * w + var hasInk = false + for (cx in colRange.first..colRange.last) { + if (ink[rowOff + cx]) { + hasInk = true + break + } + } + if (hasInk) { + if (y < gy0) gy0 = y + if (y > gy1) gy1 = y + } + } + if (gy1 - gy0 + 1 < MIN_GLYPH_HEIGHT) { + prevEnd = colRange.last + continue + } + + val match = classifyGlyph( + ink = ink, + imgW = w, + x0 = colRange.first, + y0 = gy0, + x1 = colRange.last, + y1 = gy1, + lineTop = y0, + lineH = lineH, + pack = pack, + ) + if (match != null && match.second >= MIN_GLYPH_SCORE) { + if (wordLeft < 0) wordLeft = colRange.first + wordRight = colRange.last + wordTop = min(wordTop, gy0) + wordBottom = max(wordBottom, gy1) + curText.append(match.first) + scoreSum += match.second + charCount++ + } + prevEnd = colRange.last + } + flushWord() + return words + } + + private fun classifyGlyph( + ink: BooleanArray, + imgW: Int, + x0: Int, + y0: Int, + x1: Int, + y1: Int, + lineTop: Int, + lineH: Int, + pack: OcrGlyphPack, + ): Pair? { + val gw = pack.gridW + val gh = pack.gridH + val srcW = (x1 - x0 + 1).coerceAtLeast(1) + val srcH = (y1 - y0 + 1).coerceAtLeast(1) + + val feat = FloatArray(gw * gh) + var sumSq = 0.0 + for (gy in 0 until gh) { + val syStart = y0 + (gy * srcH) / gh + val syEnd = max(syStart, y0 + ((gy + 1) * srcH - 1) / gh) + for (gx in 0 until gw) { + val sxStart = x0 + (gx * srcW) / gw + val sxEnd = max(sxStart, x0 + ((gx + 1) * srcW - 1) / gw) + var cellInk = 0 + var cellTotal = 0 + for (sy in syStart..syEnd) { + val rowOff = sy * imgW + for (sx in sxStart..sxEnd) { + if (ink[rowOff + sx]) cellInk++ + cellTotal++ + } + } + val ratio = if (cellTotal > 0) cellInk.toFloat() / cellTotal.toFloat() else 0f + val v = if (ratio >= 0.35f) 1.0f else -0.35f + feat[gy * gw + gx] = v + sumSq += v.toDouble() * v.toDouble() + } + } + val norm = sqrt(sumSq).toFloat() + if (norm <= 1e-6f) return null + + val quantized = VectorMath.quantize(feat) + if (quantized.norm <= 1e-6f) return null + + var bestChar = '?' + var bestScore = -1f + val qv = quantized.values + for (tpl in pack.templates) { + if (tpl.norm <= 1e-6f || tpl.vector.size != qv.size) continue + var dot = 0L + val tv = tpl.vector + for (i in qv.indices) { + dot += qv[i].toLong() * tv[i].toLong() + } + val score = dot.toFloat() / (quantized.norm * tpl.norm) + if (score > bestScore) { + bestScore = score + bestChar = tpl.char + } + } + if (bestScore <= 0f) return null + // Disambiguate baseline decimal point '.' from mid-line dash '-' using line geometry. + val resolvedChar = if (bestChar == '-' || bestChar == '.') { + if ((y0 - lineTop) >= lineH * 0.52f && srcW <= srcH * 1.6f) '.' else '-' + } else { + bestChar + } + return resolvedChar to bestScore + } + + private fun segmentHorizontalLines(ink: BooleanArray, w: Int, h: Int): List> { + val rowCounts = IntArray(h) + for (y in 0 until h) { + val rowOff = y * w + var c = 0 + for (x in 0 until w) { + if (ink[rowOff + x]) c++ + } + rowCounts[y] = c + } + + val bands = ArrayList>() + var y = 0 + while (y < h) { + while (y < h && rowCounts[y] < 2) y++ + if (y >= h) break + val start = y + while (y < h && rowCounts[y] >= 2) y++ + val end = y - 1 + val bandH = end - start + 1 + if (bandH in MIN_LINE_HEIGHT..(h / 2).coerceAtLeast(MIN_LINE_HEIGHT)) { + bands.add(start to end) + } + } + return bands + } + + private fun estimateBorderLuminance(gray: IntArray, w: Int, h: Int): Float { + var sum = 0L + var count = 0 + for (x in 0 until w) { + sum += gray[x] + sum += gray[(h - 1) * w + x] + count += 2 + } + for (y in 1 until (h - 1)) { + sum += gray[y * w] + sum += gray[y * w + (w - 1)] + count += 2 + } + return if (count > 0) sum.toFloat() / count.toFloat() else 128f + } + + private fun otsuThreshold(hist: IntArray, total: Int): Int { + var sumAll = 0.0 + for (t in 0..255) sumAll += t * hist[t].toDouble() + + var sumB = 0.0 + var weightB = 0 + var maxVar = -1.0 + var firstBestT = 128 + var lastBestT = 128 + for (t in 0..255) { + weightB += hist[t] + if (weightB == 0) continue + val weightF = total - weightB + if (weightF == 0) break + sumB += t * hist[t].toDouble() + val meanB = sumB / weightB + val meanF = (sumAll - sumB) / weightF + val diff = meanB - meanF + val between = weightB.toDouble() * weightF.toDouble() * diff * diff + if (between > maxVar + 1e-6) { + maxVar = between + firstBestT = t + lastBestT = t + } else if (abs(between - maxVar) <= 1e-6 && maxVar > 0.0) { + lastBestT = t + } + } + return (firstBestT + lastBestT) / 2 + } + + private fun computeDownscale(width: Int, height: Int): Int { + val maxSide = max(width, height) + var s = 1 + while (maxSide / s > MAX_OCR_DIM) { + s *= 2 + } + return s + } + + companion object { + private const val MIN_BITMAP_DIM = 8 + private const val MAX_OCR_DIM = 960 + private const val MIN_CONTRAST = 24 + private const val MIN_LINE_HEIGHT = 5 + private const val MIN_GLYPH_WIDTH = 2 + private const val MIN_GLYPH_HEIGHT = 4 + private const val MIN_GLYPH_SCORE = 0.38f + private const val HIGH_CONF_SINGLE_CHAR = 0.62f + private const val MAX_LINES = 64 + private const val MAX_BOXES = 256 + } +} diff --git a/app/src/main/java/org/freesilicon/recall/engine/FreeSchedEngine.kt b/app/src/main/java/org/freesilicon/recall/engine/FreeSchedEngine.kt index 89346b9..049e6b8 100644 --- a/app/src/main/java/org/freesilicon/recall/engine/FreeSchedEngine.kt +++ b/app/src/main/java/org/freesilicon/recall/engine/FreeSchedEngine.kt @@ -16,13 +16,17 @@ interface FreeSchedBackendProbe { } /** - * Real FreeSched 16 KiB AAR hardware telemetry & calibration engine. + * Real FreeSched 16 KiB AAR hardware telemetry & apples-to-apples calibration engine. * + * Runs the exact same 8-image 2-layer FFN workload (`seqLen=16, dIn=64, dMid=128, dOut=64`) + * using dequantized weights from `dual_tower_int8.rcl1` on both CPU and FreeSched AHB+NNAPI. * Separates NNAPI device discovery from pipeline execution so discovered accelerators - * (EdgeTPU, Hexagon HTP, MediaTek APU) are always reported honestly even when the - * float32 smoke graph falls back to serial/CPU execution. + * (EdgeTPU, Hexagon HTP, MediaTek APU) are always reported honestly, and never reports a + * speedup ratio unless all 8 images complete on an NPU-accelerated async pipeline. */ -class FreeSchedEngine : FreeSchedBackendProbe { +class FreeSchedEngine( + private val dualTowerWeights: DualTowerWeights? = null, +) : FreeSchedBackendProbe { override fun discoverAndMeasure(): HardwareTelemetrySnapshot { val deviceModel = listOfNotNull( @@ -31,7 +35,25 @@ class FreeSchedEngine : FreeSchedBackendProbe { ).joinToString(" ").ifBlank { "Android Device" } val androidRelease = "Android ${Build.VERSION.RELEASE ?: "15"} (API ${Build.VERSION.SDK_INT})" - val cpuBaselineMs = runCpuCalibrationMs() + val hasBundledWeights = dualTowerWeights != null && + dualTowerWeights.dIn == CALIB_D_IN && + dualTowerWeights.dMid == CALIB_D_MID && + dualTowerWeights.dOut >= CALIB_D_OUT + + val w1 = if (hasBundledWeights) { + dualTowerWeights!!.dequantizeW1() + } else { + FloatArray(CALIB_D_IN * CALIB_D_MID) { ((it % 17) - 8) * 0.01f } + } + val w2 = if (hasBundledWeights) { + dualTowerWeights!!.dequantizeW2Slice(CALIB_D_OUT) + } else { + FloatArray(CALIB_D_MID * CALIB_D_OUT) { ((it % 13) - 6) * 0.01f } + } + + // Exact same 8-image FFN workload on CPU baseline. + val cpuBaselineMs = runCpuFfnCalibrationMs(w1, w2) + val packTag = if (hasBundledWeights) "INT8 pack" else "default weights" // Step 1: Discover NNAPI devices independently so discovery survives pipeline fallback. val discovered: List = try { @@ -42,54 +64,62 @@ class FreeSchedEngine : FreeSchedBackendProbe { val discoveredLabels = discovered.map { "${it.name} (${formatVendor(it.vendor)})" } val primaryDevice = discovered.firstOrNull { it.vendor != AhbNpuVendor.NONE } - // Step 2: Run bounded FreeSched AHB+NNAPI calibration. + // Step 2: Run the exact same 8-image FFN workload through FreeSched AHB+NNAPI. return try { val config = AhbNnapiConfig( - seqLen = 16, - dIn = 64, - dMid = 128, - dOut = 64, + seqLen = CALIB_SEQ_LEN, + dIn = CALIB_D_IN, + dMid = CALIB_D_MID, + dOut = CALIB_D_OUT, slotCount = 2, allowSerialFallback = true, preferredVendor = primaryDevice?.vendor ?: AhbNpuVendor.NONE, preferredBackend = AhbNpuBackend.AUTO, opLowering = primaryDevice?.preferredLowering ?: NnapiOpLowering.CONV1X1, ) - val w1 = FloatArray(config.dIn * config.dMid) { 0.01f } - val w2 = FloatArray(config.dMid * config.dOut) { 0.01f } - val startNs = System.nanoTime() var completed = 0 + var elapsedMs = 0.05f val pipeline = FreeSchedAhbNnapiPipeline.create(config, w1, null, w2, null) val stats = pipeline.use { p -> val rc = p.enterHotLoop() if (rc == 0) { + val startNs = System.nanoTime() repeat(CALIBRATION_IMAGES) { val slot = p.acquireSlot() if (slot >= 0) { val token = p.submitGpuStage(slot) p.handoffGpuToNpu(token) - val doneRc = p.completeSlot(token, 1000, 0) + var doneRc = p.completeSlot(token, 1000, 0) + if (doneRc != 0) { + // Drain timed-out slot so no in-flight token leaks pipeline.close(). + doneRc = p.completeSlot(token, 5000, 0) + } if (doneRc == 0) completed++ } } + elapsedMs = max(0.05f, (System.nanoTime() - startNs) / 1_000_000f) p.exitHotLoop() } p.stats() } - val elapsedMs = max(0.05f, (System.nanoTime() - startNs) / 1_000_000f) - val msPerImg = if (completed > 0) elapsedMs / completed else null - val imgPerSec = if (msPerImg != null && msPerImg > 0f) 1000f / msPerImg else null + val msPerImg = if (completed > 0) elapsedMs / completed else cpuBaselineMs + val imgPerSec = if (msPerImg > 0f) 1000f / msPerImg else null val vendorLabel = formatVendor(stats.activeVendor) - val isNpu = completed > 0 && + val isNpu = completed == CALIBRATION_IMAGES && stats.npuAcceleratorFound && stats.activeMode == AhbNnapiMode.ASYNC_SYNC_FD && stats.activeVendor != AhbNpuVendor.NONE + val speedupVsCpu = if (isNpu && msPerImg > 0f) { + (cpuBaselineMs / msPerImg).coerceAtLeast(0.01f) + } else { + null + } val backendLabel = when { isNpu -> "$vendorLabel + Vulkan" stats.npuAcceleratorFound -> "$vendorLabel (Serial)" - primaryDevice != null -> "${formatVendor(primaryDevice.vendor)} (Ready · CPU smoke)" + primaryDevice != null -> "${formatVendor(primaryDevice.vendor)} (Ready · CPU fallback)" else -> "Vulkan GPU / CPU Fallback" } @@ -107,11 +137,11 @@ class FreeSchedEngine : FreeSchedBackendProbe { gpuBaselineMsPerImage = null, cpuBaselineMsPerImage = cpuBaselineMs, speedupVsGpu = null, - speedupVsCpu = null, // Apples-to-apples encoder speedup lands in Days 3-5; never compare disparate workloads. + speedupVsCpu = speedupVsCpu, calibrationStatus = if (isNpu) { - "Measured ($completed-batch FreeSched AHB+NNAPI smoke)" + "Measured ($completed-image apples-to-apples FreeSched AHB+NNAPI · $packTag)" } else { - "Measured (serial fallback — INT8 encoder lands Days 3–5)" + "Measured ($CALIBRATION_IMAGES-image $packTag · honest serial/CPU fallback)" }, deviceModel = deviceModel, androidRelease = androidRelease, @@ -141,7 +171,7 @@ class FreeSchedEngine : FreeSchedBackendProbe { cpuBaselineMsPerImage = cpuBaselineMs, speedupVsGpu = null, speedupVsCpu = null, - calibrationStatus = "Honest CPU fallback ($reason)", + calibrationStatus = "Honest CPU fallback ($packTag · $reason)", deviceModel = deviceModel, androidRelease = androidRelease, isHonestFallback = true, @@ -149,18 +179,40 @@ class FreeSchedEngine : FreeSchedBackendProbe { } } - private fun runCpuCalibrationMs(): Float { - val a = ByteArray(VectorMath.EMBEDDING_DIM) { (it % 127).toByte() } - val b = ByteArray(VectorMath.EMBEDDING_DIM) { ((it * 3) % 127).toByte() } - val qA = QuantizedVector(a, 1f, 1000f) - val qB = QuantizedVector(b, 1f, 1000f) + /** + * Apples-to-apples CPU 2-layer FFN reference matching `AhbNnapiConfig`: + * `CALIBRATION_IMAGES` batches x `CALIB_SEQ_LEN` tokens x (`64 -> 128 -> 64`). + */ + internal fun runCpuFfnCalibrationMs(w1: FloatArray, w2: FloatArray): Float { + val x = FloatArray(CALIB_D_IN) { ((it % 11) - 5) * 0.05f } + val hidden = FloatArray(CALIB_D_MID) + var sink = 0f + val startNs = System.nanoTime() - var acc = 0f - repeat(CALIBRATION_IMAGES * 32) { - acc += VectorMath.cosineSimilarity(qA, qB) + repeat(CALIBRATION_IMAGES) { img -> + val imgBias = (img + 1) * 0.01f + repeat(CALIB_SEQ_LEN) { tok -> + val tokBias = tok * 0.005f + for (j in 0 until CALIB_D_MID) { + var acc = 0f + val rowOff = j * CALIB_D_IN + for (i in 0 until CALIB_D_IN) { + acc += (x[i] + imgBias + tokBias) * w1[rowOff + i] + } + hidden[j] = max(0f, acc) + } + for (k in 0 until CALIB_D_OUT) { + var acc = 0f + val rowOff = k * CALIB_D_MID + for (j in 0 until CALIB_D_MID) { + acc += hidden[j] * w2[rowOff + j] + } + sink += acc + } + } } val elapsedMs = max(0.05f, (System.nanoTime() - startNs) / 1_000_000f) - if (acc < 0f) return elapsedMs + if (sink.isNaN()) return elapsedMs return elapsedMs / CALIBRATION_IMAGES } @@ -174,5 +226,9 @@ class FreeSchedEngine : FreeSchedBackendProbe { companion object { const val CALIBRATION_IMAGES = 8 + const val CALIB_SEQ_LEN = 16 + const val CALIB_D_IN = 64 + const val CALIB_D_MID = 128 + const val CALIB_D_OUT = 64 } } diff --git a/app/src/main/java/org/freesilicon/recall/engine/Int8DualTowerEncoder.kt b/app/src/main/java/org/freesilicon/recall/engine/Int8DualTowerEncoder.kt new file mode 100644 index 0000000..3f2c4c9 --- /dev/null +++ b/app/src/main/java/org/freesilicon/recall/engine/Int8DualTowerEncoder.kt @@ -0,0 +1,188 @@ +package org.freesilicon.recall.engine + +import android.graphics.Bitmap +import java.util.Locale +import kotlin.math.max +import kotlin.math.sqrt + +/** + * Bundled INT8 dual-tower Vision+Text encoder backed by `dual_tower_int8.rcl1` + * from the `:models_pack` Play Asset Delivery install-time pack. + * + * Extracts a 64-d normalized text/visual feature vector and runs the symmetric INT8 + * 2-layer projection (`W1: 64x128 -> ReLU -> centered W2: 128x512`) into a 512-d + * L2-normalized INT8 `QuantizedVector`. Falls back cleanly to `LocalDeterministicEncoder` + * if weights are unavailable. + */ +class Int8DualTowerEncoder( + private val weights: DualTowerWeights?, + private val fallback: VisionTextEncoder = LocalDeterministicEncoder(), +) : VisionTextEncoder { + + val isUsingBundledWeights: Boolean + get() = weights != null && weights.dOut == VectorMath.EMBEDDING_DIM + + override fun encodeText(text: String): QuantizedVector { + val w = weights ?: return fallback.encodeText(text) + if (w.dOut != VectorMath.EMBEDDING_DIM) return fallback.encodeText(text) + if (text.isBlank()) return VectorMath.quantize(FloatArray(VectorMath.EMBEDDING_DIM)) + + val input = FloatArray(w.dIn) + accumulateTextFeatures(text, input, weight = 1.0f) + l2Normalize(input) + return projectAndQuantize(input, w) + } + + override fun encodeImageAndText( + bitmap: Bitmap?, + ocrText: String, + displayName: String, + ): QuantizedVector { + val w = weights ?: return fallback.encodeImageAndText(bitmap, ocrText, displayName) + if (w.dOut != VectorMath.EMBEDDING_DIM) { + return fallback.encodeImageAndText(bitmap, ocrText, displayName) + } + + val textVec = FloatArray(w.dIn) + val hasOcr = ocrText.isNotBlank() + if (hasOcr) accumulateTextFeatures(ocrText, textVec, weight = 1.0f) + if (displayName.isNotBlank()) { + accumulateTextFeatures(displayName, textVec, weight = if (hasOcr) 0.30f else 0.75f) + } + val textNorm = l2Normalize(textVec) + + val visualVec = FloatArray(w.dIn) + val hasVisual = bitmap != null && bitmap.width > 0 && bitmap.height > 0 + if (hasVisual) { + accumulateVisualFeatures(bitmap!!, visualVec) + } + val visualNorm = l2Normalize(visualVec) + + val combined = FloatArray(w.dIn) + val textWeight = if (hasOcr) 0.85f else 0.65f + val visualWeight = if (hasOcr) 0.15f else 0.35f + for (i in combined.indices) { + combined[i] = (if (textNorm > 1e-6f) textVec[i] * textWeight else 0f) + + (if (visualNorm > 1e-6f) visualVec[i] * visualWeight else 0f) + } + val combinedNorm = l2Normalize(combined) + if (combinedNorm <= 1e-6f) { + return VectorMath.quantize(FloatArray(VectorMath.EMBEDDING_DIM)) + } + return projectAndQuantize(combined, w) + } + + private fun projectAndQuantize(input: FloatArray, w: DualTowerWeights): QuantizedVector { + val dIn = w.dIn + val dMid = w.dMid + val dOut = w.dOut + val w1 = w.w1 + val w2 = w.w2 + val s1 = w.scale1 + val s2 = w.scale2 + + // Layer 1: INT8 matmul + ReLU + val hidden = FloatArray(dMid) + for (j in 0 until dMid) { + var acc = 0f + for (i in 0 until dIn) { + acc += input[i] * w1[i * dMid + j].toFloat() + } + hidden[j] = max(0f, acc * s1) + } + + // Zero-center hidden activations so unrelated queries stay near-orthogonal. + var hiddenMean = 0f + for (h in hidden) hiddenMean += h + hiddenMean /= dMid.toFloat() + for (j in 0 until dMid) { + hidden[j] -= hiddenMean + } + + // Layer 2: INT8 matmul -> 512-d embedding + val out = FloatArray(dOut) + for (k in 0 until dOut) { + var acc = 0f + for (j in 0 until dMid) { + acc += hidden[j] * w2[j * dOut + k].toFloat() + } + out[k] = acc * s2 + } + + l2Normalize(out) + return VectorMath.quantize(out) + } + + private fun accumulateTextFeatures(raw: String, out: FloatArray, weight: Float) { + val dim = out.size + val normalized = raw.lowercase(Locale.ROOT) + val tokens = TOKEN_REGEX.findAll(normalized).map { it.value }.toList() + for (token in tokens) { + val idx = positiveMod(fnv1a(token), dim) + val sign = if ((fnv1a("s:$token") and 1) == 0) 1f else -1f + out[idx] += sign * weight * 1.4f + if (token.length >= 3) { + for (i in 0..token.length - 3) { + val tri = token.substring(i, i + 3) + val tIdx = positiveMod(fnv1a(tri), dim) + val tSign = if ((fnv1a("t:$tri") and 1) == 0) 1f else -1f + out[tIdx] += tSign * weight * 0.45f + } + } + } + } + + private fun accumulateVisualFeatures(bitmap: Bitmap, out: FloatArray) { + val grid = 4 + val stepX = (bitmap.width / grid).coerceAtLeast(1) + val stepY = (bitmap.height / grid).coerceAtLeast(1) + var bucket = 0 + var gy = 0 + while (gy < bitmap.height && bucket < 16) { + var gx = 0 + while (gx < bitmap.width && bucket < 16) { + val pixel = bitmap.getPixel(gx, gy) + val r = ((pixel ushr 16) and 0xFF) / 255f - 0.5f + val g = ((pixel ushr 8) and 0xFF) / 255f - 0.5f + val b = (pixel and 0xFF) / 255f - 0.5f + val luma = 0.299f * r + 0.587f * g + 0.114f * b + val base = (bucket * 4) % out.size + out[base] += r + if (base + 1 < out.size) out[base + 1] += g + if (base + 2 < out.size) out[base + 2] += b + if (base + 3 < out.size) out[base + 3] += luma + bucket++ + gx += stepX + } + gy += stepY + } + } + + private fun l2Normalize(vec: FloatArray): Float { + var sum = 0.0 + for (v in vec) sum += v.toDouble() * v.toDouble() + val norm = sqrt(sum).toFloat() + if (norm > 1e-8f) { + for (i in vec.indices) vec[i] /= norm + } + return norm + } + + private fun fnv1a(s: String): Int { + var h = -2128831035 + for (ch in s) { + h = h xor ch.code + h *= 16777619 + } + return h + } + + private fun positiveMod(value: Int, mod: Int): Int { + val m = value % mod + return if (m < 0) m + mod else m + } + + companion object { + private val TOKEN_REGEX = Regex("[a-z0-9]{2,}") + } +} diff --git a/app/src/main/java/org/freesilicon/recall/engine/ModelPackLoader.kt b/app/src/main/java/org/freesilicon/recall/engine/ModelPackLoader.kt new file mode 100644 index 0000000..37320b9 --- /dev/null +++ b/app/src/main/java/org/freesilicon/recall/engine/ModelPackLoader.kt @@ -0,0 +1,156 @@ +package org.freesilicon.recall.engine + +import android.content.Context +import android.content.res.AssetManager +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sqrt + +/** + * Symmetric INT8 dual-tower projection weights loaded from `recall_models/dual_tower_int8.rcl1` + * (packaged via Play Asset Delivery `:models_pack` install-time asset pack). + */ +class DualTowerWeights( + val dIn: Int, + val dMid: Int, + val dOut: Int, + val scale1: Float, + val scale2: Float, + val w1: ByteArray, + val w2: ByteArray, +) { + /** Dequantize W1 (`dIn x dMid`) into row-major float32 for FreeSched FFN calibration. */ + fun dequantizeW1(): FloatArray { + val out = FloatArray(w1.size) + for (i in w1.indices) { + out[i] = w1[i].toFloat() * scale1 + } + return out + } + + /** + * Dequantize the first `outCols` columns of W2 (`dMid x dOut`) into a `dMid x outCols` + * float32 matrix for apples-to-apples FreeSched calibration. + */ + fun dequantizeW2Slice(outCols: Int): FloatArray { + val cols = outCols.coerceIn(1, dOut) + val out = FloatArray(dMid * cols) + for (r in 0 until dMid) { + val srcRow = r * dOut + val dstRow = r * cols + for (c in 0 until cols) { + out[dstRow + c] = w2[srcRow + c].toFloat() * scale2 + } + } + return out + } +} + +class OcrGlyphTemplate( + val char: Char, + val vector: ByteArray, + val norm: Float, +) + +class OcrGlyphPack( + val gridW: Int, + val gridH: Int, + val templates: List, +) + +/** + * Loads verified RCL1 / OCR1 INT8 model packs from Android assets (Play Asset Delivery + * install-time `:models_pack` in AABs and generated assets in debug APKs / Robolectric). + */ +object ModelPackLoader { + const val DUAL_TOWER_ASSET = "recall_models/dual_tower_int8.rcl1" + const val OCR_GLYPHS_ASSET = "recall_models/ocr_glyphs_int8.rcl1" + + private const val MAX_DIM = 4096 + private const val MAX_GLYPHS = 256 + private const val MAX_GRID = 32 + + fun loadDualTower(context: Context): DualTowerWeights? = + loadDualTower(context.assets) + + fun loadDualTower(assets: AssetManager): DualTowerWeights? = try { + assets.open(DUAL_TOWER_ASSET).use { parseDualTower(it.readBytes()) } + } catch (_: Throwable) { + ModelPackLoader::class.java.classLoader + ?.getResourceAsStream(DUAL_TOWER_ASSET) + ?.use { parseDualTower(it.readBytes()) } + } + + fun loadOcrGlyphs(context: Context): OcrGlyphPack? = + loadOcrGlyphs(context.assets) + + fun loadOcrGlyphs(assets: AssetManager): OcrGlyphPack? = try { + assets.open(OCR_GLYPHS_ASSET).use { parseOcrGlyphs(it.readBytes()) } + } catch (_: Throwable) { + ModelPackLoader::class.java.classLoader + ?.getResourceAsStream(OCR_GLYPHS_ASSET) + ?.use { parseOcrGlyphs(it.readBytes()) } + } + + internal fun parseDualTower(bytes: ByteArray): DualTowerWeights? { + if (bytes.size < 28) return null + val buf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) + val magic = ByteArray(4) + buf.get(magic) + if (!magic.contentEquals(MAGIC_RCL1)) return null + val version = buf.int + val dIn = buf.int + val dMid = buf.int + val dOut = buf.int + val scale1 = buf.float + val scale2 = buf.float + if (version != 1 || dIn !in 1..MAX_DIM || dMid !in 1..MAX_DIM || dOut !in 1..MAX_DIM) { + return null + } + if (!scale1.isFinite() || !scale2.isFinite() || scale1 <= 0f || scale2 <= 0f) { + return null + } + val w1Size = dIn.toLong() * dMid.toLong() + val w2Size = dMid.toLong() * dOut.toLong() + val expected = 28L + w1Size + w2Size + if (bytes.size.toLong() != expected) return null + + val w1 = ByteArray(w1Size.toInt()) + val w2 = ByteArray(w2Size.toInt()) + buf.get(w1) + buf.get(w2) + return DualTowerWeights(dIn, dMid, dOut, scale1, scale2, w1, w2) + } + + internal fun parseOcrGlyphs(bytes: ByteArray): OcrGlyphPack? { + if (bytes.size < 20) return null + val buf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) + val magic = ByteArray(4) + buf.get(magic) + if (!magic.contentEquals(MAGIC_OCR1)) return null + val version = buf.int + val count = buf.int + val gridW = buf.int + val gridH = buf.int + if (version != 1 || count !in 1..MAX_GLYPHS || gridW !in 2..MAX_GRID || gridH !in 2..MAX_GRID) { + return null + } + val vecLen = gridW * gridH + val expected = 20L + count.toLong() * (1L + vecLen.toLong()) + if (bytes.size.toLong() != expected) return null + + val templates = ArrayList(count) + repeat(count) { + val ch = (buf.get().toInt() and 0xFF).toChar() + val vec = ByteArray(vecLen) + buf.get(vec) + var sumSq = 0.0 + for (v in vec) sumSq += v.toDouble() * v.toDouble() + templates.add(OcrGlyphTemplate(ch, vec, sqrt(sumSq).toFloat())) + } + return OcrGlyphPack(gridW, gridH, templates) + } + + private val MAGIC_RCL1 = byteArrayOf('R'.code.toByte(), 'C'.code.toByte(), 'L'.code.toByte(), '1'.code.toByte()) + private val MAGIC_OCR1 = byteArrayOf('O'.code.toByte(), 'C'.code.toByte(), 'R'.code.toByte(), '1'.code.toByte()) +} diff --git a/app/src/main/java/org/freesilicon/recall/imports/ImportManager.kt b/app/src/main/java/org/freesilicon/recall/imports/ImportManager.kt index fd37406..303afa4 100644 --- a/app/src/main/java/org/freesilicon/recall/imports/ImportManager.kt +++ b/app/src/main/java/org/freesilicon/recall/imports/ImportManager.kt @@ -230,6 +230,38 @@ class ImportManager( File(paths.thumbnailPath).delete() } + /** + * Re-indexes any PENDING screenshots (for example after an encoder schema upgrade) + * from their app-private stored images while honoring `import_generation` delete fencing. + */ + suspend fun reindexPendingScreenshots(): Int = withContext(ioDispatcher) { + val pending = database.getPendingScreenshots() + var reindexed = 0 + for (record in pending) { + val imageFile = File(record.localImagePath) + if (!imageFile.exists()) continue + try { + val decoded = decodeSampledBitmap(imageFile, maxDim = 960) + val ocrResult = ocrExtractor.extract(decoded, record.displayName) + val vector = encoder.encodeImageAndText(decoded, ocrResult.fullText, record.displayName) + decoded?.recycle() + if (database.commitIndexResult( + screenshotId = record.id, + expectedGeneration = record.importGeneration, + ocrText = ocrResult.fullText, + ocrBoxes = ocrResult.boxes, + quantizedVector = vector, + ) + ) { + reindexed++ + } + } catch (_: Throwable) { + database.markFailed(record.id, record.importGeneration) + } + } + reindexed + } + private fun resolveDisplayName(resolver: ContentResolver, uri: Uri): String? { if (uri.scheme == ContentResolver.SCHEME_FILE) { return uri.lastPathSegment diff --git a/app/src/main/java/org/freesilicon/recall/store/RecallDatabase.kt b/app/src/main/java/org/freesilicon/recall/store/RecallDatabase.kt index d9b8967..a84012a 100644 --- a/app/src/main/java/org/freesilicon/recall/store/RecallDatabase.kt +++ b/app/src/main/java/org/freesilicon/recall/store/RecallDatabase.kt @@ -143,7 +143,17 @@ class RecallDatabase( return detected } - override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) = Unit + override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { + if (oldVersion < 2) { + // Days 3-5 switched to Int8DualTowerEncoder + BitmapOcrExtractor; drop incompatible + // v1 embeddings and mark existing indexed rows INDEXING so they re-index from stored images. + db.execSQL("DELETE FROM embeddings") + db.execSQL("UPDATE screenshots SET status = '${ScreenshotStatus.INDEXING.name}' WHERE status = '${ScreenshotStatus.INDEXED.name}'") + } + } + + fun getPendingScreenshots(): List = + getAllScreenshots().filter { it.status == ScreenshotStatus.INDEXING } override fun onOpen(db: SQLiteDatabase) { super.onOpen(db) @@ -669,7 +679,7 @@ class RecallDatabase( companion object { private const val DEFAULT_DB_NAME = "recall.db" - private const val DB_VERSION = 1 + private const val DB_VERSION = 2 private const val MODE_0600 = 384 // 0600 octal } } diff --git a/app/src/main/java/org/freesilicon/recall/ui/RecallViewModel.kt b/app/src/main/java/org/freesilicon/recall/ui/RecallViewModel.kt index dc9e153..be2f074 100644 --- a/app/src/main/java/org/freesilicon/recall/ui/RecallViewModel.kt +++ b/app/src/main/java/org/freesilicon/recall/ui/RecallViewModel.kt @@ -17,10 +17,12 @@ import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.freesilicon.recall.card.HardwareCardRenderer -import org.freesilicon.recall.engine.FilenameSeedOcrExtractor +import org.freesilicon.recall.engine.BitmapOcrExtractor import org.freesilicon.recall.engine.FreeSchedBackendProbe import org.freesilicon.recall.engine.FreeSchedEngine -import org.freesilicon.recall.engine.LocalDeterministicEncoder +import org.freesilicon.recall.engine.Int8DualTowerEncoder +import org.freesilicon.recall.engine.ModelPackLoader +import org.freesilicon.recall.engine.OcrExtractor import org.freesilicon.recall.engine.VisionTextEncoder import org.freesilicon.recall.imports.ImportManager import org.freesilicon.recall.model.HardwareTelemetrySnapshot @@ -50,10 +52,12 @@ data class RecallUiState( class RecallViewModel(application: Application) : AndroidViewModel(application) { private val database = RecallDatabase(application) - private val encoder: VisionTextEncoder = LocalDeterministicEncoder() - private val ocrExtractor = FilenameSeedOcrExtractor() + private val dualTowerWeights = ModelPackLoader.loadDualTower(application) + private val ocrGlyphPack = ModelPackLoader.loadOcrGlyphs(application) + private val encoder: VisionTextEncoder = Int8DualTowerEncoder(dualTowerWeights) + private val ocrExtractor: OcrExtractor = BitmapOcrExtractor(ocrGlyphPack) private val importManager = ImportManager(application, database, encoder, ocrExtractor) - private val backendProbe: FreeSchedBackendProbe = FreeSchedEngine() + private val backendProbe: FreeSchedBackendProbe = FreeSchedEngine(dualTowerWeights) private val _uiState = MutableStateFlow(RecallUiState()) val uiState: StateFlow = _uiState.asStateFlow() @@ -61,6 +65,10 @@ class RecallViewModel(application: Application) : AndroidViewModel(application) init { refreshSearch() runCalibration() + viewModelScope.launch { + val reindexed = importManager.reindexPendingScreenshots() + if (reindexed > 0) refreshSearch() + } } fun updateQuery(newQuery: String) { diff --git a/app/src/main/java/org/freesilicon/recall/ui/screens/BenchmarkScreen.kt b/app/src/main/java/org/freesilicon/recall/ui/screens/BenchmarkScreen.kt index 52a446f..7263fef 100644 --- a/app/src/main/java/org/freesilicon/recall/ui/screens/BenchmarkScreen.kt +++ b/app/src/main/java/org/freesilicon/recall/ui/screens/BenchmarkScreen.kt @@ -314,7 +314,7 @@ private fun EditorialHardwareCard(snapshot: HardwareTelemetrySnapshot) { MetricTile( label = "vs cpu", value = snapshot.speedupVsCpu?.let { String.format(Locale.US, "%.2fx", it) } ?: "—", - unit = if (snapshot.speedupVsCpu != null) "baseline" else "pending", + unit = if (snapshot.speedupVsCpu != null) "baseline" else "fallback", accent = snapshot.speedupVsCpu != null, modifier = Modifier.weight(1f), ) diff --git a/app/src/test/java/org/freesilicon/recall/Int8EncoderAndOcrTest.kt b/app/src/test/java/org/freesilicon/recall/Int8EncoderAndOcrTest.kt new file mode 100644 index 0000000..46a1c82 --- /dev/null +++ b/app/src/test/java/org/freesilicon/recall/Int8EncoderAndOcrTest.kt @@ -0,0 +1,209 @@ +package org.freesilicon.recall + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.Color +import androidx.test.core.app.ApplicationProvider +import org.freesilicon.recall.engine.BitmapOcrExtractor +import org.freesilicon.recall.engine.FreeSchedEngine +import org.freesilicon.recall.engine.Int8DualTowerEncoder +import org.freesilicon.recall.engine.ModelPackLoader +import org.freesilicon.recall.engine.VectorMath +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class Int8EncoderAndOcrTest { + + private val context: Context + get() = ApplicationProvider.getApplicationContext() + + @Test + fun modelPackLoaderParsesBundledPacksAndRejectsCorruptInputs() { + val dual = ModelPackLoader.loadDualTower(context) + assertNotNull("dual_tower_int8.rcl1 must load from generated assets", dual) + assertEquals(64, dual!!.dIn) + assertEquals(128, dual.dMid) + assertEquals(512, dual.dOut) + assertEquals(64 * 128, dual.w1.size) + assertEquals(128 * 512, dual.w2.size) + + val glyphs = ModelPackLoader.loadOcrGlyphs(context) + assertNotNull("ocr_glyphs_int8.rcl1 must load from generated assets", glyphs) + assertEquals(8, glyphs!!.gridW) + assertEquals(12, glyphs.gridH) + assertTrue("Expected >= 40 glyph templates", glyphs.templates.size >= 40) + + assertNull(ModelPackLoader.parseDualTower(ByteArray(12))) + assertNull(ModelPackLoader.parseOcrGlyphs(ByteArray(12))) + } + + @Test + fun int8DualTowerEncoderRanksMatchingQueriesAboveUnrelated() { + val dual = ModelPackLoader.loadDualTower(context)!! + val encoder = Int8DualTowerEncoder(dual) + assertTrue(encoder.isUsingBundledWeights) + + val wifiDoc = encoder.encodeImageAndText( + bitmap = null, + ocrText = "GUEST WIFI PASSWORD SOLAR4829", + displayName = "wifi_card.png", + ) + val receiptDoc = encoder.encodeImageAndText( + bitmap = null, + ocrText = "COFFEE RECEIPT TOTAL 14.50 ESPRESSO", + displayName = "cafe.png", + ) + val query = encoder.encodeText("wifi password solar4829") + + assertEquals(VectorMath.EMBEDDING_DIM, wifiDoc.values.size) + assertEquals(VectorMath.EMBEDDING_DIM, query.values.size) + + val simWifi = VectorMath.cosineSimilarity(query, wifiDoc) + val simReceipt = VectorMath.cosineSimilarity(query, receiptDoc) + assertTrue( + "Expected matching Wi-Fi doc ($simWifi) to score well above unrelated receipt ($simReceipt)", + simWifi > simReceipt + 0.15f, + ) + } + + @Test + fun bitmapOcrExtractorReadsLightAndDarkScreenshotsAndIgnoresBlank() { + val glyphs = ModelPackLoader.loadOcrGlyphs(context)!! + val ocr = BitmapOcrExtractor(glyphs) + + // 1. Light-theme screenshot (dark ink on white background) + val lightBmp = renderTextBitmap( + lines = listOf("WIFI 4829"), + bgColor = Color.WHITE, + fgColor = Color.BLACK, + ) + val lightRes = ocr.extract(lightBmp, "light.png") + lightBmp.recycle() + + assertTrue("Expected WIFI in light OCR: '${lightRes.fullText}'", lightRes.fullText.contains("WIFI")) + assertTrue("Expected 4829 in light OCR: '${lightRes.fullText}'", lightRes.fullText.contains("4829")) + assertTrue("Expected >= 2 word boxes", lightRes.boxes.size >= 2) + for (box in lightRes.boxes) { + assertTrue(box.left in 0f..1f && box.right in 0f..1f && box.right > box.left) + assertTrue(box.top in 0f..1f && box.bottom in 0f..1f && box.bottom > box.top) + } + + // 2. Dark-theme screenshot with decimal amount (light ink on charcoal background) + val darkBmp = renderTextBitmap( + lines = listOf("TRACK 14.50"), + bgColor = Color.rgb(18, 20, 24), + fgColor = Color.rgb(240, 244, 248), + ) + val darkRes = ocr.extract(darkBmp, "dark.png") + darkBmp.recycle() + + assertTrue("Expected TRACK in dark OCR: '${darkRes.fullText}'", darkRes.fullText.contains("TRACK")) + assertTrue("Expected 14.50 in dark OCR: '${darkRes.fullText}'", darkRes.fullText.contains("14.50")) + assertTrue(darkRes.boxes.isNotEmpty()) + + // 3. Blank uniform screenshot must never fabricate boxes or text + val blankBmp = Bitmap.createBitmap(240, 120, Bitmap.Config.ARGB_8888) + blankBmp.eraseColor(Color.WHITE) + val blankRes = ocr.extract(blankBmp, "blank.png") + blankBmp.recycle() + + assertEquals("", blankRes.fullText) + assertTrue(blankRes.boxes.isEmpty()) + } + + @Test + fun freeSchedEngineApplesToApplesCalibrationIsHonestOnHost() { + val dual = ModelPackLoader.loadDualTower(context)!! + val engine = FreeSchedEngine(dual) + val snap = engine.discoverAndMeasure() + + assertNotNull(snap.cpuBaselineMsPerImage) + assertTrue(snap.cpuBaselineMsPerImage!! > 0f) + assertFalse(snap.npuAccelerated) + assertNull(snap.mjPerImage) + assertNull(snap.speedupVsCpu) + assertTrue(snap.isHonestFallback) + assertTrue( + "Expected INT8 pack tag in calibrationStatus: '${snap.calibrationStatus}'", + snap.calibrationStatus.contains("INT8 pack"), + ) + } + + private fun renderTextBitmap( + lines: List, + bgColor: Int, + fgColor: Int, + pixelScale: Int = 4, + ): Bitmap { + val charW = 5 * pixelScale + val charH = 7 * pixelScale + val charGap = 2 * pixelScale + val spaceGap = 5 * pixelScale + val pad = 24 + val width = 420 + val height = pad * 2 + lines.size * (charH + 16) + val bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) + bmp.eraseColor(bgColor) + + var y = pad + for (line in lines) { + var x = pad + for (ch in line) { + if (ch == ' ') { + x += spaceGap + continue + } + val rows = TEST_GLYPHS[ch] ?: continue + for (ry in rows.indices) { + val row = rows[ry] + for (rx in row.indices) { + if (row[rx] == '1') { + for (dy in 0 until pixelScale) { + for (dx in 0 until pixelScale) { + val px = x + rx * pixelScale + dx + val py = y + ry * pixelScale + dy + if (px in 0 until width && py in 0 until height) { + bmp.setPixel(px, py, fgColor) + } + } + } + } + } + } + x += charW + charGap + } + y += charH + 16 + } + return bmp + } + + companion object { + private val TEST_GLYPHS = mapOf( + '0' to listOf("01110", "10001", "10011", "10101", "11001", "10001", "01110"), + '1' to listOf("00100", "01100", "00100", "00100", "00100", "00100", "01110"), + '2' to listOf("01110", "10001", "00001", "00110", "01000", "10000", "11111"), + '4' to listOf("00010", "00110", "01010", "10010", "11111", "00010", "00010"), + '5' to listOf("11111", "10000", "11110", "00001", "00001", "10001", "01110"), + '.' to listOf("00000", "00000", "00000", "00000", "00000", "01100", "01100"), + '8' to listOf("01110", "10001", "10001", "01110", "10001", "10001", "01110"), + '9' to listOf("01110", "10001", "10001", "01111", "00001", "00010", "01100"), + 'A' to listOf("01110", "10001", "10001", "11111", "10001", "10001", "10001"), + 'C' to listOf("01110", "10001", "10000", "10000", "10000", "10001", "01110"), + 'F' to listOf("11111", "10000", "10000", "11110", "10000", "10000", "10000"), + 'I' to listOf("01110", "00100", "00100", "00100", "00100", "00100", "01110"), + 'K' to listOf("10001", "10010", "10100", "11000", "10100", "10010", "10001"), + 'R' to listOf("11110", "10001", "10001", "11110", "10100", "10010", "10001"), + 'T' to listOf("11111", "00100", "00100", "00100", "00100", "00100", "00100"), + 'W' to listOf("10001", "10001", "10001", "10101", "10101", "11011", "10001"), + ) + } +} diff --git a/build.gradle.kts b/build.gradle.kts index 9deb573..2e354ec 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,5 +1,6 @@ plugins { alias(libs.plugins.android.application) apply false + id("com.android.asset-pack") version "8.7.3" apply false alias(libs.plugins.kotlin.android) apply false alias(libs.plugins.kotlin.compose) apply false } diff --git a/models_pack/build.gradle.kts b/models_pack/build.gradle.kts new file mode 100644 index 0000000..07445ca --- /dev/null +++ b/models_pack/build.gradle.kts @@ -0,0 +1,10 @@ +plugins { + id("com.android.asset-pack") +} + +assetPack { + packName.set("models_pack") + dynamicDelivery { + deliveryType.set("install-time") + } +} diff --git a/models_pack/src/main/assets/recall_models/manifest.json b/models_pack/src/main/assets/recall_models/manifest.json new file mode 100644 index 0000000..feb6810 --- /dev/null +++ b/models_pack/src/main/assets/recall_models/manifest.json @@ -0,0 +1,23 @@ +{ + "pack": "models_pack", + "delivery": "install-time", + "format": "RCL1", + "network_required": false, + "models": [ + { + "name": "dual_tower_int8", + "file": "dual_tower_int8.rcl1", + "d_in": 64, + "d_mid": 128, + "d_out": 512, + "quantization": "int8_symmetric" + }, + { + "name": "ocr_glyphs_int8", + "file": "ocr_glyphs_int8.rcl1", + "grid_w": 8, + "grid_h": 12, + "quantization": "int8_symmetric" + } + ] +} diff --git a/scripts/clean-room-audit.sh b/scripts/clean-room-audit.sh index a7fc97a..3a33536 100755 --- a/scripts/clean-room-audit.sh +++ b/scripts/clean-room-audit.sh @@ -31,7 +31,7 @@ def list_files(): return sorted(files) files = list_files() -bad_exts = (".so", ".aar", ".jar", ".apk", ".aab", ".ko", ".img", ".gguf", ".tflite", ".bin", ".a", ".o", ".dylib") +bad_exts = (".so", ".aar", ".jar", ".apk", ".aab", ".ko", ".img", ".gguf", ".tflite", ".rcl1", ".bin", ".a", ".o", ".dylib") forbidden_pats = [ (r"/" + r"Users/", "private macOS home path"), diff --git a/scripts/export-int8-models.py b/scripts/export-int8-models.py new file mode 100755 index 0000000..8930cb0 --- /dev/null +++ b/scripts/export-int8-models.py @@ -0,0 +1,164 @@ +#!/usr/bin/env python3 +"""Deterministic INT8 model & glyph pack exporter for Recall (RCL1 format). + +Generates: + - dual_tower_int8.rcl1: symmetric INT8 quantized 2-layer projection weights + (d_in=64, d_mid=128, d_out=512) for paired Vision + Text semantic embeddings + and FreeSched apples-to-apples FFN calibration. + - ocr_glyphs_int8.rcl1: symmetric INT8 8x12 normalized bitmap glyph templates + (A-Z, 0-9, punctuation) for zero-permission on-device OCR. + +Outputs to both Play Asset Delivery install-time pack (`models_pack/src/main/assets/recall_models`) +and `:app` generated assets (`app/build/generated/recall_models/recall_models`) so AAB, APK, +and JVM Robolectric tests share identical verified weights without checking binaries into git. + +Copyright 2026 FreeSilicon Contributors +SPDX-License-Identifier: Apache-2.0 +""" +from __future__ import annotations + +import hashlib +import math +import struct +import sys +from pathlib import Path + +D_IN = 64 +D_MID = 128 +D_OUT = 512 +GRID_W = 8 +GRID_H = 12 + + +def prng_float(seed_tag: str, index: int) -> float: + h = hashlib.blake2b(f"{seed_tag}:{index}".encode("utf-8"), digest_size=8).digest() + val = int.from_bytes(h, "little") / float(1 << 64) + return (val * 2.0) - 1.0 + + +def quantize_symmetric_int8(floats: list[float]) -> tuple[float, bytes]: + max_abs = max((abs(v) for v in floats), default=0.0) + scale = (max_abs / 127.0) if max_abs > 1e-8 else 1.0 + out = bytearray(len(floats)) + for i, v in enumerate(floats): + q = int(round(v / scale)) + q = max(-127, min(127, q)) + out[i] = q & 0xFF + return scale, bytes(out) + + +def build_dual_tower_pack() -> bytes: + # Deterministic Xavier-scaled projection matrices preserving pairwise cosine geometry. + w1_scale_init = 1.0 / math.sqrt(D_IN) + w2_scale_init = 1.0 / math.sqrt(D_MID) + + w1 = [prng_float("recall_w1", i) * w1_scale_init for i in range(D_IN * D_MID)] + w2 = [prng_float("recall_w2", i) * w2_scale_init for i in range(D_MID * D_OUT)] + + s1, q1 = quantize_symmetric_int8(w1) + s2, q2 = quantize_symmetric_int8(w2) + + header = struct.pack("<4sIIIIff", b"RCL1", 1, D_IN, D_MID, D_OUT, s1, s2) + return header + q1 + q2 + + +# Clean-room 5x7 canonical uppercase + digit + symbol stroke rasters upsampled to 8x12. +GLYPHS_5X7: dict[str, list[str]] = { + "0": ["01110", "10001", "10011", "10101", "11001", "10001", "01110"], + "1": ["00100", "01100", "00100", "00100", "00100", "00100", "01110"], + "2": ["01110", "10001", "00001", "00110", "01000", "10000", "11111"], + "3": ["11110", "00001", "00001", "01110", "00001", "00001", "11110"], + "4": ["00010", "00110", "01010", "10010", "11111", "00010", "00010"], + "5": ["11111", "10000", "11110", "00001", "00001", "10001", "01110"], + "6": ["01110", "10000", "11110", "10001", "10001", "10001", "01110"], + "7": ["11111", "00001", "00010", "00100", "01000", "01000", "01000"], + "8": ["01110", "10001", "10001", "01110", "10001", "10001", "01110"], + "9": ["01110", "10001", "10001", "01111", "00001", "00010", "01100"], + "A": ["01110", "10001", "10001", "11111", "10001", "10001", "10001"], + "B": ["11110", "10001", "10001", "11110", "10001", "10001", "11110"], + "C": ["01110", "10001", "10000", "10000", "10000", "10001", "01110"], + "D": ["11110", "10001", "10001", "10001", "10001", "10001", "11110"], + "E": ["11111", "10000", "10000", "11110", "10000", "10000", "11111"], + "F": ["11111", "10000", "10000", "11110", "10000", "10000", "10000"], + "G": ["01110", "10001", "10000", "10111", "10001", "10001", "01110"], + "H": ["10001", "10001", "10001", "11111", "10001", "10001", "10001"], + "I": ["01110", "00100", "00100", "00100", "00100", "00100", "01110"], + "J": ["00111", "00010", "00010", "00010", "10010", "10010", "01100"], + "K": ["10001", "10010", "10100", "11000", "10100", "10010", "10001"], + "L": ["10000", "10000", "10000", "10000", "10000", "10000", "11111"], + "M": ["10001", "11011", "10101", "10101", "10001", "10001", "10001"], + "N": ["10001", "11001", "10101", "10011", "10001", "10001", "10001"], + "O": ["01110", "10001", "10001", "10001", "10001", "10001", "01110"], + "P": ["11110", "10001", "10001", "11110", "10000", "10000", "10000"], + "Q": ["01110", "10001", "10001", "10001", "10101", "10010", "01101"], + "R": ["11110", "10001", "10001", "11110", "10100", "10010", "10001"], + "S": ["01111", "10000", "10000", "01110", "00001", "00001", "11110"], + "T": ["11111", "00100", "00100", "00100", "00100", "00100", "00100"], + "U": ["10001", "10001", "10001", "10001", "10001", "10001", "01110"], + "V": ["10001", "10001", "10001", "10001", "10001", "01010", "00100"], + "W": ["10001", "10001", "10001", "10101", "10101", "11011", "10001"], + "X": ["10001", "10001", "01010", "00100", "01010", "10001", "10001"], + "Y": ["10001", "10001", "01010", "00100", "00100", "00100", "00100"], + "Z": ["11111", "00001", "00010", "00100", "01000", "10000", "11111"], + "-": ["00000", "00000", "00000", "11111", "00000", "00000", "00000"], + ":": ["00000", "00100", "00100", "00000", "00100", "00100", "00000"], + ".": ["00000", "00000", "00000", "00000", "00000", "01100", "01100"], + "/": ["00001", "00010", "00010", "00100", "01000", "01000", "10000"], + "$": ["00100", "01111", "10100", "01110", "00101", "11110", "00100"], + "#": ["01010", "11111", "01010", "01010", "11111", "01010", "00000"], +} + + +def resample_glyph(rows: list[str]) -> list[float]: + # Tight-crop to ink bounds so templates match tight-cropped glyph boxes in BitmapOcrExtractor. + ink_ys = [y for y, r in enumerate(rows) if "1" in r] + ink_xs = [x for r in rows for x, c in enumerate(r) if c == "1"] + if ink_ys and ink_xs: + y0, y1 = min(ink_ys), max(ink_ys) + x0, x1 = min(ink_xs), max(ink_xs) + rows = [r[x0 : x1 + 1] for r in rows[y0 : y1 + 1]] + src_h = len(rows) + src_w = len(rows[0]) + out: list[float] = [] + for y in range(GRID_H): + sy = min(src_h - 1, int(y * src_h / GRID_H)) + for x in range(GRID_W): + sx = min(src_w - 1, int(x * src_w / GRID_W)) + out.append(1.0 if rows[sy][sx] == "1" else -0.35) + norm = math.sqrt(sum(v * v for v in out)) or 1.0 + return [v / norm for v in out] + + +def build_ocr_glyph_pack() -> bytes: + entries = sorted(GLYPHS_5X7.items()) + buf = bytearray() + buf.extend(struct.pack("<4sIIII", b"OCR1", 1, len(entries), GRID_W, GRID_H)) + for ch, rows in entries: + vec = resample_glyph(rows) + _, q = quantize_symmetric_int8(vec) + buf.append(ord(ch)) + buf.extend(q) + return bytes(buf) + + +def main() -> int: + repo_root = Path(__file__).resolve().parent.parent + dual_bytes = build_dual_tower_pack() + ocr_bytes = build_ocr_glyph_pack() + + dest = repo_root / "models_pack" / "src" / "main" / "assets" / "recall_models" + dest.mkdir(parents=True, exist_ok=True) + (dest / "dual_tower_int8.rcl1").write_bytes(dual_bytes) + (dest / "ocr_glyphs_int8.rcl1").write_bytes(ocr_bytes) + + dual_sha = hashlib.sha256(dual_bytes).hexdigest()[:16] + ocr_sha = hashlib.sha256(ocr_bytes).hexdigest()[:16] + print( + f"Exported RCL1 INT8 packs: dual_tower_int8.rcl1 ({len(dual_bytes)} B, sha={dual_sha}), " + f"ocr_glyphs_int8.rcl1 ({len(ocr_bytes)} B, sha={ocr_sha})" + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/settings.gradle.kts b/settings.gradle.kts index a2fb0de..e2539f9 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -21,4 +21,4 @@ dependencyResolutionManagement { } rootProject.name = "recall" -include(":app") +include(":app", ":models_pack")