library:ml: Vulkan compute runtime replaces ncnn in camera
- Commit
6ed0fafc19b733e9e21101d5a39d8dc33cad8d4e- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-27 01:26 UTC (3 months ago)
- Parents
d4a2ee8
Diff
Cargo.toml
diff --git a/Cargo.toml b/Cargo.tomlindex 0631416acb..9e57dbbe07 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -10,9 +10,12 @@ members = [ "networklocation/src/main/rust", "euicc/src/main/rust", "passwords/src/main/rust",+ "appstore/src/main/rust", "vpn/src/main/rust", "library/e2ee-p2p/src/main/rust", "library/jni-http/src/main/rust",+ "library/map/src/main/rust",+ "library/ml/src/main/rust", "library/vision/src/main/rust", "measure/src/main/rust", "communicate/src/main/rust",@@ -39,6 +42,12 @@ members = [ "third_party/betocore/ukey2_proto", "third_party/betocore/ukey2_connections", ]+# `tilecodec` is a workspace root of its own, because it is consumed both by this+# workspace's `map_renderer` cdylib and by the detached host tool+# `scripts/maps/tile_build`. It lives inside this tree, so it has to be excluded+# explicitly or cargo reports "multiple workspace roots found in the same workspace"+# as soon as a member depends on it.+exclude = ["library/tilecodec/src/main/rust"] resolver = "2" [workspace.package]
SUPPLY_CHAIN_RISKS.md
diff --git a/SUPPLY_CHAIN_RISKS.md b/SUPPLY_CHAIN_RISKS.mdindex fc80a78f59..f4b55305cd 100644--- a/SUPPLY_CHAIN_RISKS.md+++ b/SUPPLY_CHAIN_RISKS.md@@ -57,7 +57,16 @@ So a clean install transcribes with no network, but speaking still needs one voi `photos` **semantic search no longer needs a second app**. It previously delegated image/text embedding to the OpenAssistant app over IPC, so search only worked if OpenAssistant was installed, recent enough, and had finished a ~452 MB SigLIP2 download. It now runs **TinyCLIP-ViT-8M/16 Text-3M** int8 in-process from `photos/src/main/assets/clip/model_int8.onnx` (24 MB), with the CLIP BPE table in `clip/bpe_simple_vocab_16e6.txt`. Upstream is **`onnx-community/TinyCLIP-ViT-8M-16-Text-3M-YFCC15M-ONNX`** (MIT, an ONNX export of `wkcn/TinyCLIP-ViT-8M-16-Text-3M-YFCC15M`) — a **build-host** dependency only. The int8 export costs almost nothing in fidelity (measured cosine vs fp32: 0.998 image, 0.9995 text, same latency), because TinyCLIP is a plain ViT and quantizes cleanly. The trade-off accepted here is accuracy in absolute terms: TinyCLIP-8M scores 41.1% zero-shot ImageNet-1k against SigLIP2-base's high-70s, so single-concept queries are noticeably weaker than the IPC path it replaces. -Notably **offline after first launch**: `astronomy`, `calendar`, `clock`, `contacts` (only `libphonenumber` locally), `files`, `notes` (Room + Ink), `things`, `camera` (on-device `tasks-vision:0.10.14` BlazeFace), `pdf` (Rust `libpdf_render.so`), `music` (Media3 ExoPlayer + local scan), `games/*`, `passwords` (biometric + KeePass), `library/*`, `health` (including food search, which ships its database in the APK).+`camera` and `photos` **no longer bundle two unattributable models**. Both `erdnet.{param,bin}` (portrait segmentation) and `u2netp.ncnn.{param,bin}` (subject segmentation) were added in a single commit (`72dde80df`, "make apps smaller") with no upstream URL, no license and no conversion recipe, and neither was ever listed here. They are replaced by fp16 `.vkml` weights converted from **Apache-2.0** ONNX exports, run on `:library:ml` — our own Vulkan compute runtime — rather than on ncnn:++- `camera/src/main/assets/selfie_segmentation.vkml` (211 KB, was 1.63 MB) from **`onnx-community/mediapipe_selfie_segmentation`**. A deliberate model *change*, not a port: erdnet was Caffe-derived from nihui's ncnn demo family and had no obtainable ONNX, so it could not be attributed or rebuilt at all. Bokeh masks therefore differ from before.+- `photos/src/main/assets/u2netp.vkml` (2.15 MB, was 2.26 MB) from **`BritishWerewolf/U-2-Netp`**. The same network re-sourced — the ncnn model's op inventory (Convolution 119, Pooling 33, Interp 38) matches the ONNX exactly.++Both are **build-host** dependencies only, pinned by upstream revision *and* file SHA-256 in `scripts/ml/fetch_and_convert.sh`, with provenance in a `README.md` beside each asset and the source ONNX SHA-256 baked into each `.vkml` header. If either vanished, shipped builds keep working. The ONNX itself is not vendored: it is twice the size and nothing reads it at run time.++The trade-off accepted is **GPU-only**: `:library:ml` needs Vulkan 1.1 plus `VK_KHR_shader_float16_int8`, which was promoted to core only in Vulkan 1.2 and so is optional at the 1.1 floor minSdk 31 guarantees. On a device without it, portrait bokeh and auto-select-subject turn off rather than falling back to CPU. `camera` sheds ncnn entirely as a result — `libncnn_android.so` is no longer in that APK — while `photos` keeps it for its two face models.++Notably **offline after first launch**: `astronomy`, `calendar`, `clock`, `contacts` (only `libphonenumber` locally), `files`, `notes` (Room + Ink), `things`, `camera` (on-device MediaPipe Selfie Segmentation on `:library:ml`), `pdf` (Rust `libpdf_render.so`), `music` (Media3 ExoPlayer + local scan), `games/*`, `passwords` (biometric + KeePass), `library/*`, `health` (including food search, which ships its database in the APK). --- @@ -65,11 +74,11 @@ Notably **offline after first launch**: `astronomy`, `calendar`, `clock`, `conta ### Build Infrastructure -- **Maven repositories**: `google()` (filtered), `mavenCentral()`, `gradlePluginPortal()` in `build-logic/settings`, plus **`https://jitpack.io`** in root `settings.gradle.kts`. JitPack now builds only `Stockfish-Library` (games:chess) — `nanojson` was vendored to `:third_party:nanojson` (✅ mitigation #2). JitPack remains a reproducible-build SPOF for Stockfish only.+- **Maven repositories**: `google()` (filtered), `mavenCentral()`, `gradlePluginPortal()` in `build-logic/settings`, plus **`https://jitpack.io`** in root `settings.gradle.kts`. JitPack builds **two** personal forks: `Stockfish-Library` (games:chess) and `ncnn-android` (`library:ocr`, `photos`, `speech`, `translate` — no longer `camera`, which moved to `:library:ml`). `nanojson` was vendored to `:third_party:nanojson` (✅ mitigation #2). JitPack remains a reproducible-build SPOF for both. - **Launch icon generator**: `build-logic/src/main/kotlin/LauncherIconGen.kt` downloads `https://raw.githubusercontent.com/google/material-design-icons/819d786.../symbols/android/{icon}/...24px.xml` at build time, cached under `~/.gradle/material-symbols-cache`. Build needs GitHub availability on first (uncached) build. ⚠️ Not yet mitigated. - **Alpha toolchain**: `agp = 9.4.0-alpha04`, `composeBom = 2026.06.01` (future-dated), `navigation3 = 1.2.0-alpha05`, `material3 = 1.5.0-alpha23`, `biometric = 1.4.0-alpha07`, `camerax = 1.7.0-alpha02`, `datastore = 1.3.0-alpha09`. ⚠️ Stable release branch should pin stable versions (not yet done). - **Version drift**: `okhttp 4.12.0` (2y old, 5.x exists) ⚠️ still pinned. `ktor` fully removed (`:messages` migrated to `:library:network` ✅) and `mediapipe tasks-vision` unified at `0.10.35` (camera inline `0.10.14` removed ✅).-- **Vendored third_party**: `third_party/nanojson/` (vendored `TeamNewPipe/nanojson`, was JitPack — ✅ mitigation #2), `third_party/om-file-format-sys/` (C + Rust bindings for `open-meteo/om-file-format` GPL-2.0-only) patched for reproducible `readdir` sort, `maps/src/main/cpp/sqlite3.c` amalgamation (SQLite NDK workaround), `youpipe/extractor/` full NewPipe Extractor GPLv3, `library/ocr/assets/det.onnx, rec.onnx` from `RapidAI/RapidOCR` Apache-2.0.+- **Vendored third_party**: `third_party/nanojson/` (vendored `TeamNewPipe/nanojson`, was JitPack — ✅ mitigation #2), `third_party/om-file-format-sys/` (C + Rust bindings for `open-meteo/om-file-format` GPL-2.0-only) patched for reproducible `readdir` sort, `maps/src/main/cpp/sqlite3.c` amalgamation (SQLite NDK workaround), `youpipe/extractor/` full NewPipe Extractor GPLv3, `library/ocr/src/main/assets/PP_OCRv5_mobile_det.ncnn.{param,bin}` + `latin_PP_OCRv5_mobile_rec.ncnn.{param,bin}` from `RapidAI/RapidOCR` Apache-2.0 (ncnn conversions — `:library:ocr` ships no `.onnx`). All versions in `gradle/libs.versions.toml`. Rust versions unified in root `/Cargo.toml` (workspace resolver 2, mirrors Gradle catalog) – see `/scripts/rust-deps-count.sh`.
camera/build.gradle.kts
diff --git a/camera/build.gradle.kts b/camera/build.gradle.ktsindex bf89e59cbf..cdd85faead 100644--- a/camera/build.gradle.kts+++ b/camera/build.gradle.kts@@ -14,6 +14,12 @@ android { defaultConfig { applicationId = "com.vayunmathur.camera" }+ androidResources {+ // selfie_segmentation.vkml is read straight out of the APK by SelfieSegmenter, so+ // leave it uncompressed: fp16 weights barely deflate, and a compressed asset would+ // have to be inflated into a heap buffer before it could be uploaded.+ noCompress += "vkml"+ } } androidComponents {@@ -37,6 +43,10 @@ dependencies { implementation(libs.androidx.camera.extensions) implementation(libs.androidx.exifinterface) implementation(libs.zxing.core)- // On-device portrait segmentation via ncnn (Tencent, BSD-3, CPU-only), forked AAR.- implementation(libs.ncnn.android)+ // On-device portrait segmentation. MediaPipe Selfie Segmentation (Apache-2.0) on our+ // own Vulkan compute runtime; see camera/src/main/assets/README.md.+ //+ // ncnn is gone from this app entirely: PortraitSegmenter was its only user, so+ // libncnn_android.so is no longer in the APK.+ implementation(project(":library:ml")) }
camera/src/main/assets/README.md
diff --git a/camera/src/main/assets/README.md b/camera/src/main/assets/README.mdnew file mode 100644index 0000000000..5b0e41d239--- /dev/null+++ b/camera/src/main/assets/README.md@@ -0,0 +1,32 @@+# `:camera` bundled model assets++## `selfie_segmentation.vkml`++Apache-2.0, from https://huggingface.co/onnx-community/mediapipe_selfie_segmentation+@ `be49485c8e027524be38591817fc5cd31bd9d00e` (`onnx/model.onnx`, 462,352 B fp32,+SHA-256 `3241ac4a…4531aad`) — an ONNX export of Google's MediaPipe Selfie+Segmentation, the model purpose-built for exactly this job.++Not the ONNX itself: `scripts/ml/fetch_and_convert.sh` converts it to the fp16+`.vkml` weights container that `:library:ml` reads, which is half the size and the+only form anything here loads. The source ONNX SHA-256 is in the `.vkml` header, so+a shipped asset traces back to this line without needing the ONNX on disk.++Run at 256×256 RGB, rescale 1/255 and **no** mean/std (`do_normalize: false`+upstream), output a single 256×256 alpha channel through a sigmoid. Consumed by+`SelfieSegmenter` from `BokehAnalyzer` and `PortraitBokeh.StillBokehRenderer`.++This replaces `erdnet.{param,bin}`, which was added in `72dde80df` with no upstream+URL, license or conversion recipe. It was Caffe-derived from nihui's ncnn demo+family, had no obtainable ONNX, and so could not be attributed or rebuilt — see+`SUPPLY_CHAIN_RISKS.md`. The masks differ from erdnet's; this is a different model,+not a port.++Update: `./scripts/ml/fetch_and_convert.sh --update`, which reports the moved+SHA-256 to re-pin. If the ordered layer table changed too, the converter says so+and the hardcoded forward pass in+`library/ml/src/main/rust/src/nets/selfie.rs` has to be updated with it.++This file is inside `assets/`, so it is packaged into the APK. That is deliberate+rather than overlooked: it is ~1 KB, and Apache-2.0 §4 asks that attribution+notices travel with the distributed work, which here is the weights next to it.
camera/src/main/assets/erdnet.bin
diff --git a/camera/src/main/assets/erdnet.bin b/camera/src/main/assets/erdnet.bindeleted file mode 100644index b60591d279..0000000000Binary files a/camera/src/main/assets/erdnet.bin and /dev/null differ
camera/src/main/assets/erdnet.param
diff --git a/camera/src/main/assets/erdnet.param b/camera/src/main/assets/erdnet.paramdeleted file mode 100644index 7c90eb24f9..0000000000--- a/camera/src/main/assets/erdnet.param+++ /dev/null@@ -1,196 +0,0 @@-7767517-194 249-Input input1 0 1 input_blob1 -23330=4,3,256,256,3 0=256 1=256 2=3-Split splitncnn_0 1 6 input_blob1 input_blob1_splitncnn_0 input_blob1_splitncnn_1 input_blob1_splitncnn_2 input_blob1_splitncnn_3 input_blob1_splitncnn_4 input_blob1_splitncnn_5 -23330=24,3,256,256,3,3,256,256,3,3,256,256,3,3,256,256,3,3,256,256,3,3,256,256,3-Pooling ave_pool1 1 1 input_blob1_splitncnn_5 ave_pool_blob1 -23330=4,3,128,128,3 0=1 1=3 2=2 3=1 5=1-Split splitncnn_1 1 2 ave_pool_blob1 ave_pool_blob1_splitncnn_0 ave_pool_blob1_splitncnn_1 -23330=8,3,128,128,3,3,128,128,3-Pooling ave_pool2 1 1 ave_pool_blob1_splitncnn_1 ave_pool_blob2 -23330=4,3,64,64,3 0=1 1=3 2=2 3=1 5=1-Split splitncnn_2 1 2 ave_pool_blob2 ave_pool_blob2_splitncnn_0 ave_pool_blob2_splitncnn_1 -23330=8,3,64,64,3,3,64,64,3-Pooling ave_pool3 1 1 ave_pool_blob2_splitncnn_1 ave_pool_blob3 -23330=4,3,32,32,3 0=1 1=3 2=2 3=1 5=1-Split splitncnn_3 1 2 ave_pool_blob3 ave_pool_blob3_splitncnn_0 ave_pool_blob3_splitncnn_1 -23330=8,3,32,32,3,3,32,32,3-Pooling ave_pool4 1 1 ave_pool_blob3_splitncnn_1 ave_pool_blob4 -23330=4,3,16,16,3 0=1 1=3 2=2 3=1 5=1-Convolution conv1 1 1 input_blob1_splitncnn_4 conv_blob1 -23330=4,3,128,128,12 0=12 1=3 3=2 4=1 5=1 6=324-PReLU prelu1 1 1 conv_blob1 prelu_blob1 -23330=4,3,128,128,12 0=12-Split splitncnn_4 1 2 prelu_blob1 prelu_blob1_splitncnn_0 prelu_blob1_splitncnn_1 -23330=8,3,128,128,12,3,128,128,12-Convolution conv2 1 1 prelu_blob1_splitncnn_1 conv_blob2 -23330=4,3,128,128,4 0=4 1=1 6=48-Split splitncnn_5 1 2 conv_blob2 conv_blob2_splitncnn_0 conv_blob2_splitncnn_1 -23330=8,3,128,128,4,3,128,128,4-Convolution conv3 1 1 conv_blob2_splitncnn_1 relu_blob1 -23330=4,3,128,128,4 0=4 1=3 4=1 5=1 6=144 9=1-Concat cat1 2 1 conv_blob2_splitncnn_0 relu_blob1 cat_blob1 -23330=4,3,128,128,8-Split splitncnn_6 1 2 cat_blob1 cat_blob1_splitncnn_0 cat_blob1_splitncnn_1 -23330=8,3,128,128,8,3,128,128,8-Convolution conv4 1 1 cat_blob1_splitncnn_1 relu_blob2 -23330=4,3,128,128,4 0=4 1=3 4=1 5=1 6=288 9=1-Concat cat2 2 1 cat_blob1_splitncnn_0 relu_blob2 cat_blob2 -23330=4,3,128,128,12-Eltwise add1 2 1 prelu_blob1_splitncnn_0 cat_blob2 add_blob1 -23330=4,3,128,128,12 0=1-BatchNorm batch_norm1 1 1 add_blob1 batch_norm_blob1_bn_scale1 -23330=4,3,128,128,12 0=12-PReLU prelu2 1 1 batch_norm_blob1_bn_scale1 prelu_blob2 -23330=4,3,128,128,12 0=12-Split splitncnn_7 1 2 prelu_blob2 prelu_blob2_splitncnn_0 prelu_blob2_splitncnn_1 -23330=8,3,128,128,12,3,128,128,12-Concat cat3 2 1 ave_pool_blob1_splitncnn_0 prelu_blob2_splitncnn_1 cat_blob3 -23330=4,3,128,128,15-BatchNorm batch_norm2 1 1 cat_blob3 batch_norm_blob2_bn_scale2 -23330=4,3,128,128,15 0=15-PReLU prelu3 1 1 batch_norm_blob2_bn_scale2 prelu_blob3 -23330=4,3,128,128,15 0=15-Convolution conv5 1 1 prelu_blob3 conv_blob5 -23330=4,3,64,64,24 0=24 1=3 3=2 4=1 5=1 6=3240-PReLU prelu4 1 1 conv_blob5 prelu_blob4 -23330=4,3,64,64,24 0=24-Split splitncnn_8 1 3 prelu_blob4 prelu_blob4_splitncnn_0 prelu_blob4_splitncnn_1 prelu_blob4_splitncnn_2 -23330=12,3,64,64,24,3,64,64,24,3,64,64,24-Convolution conv6 1 1 prelu_blob4_splitncnn_2 conv_blob6 -23330=4,3,64,64,8 0=8 1=1 6=192-Split splitncnn_9 1 2 conv_blob6 conv_blob6_splitncnn_0 conv_blob6_splitncnn_1 -23330=8,3,64,64,8,3,64,64,8-Convolution conv7 1 1 conv_blob6_splitncnn_1 relu_blob3 -23330=4,3,64,64,8 0=8 1=3 4=1 5=1 6=576 9=1-Concat cat4 2 1 conv_blob6_splitncnn_0 relu_blob3 cat_blob4 -23330=4,3,64,64,16-Split splitncnn_10 1 2 cat_blob4 cat_blob4_splitncnn_0 cat_blob4_splitncnn_1 -23330=8,3,64,64,16,3,64,64,16-Convolution conv8 1 1 cat_blob4_splitncnn_1 relu_blob4 -23330=4,3,64,64,8 0=8 1=3 4=1 5=1 6=1152 9=1-Concat cat5 2 1 cat_blob4_splitncnn_0 relu_blob4 cat_blob5 -23330=4,3,64,64,24-Eltwise add2 2 1 prelu_blob4_splitncnn_1 cat_blob5 add_blob2 -23330=4,3,64,64,24 0=1-BatchNorm batch_norm3 1 1 add_blob2 batch_norm_blob3_bn_scale3 -23330=4,3,64,64,24 0=24-PReLU prelu5 1 1 batch_norm_blob3_bn_scale3 prelu_blob5 -23330=4,3,64,64,24 0=24-Split splitncnn_11 1 2 prelu_blob5 prelu_blob5_splitncnn_0 prelu_blob5_splitncnn_1 -23330=8,3,64,64,24,3,64,64,24-Concat cat6 3 1 ave_pool_blob2_splitncnn_0 prelu_blob4_splitncnn_0 prelu_blob5_splitncnn_1 cat_blob6 -23330=4,3,64,64,51-BatchNorm batch_norm4 1 1 cat_blob6 batch_norm_blob4_bn_scale4 -23330=4,3,64,64,51 0=51-PReLU prelu6 1 1 batch_norm_blob4_bn_scale4 prelu_blob6 -23330=4,3,64,64,51 0=51-Convolution conv9 1 1 prelu_blob6 conv_blob9 -23330=4,3,32,32,48 0=48 1=3 3=2 4=1 5=1 6=22032-PReLU prelu7 1 1 conv_blob9 prelu_blob7 -23330=4,3,32,32,48 0=48-Split splitncnn_12 1 3 prelu_blob7 prelu_blob7_splitncnn_0 prelu_blob7_splitncnn_1 prelu_blob7_splitncnn_2 -23330=12,3,32,32,48,3,32,32,48,3,32,32,48-Convolution conv10 1 1 prelu_blob7_splitncnn_2 conv_blob10 -23330=4,3,32,32,16 0=16 1=1 6=768-Split splitncnn_13 1 2 conv_blob10 conv_blob10_splitncnn_0 conv_blob10_splitncnn_1 -23330=8,3,32,32,16,3,32,32,16-Convolution conv11 1 1 conv_blob10_splitncnn_1 relu_blob5 -23330=4,3,32,32,16 0=16 1=3 4=1 5=1 6=2304 9=1-Concat cat7 2 1 conv_blob10_splitncnn_0 relu_blob5 cat_blob7 -23330=4,3,32,32,32-Split splitncnn_14 1 2 cat_blob7 cat_blob7_splitncnn_0 cat_blob7_splitncnn_1 -23330=8,3,32,32,32,3,32,32,32-Convolution conv12 1 1 cat_blob7_splitncnn_1 relu_blob6 -23330=4,3,32,32,16 0=16 1=3 4=1 5=1 6=4608 9=1-Concat cat8 2 1 cat_blob7_splitncnn_0 relu_blob6 cat_blob8 -23330=4,3,32,32,48-Eltwise add3 2 1 prelu_blob7_splitncnn_1 cat_blob8 add_blob3 -23330=4,3,32,32,48 0=1-BatchNorm batch_norm5 1 1 add_blob3 batch_norm_blob5_bn_scale5 -23330=4,3,32,32,48 0=48-PReLU prelu8 1 1 batch_norm_blob5_bn_scale5 prelu_blob8 -23330=4,3,32,32,48 0=48-Split splitncnn_15 1 2 prelu_blob8 prelu_blob8_splitncnn_0 prelu_blob8_splitncnn_1 -23330=8,3,32,32,48,3,32,32,48-Concat cat9 3 1 ave_pool_blob3_splitncnn_0 prelu_blob7_splitncnn_0 prelu_blob8_splitncnn_1 cat_blob9 -23330=4,3,32,32,99-BatchNorm batch_norm6 1 1 cat_blob9 batch_norm_blob6_bn_scale6 -23330=4,3,32,32,99 0=99-PReLU prelu9 1 1 batch_norm_blob6_bn_scale6 prelu_blob9 -23330=4,3,32,32,99 0=99-Convolution conv13 1 1 prelu_blob9 conv_blob13 -23330=4,3,16,16,96 0=96 1=3 3=2 4=1 5=1 6=85536-PReLU prelu10 1 1 conv_blob13 prelu_blob10 -23330=4,3,16,16,96 0=96-Split splitncnn_16 1 3 prelu_blob10 prelu_blob10_splitncnn_0 prelu_blob10_splitncnn_1 prelu_blob10_splitncnn_2 -23330=12,3,16,16,96,3,16,16,96,3,16,16,96-Convolution conv14 1 1 prelu_blob10_splitncnn_2 conv_blob14 -23330=4,3,16,16,16 0=16 1=1 6=1536-Split splitncnn_17 1 2 conv_blob14 conv_blob14_splitncnn_0 conv_blob14_splitncnn_1 -23330=8,3,16,16,16,3,16,16,16-Convolution conv15 1 1 conv_blob14_splitncnn_1 relu_blob7 -23330=4,3,16,16,16 0=16 1=3 4=1 5=1 6=2304 9=1-Concat cat10 2 1 conv_blob14_splitncnn_0 relu_blob7 cat_blob10 -23330=4,3,16,16,32-Split splitncnn_18 1 2 cat_blob10 cat_blob10_splitncnn_0 cat_blob10_splitncnn_1 -23330=8,3,16,16,32,3,16,16,32-Convolution conv16 1 1 cat_blob10_splitncnn_1 relu_blob8 -23330=4,3,16,16,16 0=16 1=3 4=1 5=1 6=4608 9=1-Concat cat11 2 1 cat_blob10_splitncnn_0 relu_blob8 cat_blob11 -23330=4,3,16,16,48-Split splitncnn_19 1 2 cat_blob11 cat_blob11_splitncnn_0 cat_blob11_splitncnn_1 -23330=8,3,16,16,48,3,16,16,48-Convolution conv17 1 1 cat_blob11_splitncnn_1 relu_blob9 -23330=4,3,16,16,16 0=16 1=3 4=1 5=1 6=6912 9=1-Concat cat12 2 1 cat_blob11_splitncnn_0 relu_blob9 cat_blob12 -23330=4,3,16,16,64-Split splitncnn_20 1 2 cat_blob12 cat_blob12_splitncnn_0 cat_blob12_splitncnn_1 -23330=8,3,16,16,64,3,16,16,64-Convolution conv18 1 1 cat_blob12_splitncnn_1 relu_blob10 -23330=4,3,16,16,16 0=16 1=3 4=1 5=1 6=9216 9=1-Concat cat13 2 1 cat_blob12_splitncnn_0 relu_blob10 cat_blob13 -23330=4,3,16,16,80-Split splitncnn_21 1 2 cat_blob13 cat_blob13_splitncnn_0 cat_blob13_splitncnn_1 -23330=8,3,16,16,80,3,16,16,80-Convolution conv19 1 1 cat_blob13_splitncnn_1 relu_blob11 -23330=4,3,16,16,16 0=16 1=3 4=1 5=1 6=11520 9=1-Concat cat14 2 1 cat_blob13_splitncnn_0 relu_blob11 cat_blob14 -23330=4,3,16,16,96-Eltwise add4 2 1 prelu_blob10_splitncnn_1 cat_blob14 add_blob4 -23330=4,3,16,16,96 0=1-BatchNorm batch_norm7 1 1 add_blob4 batch_norm_blob7_bn_scale7 -23330=4,3,16,16,96 0=96-PReLU prelu11 1 1 batch_norm_blob7_bn_scale7 prelu_blob11 -23330=4,3,16,16,96 0=96-Split splitncnn_22 1 2 prelu_blob11 prelu_blob11_splitncnn_0 prelu_blob11_splitncnn_1 -23330=8,3,16,16,96,3,16,16,96-Convolution conv20 1 1 prelu_blob11_splitncnn_1 conv_blob20 -23330=4,3,16,16,16 0=16 1=1 6=1536-Split splitncnn_23 1 2 conv_blob20 conv_blob20_splitncnn_0 conv_blob20_splitncnn_1 -23330=8,3,16,16,16,3,16,16,16-Convolution conv21 1 1 conv_blob20_splitncnn_1 relu_blob12 -23330=4,3,16,16,16 0=16 1=3 4=1 5=1 6=2304 9=1-Concat cat15 2 1 conv_blob20_splitncnn_0 relu_blob12 cat_blob15 -23330=4,3,16,16,32-Split splitncnn_24 1 2 cat_blob15 cat_blob15_splitncnn_0 cat_blob15_splitncnn_1 -23330=8,3,16,16,32,3,16,16,32-Convolution conv22 1 1 cat_blob15_splitncnn_1 relu_blob13 -23330=4,3,16,16,16 0=16 1=3 4=1 5=1 6=4608 9=1-Concat cat16 2 1 cat_blob15_splitncnn_0 relu_blob13 cat_blob16 -23330=4,3,16,16,48-Split splitncnn_25 1 2 cat_blob16 cat_blob16_splitncnn_0 cat_blob16_splitncnn_1 -23330=8,3,16,16,48,3,16,16,48-Convolution conv23 1 1 cat_blob16_splitncnn_1 relu_blob14 -23330=4,3,16,16,16 0=16 1=3 4=1 5=1 6=6912 9=1-Concat cat17 2 1 cat_blob16_splitncnn_0 relu_blob14 cat_blob17 -23330=4,3,16,16,64-Split splitncnn_26 1 2 cat_blob17 cat_blob17_splitncnn_0 cat_blob17_splitncnn_1 -23330=8,3,16,16,64,3,16,16,64-Convolution conv24 1 1 cat_blob17_splitncnn_1 relu_blob15 -23330=4,3,16,16,16 0=16 1=3 4=1 5=1 6=9216 9=1-Concat cat18 2 1 cat_blob17_splitncnn_0 relu_blob15 cat_blob18 -23330=4,3,16,16,80-Split splitncnn_27 1 2 cat_blob18 cat_blob18_splitncnn_0 cat_blob18_splitncnn_1 -23330=8,3,16,16,80,3,16,16,80-Convolution conv25 1 1 cat_blob18_splitncnn_1 relu_blob16 -23330=4,3,16,16,16 0=16 1=3 4=1 5=1 6=11520 9=1-Concat cat19 2 1 cat_blob18_splitncnn_0 relu_blob16 cat_blob19 -23330=4,3,16,16,96-Eltwise add5 2 1 prelu_blob11_splitncnn_0 cat_blob19 add_blob5 -23330=4,3,16,16,96 0=1-BatchNorm batch_norm8 1 1 add_blob5 batch_norm_blob8_bn_scale8 -23330=4,3,16,16,96 0=96-PReLU prelu12 1 1 batch_norm_blob8_bn_scale8 prelu_blob12 -23330=4,3,16,16,96 0=96-Split splitncnn_28 1 2 prelu_blob12 prelu_blob12_splitncnn_0 prelu_blob12_splitncnn_1 -23330=8,3,16,16,96,3,16,16,96-Concat cat20 3 1 ave_pool_blob4 prelu_blob10_splitncnn_0 prelu_blob12_splitncnn_1 cat_blob20 -23330=4,3,16,16,195-BatchNorm batch_norm9 1 1 cat_blob20 batch_norm_blob9_bn_scale9 -23330=4,3,16,16,195 0=195-PReLU prelu13 1 1 batch_norm_blob9_bn_scale9 prelu_blob13 -23330=4,3,16,16,195 0=195-Convolution conv26 1 1 prelu_blob13 conv_blob26 -23330=4,3,8,8,192 0=192 1=3 3=2 4=1 5=1 6=336960-PReLU prelu14 1 1 conv_blob26 prelu_blob14 -23330=4,3,8,8,192 0=192-Split splitncnn_29 1 2 prelu_blob14 prelu_blob14_splitncnn_0 prelu_blob14_splitncnn_1 -23330=8,3,8,8,192,3,8,8,192-Convolution conv27 1 1 prelu_blob14_splitncnn_1 conv_blob27 -23330=4,3,8,8,32 0=32 1=1 6=6144-Split splitncnn_30 1 2 conv_blob27 conv_blob27_splitncnn_0 conv_blob27_splitncnn_1 -23330=8,3,8,8,32,3,8,8,32-Convolution conv28 1 1 conv_blob27_splitncnn_1 relu_blob17 -23330=4,3,8,8,32 0=32 1=3 4=1 5=1 6=9216 9=1-Concat cat21 2 1 conv_blob27_splitncnn_0 relu_blob17 cat_blob21 -23330=4,3,8,8,64-Split splitncnn_31 1 2 cat_blob21 cat_blob21_splitncnn_0 cat_blob21_splitncnn_1 -23330=8,3,8,8,64,3,8,8,64-Convolution conv29 1 1 cat_blob21_splitncnn_1 relu_blob18 -23330=4,3,8,8,32 0=32 1=3 4=1 5=1 6=18432 9=1-Concat cat22 2 1 cat_blob21_splitncnn_0 relu_blob18 cat_blob22 -23330=4,3,8,8,96-Split splitncnn_32 1 2 cat_blob22 cat_blob22_splitncnn_0 cat_blob22_splitncnn_1 -23330=8,3,8,8,96,3,8,8,96-Convolution conv30 1 1 cat_blob22_splitncnn_1 relu_blob19 -23330=4,3,8,8,32 0=32 1=3 4=1 5=1 6=27648 9=1-Concat cat23 2 1 cat_blob22_splitncnn_0 relu_blob19 cat_blob23 -23330=4,3,8,8,128-Split splitncnn_33 1 2 cat_blob23 cat_blob23_splitncnn_0 cat_blob23_splitncnn_1 -23330=8,3,8,8,128,3,8,8,128-Convolution conv31 1 1 cat_blob23_splitncnn_1 relu_blob20 -23330=4,3,8,8,32 0=32 1=3 4=1 5=1 6=36864 9=1-Concat cat24 2 1 cat_blob23_splitncnn_0 relu_blob20 cat_blob24 -23330=4,3,8,8,160-Split splitncnn_34 1 2 cat_blob24 cat_blob24_splitncnn_0 cat_blob24_splitncnn_1 -23330=8,3,8,8,160,3,8,8,160-Convolution conv32 1 1 cat_blob24_splitncnn_1 relu_blob21 -23330=4,3,8,8,32 0=32 1=3 4=1 5=1 6=46080 9=1-Concat cat25 2 1 cat_blob24_splitncnn_0 relu_blob21 cat_blob25 -23330=4,3,8,8,192-Eltwise add6 2 1 prelu_blob14_splitncnn_0 cat_blob25 add_blob6 -23330=4,3,8,8,192 0=1-BatchNorm batch_norm10 1 1 add_blob6 batch_norm_blob10_bn_scale10 -23330=4,3,8,8,192 0=192-PReLU prelu15 1 1 batch_norm_blob10_bn_scale10 prelu_blob15 -23330=4,3,8,8,192 0=192-Split splitncnn_35 1 2 prelu_blob15 prelu_blob15_splitncnn_0 prelu_blob15_splitncnn_1 -23330=8,3,8,8,192,3,8,8,192-Convolution conv33 1 1 prelu_blob15_splitncnn_1 conv_blob33 -23330=4,3,8,8,32 0=32 1=1 6=6144-Split splitncnn_36 1 2 conv_blob33 conv_blob33_splitncnn_0 conv_blob33_splitncnn_1 -23330=8,3,8,8,32,3,8,8,32-Convolution conv34 1 1 conv_blob33_splitncnn_1 relu_blob22 -23330=4,3,8,8,32 0=32 1=3 4=1 5=1 6=9216 9=1-Concat cat26 2 1 conv_blob33_splitncnn_0 relu_blob22 cat_blob26 -23330=4,3,8,8,64-Split splitncnn_37 1 2 cat_blob26 cat_blob26_splitncnn_0 cat_blob26_splitncnn_1 -23330=8,3,8,8,64,3,8,8,64-Convolution conv35 1 1 cat_blob26_splitncnn_1 relu_blob23 -23330=4,3,8,8,32 0=32 1=3 4=1 5=1 6=18432 9=1-Concat cat27 2 1 cat_blob26_splitncnn_0 relu_blob23 cat_blob27 -23330=4,3,8,8,96-Split splitncnn_38 1 2 cat_blob27 cat_blob27_splitncnn_0 cat_blob27_splitncnn_1 -23330=8,3,8,8,96,3,8,8,96-Convolution conv36 1 1 cat_blob27_splitncnn_1 relu_blob24 -23330=4,3,8,8,32 0=32 1=3 4=1 5=1 6=27648 9=1-Concat cat28 2 1 cat_blob27_splitncnn_0 relu_blob24 cat_blob28 -23330=4,3,8,8,128-Split splitncnn_39 1 2 cat_blob28 cat_blob28_splitncnn_0 cat_blob28_splitncnn_1 -23330=8,3,8,8,128,3,8,8,128-Convolution conv37 1 1 cat_blob28_splitncnn_1 relu_blob25 -23330=4,3,8,8,32 0=32 1=3 4=1 5=1 6=36864 9=1-Concat cat29 2 1 cat_blob28_splitncnn_0 relu_blob25 cat_blob29 -23330=4,3,8,8,160-Split splitncnn_40 1 2 cat_blob29 cat_blob29_splitncnn_0 cat_blob29_splitncnn_1 -23330=8,3,8,8,160,3,8,8,160-Convolution conv38 1 1 cat_blob29_splitncnn_1 relu_blob26 -23330=4,3,8,8,32 0=32 1=3 4=1 5=1 6=46080 9=1-Concat cat30 2 1 cat_blob29_splitncnn_0 relu_blob26 cat_blob30 -23330=4,3,8,8,192-Eltwise add7 2 1 prelu_blob15_splitncnn_0 cat_blob30 add_blob7 -23330=4,3,8,8,192 0=1-BatchNorm batch_norm11 1 1 add_blob7 batch_norm_blob11_bn_scale11 -23330=4,3,8,8,192 0=192-PReLU prelu16 1 1 batch_norm_blob11_bn_scale11 prelu_blob16 -23330=4,3,8,8,192 0=192-Convolution conv39 1 1 prelu_blob16 conv_blob39 -23330=4,3,8,8,2 0=2 1=1 6=384-Interp interp1 1 1 conv_blob39 interp_blob1 -23330=4,3,16,16,2 0=2 1=2.000000e+00 2=2.000000e+00-Convolution conv40 1 1 prelu_blob12_splitncnn_0 conv_blob40 -23330=4,3,16,16,2 0=2 1=3 4=1 5=1 6=1728-PReLU prelu17 1 1 conv_blob40 prelu_blob17 -23330=4,3,16,16,2 0=2-BatchNorm batch_norm12 1 1 prelu_blob17 batch_norm_blob12_bn_scale12 -23330=4,3,16,16,2 0=2-PReLU prelu18 1 1 batch_norm_blob12_bn_scale12 prelu_blob18 -23330=4,3,16,16,2 0=2-Eltwise add8 2 1 interp_blob1 prelu_blob18 add_blob8 -23330=4,3,16,16,2 0=1-Convolution conv41 1 1 add_blob8 conv_blob41 -23330=4,3,16,16,2 0=2 1=3 4=1 6=36-Interp interp2 1 1 conv_blob41 interp_blob2 -23330=4,3,32,32,2 0=2 1=2.000000e+00 2=2.000000e+00-Convolution conv42 1 1 prelu_blob8_splitncnn_0 conv_blob42 -23330=4,3,32,32,2 0=2 1=3 4=1 5=1 6=864-PReLU prelu19 1 1 conv_blob42 prelu_blob19 -23330=4,3,32,32,2 0=2-BatchNorm batch_norm13 1 1 prelu_blob19 batch_norm_blob13_bn_scale13 -23330=4,3,32,32,2 0=2-PReLU prelu20 1 1 batch_norm_blob13_bn_scale13 prelu_blob20 -23330=4,3,32,32,2 0=2-Eltwise add9 2 1 interp_blob2 prelu_blob20 add_blob9 -23330=4,3,32,32,2 0=1-Convolution conv43 1 1 add_blob9 conv_blob43 -23330=4,3,32,32,2 0=2 1=3 4=1 6=36-Interp interp3 1 1 conv_blob43 interp_blob3 -23330=4,3,64,64,2 0=2 1=2.000000e+00 2=2.000000e+00-Convolution conv44 1 1 prelu_blob5_splitncnn_0 conv_blob44 -23330=4,3,64,64,2 0=2 1=3 4=1 5=1 6=432-PReLU prelu21 1 1 conv_blob44 prelu_blob21 -23330=4,3,64,64,2 0=2-BatchNorm batch_norm14 1 1 prelu_blob21 batch_norm_blob14_bn_scale14 -23330=4,3,64,64,2 0=2-PReLU prelu22 1 1 batch_norm_blob14_bn_scale14 prelu_blob22 -23330=4,3,64,64,2 0=2-Eltwise add10 2 1 interp_blob3 prelu_blob22 add_blob10 -23330=4,3,64,64,2 0=1-Convolution conv45 1 1 add_blob10 conv_blob45 -23330=4,3,64,64,2 0=2 1=3 4=1 6=36-Interp interp4 1 1 conv_blob45 interp_blob4 -23330=4,3,128,128,2 0=2 1=2.000000e+00 2=2.000000e+00-Convolution conv46 1 1 prelu_blob2_splitncnn_0 conv_blob46 -23330=4,3,128,128,2 0=2 1=3 4=1 5=1 6=216-PReLU prelu23 1 1 conv_blob46 prelu_blob23 -23330=4,3,128,128,2 0=2-BatchNorm batch_norm15 1 1 prelu_blob23 batch_norm_blob15_bn_scale15 -23330=4,3,128,128,2 0=2-PReLU prelu24 1 1 batch_norm_blob15_bn_scale15 prelu_blob24 -23330=4,3,128,128,2 0=2-Eltwise add11 2 1 interp_blob4 prelu_blob24 add_blob11 -23330=4,3,128,128,2 0=1-Convolution conv47 1 1 add_blob11 conv_blob47 -23330=4,3,128,128,2 0=2 1=3 4=1 6=36-Interp interp5 1 1 conv_blob47 interp_blob5 -23330=4,3,256,256,2 0=2 1=2.000000e+00 2=2.000000e+00-Softmax softmax1 1 1 interp_blob5 softmax_blob1 -23330=4,3,256,256,2-Split splitncnn_41 1 2 softmax_blob1 softmax_blob1_splitncnn_0 softmax_blob1_splitncnn_1 -23330=8,3,256,256,2,3,256,256,2-Slice slice1 1 2 softmax_blob1_splitncnn_1 slice_blob1 slice_blob2 -23330=8,3,256,256,1,3,256,256,1 -23300=2,1,-233-Split splitncnn_42 1 4 slice_blob2 slice_blob2_splitncnn_0 slice_blob2_splitncnn_1 slice_blob2_splitncnn_2 slice_blob2_splitncnn_3 -23330=16,3,256,256,1,3,256,256,1,3,256,256,1,3,256,256,1-Eltwise mul1 2 1 input_blob1_splitncnn_3 input_blob1_splitncnn_2 mul_blob1 -23330=4,3,256,256,3-Concat cat31 3 1 slice_blob2_splitncnn_3 slice_blob2_splitncnn_2 slice_blob2_splitncnn_1 cat_blob31 -23330=4,3,256,256,3-Eltwise mul2 2 1 input_blob1_splitncnn_1 cat_blob31 mul_blob2 -23330=4,3,256,256,3-Concat cat32 4 1 input_blob1_splitncnn_0 softmax_blob1_splitncnn_0 mul_blob1 mul_blob2 cat_blob32 -23330=4,3,256,256,11-Convolution conv48 1 1 cat_blob32 relu_blob27 -23330=4,3,256,256,8 0=8 1=3 4=1 5=1 6=792 9=1-Convolution conv49 1 1 relu_blob27 conv_blob49 -23330=4,3,256,256,3 0=3 1=3 4=1 5=1 6=216-Slice slice2 1 3 conv_blob49 slice_blob3 slice_blob4 slice_blob5 -23330=12,3,256,256,1,3,256,256,1,3,256,256,1 -23300=3,1,1,1-Eltwise mul3 2 1 slice_blob3 slice_blob2_splitncnn_0 mul_blob3 -23330=4,3,256,256,1-Eltwise mul4 2 1 slice_blob4 slice_blob1 mul_blob4 -23330=4,3,256,256,1-Eltwise add12 2 1 mul_blob3 mul_blob4 add_blob12 -23330=4,3,256,256,1 0=1-Eltwise add13 2 1 add_blob12 slice_blob5 add_blob13 -23330=4,3,256,256,1 0=1-Sigmoid sigmoid1 1 1 add_blob13 sigmoid_blob1 -23330=4,3,256,256,1
camera/src/main/assets/selfie_segmentation.vkml
diff --git a/camera/src/main/assets/selfie_segmentation.vkml b/camera/src/main/assets/selfie_segmentation.vkmlnew file mode 100644index 0000000000..613247ef46Binary files /dev/null and b/camera/src/main/assets/selfie_segmentation.vkml differ
camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.kt b/camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.ktindex 06d74e2523..915b2c47f6 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.kt@@ -8,7 +8,7 @@ import android.util.Log import androidx.camera.core.ImageAnalysis import androidx.camera.core.ImageProxy import androidx.core.graphics.scale-import com.vayunmathur.ncnn.PortraitSegmenter+import com.vayunmathur.library.ml.SelfieSegmenter private const val TEMPORAL_WEIGHT = 0.35f // Throttle segmentation to avoid running more than ~15 fps even if analysis@@ -26,8 +26,9 @@ class BokehAnalyzer( // Guard for the native handle and buffer fields – analyze() runs on bokehExecutor // while close() runs on the main composable's DisposableEffect. Without mutual- // exclusion, close() destroys the ncnn net while openmp_worker threads are still- // reading it → SEGV_MTESERR tagged fault in libncnn_android.so.+ // exclusion, close() destroys the net while the GPU is still reading the buffers it+ // owns → the SEGV_MTESERR tagged fault this used to hit in libncnn_android.so. The+ // model changed; the hazard did not. private val lock = Any() private var prevMask: FloatArray? = null private var blurTemp: FloatArray? = null@@ -35,7 +36,9 @@ class BokehAnalyzer( private var pixelBuffer: IntArray? = null private var lastSegmentMs: Long = 0L @Volatile private var closed = false- private var segmenter: PortraitSegmenter? = PortraitSegmenter(context, "erdnet.param", "erdnet.bin")+ // GPU-only: null-returning rather than throwing when the device has no Vulkan fp16+ // compute, in which case the preview simply stays sharp.+ private var segmenter: SelfieSegmenter? = SelfieSegmenter(context) @androidx.annotation.OptIn(androidx.camera.core.ExperimentalGetImage::class) override fun analyze(imageProxy: ImageProxy) {@@ -73,8 +76,9 @@ class BokehAnalyzer( } // Synchronous forward pass; runs on dedicated bokehExecutor with KEEP_ONLY_LATEST.- // Hold lock across the native call so close() blocks until OpenMP workers finish,- // preventing the SEGV_MTESERR use-after-free seen in tombstones.+ // Hold lock across the native call so close() blocks until the submitted command+ // buffer has been waited on, preventing the SEGV_MTESERR use-after-free seen in+ // tombstones. val result = synchronized(lock) { if (closed) { frame.recycle()@@ -85,11 +89,9 @@ class BokehAnalyzer( frame.recycle() return }- try {- seg.segment(frame)- } catch (e: IllegalStateException) {- // PortraitSegmenter is closed – analyzer disposed while frame in-flight- Log.w("BokehAnalyzer", "segmenter closed mid-frame", e)+ // Null on an unavailable GPU or a failed submit; either way there is no+ // mask this frame and the preview keeps the last one.+ seg.segment(frame) ?: run { frame.recycle() return }@@ -144,7 +146,7 @@ class BokehAnalyzer( } fun close() {- val toClose: PortraitSegmenter?+ val toClose: SelfieSegmenter? synchronized(lock) { if (closed) return closed = true@@ -156,8 +158,8 @@ class BokehAnalyzer( pixelBuffer = null } // Destroy outside lock after nulling handle, but close() itself was blocked until- // any in-flight segment() finished (lock held across native call), so no OpenMP- // worker is still reading the net.+ // any in-flight segment() finished (lock held across native call), so the GPU is+ // no longer reading the buffers this frees. try { toClose?.close() } catch (_: Exception) {} }
camera/src/main/java/com/vayunmathur/camera/util/PortraitBokeh.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/PortraitBokeh.kt b/camera/src/main/java/com/vayunmathur/camera/util/PortraitBokeh.ktindex 955764627f..739122433d 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/PortraitBokeh.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/PortraitBokeh.kt@@ -22,7 +22,7 @@ import android.os.Build import android.util.Log import androidx.core.graphics.createBitmap import androidx.core.graphics.scale-import com.vayunmathur.ncnn.PortraitSegmenter+import com.vayunmathur.library.ml.SelfieSegmenter import kotlin.math.max import kotlin.math.min import kotlin.math.roundToInt@@ -183,7 +183,9 @@ internal fun maskToBitmap(mask: FloatArray, w: Int, h: Int, pixels: IntArray): B } // Segmentation input: the model runs at 256x256 internally, so there is nothing to gain from-// feeding it the full-resolution still. Matches the preview analyzer's cap.+// feeding it the full-resolution still. Matches the preview analyzer's cap. The downscale and+// the normalise both happen natively now (library/ml/src/main/rust/src/preprocess.rs), so this+// only bounds how much gets copied across JNI. private const val SEGMENT_INPUT_MAX_SIDE = 512 // The shader's tap spacing is in surface pixels and was tuned against a phone-sized viewfinder, so@@ -195,12 +197,14 @@ private const val BLUR_LONG_SIDE = 1440 /** * Bakes the portrait bokeh the viewfinder previews into a captured still. *- * Owns its own [PortraitSegmenter] (created on first use) because the preview's instance lives in- * [BokehAnalyzer], which is disposed with the composable and runs on a different thread.+ * Owns its own [SelfieSegmenter] (created on first use) because the preview's instance lives in+ * [BokehAnalyzer], which is disposed with the composable and runs on a different thread. The two+ * share one `VkDevice` regardless — `:library:ml` reference-counts it — so this costs buffers and+ * pipelines, not a second driver context. */ class StillBokehRenderer(private val context: Context) : AutoCloseable { - private var segmenter: PortraitSegmenter? = null+ private var segmenter: SelfieSegmenter? = null @Volatile private var closed = false /**@@ -226,12 +230,14 @@ class StillBokehRenderer(private val context: Context) : AutoCloseable { // The blur pass is AGSL, which needs RuntimeShader (API 33+). Below that // there is no bokeh; the caller keeps the sharp frame. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return null- val mask = try {- buildMask(src, rotationDegrees)- } catch (e: Throwable) {- Log.e("StillBokeh", "segmentation failed", e)- return null- }+ val mask = (+ try {+ buildMask(src, rotationDegrees)+ } catch (e: Throwable) {+ Log.e("StillBokeh", "segmentation failed", e)+ null+ }+ ) ?: return null // Blurred background, viewfinder-sized: alpha is punched out where the subject is so it can // be laid straight over the sharp frame.@@ -278,11 +284,11 @@ class StillBokehRenderer(private val context: Context) : AutoCloseable { /** * Runs the segmenter on a downscaled, upright copy of [src] and returns the softened mask- * rotated back into [src]'s orientation.+ * rotated back into [src]'s orientation, or null when the GPU cannot run it — in which case+ * the caller keeps the sharp frame. */- private fun buildMask(src: Bitmap, rotationDegrees: Int): Bitmap {- val seg = segmenter ?: PortraitSegmenter(context, "erdnet.param", "erdnet.bin")- .also { segmenter = it }+ private fun buildMask(src: Bitmap, rotationDegrees: Int): Bitmap? {+ val seg = segmenter ?: SelfieSegmenter(context).also { segmenter = it } // Both helpers hand back their input when there is nothing to do, so only recycle the // intermediates we actually allocated – never the caller's bitmap.@@ -290,11 +296,13 @@ class StillBokehRenderer(private val context: Context) : AutoCloseable { val upright = rotate(downscaled, rotationDegrees.toFloat()) if (downscaled !== src && downscaled !== upright) downscaled.recycle() - val result = try {- seg.segment(upright)- } finally {- if (upright !== src) upright.recycle()- }+ val result = (+ try {+ seg.segment(upright)+ } finally {+ if (upright !== src) upright.recycle()+ }+ ) ?: return null val w = result.width val h = result.height
camera/src/main/res/xml/data_extraction_rules.xml
diff --git a/camera/src/main/res/xml/data_extraction_rules.xml b/camera/src/main/res/xml/data_extraction_rules.xmlindex d45c9102eb..a07edd3ba6 100644--- a/camera/src/main/res/xml/data_extraction_rules.xml+++ b/camera/src/main/res/xml/data_extraction_rules.xml@@ -13,9 +13,9 @@ app's. Intermediate capture files (motion_*.mp4, VID_*.mp4, TL_*.mp4) go to cacheDir,- which the platform excludes from every backup on its own. erdnet.param /- erdnet.bin are bundled ncnn assets loaded from the APK by PortraitSegmenter,- not downloads.+ which the platform excludes from every backup on its own.+ selfie_segmentation.vkml is a bundled model asset read out of the APK by+ SelfieSegmenter, not a download. Nothing large, nothing personal — back the settings up in both directions. -->
library/ml/build.gradle.kts
diff --git a/library/ml/build.gradle.kts b/library/ml/build.gradle.ktsnew file mode 100644index 0000000000..ac2c6afb92--- /dev/null+++ b/library/ml/build.gradle.kts@@ -0,0 +1,21 @@+plugins {+ id("common-conventions-library")+}++androidComponents {+ onVariants { variant ->+ variant.sources.jniLibs?.addStaticSourceDirectory(+ layout.buildDirectory.dir("rustJniLibs").get().asFile.absolutePath+ )+ }+}++// The Vulkan compute ML runtime: `library/ml/src/main/rust`, on ash.+//+// No `externalNativeBuild` and no `ndkVersion`: there is no C++ or CMake in this repo+// (CMake was deliberately removed — see maps/build.gradle.kts:29-31), so cargo does the+// cross-compile and the NDK is only reached for its clang wrappers and glslc.+//+// Shaders are GLSL compute compiled to SPIR-V by the crate's own build.rs, which resolves+// glslc from the NDK and fails the build if it cannot.+rustNativeLib("modelrunner", "ml")
library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.ktnew file mode 100644index 0000000000..1188e5a704--- /dev/null+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt@@ -0,0 +1,69 @@+package com.vayunmathur.library.ml++/**+ * The JNI surface of the Vulkan compute runtime in `library/ml/src/main/rust`.+ *+ * Deliberately narrow: create a network from its weights, hand it a bitmap's pixels, get+ * a mask back, destroy it. Preprocessing, the whole forward pass and the readback happen+ * on the native side, so the boundary is crossed three times per inference rather than+ * once per pixel.+ *+ * [handle] values are opaque pointers owned by the native side. Every method tolerates+ * `0`, which is what the create functions return on failure — so a device without Vulkan+ * fp16 compute degrades to a disabled feature rather than a crash. See [isAvailable].+ *+ * Nothing here is thread-safe. Callers hold a lock across [segment] and [destroy]; see+ * [SelfieSegmenter] and [SubjectSegmenter], which do.+ */+internal object MlNative {++ /**+ * Whether `libmodelrunner.so` loaded.+ *+ * False on a device whose ABI we did not build for. It says nothing about whether+ * Vulkan or fp16 is available — that is only known once a create call is attempted,+ * because it needs a `VkDevice` to ask.+ */+ val isAvailable: Boolean = try {+ System.loadLibrary("modelrunner")+ true+ } catch (_: Throwable) {+ false+ }++ /**+ * Bring up MediaPipe Selfie Segmentation from a `.vkml` blob. Returns 0 on failure.+ *+ * Failure is expected and normal on a device without `VK_KHR_shader_float16_int8`,+ * which is a Vulkan 1.2 promotion and so optional at the 1.1 floor minSdk 31+ * guarantees. The reason is written to logcat under the `ModelRunner` tag.+ */+ external fun createSelfie(weights: ByteArray): Long++ /** Bring up U²-Net portable. Returns 0 on failure, as [createSelfie]. */+ external fun createU2netp(weights: ByteArray): Long++ /**+ * Run the network over [pixels] and return the mask, or null on failure.+ *+ * [pixels] is `ARGB_8888` as `Bitmap.getPixels` produces it, [width] × [height] long.+ * The bitmap is resized and normalised natively, so any size is accepted; the+ * returned mask is always [maskWidth] × [maskHeight], row-major, in `0..1`.+ */+ external fun segment(handle: Long, pixels: IntArray, width: Int, height: Int): FloatArray?++ /** The mask's width, so callers need not know either network's input size. */+ external fun maskWidth(handle: Long): Int++ /** The mask's height. */+ external fun maskHeight(handle: Long): Int++ /**+ * Free everything the handle owns, after waiting for the GPU to go idle.+ *+ * Exactly once per non-zero handle. When it is the last live network the shared+ * `VkDevice` is destroyed with it, so nothing stays resident once the feature is+ * closed.+ */+ external fun destroy(handle: Long)+}
library/ml/src/main/java/com/vayunmathur/library/ml/Segmentation.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/Segmentation.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/Segmentation.ktnew file mode 100644index 0000000000..c220ce08d9--- /dev/null+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/Segmentation.kt@@ -0,0 +1,122 @@+package com.vayunmathur.library.ml++import android.content.Context+import android.graphics.Bitmap+import android.util.Log++/** A segmentation mask: [width] × [height] probabilities in `0..1`, row-major. */+class SegmentationMask(+ /** Columns. Fixed per network, and independent of the input bitmap's size. */+ val width: Int,+ /** Rows. */+ val height: Int,+ /**+ * Foreground probability per pixel.+ *+ * A fresh array each call — the caller owns it and both call sites blend or threshold+ * it in place.+ */+ val mask: FloatArray,+)++/**+ * The safe half of the JNI surface: a network handle with a lifetime.+ *+ * `internal`, and held by composition rather than inherited from, so the public API of+ * this module is exactly [SelfieSegmenter] and [SubjectSegmenter] with three members each+ * — Kotlin would otherwise force this type public to let a public class extend it.+ *+ * # Failure is a state, not an exception+ *+ * The constructor never throws. If `libmodelrunner.so` is missing, or the device has no+ * Vulkan fp16 compute, or the asset will not parse, [isAvailable] is false and [segment]+ * returns null — the graceful-degradation shape `GpuStitcher` uses in `:camera`. That is+ * the GPU-only decision made visible: there is no CPU fallback, so the feature turns off+ * and the caller keeps whatever it had.+ *+ * # Not thread-safe, on purpose+ *+ * [segment] and [close] must not overlap. `BokehAnalyzer` holds `synchronized(lock)`+ * across the whole native call for exactly this reason — its comments record a real+ * `SEGV_MTESERR` use-after-free where `close` destroyed the net while worker threads were+ * still reading it. A `VkDevice` handle has the identical hazard, so putting a lock in+ * here as well would be a second, redundant one; the discipline stays where the threading+ * actually is.+ */+internal class NativeSegmenter(+ context: Context,+ assetName: String,+ tag: String,+ create: (ByteArray) -> Long,+) : AutoCloseable {++ /**+ * `@Volatile` because it is the one field whose staleness would be a use-after-free.+ *+ * Callers do establish happens-before via their own locks, so this is belt and braces+ * — but the cost is nothing and the failure mode is a native crash.+ */+ @Volatile private var handle: Long = if (!MlNative.isAvailable) {+ 0L+ } else {+ try {+ // `.vkml` is `noCompress` in both apps, so this is a straight copy out of the+ // mapped APK rather than an inflate into a second buffer.+ create(context.assets.open(assetName).use { it.readBytes() })+ } catch (e: Throwable) {+ Log.e(tag, "cannot load $assetName", e)+ 0L+ }+ }++ /** Whether the network came up. False means the feature is off on this device. */+ val isAvailable: Boolean get() = handle != 0L++ /**+ * Run the network over [bitmap] and return the mask, or null if it is unavailable or+ * the inference failed.+ *+ * [bitmap] may be any size: it is resized and normalised natively. The returned mask+ * is the network's own resolution, which the caller upsamples.+ */+ fun segment(bitmap: Bitmap): SegmentationMask? {+ if (handle == 0L) return null+ // `getPixels` cannot read a HARDWARE bitmap, and a null config means an unknown+ // one. Copying is the only option, and doing it here keeps both call sites from+ // each having to remember.+ val readable = if (bitmap.config == Bitmap.Config.HARDWARE || bitmap.config == null) {+ bitmap.copy(Bitmap.Config.ARGB_8888, false)+ } else {+ bitmap+ } ?: return null++ return try {+ val count = readable.width * readable.height+ var buffer = pixels+ if (buffer == null || buffer.size != count) {+ buffer = IntArray(count)+ pixels = buffer+ }+ readable.getPixels(buffer, 0, readable.width, 0, 0, readable.width, readable.height)+ val values = MlNative.segment(handle, buffer, readable.width, readable.height)+ ?: return null+ SegmentationMask(MlNative.maskWidth(handle), MlNative.maskHeight(handle), values)+ } finally {+ if (readable !== bitmap) readable.recycle()+ }+ }++ /**+ * Reused across calls so the ~15 fps preview path does not allocate a megabyte of+ * `int[]` per second.+ */+ private var pixels: IntArray? = null++ /** Free the network. Idempotent, and safe to call from a `DisposableEffect`. */+ override fun close() {+ val toDestroy = handle+ handle = 0L+ pixels = null+ if (toDestroy != 0L) MlNative.destroy(toDestroy)+ }+}
library/ml/src/main/java/com/vayunmathur/library/ml/SelfieSegmenter.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/SelfieSegmenter.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/SelfieSegmenter.ktnew file mode 100644index 0000000000..2f11c64e73--- /dev/null+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/SelfieSegmenter.kt@@ -0,0 +1,46 @@+package com.vayunmathur.library.ml++import android.content.Context+import android.graphics.Bitmap++/**+ * Person-versus-background segmentation, for `:camera`'s portrait bokeh.+ *+ * **MediaPipe Selfie Segmentation** (Apache-2.0), run on Vulkan compute at 256×256 with+ * fp16 weights. See `camera/src/main/assets/README.md` for provenance and+ * `library/ml/src/main/rust/src/nets/selfie.rs` for the forward pass.+ *+ * Replaces `com.vayunmathur.ncnn.PortraitSegmenter` and its `erdnet` model, which shipped+ * with no upstream URL, license or conversion recipe. This is a different model rather+ * than a port of that one, so its masks differ.+ *+ * GPU-only: if [isAvailable] is false the device has no Vulkan fp16 compute and [segment]+ * returns null, which callers treat as "no mask" rather than as an error.+ *+ * Not thread-safe: [segment] and [close] must not overlap.+ *+ * @param context used only to read the asset; not retained.+ * @param assetName the `.vkml` in the app's assets.+ */+class SelfieSegmenter(context: Context, assetName: String = DEFAULT_ASSET) : AutoCloseable {++ private val native =+ NativeSegmenter(context, assetName, "SelfieSegmenter", MlNative::createSelfie)++ /** Whether the network came up. False means portrait bokeh is off on this device. */+ val isAvailable: Boolean get() = native.isAvailable++ /**+ * Run the network over [bitmap] and return a 256×256 mask, or null on failure.+ *+ * [bitmap] may be any size and any config: it is resized and normalised natively.+ */+ fun segment(bitmap: Bitmap): SegmentationMask? = native.segment(bitmap)++ override fun close() = native.close()++ companion object {+ /** What `:camera` ships. */+ const val DEFAULT_ASSET: String = "selfie_segmentation.vkml"+ }+}
library/ml/src/main/java/com/vayunmathur/library/ml/SubjectSegmenter.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/SubjectSegmenter.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/SubjectSegmenter.ktnew file mode 100644index 0000000000..989ba8e1cd--- /dev/null+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/SubjectSegmenter.kt@@ -0,0 +1,50 @@+package com.vayunmathur.library.ml++import android.content.Context+import android.graphics.Bitmap++/**+ * General salient-object detection, for `:photos`'s auto-select-subject.+ *+ * **U²-Net portable** (Apache-2.0), run on Vulkan compute at 320×320 with fp16 weights.+ * Unlike [SelfieSegmenter] it is not person-specific: it predicts a per-pixel saliency map+ * and so picks out arbitrary subjects. See `photos/src/main/assets/README.md` for+ * provenance and `library/ml/src/main/rust/src/nets/u2netp.rs` for the forward pass.+ *+ * Replaces `com.vayunmathur.ncnn.Segmenter`. Same network, re-sourced from a licensed ONNX+ * export — the ncnn model's op inventory matched it exactly — so masks should look the+ * same as before, unlike `:camera`'s.+ *+ * Its activation arena is 76 MiB of device memory, so [close] it when the editor session+ * ends rather than holding it for the life of the process.+ *+ * GPU-only: if [isAvailable] is false the device has no Vulkan fp16 compute and [segment]+ * returns null, which the caller treats as "no subject found".+ *+ * Not thread-safe: [segment] and [close] must not overlap.+ *+ * @param context used only to read the asset; not retained.+ * @param assetName the `.vkml` in the app's assets.+ */+class SubjectSegmenter(context: Context, assetName: String = DEFAULT_ASSET) : AutoCloseable {++ private val native =+ NativeSegmenter(context, assetName, "SubjectSegmenter", MlNative::createU2netp)++ /** Whether the network came up. False means auto-select-subject is off on this device. */+ val isAvailable: Boolean get() = native.isAvailable++ /**+ * Run the network over [bitmap] and return a 320×320 saliency map, or null on failure.+ *+ * [bitmap] may be any size and any config: it is resized and normalised natively.+ */+ fun segment(bitmap: Bitmap): SegmentationMask? = native.segment(bitmap)++ override fun close() = native.close()++ companion object {+ /** What `:photos` ships. */+ const val DEFAULT_ASSET: String = "u2netp.vkml"+ }+}
library/ml/src/main/rust/Cargo.toml
diff --git a/library/ml/src/main/rust/Cargo.toml b/library/ml/src/main/rust/Cargo.tomlnew file mode 100644index 0000000000..b868ef63ae--- /dev/null+++ b/library/ml/src/main/rust/Cargo.toml@@ -0,0 +1,41 @@+# The Vulkan compute ML runtime for `:library:ml`.+#+# Replaces `com.github.vayun-mathur:ncnn-android` for the two pure-CNN vision models+# the repo ships: MediaPipe Selfie Segmentation (`:camera` portrait bokeh) and U^2-Net+# portable (`:photos` auto-select-subject). ncnn stays for the two face models in+# `:photos` and for `:library:ocr`, `:pdf`, `:translate` and `:speech`.+#+# Why this exists: the ncnn fork is built CPU-only (`NCNN_VULKAN=OFF`) and compiles+# ncnn's entire layer registry into one `libncnn_android.so` for models that use a+# small fraction of it. This runs on Vulkan compute with our own weights encoding and+# only the ~11 shaders these two nets need.+#+# Why `ash` and not `androidx.webgpu`: the same reasoning as `library/map` — read the+# header comment there. `features = ["loaded"]` dlopens `libvulkan.so` and links+# nothing, so the only native code shipped is our own.+#+# There is no graph interpreter: each net's forward pass is hardcoded Rust in `nets/`,+# so a `.vkml` file carries ordered tensors and no topology. See `src/weights.rs`.++[package]+name = "modelrunner"+version = "0.1.0"+edition = "2021"+publish = false+license = "GPL-2.0-only"+description = "Vulkan compute ML runtime: .vkml weights in, segmentation mask out"++[lib]+name = "modelrunner"+# cdylib for the JNI surface; rlib so the host test binary can link it and exercise+# the `.vkml` reader and the CPU preprocessing without a device.+crate-type = ["cdylib", "rlib"]++[dependencies]+jni.workspace = true++# `default-features = false` drops the `linked` feature, so nothing links against+# libvulkan at build time; `loaded` dlopens it, which is what an Android app must do+# anyway.+[target.'cfg(target_os = "android")'.dependencies]+ash = { version = "0.38", default-features = false, features = ["loaded"] }
library/ml/src/main/rust/build.rs
diff --git a/library/ml/src/main/rust/build.rs b/library/ml/src/main/rust/build.rsnew file mode 100644index 0000000000..9c5e9b4458--- /dev/null+++ b/library/ml/src/main/rust/build.rs@@ -0,0 +1,197 @@+//! Compiles the GLSL in `shaders/` to SPIR-V with the NDK's `glslc`.+//!+//! Copied from `library/map/src/main/rust/build.rs`, which already globbed `.comp`+//! alongside `.vert`/`.frag` and already targeted `vulkan1.1`. Only the doc comments+//! and the final panic message differ.+//!+//! # This deliberately does not do what `games/voxels/build.rs` does+//!+//! That build script (`build.rs:94-106`) resolves `glslc` from two hardcoded+//! absolute paths under one developer's home directory, and when it finds neither+//! it calls `minimal_vert_spv()` / `minimal_frag_spv()` — writing a **28-byte stub**+//! consisting of a SPIR-V header and a single `OpCapability`. A build that takes+//! that path succeeds, installs, runs, and draws nothing at all, with no warning+//! anywhere. The failure surfaces as "the screen is black" long after the build.+//!+//! So this script resolves the compiler from the environment for the *host*+//! platform it is running on, and [`panic!`]s if it cannot find it or if a shader+//! fails to compile. A missing shader compiler must stop the build.+//!+//! SPIR-V is `include_bytes!`d rather than shipped as an asset: the shaders are+//! part of the runtime, and an asset can be missing at run time while a linked+//! `&[u8]` cannot.++use std::env;+use std::path::{Path, PathBuf};+use std::process::Command;++fn main() {+ let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR"));+ let shader_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"))+ .join("shaders");++ let glslc = find_glslc();+ println!("cargo:rerun-if-changed=build.rs");+ println!("cargo:rerun-if-changed=shaders");++ let mut compiled = 0;+ let mut entries: Vec<PathBuf> = std::fs::read_dir(&shader_dir)+ .unwrap_or_else(|e| panic!("cannot read {}: {e}", shader_dir.display()))+ .filter_map(|e| e.ok().map(|e| e.path()))+ .filter(|p| {+ matches!(+ p.extension().and_then(|e| e.to_str()),+ Some("vert") | Some("frag") | Some("comp")+ )+ })+ .collect();+ // Sorted so the build is reproducible and a diff of the log is stable.+ entries.sort();++ for shader in &entries {+ let name = shader.file_name().expect("shader file name");+ println!("cargo:rerun-if-changed={}", shader.display());+ let target = out_dir.join(format!("{}.spv", name.to_string_lossy()));++ let output = Command::new(&glslc)+ .arg("--target-env=vulkan1.1")+ .arg("-O")+ .arg("-o")+ .arg(&target)+ .arg(shader)+ .output()+ .unwrap_or_else(|e| panic!("cannot run {}: {e}", glslc.display()));++ if !output.status.success() {+ panic!(+ "glslc failed on {}:\n{}{}",+ shader.display(),+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr),+ );+ }+ // A zero-exit that wrote nothing usable is the silent-stub case, caught here+ // rather than at run time on a black screen.+ let written = std::fs::metadata(&target).map(|m| m.len()).unwrap_or(0);+ if written < MIN_SPIRV_BYTES {+ panic!(+ "glslc produced {written} bytes for {}; a real SPIR-V module is at least \+ {MIN_SPIRV_BYTES} bytes",+ shader.display(),+ );+ }+ compiled += 1;+ }++ if compiled == 0 {+ panic!("no shaders found in {}", shader_dir.display());+ }+}++/// A SPIR-V module is a five-word header plus at least a few instructions.+const MIN_SPIRV_BYTES: u64 = 64;++/// `glslc` for the **host** platform, from the NDK.+///+/// Cargo runs this script on the build machine while cross-compiling for Android,+/// so the host triple is what matters, not the target. Searched in order:+///+/// 1. `GLSLC` — an explicit override, for a CI image that puts it elsewhere.+/// 2. `ANDROID_NDK_HOME` / `ANDROID_NDK_ROOT` — set directly by some CI setups.+/// 3. `ANDROID_HOME` / `ANDROID_SDK_ROOT`, then the highest installed `ndk/*`.+/// 4. `sdk.dir` from the repo's `local.properties`, which is what a dev box has.+/// 5. `glslc` on `PATH`.+fn find_glslc() -> PathBuf {+ if let Some(explicit) = env::var_os("GLSLC").map(PathBuf::from) {+ if explicit.is_file() {+ return explicit;+ }+ panic!("GLSLC is set to {explicit:?} but that is not a file");+ }++ let host = host_dir();+ let executable = if cfg!(windows) { "glslc.exe" } else { "glslc" };++ let mut ndks: Vec<PathBuf> = Vec::new();+ for key in ["ANDROID_NDK_HOME", "ANDROID_NDK_ROOT"] {+ if let Some(dir) = env::var_os(key) {+ ndks.push(PathBuf::from(dir));+ }+ }+ let mut sdks: Vec<PathBuf> = Vec::new();+ for key in ["ANDROID_HOME", "ANDROID_SDK_ROOT"] {+ if let Some(dir) = env::var_os(key) {+ sdks.push(PathBuf::from(dir));+ }+ }+ if let Some(dir) = sdk_dir_from_local_properties() {+ sdks.push(dir);+ }+ for sdk in &sdks {+ // Highest version first, so a box with several NDKs uses the newest.+ let mut installed: Vec<PathBuf> = std::fs::read_dir(sdk.join("ndk"))+ .into_iter()+ .flatten()+ .filter_map(|e| e.ok().map(|e| e.path()))+ .filter(|p| p.is_dir())+ .collect();+ installed.sort();+ installed.reverse();+ ndks.extend(installed);+ }++ for ndk in &ndks {+ let candidate = ndk.join("shader-tools").join(&host).join(executable);+ if candidate.is_file() {+ return candidate;+ }+ }++ if Command::new(executable).arg("--version").output().map(|o| o.status.success()).unwrap_or(false) {+ return PathBuf::from(executable);+ }++ panic!(+ "glslc not found. Looked for ndk/*/shader-tools/{host}/{executable} under \+ {sdks:?} and {ndks:?}, then on PATH. Install the NDK, or set GLSLC. Every \+ layer of both networks is a compute shader, so this build stops here rather \+ than producing a runtime that reports itself unavailable on every device.",+ );+}++/// The NDK's prebuilt-tool directory name for the host we are running on.+fn host_dir() -> String {+ let os = if cfg!(target_os = "windows") {+ "windows"+ } else if cfg!(target_os = "macos") {+ "darwin"+ } else {+ "linux"+ };+ // The NDK ships x86_64 host tools even on arm64 macOS, where they run under+ // Rosetta, so the host CPU is deliberately not consulted.+ format!("{os}-x86_64")+}++/// `sdk.dir` out of the repo root's `local.properties`.+///+/// Walks up from the crate rather than assuming a depth, so moving the crate does+/// not silently break shader compilation.+fn sdk_dir_from_local_properties() -> Option<PathBuf> {+ let mut dir: &Path = &PathBuf::from(env::var("CARGO_MANIFEST_DIR").ok()?);+ loop {+ let candidate = dir.join("local.properties");+ if candidate.is_file() {+ let text = std::fs::read_to_string(&candidate).ok()?;+ for line in text.lines() {+ let line = line.trim();+ if let Some(value) = line.strip_prefix("sdk.dir=") {+ // Gradle properties escape the Windows separator.+ return Some(PathBuf::from(value.replace("\\\\", "\\").replace("\\:", ":")));+ }+ }+ return None;+ }+ dir = dir.parent()?;+ }+}
library/ml/src/main/rust/shaders/add.comp
diff --git a/library/ml/src/main/rust/shaders/add.comp b/library/ml/src/main/rust/shaders/add.compnew file mode 100644index 0000000000..6fa75f319b--- /dev/null+++ b/library/ml/src/main/rust/shaders/add.comp@@ -0,0 +1,20 @@+#version 450+//! Elementwise sum of two equally-shaped tensors. 25 uses: U^2-Netp's 11 RSU residuals+//! and the selfie net's 14.+//!+//! Not fused into the producing convolution the way activations are. It could be — the+//! convolution's accumulator could start from the skip instead of from the bias — but+//! every one of these adds a tensor that is *also* read elsewhere, so the fused form+//! would need a second input binding and a flag on the conv shader for a saving of one+//! pass over data that is already in cache.++#include "common.glsl"++void main() {+ uint index = global_index();+ if (index >= p.count) {+ return;+ }+ float sum = float(arena[p.in0 + index]) + float(arena[p.in1 + index]);+ arena[p.out_at + index] = float16_t(sum);+}
library/ml/src/main/rust/shaders/common.glsl
diff --git a/library/ml/src/main/rust/shaders/common.glsl b/library/ml/src/main/rust/shaders/common.glslnew file mode 100644index 0000000000..d1eed5c0f1--- /dev/null+++ b/library/ml/src/main/rust/shaders/common.glsl@@ -0,0 +1,116 @@+// Shared declarations for every compute shader in this runtime.+//+// Not a shader itself: `build.rs` compiles only `.vert`/`.frag`/`.comp`, so this is+// pulled in by `#include` and never compiled alone. glslc resolves the path relative+// to the including file.+//+// # Two bindings, and offsets in push constants+//+// There are exactly two storage buffers for the whole runtime:+//+// binding 0 the activation arena, read and written+// binding 1 the weights, read only+//+// Every tensor is a *region* of one of those, addressed by an element offset in the+// push-constant block. So the descriptor set is written once at setup and never+// rebound, there are no uniform buffers, no dynamic offsets and nothing to keep in+// sync per layer — `vkCmdPushConstants` before each dispatch is the entire per-layer+// state. See `nets::Push`, which this block must match field for field.+//+// # fp16 storage, fp32 arithmetic+//+// Weights and activations are fp16; every accumulator here is `float`. Half the+// bandwidth and half the memory, without half's 11-bit mantissa accumulating error+// down a 119-layer net.+//+// `shaderFloat16` and `storageBuffer16BitAccess` are both required at device creation.+// `VK_KHR_shader_float16_int8` is a Vulkan 1.2 promotion, so at the 1.1 floor minSdk 31+// guarantees it is an extension that may be absent — see `vulkan::context`, which+// refuses to create a device without it rather than silently producing fp32 code.++#extension GL_EXT_shader_16bit_storage : require+#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require++// 64 invocations per workgroup: a multiple of every wave width in use (16 on some+// Mali, 32 on Adreno, 64 on older GCN-derived parts) so no wave is ever half idle.+layout(local_size_x = 64) in;++layout(std430, binding = 0) buffer Arena {+ float16_t arena[];+};++layout(std430, binding = 1) readonly buffer Weights {+ float16_t weights[];+};++layout(push_constant) uniform Push {+ uint in0;+ uint in1;+ uint out_at;+ uint weight;+ uint bias;+ uint in_c;+ uint in_h;+ uint in_w;+ uint out_c;+ uint out_h;+ uint out_w;+ uint kh;+ uint kw;+ uint stride_h;+ uint stride_w;+ uint dil_h;+ uint dil_w;+ uint pad_t;+ uint pad_l;+ uint group;+ uint act;+ uint count;+} p;++// `nets::Act`.+#define ACT_NONE 0u+#define ACT_RELU 1u+#define ACT_HARDSWISH 2u+#define ACT_SIGMOID 3u++// This invocation's output element, across a 2D grid of workgroups.+//+// Not `gl_GlobalInvocationID.x`: U^2-Netp's largest layer writes 64x320x320 = 6,553,600+// elements, which at 64 per workgroup is 102,400 workgroups, and `maxComputeWorkGroupCount`+// is only guaranteed to be **65,535** per dimension. A 1D dispatch that big is rejected+// outright on any device at the guaranteed minimum, so `vulkan::run` splits the count+// across x and y and this flattens it back. `gl_NumWorkGroups` is the actual dispatch+// extent, so the two cannot disagree.+//+// The grid over-covers, so every shader here tests the result against `p.count`.+uint global_index() {+ uint group = gl_WorkGroupID.y * gl_NumWorkGroups.x + gl_WorkGroupID.x;+ return group * gl_WorkGroupSize.x + gl_LocalInvocationID.x;+}++// The activation fused into a layer's store. Every ReLU, HardSwish and Sigmoid in both+// networks directly follows a convolution, so this is the only place activations+// happen and there is no standalone activation pass.+float activate(float x, uint kind) {+ if (kind == ACT_RELU) {+ return max(x, 0.0);+ }+ if (kind == ACT_HARDSWISH) {+ // ONNX HardSwish at its default alpha = 1/6, beta = 0.5.+ return x * clamp(x * (1.0 / 6.0) + 0.5, 0.0, 1.0);+ }+ if (kind == ACT_SIGMOID) {+ return 1.0 / (1.0 + exp(-x));+ }+ return x;+}++// Unpack a flat output index into channel, row and column. Every shader here runs one+// invocation per output element, in NCHW order, so this is the first thing each does.+void unpack(uint index, out uint c, out uint y, out uint x) {+ x = index % p.out_w;+ uint rest = index / p.out_w;+ y = rest % p.out_h;+ c = rest / p.out_h;+}
library/ml/src/main/rust/shaders/conv.comp
diff --git a/library/ml/src/main/rust/shaders/conv.comp b/library/ml/src/main/rust/shaders/conv.compnew file mode 100644index 0000000000..139e63aec7--- /dev/null+++ b/library/ml/src/main/rust/shaders/conv.comp@@ -0,0 +1,66 @@+#version 450+//! Convolution: dense, grouped, depthwise and dilated, with a fused activation.+//!+//! One shader for all 173 convolutions across both networks. The variants that would+//! usually get their own kernel — 1x1, 3x3, 5x5, depthwise, dilation 1/2/4/8, stride 1/2,+//! asymmetric padding — differ only in the loop bounds and strides below, all of which+//! come from push constants.+//!+//! # Gather, not scatter+//!+//! Each invocation owns one output element and reads everything it needs. Nothing is+//! written twice, so there are no atomics and no clearing pass, and the bias is simply+//! the accumulator's initial value rather than a separate op.+//!+//! Weights are ONNX's layout verbatim, `[m, in_c / group, kh, kw]` row-major, so+//! `vkml_convert.py` transposes nothing and there is no layout to disagree about.+//!+//! # What this deliberately does not do+//!+//! No tiling, no shared-memory staging of the input patch, no vectorised loads. A+//! tiled kernel would read each input element once per output tile instead of once per+//! output element, which is the obvious next optimisation if U^2-Netp's ~2.2 GMAC at+//! 320x320 turns out too slow. It is not done yet because a naive gather is the version+//! whose indexing can be reasoned about, and there is no numeric reference to catch a+//! tiling bug.++#include "common.glsl"++void main() {+ uint index = global_index();+ if (index >= p.count) {+ return;+ }+ uint oc, oy, ox;+ unpack(index, oc, oy, ox);++ // Grouped convolution: output channel `oc` reads only its own group's slice of the+ // input. group == in_c == out_c is depthwise, where this collapses to one channel.+ uint in_per_group = p.in_c / p.group;+ uint out_per_group = p.out_c / p.group;+ uint first_in = (oc / out_per_group) * in_per_group;++ float acc = float(weights[p.bias + oc]);+ uint kernel_at = p.weight + oc * in_per_group * p.kh * p.kw;++ for (uint ic = 0u; ic < in_per_group; ic++) {+ uint plane = p.in0 + (first_in + ic) * p.in_h * p.in_w;+ for (uint ky = 0u; ky < p.kh; ky++) {+ int iy = int(oy * p.stride_h + ky * p.dil_h) - int(p.pad_t);+ if (iy < 0 || iy >= int(p.in_h)) {+ continue;+ }+ uint row = plane + uint(iy) * p.in_w;+ uint tap = kernel_at + (ic * p.kh + ky) * p.kw;+ for (uint kx = 0u; kx < p.kw; kx++) {+ int ix = int(ox * p.stride_w + kx * p.dil_w) - int(p.pad_l);+ if (ix < 0 || ix >= int(p.in_w)) {+ continue;+ }+ acc += float(arena[row + uint(ix)]) * float(weights[tap + kx]);+ }+ }+ }++ arena[p.out_at + index] = float16_t(activate(acc, p.act));+}
library/ml/src/main/rust/shaders/conv_transpose.comp
diff --git a/library/ml/src/main/rust/shaders/conv_transpose.comp b/library/ml/src/main/rust/shaders/conv_transpose.compnew file mode 100644index 0000000000..c8f71a2da2--- /dev/null+++ b/library/ml/src/main/rust/shaders/conv_transpose.comp@@ -0,0 +1,64 @@+#version 450+//! Transposed convolution, written as a gather.+//!+//! One use in either network: the selfie net's final 2x2 stride-2 upsample from+//! 16x128x128 to 1x256x256, which is what turns the decoder's feature map into an alpha.+//!+//! # Gather, not scatter+//!+//! The natural reading of a transposed convolution scatters — each input element adds+//! into `kh * kw` outputs — which needs atomics or a separate clear-and-accumulate pass.+//! Inverting it costs only a divisibility test: output row `oy` is fed by input row+//! `(oy + pad_t - ky) / stride_h`, when that division is exact. So this stays one+//! invocation per output element like every other shader here, with no atomics.+//!+//! The weight layout is ONNX's, which for `ConvTranspose` is `[in_c, out_c / group,+//! kh, kw]` — input channels outermost, the transpose of `Conv`'s. That inversion is the+//! one place the two convolution shaders genuinely differ, and getting it backwards+//! would produce a mask that looks like noise rather than one that looks nearly right.+//!+//! `group` is 1 at the only call site and is not modelled: a grouped transposed+//! convolution would need the input-channel range restricted the way `conv.comp` does it.++#include "common.glsl"++void main() {+ uint index = global_index();+ if (index >= p.count) {+ return;+ }+ uint oc, oy, ox;+ unpack(index, oc, oy, ox);++ float acc = float(weights[p.bias + oc]);++ for (uint ic = 0u; ic < p.in_c; ic++) {+ uint plane = p.in0 + ic * p.in_h * p.in_w;+ uint kernel_at = p.weight + (ic * p.out_c + oc) * p.kh * p.kw;+ for (uint ky = 0u; ky < p.kh; ky++) {+ int numerator = int(oy + p.pad_t) - int(ky);+ if (numerator < 0 || uint(numerator) % p.stride_h != 0u) {+ continue;+ }+ uint iy = uint(numerator) / p.stride_h;+ if (iy >= p.in_h) {+ continue;+ }+ uint row = plane + iy * p.in_w;+ uint tap = kernel_at + ky * p.kw;+ for (uint kx = 0u; kx < p.kw; kx++) {+ int denominator = int(ox + p.pad_l) - int(kx);+ if (denominator < 0 || uint(denominator) % p.stride_w != 0u) {+ continue;+ }+ uint ix = uint(denominator) / p.stride_w;+ if (ix >= p.in_w) {+ continue;+ }+ acc += float(arena[row + ix]) * float(weights[tap + kx]);+ }+ }+ }++ arena[p.out_at + index] = float16_t(activate(acc, p.act));+}
library/ml/src/main/rust/shaders/gap.comp
diff --git a/library/ml/src/main/rust/shaders/gap.comp b/library/ml/src/main/rust/shaders/gap.compnew file mode 100644index 0000000000..ed4564cb34--- /dev/null+++ b/library/ml/src/main/rust/shaders/gap.comp@@ -0,0 +1,30 @@+#version 450+//! Mean over H and W, to `C x 1 x 1`. The squeeze half of a squeeze-excite block.+//!+//! Ten uses, all in the selfie net, and all on a small map: the largest is 128x16x16, so+//! one invocation per *channel* reducing 256 elements serially is the right shape. A+//! tree reduction across a workgroup would be faster per channel and slower overall,+//! because there are only 16 to 128 channels to keep the GPU busy with.+//!+//! ONNX calls this `ReduceMean` with `axes = [2, 3]` and `keepdims = 1`, which is why the+//! output keeps its two trailing unit dimensions and `mul_bcast.comp` can index it by+//! channel alone.++#include "common.glsl"++void main() {+ uint channel = global_index();+ if (channel >= p.count) {+ return;+ }++ uint plane = p.in0 + channel * p.in_h * p.in_w;+ uint elements = p.in_h * p.in_w;++ float total = 0.0;+ for (uint i = 0u; i < elements; i++) {+ total += float(arena[plane + i]);+ }++ arena[p.out_at + channel] = float16_t(total / float(elements));+}
library/ml/src/main/rust/shaders/maxpool.comp
diff --git a/library/ml/src/main/rust/shaders/maxpool.comp b/library/ml/src/main/rust/shaders/maxpool.compnew file mode 100644index 0000000000..f9c1f88222--- /dev/null+++ b/library/ml/src/main/rust/shaders/maxpool.comp@@ -0,0 +1,50 @@+#version 450+//! Max pooling. 33 uses, all of them 2x2 stride 2 in U^2-Netp.+//!+//! The kernel and stride still come from push constants rather than being hardcoded to+//! 2, because that costs nothing here and keeps the shader honest about what the plan+//! actually asked for.+//!+//! ONNX marks all 33 `ceil_mode=1`; this floors. Every pooled extent in U^2-Netp is even+//! — 320 halves five times to 10 — so the two agree, and `nets::Builder::max_pool_2x2`+//! refuses an odd extent rather than letting the difference pass silently.+//!+//! There is no padding: all 33 have `pads = [0, 0, 0, 0]`, so no `-inf` initial value is+//! needed and every window is fully inside the input.++#include "common.glsl"++void main() {+ uint index = global_index();+ if (index >= p.count) {+ return;+ }+ uint oc, oy, ox;+ unpack(index, oc, oy, ox);++ uint plane = p.in0 + oc * p.in_h * p.in_w;+ uint top = oy * p.stride_h;+ uint left = ox * p.stride_w;++ // The most negative fp16, rather than a literal -inf: every one of the 33 pools has+ // `pads = [0, 0, 0, 0]` and an even extent, so this initial value is never actually+ // the answer, and a real -inf would be relying on GLSL's division-by-zero behaviour+ // for a value that cannot be observed.+ float best = -65504.0;+ for (uint ky = 0u; ky < p.kh; ky++) {+ uint iy = top + ky;+ if (iy >= p.in_h) {+ continue;+ }+ uint row = plane + iy * p.in_w;+ for (uint kx = 0u; kx < p.kw; kx++) {+ uint ix = left + kx;+ if (ix >= p.in_w) {+ continue;+ }+ best = max(best, float(arena[row + ix]));+ }+ }++ arena[p.out_at + index] = float16_t(best);+}
library/ml/src/main/rust/shaders/mul_bcast.comp
diff --git a/library/ml/src/main/rust/shaders/mul_bcast.comp b/library/ml/src/main/rust/shaders/mul_bcast.compnew file mode 100644index 0000000000..613318f467--- /dev/null+++ b/library/ml/src/main/rust/shaders/mul_bcast.comp@@ -0,0 +1,25 @@+#version 450+//! `out[c][y][x] = a[c][y][x] * b[c]`, the excite half of a squeeze-excite block.+//!+//! Ten uses, all in the selfie net, `b` always the `C x 1 x 1` output of `gap.comp` put+//! through a 1x1 convolution and a sigmoid.+//!+//! The broadcast is over H and W only, so the second operand is indexed by channel+//! alone. Four of the ten multiply a tensor that is **not** the one that was pooled —+//! see the note in `nets::selfie` — which is why the two operands are separate push+//! constants rather than one tensor read twice.++#include "common.glsl"++void main() {+ uint index = global_index();+ if (index >= p.count) {+ return;+ }+ uint oc, oy, ox;+ unpack(index, oc, oy, ox);++ float value = float(arena[p.in0 + index]);+ float gate = float(arena[p.in1 + oc]);+ arena[p.out_at + index] = float16_t(value * gate);+}
library/ml/src/main/rust/shaders/resize.comp
diff --git a/library/ml/src/main/rust/shaders/resize.comp b/library/ml/src/main/rust/shaders/resize.compnew file mode 100644index 0000000000..b8f6f3edb1--- /dev/null+++ b/library/ml/src/main/rust/shaders/resize.comp@@ -0,0 +1,52 @@+#version 450+//! Bilinear resize with `half_pixel` coordinates. 41 uses across both networks.+//!+//! # One convention, everywhere+//!+//! `src = (dst + 0.5) * in / out - 0.5`. The selfie net's three `Resize` nodes are+//! `coordinate_transformation_mode=half_pixel`; U^2-Netp's 38 are `pytorch_half_pixel`,+//! which differs from `half_pixel` only when the resized extent is 1 — and none of these+//! are, since every one is an exact 2x upsample. So both lower to this, and+//! `preprocess::to_planar_f16` uses the same formula for the input resize.+//!+//! That agreement is load-bearing rather than tidy: U^2-Netp's decoder upsamples and then+//! *adds* to an encoder skip five times over, so a half-pixel shift between the two paths+//! would misregister every residual in the net.+//!+//! Coordinates outside the source clamp to the edge, which is what ONNX `Resize` does+//! with its default `nearest_mode`/exclude-outside behaviour for linear sampling.++#include "common.glsl"++// The two bracketing source indices and the weight of the second, at `half_pixel`.+void bracket(uint dst, uint in_extent, uint out_extent, out uint low, out uint high, out float t) {+ float source = (float(dst) + 0.5) * float(in_extent) / float(out_extent) - 0.5;+ source = max(source, 0.0);+ float base = floor(source);+ t = source - base;+ low = min(uint(base), in_extent - 1u);+ high = min(low + 1u, in_extent - 1u);+}++void main() {+ uint index = global_index();+ if (index >= p.count) {+ return;+ }+ uint oc, oy, ox;+ unpack(index, oc, oy, ox);++ uint y0, y1, x0, x1;+ float ty, tx;+ bracket(oy, p.in_h, p.out_h, y0, y1, ty);+ bracket(ox, p.in_w, p.out_w, x0, x1, tx);++ uint plane = p.in0 + oc * p.in_h * p.in_w;+ uint row0 = plane + y0 * p.in_w;+ uint row1 = plane + y1 * p.in_w;++ float top = mix(float(arena[row0 + x0]), float(arena[row0 + x1]), tx);+ float bottom = mix(float(arena[row1 + x0]), float(arena[row1 + x1]), tx);++ arena[p.out_at + index] = float16_t(mix(top, bottom, ty));+}
library/ml/src/main/rust/src/bridge.rs
diff --git a/library/ml/src/main/rust/src/bridge.rs b/library/ml/src/main/rust/src/bridge.rsnew file mode 100644index 0000000000..64cacf5fbf--- /dev/null+++ b/library/ml/src/main/rust/src/bridge.rs@@ -0,0 +1,258 @@+//! The JNI surface: three entry points per network, and nothing per-pixel.+//!+//! Kotlin creates a segmenter, hands it a bitmap's pixels, gets a mask back, and closes+//! it. Preprocessing, the whole forward pass and the readback all happen on this side, so+//! the boundary is crossed three times per inference rather than once per element.+//!+//! # Why pixels and not the `Bitmap`+//!+//! `AndroidBitmap_lockPixels` from `libjnigraphics` would avoid copying the pixel array+//! across, but it also means handling every `Bitmap.Config` the platform might hand over+//! — including `HARDWARE`, which cannot be locked at all — and both call sites already+//! hold an ARGB_8888 copy. So Kotlin does `getPixels` into a reused `IntArray` and passes+//! that, which is one copy of at most 512x512 ints and no `libjnigraphics` dependency.+//!+//! # Threading+//!+//! Neither entry point is thread-safe, and neither needs to be: `BokehAnalyzer` holds its+//! segmenter behind a `synchronized(lock)` and `MlSegmentation` behind `segLock`. That+//! discipline is what the comments in `BokehAnalyzer.kt` are about — a use-after-free+//! tombstone with the ncnn net — and the hazard is identical with a Vulkan handle, which+//! is why the Kotlin side keeps it.+//!+//! # Handles+//!+//! A handle is a leaked `Box`, handed to Kotlin as an opaque `jlong`. `0` means failure,+//! and every entry point tolerates it, so a device without fp16 compute degrades to "no+//! bokeh" rather than to a crash.++use jni::objects::{JByteArray, JClass, JFloatArray, JIntArray};+use jni::sys::{jfloatArray, jint, jlong};+use jni::JNIEnv;++use crate::nets::{selfie, u2netp};+use crate::preprocess::{IMAGENET, RESCALE_ONLY};+use crate::vulkan::context;+use crate::vulkan::run::Net;+use crate::weights::{graph, Weights};++/// One segmenter. Handed to Kotlin as an opaque `jlong`.+struct Handle {+ net: Net,+ /// The pixel array, reused across calls.+ ///+ /// `:camera` runs this ~15 times a second on frames of up to 512x512, so a fresh+ /// `Vec<i32>` per call would be a megabyte of allocation and free per second on the+ /// preview path for nothing.+ pixels: Vec<i32>,+}++/// `SelfieSegmenter`'s constructor. Returns 0 on failure, having logged why.+///+/// # Safety+///+/// Called only by the JVM, with a valid `env` and a `weights` array it owns.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createSelfie<'l>(+ mut env: JNIEnv<'l>,+ _class: JClass<'l>,+ weights: JByteArray<'l>,+) -> jlong {+ open(&mut env, weights, graph::SELFIE, "selfie")+}++/// `SubjectSegmenter`'s constructor. Returns 0 on failure, having logged why.+///+/// # Safety+///+/// Called only by the JVM, with a valid `env` and a `weights` array it owns.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createU2netp<'l>(+ mut env: JNIEnv<'l>,+ _class: JClass<'l>,+ weights: JByteArray<'l>,+) -> jlong {+ open(&mut env, weights, graph::U2NETP, "u2netp")+}++fn open<'l>(env: &mut JNIEnv<'l>, weights: JByteArray<'l>, graph_id: u32, name: &str) -> jlong {+ match build(env, weights, graph_id) {+ Ok(handle) => Box::into_raw(Box::new(handle)) as jlong,+ Err(e) => {+ log(&format!("{name} is unavailable: {e}"));+ 0+ }+ }+}++fn build<'l>(+ env: &mut JNIEnv<'l>,+ weights: JByteArray<'l>,+ graph_id: u32,+) -> Result<Handle, String> {+ // The blob arrives as bytes rather than a path because an asset lives inside the APK+ // and has no filesystem path unless it is extracted first. Both `.vkml` files are+ // `noCompress`, so Kotlin's read is a straight copy out of the mapped APK.+ let bytes = env+ .convert_byte_array(&weights)+ .map_err(|e| format!("cannot read the weights array: {e}"))?;+ let parsed = Weights::parse(&bytes, graph_id)?;+ // The device comes up lazily and is shared, so `:camera`'s two segmenters do not+ // create two `VkDevice`s.+ let shared = context::shared()?;+ let (plan, normalise) = match graph_id {+ graph::SELFIE => (selfie::build(&parsed)?, RESCALE_ONLY),+ graph::U2NETP => (u2netp::build(&parsed)?, IMAGENET),+ other => return Err(format!("no forward pass for graph {other}")),+ };+ Ok(Handle {+ net: Net::new(shared, plan, &parsed, normalise)?,+ pixels: Vec::new(),+ })+}++/// Run the network over `pixels` and return the mask as a `float[]`.+///+/// Returns null on failure or on a `0` handle, which the Kotlin wrapper turns into "no+/// mask this frame" rather than an exception.+///+/// # Safety+///+/// `handle` must be `0` or a value returned by one of the create functions and not yet+/// destroyed.+#[no_mangle]+pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_segment<'l>(+ mut env: JNIEnv<'l>,+ _class: JClass<'l>,+ handle: jlong,+ pixels: JIntArray<'l>,+ width: jint,+ height: jint,+) -> jfloatArray {+ let null = std::ptr::null_mut();+ if handle == 0 || width <= 0 || height <= 0 {+ return null;+ }+ // SAFETY: the caller guarantees `handle` came from a create function and is live, and+ // the Kotlin side serialises `segment` against `destroy` with a lock held across the+ // whole call.+ let state = unsafe { &mut *(handle as *mut Handle) };++ let count = match env.get_array_length(&pixels) {+ Ok(n) if n >= 0 => n as usize,+ Ok(n) => {+ log(&format!("a pixel array of length {n}"));+ return null;+ }+ Err(e) => {+ log(&format!("cannot size the pixel array: {e}"));+ return null;+ }+ };+ if count != (width as usize) * (height as usize) {+ log(&format!("{count} pixels for a {width}x{height} bitmap"));+ return null;+ }+ state.pixels.resize(count, 0);+ if let Err(e) = env.get_int_array_region(&pixels, 0, &mut state.pixels) {+ log(&format!("cannot read the pixel array: {e}"));+ return null;+ }+ let mask = match state.net.infer(&state.pixels, width as u32, height as u32) {+ Ok(m) => m,+ Err(e) => {+ log(&format!("inference failed: {e}"));+ return null;+ }+ };+ match new_float_array(&mut env, &mask) {+ Ok(array) => array,+ Err(e) => {+ log(&format!("cannot return the mask: {e}"));+ null+ }+ }+}++/// The mask's width, so Kotlin does not have to know either network's input size.+///+/// # Safety+///+/// As [`Java_com_vayunmathur_library_ml_MlNative_segment`].+#[no_mangle]+pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_maskWidth<'l>(+ _env: JNIEnv<'l>,+ _class: JClass<'l>,+ handle: jlong,+) -> jint {+ if handle == 0 {+ return 0;+ }+ // SAFETY: as `segment`.+ unsafe { &*(handle as *const Handle) }.net.output_size().0 as jint+}++/// The mask's height.+///+/// # Safety+///+/// As [`Java_com_vayunmathur_library_ml_MlNative_segment`].+#[no_mangle]+pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_maskHeight<'l>(+ _env: JNIEnv<'l>,+ _class: JClass<'l>,+ handle: jlong,+) -> jint {+ if handle == 0 {+ return 0;+ }+ // SAFETY: as `segment`.+ unsafe { &*(handle as *const Handle) }.net.output_size().1 as jint+}++/// Free everything the handle owns, waiting for the GPU to go idle first.+///+/// Must be called exactly once per non-zero handle. When it is the last segmenter, the+/// shared `VkDevice` goes away with it.+///+/// # Safety+///+/// As [`Java_com_vayunmathur_library_ml_MlNative_segment`], and the handle must not be+/// used again afterwards.+#[no_mangle]+pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroy<'l>(+ _env: JNIEnv<'l>,+ _class: JClass<'l>,+ handle: jlong,+) {+ if handle == 0 {+ return;+ }+ // SAFETY: the caller guarantees this handle came from a create function and has not+ // been destroyed. `Net`'s Drop waits for the device to go idle before freeing.+ drop(unsafe { Box::from_raw(handle as *mut Handle) });+}++fn new_float_array(env: &mut JNIEnv, values: &[f32]) -> Result<jfloatArray, String> {+ let array: JFloatArray = env+ .new_float_array(values.len() as jint)+ .map_err(|e| format!("new_float_array: {e}"))?;+ env.set_float_array_region(&array, 0, values)+ .map_err(|e| format!("set_float_array_region: {e}"))?;+ Ok(array.into_raw())+}++fn log(message: &str) {+ #[link(name = "log")]+ extern "C" {+ fn __android_log_write(priority: i32, tag: *const u8, text: *const u8) -> i32;+ }+ const ERROR: i32 = 6;+ let tag = b"ModelRunner\0";+ let mut text: Vec<u8> = message.as_bytes().to_vec();+ text.push(0);+ // SAFETY: both pointers are to NUL-terminated buffers that outlive the call.+ unsafe {+ let _ = __android_log_write(ERROR, tag.as_ptr(), text.as_ptr());+ }+}
library/ml/src/main/rust/src/lib.rs
diff --git a/library/ml/src/main/rust/src/lib.rs b/library/ml/src/main/rust/src/lib.rsnew file mode 100644index 0000000000..cc0ca019ec--- /dev/null+++ b/library/ml/src/main/rust/src/lib.rs@@ -0,0 +1,46 @@+//! The Vulkan compute ML runtime behind `:library:ml`.+//!+//! Runs the two pure-CNN vision models the repo ships — MediaPipe Selfie Segmentation+//! for `:camera`'s portrait bokeh, U^2-Net portable for `:photos`'s auto-select-subject+//! — replacing the CPU-only ncnn fork for both. ncnn stays for `:photos`'s two face+//! models and for `:library:ocr`, `:pdf`, `:translate` and `:speech`.+//!+//! # Layout+//!+//! * [`weights`] — the `.vkml` reader. Ordered tensors, no topology.+//! * [`nets`] — the two hardcoded forward passes, and the small compiler that packs+//! their activations into one arena and resolves every offset.+//! * [`preprocess`] — bitmap to fp16 NCHW, and the fp16 conversions.+//! * `vulkan` — device, pipelines, the recorded command buffer. Android only.+//!+//! # GPU only, by decision+//!+//! There is no CPU fallback. Vulkan 1.1 is guaranteed at minSdk 31, but fp16 is not:+//! `VK_KHR_shader_float16_int8` was promoted only in 1.2, so the device extension and+//! its feature struct have to be asked for explicitly. Where they are missing the+//! runtime reports itself unavailable and the feature turns off — no bokeh, no+//! auto-subject-select — rather than falling back to a second implementation that would+//! have to be kept correct with no way to test it.+//!+//! # Nothing runs per frame+//!+//! A net is compiled to a flat [`nets::Plan`] once, and that plan is recorded into a+//! single command buffer once, at construction. An inference is then an upload, one+//! submit, one fence wait and one readback. That matters because `:camera` calls this+//! at ~15 fps while the UI is also using the GPU.+//!+//! # Host builds+//!+//! Everything except the Vulkan and JNI layers compiles and tests on the host, so+//! `cargo test` builds **both** networks in full, checks the `.vkml` round trip, the+//! arena arithmetic and the preprocessing, with no device and no asset.++pub mod nets;+pub mod preprocess;+pub mod weights;++#[cfg(target_os = "android")]+pub mod vulkan;++#[cfg(target_os = "android")]+mod bridge;
library/ml/src/main/rust/src/nets/mod.rs
diff --git a/library/ml/src/main/rust/src/nets/mod.rs b/library/ml/src/main/rust/src/nets/mod.rsnew file mode 100644index 0000000000..24cc3727fb--- /dev/null+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -0,0 +1,1120 @@+//! The two hardcoded forward passes, and the small compiler they are written against.+//!+//! # Why a plan and not a graph interpreter+//!+//! Each network is code: [`u2netp::build`] and [`selfie::build`] call [`Builder`] in+//! the order the ONNX nodes run. There is no operator table, no name lookup and no+//! topology in the weights file — a `.vkml` is ordered tensors and nothing else.+//!+//! But the *shape* of the pass being code does not mean the offsets should be. So a+//! builder call records a [`Node`] against symbolic tensor ids, and [`Builder::finish`]+//! then does three things a hand-written pass would get wrong:+//!+//! 1. Propagates shapes, so every conv's output size is derived from its pads,+//! stride and dilation rather than restated.+//! 2. Computes each tensor's last use and packs the arena with a free list, so U^2-Netp+//! at 320x320 reuses memory instead of holding every intermediate at once.+//! 3. Resolves everything to `u32` element offsets in one place, which is the+//! arithmetic the host tests check.+//!+//! The result is a flat [`Plan`] of [`Op`]s. `vulkan::run` records it into **one**+//! command buffer once, at construction, so an inference is an upload, one submit and+//! one readback — nothing here runs per frame.+//!+//! # Host-testable+//!+//! Nothing in this module or its children touches Vulkan. Builders take a+//! [`WeightSource`] rather than a [`crate::weights::Weights`], so `cargo test` builds+//! both real networks, in full, with no device and no asset.++pub mod selfie;+pub mod u2netp;++/// A `1 x c x h x w` fp16 tensor. Batch is always 1; neither net is ever batched.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Shape {+ /// Channels.+ pub c: u32,+ /// Height.+ pub h: u32,+ /// Width.+ pub w: u32,+}++impl Shape {+ /// A shape, for readability at the call sites in the net modules.+ pub const fn new(c: u32, h: u32, w: u32) -> Shape {+ Shape { c, h, w }+ }++ /// Elements, which for fp16 is bytes / 2. Not `usize`, because every consumer is+ /// a `u32` push constant or a `u32` device offset.+ // No `is_empty`: a zero-sized tensor is a bug the builder rejects, not a state worth+ // asking about.+ #[allow(clippy::len_without_is_empty)]+ pub fn len(&self) -> u32 {+ self.c * self.h * self.w+ }+}++/// The activation a layer folds into its own store, saving a full pass over the+/// output. U^2-Netp is 112 ReLUs over up to 6.5M elements each; not fusing them would+/// roughly double its memory traffic.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Act {+ /// Store the accumulator as-is.+ None,+ /// `max(x, 0)`.+ Relu,+ /// `x * clamp(x/6 + 0.5, 0, 1)`, i.e. ONNX `HardSwish` at its default alpha/beta.+ HardSwish,+ /// `1 / (1 + exp(-x))`.+ Sigmoid,+}++impl Act {+ fn code(self) -> u32 {+ match self {+ Act::None => 0,+ Act::Relu => 1,+ Act::HardSwish => 2,+ Act::Sigmoid => 3,+ }+ }+}++/// Which compute pipeline an [`Op::Dispatch`] wants.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Kind {+ /// Dense, grouped or dilated convolution with a fused activation.+ Conv,+ /// Transposed convolution. One use, in the selfie net's 2x upsample to 256x256.+ ConvTranspose,+ /// Max pooling.+ MaxPool,+ /// Bilinear resize, `half_pixel` coordinates.+ Resize,+ /// Mean over H and W, keeping C. The squeeze in a squeeze-excite block.+ GlobalAvgPool,+ /// Elementwise sum of two equal shapes.+ Add,+ /// `a * b` where `b` is `C x 1 x 1`. The excite in a squeeze-excite block.+ MulBroadcast,+}++/// The push-constant block every shader declares.+///+/// `repr(C)` so field order is declaration order, which is what the SPIR-V offsets+/// assume. Deliberately one block shared by all seven pipelines: it fits inside the+/// 128 bytes the spec guarantees (asserted in [`tests`]), so there is a single+/// pipeline layout, no uniform buffers and no descriptor writes after setup.+#[repr(C)]+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct Push {+ /// Element offset of the first input in the activation arena.+ pub in0: u32,+ /// Element offset of the second input, for the binary ops.+ pub in1: u32,+ /// Element offset of the output in the arena.+ pub out: u32,+ /// Element offset of the kernel in the weights buffer.+ pub weight: u32,+ /// Element offset of the bias in the weights buffer.+ pub bias: u32,+ /// Input channels.+ pub in_c: u32,+ /// Input height.+ pub in_h: u32,+ /// Input width.+ pub in_w: u32,+ /// Output channels.+ pub out_c: u32,+ /// Output height.+ pub out_h: u32,+ /// Output width.+ pub out_w: u32,+ /// Kernel height.+ pub kh: u32,+ /// Kernel width.+ pub kw: u32,+ /// Vertical stride.+ pub stride_h: u32,+ /// Horizontal stride.+ pub stride_w: u32,+ /// Vertical dilation.+ pub dil_h: u32,+ /// Horizontal dilation.+ pub dil_w: u32,+ /// Padding above row 0. ONNX's `pads[0]`.+ pub pad_t: u32,+ /// Padding left of column 0. ONNX's `pads[1]`.+ pub pad_l: u32,+ /// Convolution groups. `group == in_c == out_c` is depthwise.+ pub group: u32,+ /// [`Act::code`].+ pub act: u32,+ /// Output elements, so an over-dispatched workgroup can bail.+ pub count: u32,+}++/// One step of a compiled forward pass.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Op {+ /// Run `kind` over `invocations` output elements.+ Dispatch {+ /// The pipeline to bind.+ kind: Kind,+ /// Its parameters.+ push: Push,+ /// Output elements, one per invocation.+ invocations: u32,+ },+ /// A contiguous copy inside the arena, in fp16 elements.+ ///+ /// This is how `Concat` along the channel axis is done, and it needs no shader:+ /// in NCHW a run of channels *is* contiguous, so concatenation is placing each+ /// part end to end. `vkCmdCopyBuffer` does that faster than a compute pass and+ /// is why there is no `concat.comp`.+ Copy {+ /// Source element offset.+ src: u32,+ /// Destination element offset.+ dst: u32,+ /// Elements to move.+ elems: u32,+ },+}++/// A compiled forward pass: what to run, and how much scratch it needs.+#[derive(Debug, PartialEq, Eq)]+pub struct Plan {+ /// In order. Each depends on the results of the ones before it.+ pub ops: Vec<Op>,+ /// Elements the activation arena must hold.+ pub arena_elems: u32,+ /// Where the preprocessed input goes, in elements.+ pub input: u32,+ /// The input's shape, so preprocessing does not restate it.+ pub input_shape: Shape,+ /// Where the mask comes back from, in elements.+ pub output: u32,+ /// The output's shape.+ pub output_shape: Shape,+}++/// Where a net's weights come from.+///+/// An indirection purely so the net modules are host-testable: the real+/// implementation is [`crate::weights::Weights`], and [`tests::Shapes`] is a stub that+/// only checks the shapes it is asked for. That lets `cargo test` build both networks+/// in full with no `.vkml` on disk.+pub trait WeightSource {+ /// The fp16 element offset of tensor `index`, which must have shape `dims`.+ fn shaped(&self, index: usize, dims: &[u32]) -> Result<u32, String>;++ /// How many tensors there are, so a builder can insist it consumed all of them.+ fn count(&self) -> usize;+}++impl WeightSource for crate::weights::Weights {+ fn shaped(&self, index: usize, dims: &[u32]) -> Result<u32, String> {+ Ok(crate::weights::Weights::shaped(self, index, dims)?.elem_offset())+ }++ fn count(&self) -> usize {+ self.len()+ }+}++/// A tensor in the graph being built. Copy, so it can be passed and reused freely.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Id(usize);++/// An unresolved step, against [`Id`]s rather than offsets.+#[derive(Clone, Debug)]+enum Node {+ Conv {+ input: Id,+ out: Id,+ weight: u32,+ bias: u32,+ kernel: (u32, u32),+ stride: (u32, u32),+ dilation: (u32, u32),+ pad: (u32, u32),+ group: u32,+ act: Act,+ transpose: bool,+ },+ MaxPool {+ input: Id,+ out: Id,+ kernel: (u32, u32),+ stride: (u32, u32),+ },+ Resize {+ input: Id,+ out: Id,+ },+ GlobalAvgPool {+ input: Id,+ out: Id,+ },+ Binary {+ kind: Kind,+ a: Id,+ b: Id,+ out: Id,+ },+ Concat {+ parts: Vec<Id>,+ out: Id,+ },+}++/// Records a forward pass, then packs and resolves it.+pub struct Builder<'a> {+ weights: &'a dyn WeightSource,+ shapes: Vec<Shape>,+ nodes: Vec<Node>,+ /// Tensors that must keep a stable offset for the whole pass: the input and the+ /// output. Everything else is free to be reused once its last reader has run.+ pinned: Vec<Id>,+ error: Option<String>,+ input: Id,+ input_shape: Shape,+}++/// Arena allocations are aligned to this many fp16 elements, i.e. 16 bytes — the same+/// boundary `.vkml` aligns its tensors to.+const ALIGN_ELEMS: u32 = 8;++impl<'a> Builder<'a> {+ /// Start a pass whose input is `shape`.+ pub fn new(weights: &'a dyn WeightSource, shape: Shape) -> Builder<'a> {+ let mut builder = Builder {+ weights,+ shapes: Vec::new(),+ nodes: Vec::new(),+ pinned: Vec::new(),+ error: None,+ input: Id(0),+ input_shape: shape,+ };+ builder.input = builder.tensor(shape);+ builder.pinned.push(builder.input);+ builder+ }++ /// The network's input tensor.+ pub fn input(&self) -> Id {+ self.input+ }++ fn tensor(&mut self, shape: Shape) -> Id {+ self.shapes.push(shape);+ Id(self.shapes.len() - 1)+ }++ /// The first error recorded, so the net modules can chain calls without a `?` on+ /// each of 119 layers and still fail loudly.+ fn fail(&mut self, message: String) {+ if self.error.is_none() {+ self.error = Some(message);+ }+ }++ fn shape_of(&self, id: Id) -> Shape {+ // Ids only come from `tensor`, so this cannot be out of range; a zero shape+ // is returned rather than panicking if a future refactor breaks that, because+ // `finish` will reject the plan anyway.+ self.shapes.get(id.0).copied().unwrap_or(Shape::new(0, 0, 0))+ }++ /// The shape of `id`, for the net modules that need a channel count to size the+ /// next layer — a squeeze-excite's expand stage, for instance.+ pub fn shape(&self, id: Id) -> Shape {+ self.shape_of(id)+ }++ /// A convolution, with ONNX's semantics: weights `[m, in_c/group, kh, kw]`, pads+ /// `[top, left, bottom, right]`, output size floor-divided.+ ///+ /// `weight_index` and `bias_index` are positions in the `.vkml` tensor table, so a+ /// net module reads as the ordered list of layers that it is.+ #[allow(clippy::too_many_arguments)]+ pub fn conv(+ &mut self,+ input: Id,+ weight_index: usize,+ m: u32,+ kernel: (u32, u32),+ stride: (u32, u32),+ dilation: (u32, u32),+ pads: (u32, u32, u32, u32),+ group: u32,+ act: Act,+ ) -> Id {+ let in_shape = self.shape_of(input);+ let (kh, kw) = kernel;+ let splits = group != 0+ && in_shape.c.is_multiple_of(group)+ && m.is_multiple_of(group);+ if !splits {+ self.fail(format!(+ "tensor {weight_index}: {} in / {m} out channels do not split into \+ {group} groups",+ in_shape.c+ ));+ }+ let per_group = in_shape.c.checked_div(group).unwrap_or(0);+ let weight = self.weight(weight_index, &[m, per_group, kh, kw]);+ let bias = self.weight(weight_index + 1, &[m]);++ let (pad_t, pad_l, pad_b, pad_r) = pads;+ let out_h = conv_out(in_shape.h, kh, stride.0, dilation.0, pad_t + pad_b);+ let out_w = conv_out(in_shape.w, kw, stride.1, dilation.1, pad_l + pad_r);+ let out = self.tensor(Shape::new(m, out_h, out_w));+ self.nodes.push(Node::Conv {+ input,+ out,+ weight,+ bias,+ kernel,+ stride,+ dilation,+ pad: (pad_t, pad_l),+ group,+ act,+ transpose: false,+ });+ out+ }++ /// The common case in both nets: `3x3` or `1x1`, stride 1, `pad == dilation`+ /// (which keeps the output size), one group.+ pub fn conv_same(+ &mut self,+ input: Id,+ weight_index: usize,+ m: u32,+ kernel: u32,+ dilation: u32,+ act: Act,+ ) -> Id {+ // `pad == dilation` holds the spatial size only for an odd kernel, which is+ // the only case either net uses it for.+ let pad = if kernel == 1 { 0 } else { dilation };+ self.conv(+ input,+ weight_index,+ m,+ (kernel, kernel),+ (1, 1),+ (dilation, dilation),+ (pad, pad, pad, pad),+ 1,+ act,+ )+ }++ /// A transposed convolution: weights `[in_c, m/group, kh, kw]`, output+ /// `(in - 1) * stride + dilation * (k - 1) + 1 - pads`.+ #[allow(clippy::too_many_arguments)]+ pub fn conv_transpose(+ &mut self,+ input: Id,+ weight_index: usize,+ m: u32,+ kernel: (u32, u32),+ stride: (u32, u32),+ pads: (u32, u32, u32, u32),+ act: Act,+ ) -> Id {+ let in_shape = self.shape_of(input);+ let (kh, kw) = kernel;+ let weight = self.weight(weight_index, &[in_shape.c, m, kh, kw]);+ let bias = self.weight(weight_index + 1, &[m]);+ let (pad_t, pad_l, pad_b, pad_r) = pads;+ let out_h = deconv_out(in_shape.h, kh, stride.0, pad_t + pad_b);+ let out_w = deconv_out(in_shape.w, kw, stride.1, pad_l + pad_r);+ let out = self.tensor(Shape::new(m, out_h, out_w));+ self.nodes.push(Node::Conv {+ input,+ out,+ weight,+ bias,+ kernel,+ stride,+ dilation: (1, 1),+ pad: (pad_t, pad_l),+ group: 1,+ act,+ transpose: true,+ });+ out+ }++ fn weight(&mut self, index: usize, dims: &[u32]) -> u32 {+ match self.weights.shaped(index, dims) {+ Ok(offset) => offset,+ Err(e) => {+ self.fail(e);+ 0+ }+ }+ }++ /// `2x2` stride-2 max pooling, which is the only pooling either net does.+ ///+ /// ONNX marks these `ceil_mode=1`, but every pooled extent in U^2-Netp is even+ /// (320 halves five times to 10), so ceil and floor agree and the distinction is+ /// deliberately not modelled. [`tests::u2netp_pools_only_even_extents`] holds that.+ pub fn max_pool_2x2(&mut self, input: Id) -> Id {+ let in_shape = self.shape_of(input);+ if !in_shape.h.is_multiple_of(2) || !in_shape.w.is_multiple_of(2) {+ self.fail(format!(+ "max_pool_2x2 on {}x{}: ceil_mode is not modelled, so an odd extent \+ would silently drop a row",+ in_shape.h, in_shape.w+ ));+ }+ let out = self.tensor(Shape::new(in_shape.c, in_shape.h / 2, in_shape.w / 2));+ self.nodes.push(Node::MaxPool {+ input,+ out,+ kernel: (2, 2),+ stride: (2, 2),+ });+ out+ }++ /// Bilinear resize to `like`'s spatial size, which is how both nets always use it+ /// — U^2-Net's `_upsample_like`, and the selfie net's decoder skips.+ pub fn resize_like(&mut self, input: Id, like: Id) -> Id {+ let target = self.shape_of(like);+ self.resize_to(input, target.h, target.w)+ }++ /// Bilinear resize to an explicit size.+ pub fn resize_to(&mut self, input: Id, h: u32, w: u32) -> Id {+ let in_shape = self.shape_of(input);+ let out = self.tensor(Shape::new(in_shape.c, h, w));+ self.nodes.push(Node::Resize { input, out });+ out+ }++ /// Mean over H and W, to `C x 1 x 1`.+ pub fn global_avg_pool(&mut self, input: Id) -> Id {+ let in_shape = self.shape_of(input);+ let out = self.tensor(Shape::new(in_shape.c, 1, 1));+ self.nodes.push(Node::GlobalAvgPool { input, out });+ out+ }++ /// Elementwise `a + b`. Shapes must match.+ pub fn add(&mut self, a: Id, b: Id) -> Id {+ let (sa, sb) = (self.shape_of(a), self.shape_of(b));+ if sa != sb {+ self.fail(format!("add of {sa:?} and {sb:?}"));+ }+ let out = self.tensor(sa);+ self.nodes.push(Node::Binary { kind: Kind::Add, a, b, out });+ out+ }++ /// `a * b` with `b` broadcast over H and W — the excite half of a squeeze-excite+ /// block, where `b` came from [`Builder::global_avg_pool`].+ pub fn mul_channel(&mut self, a: Id, b: Id) -> Id {+ let (sa, sb) = (self.shape_of(a), self.shape_of(b));+ if sb.c != sa.c || sb.h != 1 || sb.w != 1 {+ self.fail(format!("mul_channel of {sa:?} by {sb:?}, which is not Cx1x1"));+ }+ let out = self.tensor(sa);+ self.nodes.push(Node::Binary { kind: Kind::MulBroadcast, a, b, out });+ out+ }++ /// Concatenate along the channel axis. Spatial sizes must match.+ pub fn concat(&mut self, parts: &[Id]) -> Id {+ let shapes: Vec<Shape> = parts.iter().map(|&p| self.shape_of(p)).collect();+ let first = match shapes.first() {+ Some(&s) => s,+ None => {+ self.fail("concat of nothing".into());+ Shape::new(0, 0, 0)+ }+ };+ let mut channels = 0;+ for s in &shapes {+ if s.h != first.h || s.w != first.w {+ self.fail(format!("concat of {first:?} with {s:?}"));+ }+ channels += s.c;+ }+ let out = self.tensor(Shape::new(channels, first.h, first.w));+ self.nodes.push(Node::Concat { parts: parts.to_vec(), out });+ out+ }++ /// Pack the arena and resolve every offset, with `output` as the result tensor.+ pub fn finish(mut self, output: Id) -> Result<Plan, String> {+ self.pinned.push(output);+ if let Some(e) = self.error.take() {+ return Err(e);+ }+ let consumed = self.weights.count();+ // Every tensor in the file must have been read. An unread tail is the shape+ // of a forward pass that stopped early, which is otherwise invisible.+ let read = self+ .nodes+ .iter()+ .filter(|n| matches!(n, Node::Conv { .. }))+ .count()+ * 2;+ if read != consumed {+ return Err(format!(+ "the forward pass reads {read} tensors but the file holds {consumed}"+ ));+ }++ let last_use = self.last_use();+ let mut arena = Arena::new();+ let mut offsets: Vec<Option<u32>> = vec![None; self.shapes.len()];+ for &Id(id) in &self.pinned {+ let shape = self.shapes.get(id).copied().unwrap_or(Shape::new(0, 0, 0));+ *offsets.get_mut(id).ok_or("pinned id out of range")? =+ Some(arena.alloc(shape.len()));+ }++ let mut ops = Vec::new();+ for (step, node) in self.nodes.iter().enumerate() {+ // Allocate this node's output before freeing its inputs: an op reads and+ // writes the same buffer, so overlapping them would be a data race that+ // no barrier can fix.+ let out = node.out();+ if offsets.get(out.0).copied().flatten().is_none() {+ let shape = self.shapes.get(out.0).copied().ok_or("output id out of range")?;+ *offsets.get_mut(out.0).ok_or("output id out of range")? =+ Some(arena.alloc(shape.len()));+ }++ let at = |id: Id| -> Result<u32, String> {+ offsets+ .get(id.0)+ .copied()+ .flatten()+ .ok_or_else(|| format!("step {step} reads tensor {} before it is written", id.0))+ };+ let shape = |id: Id| -> Shape {+ self.shapes.get(id.0).copied().unwrap_or(Shape::new(0, 0, 0))+ };+ self.emit(node, &at, &shape, &mut ops)?;++ for (id, &last) in last_use.iter().enumerate() {+ if last == Some(step) && !self.pinned.contains(&Id(id)) {+ if let Some(offset) = offsets.get(id).copied().flatten() {+ let len = self.shapes.get(id).map(|s| s.len()).unwrap_or(0);+ arena.free(offset, len);+ }+ }+ }+ }++ let input = offsets+ .get(self.input.0)+ .copied()+ .flatten()+ .ok_or("the input was never allocated")?;+ let out_offset = offsets+ .get(output.0)+ .copied()+ .flatten()+ .ok_or("the output was never written")?;+ Ok(Plan {+ ops,+ arena_elems: arena.high_water,+ input,+ input_shape: self.input_shape,+ output: out_offset,+ output_shape: self.shapes.get(output.0).copied().ok_or("bad output id")?,+ })+ }++ /// For each tensor, the last step that reads it, or `None` if nothing does.+ fn last_use(&self) -> Vec<Option<usize>> {+ let mut last = vec![None; self.shapes.len()];+ for (step, node) in self.nodes.iter().enumerate() {+ for Id(id) in node.inputs() {+ if let Some(slot) = last.get_mut(id) {+ *slot = Some(step);+ }+ }+ }+ last+ }++ fn emit(+ &self,+ node: &Node,+ at: &dyn Fn(Id) -> Result<u32, String>,+ shape: &dyn Fn(Id) -> Shape,+ ops: &mut Vec<Op>,+ ) -> Result<(), String> {+ match node {+ Node::Conv {+ input,+ out,+ weight,+ bias,+ kernel,+ stride,+ dilation,+ pad,+ group,+ act,+ transpose,+ } => {+ let (si, so) = (shape(*input), shape(*out));+ ops.push(Op::Dispatch {+ kind: if *transpose { Kind::ConvTranspose } else { Kind::Conv },+ push: Push {+ in0: at(*input)?,+ out: at(*out)?,+ weight: *weight,+ bias: *bias,+ in_c: si.c,+ in_h: si.h,+ in_w: si.w,+ out_c: so.c,+ out_h: so.h,+ out_w: so.w,+ kh: kernel.0,+ kw: kernel.1,+ stride_h: stride.0,+ stride_w: stride.1,+ dil_h: dilation.0,+ dil_w: dilation.1,+ pad_t: pad.0,+ pad_l: pad.1,+ group: *group,+ act: act.code(),+ count: so.len(),+ ..Push::default()+ },+ invocations: so.len(),+ });+ }+ Node::MaxPool { input, out, kernel, stride } => {+ let (si, so) = (shape(*input), shape(*out));+ ops.push(Op::Dispatch {+ kind: Kind::MaxPool,+ push: Push {+ in0: at(*input)?,+ out: at(*out)?,+ in_c: si.c,+ in_h: si.h,+ in_w: si.w,+ out_c: so.c,+ out_h: so.h,+ out_w: so.w,+ kh: kernel.0,+ kw: kernel.1,+ stride_h: stride.0,+ stride_w: stride.1,+ count: so.len(),+ ..Push::default()+ },+ invocations: so.len(),+ });+ }+ Node::Resize { input, out } => {+ let (si, so) = (shape(*input), shape(*out));+ ops.push(Op::Dispatch {+ kind: Kind::Resize,+ push: Push {+ in0: at(*input)?,+ out: at(*out)?,+ in_c: si.c,+ in_h: si.h,+ in_w: si.w,+ out_c: so.c,+ out_h: so.h,+ out_w: so.w,+ count: so.len(),+ ..Push::default()+ },+ invocations: so.len(),+ });+ }+ Node::GlobalAvgPool { input, out } => {+ let (si, so) = (shape(*input), shape(*out));+ ops.push(Op::Dispatch {+ kind: Kind::GlobalAvgPool,+ push: Push {+ in0: at(*input)?,+ out: at(*out)?,+ in_c: si.c,+ in_h: si.h,+ in_w: si.w,+ out_c: so.c,+ out_h: 1,+ out_w: 1,+ count: so.len(),+ ..Push::default()+ },+ invocations: so.len(),+ });+ }+ Node::Binary { kind, a, b, out } => {+ let so = shape(*out);+ ops.push(Op::Dispatch {+ kind: *kind,+ push: Push {+ in0: at(*a)?,+ in1: at(*b)?,+ out: at(*out)?,+ in_c: so.c,+ in_h: so.h,+ in_w: so.w,+ out_c: so.c,+ out_h: so.h,+ out_w: so.w,+ count: so.len(),+ ..Push::default()+ },+ invocations: so.len(),+ });+ }+ Node::Concat { parts, out } => {+ let base = at(*out)?;+ let mut written = 0;+ for &part in parts {+ let len = shape(part).len();+ ops.push(Op::Copy {+ src: at(part)?,+ dst: base + written,+ elems: len,+ });+ written += len;+ }+ }+ }+ Ok(())+ }+}++impl Node {+ fn out(&self) -> Id {+ match self {+ Node::Conv { out, .. }+ | Node::MaxPool { out, .. }+ | Node::Resize { out, .. }+ | Node::GlobalAvgPool { out, .. }+ | Node::Binary { out, .. }+ | Node::Concat { out, .. } => *out,+ }+ }++ fn inputs(&self) -> Vec<Id> {+ match self {+ Node::Conv { input, .. }+ | Node::MaxPool { input, .. }+ | Node::Resize { input, .. }+ | Node::GlobalAvgPool { input, .. } => vec![*input],+ Node::Binary { a, b, .. } => vec![*a, *b],+ Node::Concat { parts, .. } => parts.clone(),+ }+ }+}++/// `floor((in + pad - dilation * (k - 1) - 1) / stride) + 1`, ONNX's convolution+/// output size.+fn conv_out(input: u32, kernel: u32, stride: u32, dilation: u32, pad_total: u32) ->
Diff truncated.