ml: profile_vision + dump_conv_shapes examples for vision net perf
- Commit
a8c20e140f7662b1138dc11b92bf52e7dac4c7e1- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-25 23:17 UTC (1 month ago)
- Parents
9155551
Diff
communicate/src/main/java/com/vayunmathur/communicate/data/SimManager.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/SimManager.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/SimManager.ktindex 4fa08e11d1..e0b8100284 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/SimManager.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/SimManager.kt@@ -24,7 +24,11 @@ object SimManager { fun activeSims(context: Context): List<CommunicateSim> { if (!context.hasPhoneStatePermission()) return emptyList()- val sm = context.getSystemService(SubscriptionManager::class.java) ?: return emptyList()+ // The service lookup itself can throw where no telephony stack exists+ // (Layoutlib screenshot renders have no subscription service) — treat+ // that like zero SIMs rather than crashing composition.+ val sm = runCatching { context.getSystemService(SubscriptionManager::class.java) }+ .getOrNull() ?: return emptyList() return runCatching { sm.activeSubscriptionInfoList?.map { info -> CommunicateSim(
communicate/src/main/java/com/vayunmathur/communicate/ui/CallLogsScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/CallLogsScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/CallLogsScreen.ktindex 82a7a26a76..dfbcbfcc34 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/CallLogsScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/CallLogsScreen.kt@@ -77,46 +77,70 @@ fun CallLogsScreen() { icon = { IconHistory() }, modifier = Modifier.padding(padding), )- else -> LazyColumn(- modifier = Modifier- .padding(padding)- .fillMaxSize(),- contentPadding = PaddingValues(vertical = 8.dp),- ) {- items(rows, key = { it.id }) { entry ->- CallLogRow(- entry = entry,- onClick = { CommunicateRepository.placeCall(context, entry.phoneNumber) },- onDelete = { pendingDelete = entry },- )- }+ else -> {+ CallLogsContent(+ entries = rows,+ modifier = Modifier.padding(padding),+ onCall = { CommunicateRepository.placeCall(context, it.phoneNumber) },+ onDelete = { toDelete ->+ scope.launch {+ val ok = withContext(Dispatchers.IO) { CommunicateRepository.deleteCallLog(+ context,+ toDelete) }+ if (ok) tick++ else AppMessages.show(context.getString(R.string.delete_failed))+ }+ },+ ) } }- val toDelete = pendingDelete- if (toDelete != null) {- com.vayunmathur.library.ui.ConfirmDialog(- title = stringResource(R.string.delete_call_log_title),- message = stringResource(R.string.delete_call_log_message),- confirmLabel = stringResource(com.vayunmathur.library.ui.R.string.delete),- dismissLabel = stringResource(com.vayunmathur.library.ui.R.string.cancel),- destructive = true,- onConfirm = {- pendingDelete = null- scope.launch {- val ok = withContext(Dispatchers.IO) { CommunicateRepository.deleteCallLog(- context,- toDelete) }- if (ok) tick++ else AppMessages.show(context.getString(R.string.delete_failed))- }- },- onDismiss = { pendingDelete = null },- )- } } } } } +/**+ * Call-log list, stateless: rows plus the delete-confirm dialog. Split out so+ * screenshot previews can render entries without the call-log provider, the+ * polling tick, or the permission gates above.+ */+@Composable+fun CallLogsContent(+ entries: List<CommunicateCallLogEntry>,+ modifier: Modifier = Modifier,+ onCall: (CommunicateCallLogEntry) -> Unit,+ onDelete: (CommunicateCallLogEntry) -> Unit,+) {+ var pendingDelete by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf<CommunicateCallLogEntry?>(null) }+ LazyColumn(+ modifier = modifier+ .fillMaxSize(),+ contentPadding = PaddingValues(vertical = 8.dp),+ ) {+ items(entries, key = { it.id }) { entry ->+ CallLogRow(+ entry = entry,+ onClick = { onCall(entry) },+ onDelete = { pendingDelete = entry },+ )+ }+ }+ val toDelete = pendingDelete+ if (toDelete != null) {+ com.vayunmathur.library.ui.ConfirmDialog(+ title = stringResource(R.string.delete_call_log_title),+ message = stringResource(R.string.delete_call_log_message),+ confirmLabel = stringResource(com.vayunmathur.library.ui.R.string.delete),+ dismissLabel = stringResource(com.vayunmathur.library.ui.R.string.cancel),+ destructive = true,+ onConfirm = {+ pendingDelete = null+ onDelete(toDelete)+ },+ onDismiss = { pendingDelete = null },+ )+ }+}+ @Composable private fun CallLogRow(entry: CommunicateCallLogEntry, onClick: () -> Unit, onDelete: () -> Unit = {}) { val context = LocalContext.current
communicate/src/main/java/com/vayunmathur/communicate/ui/DialerScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/DialerScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/DialerScreen.ktindex 1e8de6d1c4..ffd028b030 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/DialerScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/DialerScreen.kt@@ -72,9 +72,6 @@ import kotlinx.coroutines.withContext @Composable fun DialerScreen() { val context = LocalContext.current- val clipboard = LocalClipboard.current- val scope = rememberCoroutineScope()- var number by remember { mutableStateOf("") } val lineChoices = rememberLineChoices() var selectedLine by remember { mutableStateOf<LineChoice?>(null) } var userSelectedLine by remember { mutableStateOf(false) }@@ -135,13 +132,6 @@ fun DialerScreen() { } // Keyed on the contact list only: the query must never re-run the provider query. val rows = contacts.value- val entries = remember(rows) { rows.orEmpty().map { T9.entryFor(it.name, it.phoneNumber) } }- val query = T9.normalizeQuery(number)- val filtered = remember(rows, query) {- val all = rows.orEmpty()- if (query.isEmpty()) all- else all.filterIndexed { index, _ -> T9.matches(entries[index], query) }- } when { rows == null -> com.vayunmathur.library.ui.LoadingState(Modifier.weight(1f)) rows.isEmpty() -> EmptyState(@@ -149,55 +139,98 @@ fun DialerScreen() { icon = { IconContacts() }, modifier = Modifier.weight(1f), )- filtered.isEmpty() -> EmptyState(- title = stringResource(R.string.empty_contacts_for_digits),- icon = { IconContacts() },- modifier = Modifier.weight(1f),- )- else -> LazyColumn(- modifier = Modifier.weight(1f),- contentPadding = PaddingValues(bottom = 8.dp),- ) {- item {- Text(- stringResource(UiR.string.contacts),- modifier = Modifier.padding(horizontal = 20.dp, vertical = 12.dp),- style = MaterialTheme.typography.titleMedium,- fontWeight = FontWeight.SemiBold,- )- }- items(filtered, key = { "${it.id}-${it.phoneNumber}" }) { contact ->- ContactRow(contact) {- place(contact.phoneNumber)- }- }+ else -> {+ DialerContent(+ contacts = rows,+ onPlace = ::place,+ modifier = Modifier.weight(1f),+ ) } } }- DialPad(- number = number,- onAppend = { number += it },- onBackspace = { number = number.dropLast(1) },- onClear = { number = "" },- onPaste = {- scope.launch {- val pasted = clipboard.getClipEntry()- ?.clipData- ?.getItemAt(0)- ?.coerceToText(context)- ?.toString()- .orEmpty()- .filter { it.isDigit() || it == '+' || it == '*' || it == '#' }- if (pasted.isNotBlank()) number = pasted- }- },- onCall = { place(number) },- ) } } } } +/**+ * Dialer list plus pad, stateless apart from the entered number: contacts,+ * lines and placement come in as parameters so screenshot previews can render+ * without the SIM/session providers, the role and permission gates, or the+ * contact content provider above.+ */+@Composable+fun DialerContent(+ contacts: List<CommunicateContact>,+ onPlace: (String) -> Unit,+ modifier: Modifier = Modifier,+) {+ var number by remember { mutableStateOf("") }+ val context = LocalContext.current+ val clipboard = LocalClipboard.current+ val scope = rememberCoroutineScope()+ // Keyed on the contact list only: the query must never re-run the provider query.+ val entries = remember(contacts) { contacts.map { T9.entryFor(it.name, it.phoneNumber) } }+ val query = T9.normalizeQuery(number)+ val filtered = remember(contacts, query) {+ if (query.isEmpty()) contacts+ else contacts.filterIndexed { index, _ -> T9.matches(entries[index], query) }+ }+ Column(modifier = modifier.fillMaxSize()) {+ if (contacts.isEmpty()) {+ EmptyState(+ title = stringResource(R.string.empty_contacts),+ icon = { IconContacts() },+ modifier = Modifier.weight(1f),+ )+ } else if (filtered.isEmpty()) {+ EmptyState(+ title = stringResource(R.string.empty_contacts_for_digits),+ icon = { IconContacts() },+ modifier = Modifier.weight(1f),+ )+ } else {+ LazyColumn(+ modifier = Modifier.weight(1f),+ contentPadding = PaddingValues(bottom = 8.dp),+ ) {+ item {+ Text(+ stringResource(UiR.string.contacts),+ modifier = Modifier.padding(horizontal = 20.dp, vertical = 12.dp),+ style = MaterialTheme.typography.titleMedium,+ fontWeight = FontWeight.SemiBold,+ )+ }+ items(filtered, key = { "${it.id}-${it.phoneNumber}" }) { contact ->+ ContactRow(contact) {+ onPlace(contact.phoneNumber)+ }+ }+ }+ }+ DialPad(+ number = number,+ onAppend = { number += it },+ onBackspace = { number = number.dropLast(1) },+ onClear = { number = "" },+ onPaste = {+ scope.launch {+ val pasted = clipboard.getClipEntry()+ ?.clipData+ ?.getItemAt(0)+ ?.coerceToText(context)+ ?.toString()+ .orEmpty()+ .filter { it.isDigit() || it == '+' || it == '*' || it == '#' }+ if (pasted.isNotBlank()) number = pasted+ }+ },+ onCall = { onPlace(number) },+ )+ }+}+ @Composable private fun DialPad( number: String,
communicate/src/screenshotTest/kotlin/com/vayunmathur/communicate/ui/CarMetadataPreviews.kt
diff --git a/communicate/src/screenshotTest/kotlin/com/vayunmathur/communicate/ui/CarMetadataPreviews.kt b/communicate/src/screenshotTest/kotlin/com/vayunmathur/communicate/ui/CarMetadataPreviews.ktindex 42dd042117..38f36aa7de 100644--- a/communicate/src/screenshotTest/kotlin/com/vayunmathur/communicate/ui/CarMetadataPreviews.kt+++ b/communicate/src/screenshotTest/kotlin/com/vayunmathur/communicate/ui/CarMetadataPreviews.kt@@ -27,9 +27,9 @@ private const val CAR = "spec:width=1024dp,height=600dp,dpi=160" class CarMetadataPreviews { @PreviewTest- @Preview(name = "1-car-threads", device = CAR, group = "phone", showSystemUi = false)+ @Preview(name = "4-car-threads", device = CAR, group = "phone", showSystemUi = false) @Composable- fun Preview1CarThreads() {+ fun Preview4CarThreads() { DynamicTheme(darkTheme = true) { Surface(Modifier.fillMaxSize()) { CarTemplateView(@@ -84,9 +84,9 @@ class CarMetadataPreviews { } @PreviewTest- @Preview(name = "2-car-incall", device = CAR, group = "phone", showSystemUi = false)+ @Preview(name = "5-car-incall", device = CAR, group = "phone", showSystemUi = false) @Composable- fun Preview2CarInCall() {+ fun Preview5CarInCall() { DynamicTheme(darkTheme = true) { Surface(Modifier.fillMaxSize()) { CarTemplateView(@@ -105,9 +105,9 @@ class CarMetadataPreviews { } @PreviewTest- @Preview(name = "3-car-keypad", device = CAR, group = "phone", showSystemUi = false)+ @Preview(name = "6-car-keypad", device = CAR, group = "phone", showSystemUi = false) @Composable- fun Preview3CarKeypad() {+ fun Preview6CarKeypad() { DynamicTheme(darkTheme = true) { Surface(Modifier.fillMaxSize()) { CarTemplateView(
communicate/src/screenshotTest/kotlin/com/vayunmathur/communicate/ui/MetadataPreviews.kt
diff --git a/communicate/src/screenshotTest/kotlin/com/vayunmathur/communicate/ui/MetadataPreviews.kt b/communicate/src/screenshotTest/kotlin/com/vayunmathur/communicate/ui/MetadataPreviews.ktnew file mode 100644index 0000000000..c632e8e63b--- /dev/null+++ b/communicate/src/screenshotTest/kotlin/com/vayunmathur/communicate/ui/MetadataPreviews.kt@@ -0,0 +1,165 @@+package com.vayunmathur.communicate.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.pager.rememberPagerState+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.tooling.preview.Preview+import com.android.tools.screenshot.PreviewTest+import com.vayunmathur.communicate.data.CommunicateCallLogEntry+import com.vayunmathur.communicate.data.CommunicateCallType+import com.vayunmathur.communicate.data.CommunicateContact+import com.vayunmathur.communicate.data.SmsThread+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.ui.IconCall+import com.vayunmathur.library.ui.IconHistory+import com.vayunmathur.library.ui.IconSms+import com.vayunmathur.library.ui.PagerTab+import com.vayunmathur.library.ui.TabStyle+import com.vayunmathur.library.ui.TabbedPagerScaffold++/** Phone-shaped, roughly 1080x2340 at xxhdpi — comfortably above the F-Droid minimum. */+private const val PHONE = "spec:width=411dp,height=891dp,dpi=420"++/**+ * Store listing images for `:communicate` phone tabs, rendered from Compose previews.+ *+ * The car shots live in CarMetadataPreviews (head-unit UI, no phone chrome). These+ * cover the handset tabs: Messages, Dialer, Call logs. The tab screens were split+ * into stateless `*Content` slices so previews render without the SMS provider,+ * the SIM/session lines, or the contact/call-log content providers.+ */+class MetadataPreviews {++ private val threads = listOf(+ SmsThread(+ threadId = 1,+ address = "+14155550102",+ displayName = "Aisha Rahman",+ snippet = "Running 10 minutes late, start without me",+ timestampMillis = 1_785_566_534_600,+ unreadCount = 2,+ ),+ SmsThread(+ threadId = 2,+ address = "+14155550103",+ displayName = "Weekend Hike",+ snippet = "Sam: Trailhead at 8?",+ timestampMillis = 1_785_563_000_000,+ unreadCount = 0,+ isGroup = true,+ participants = listOf("+14155550103", "+14155550104"),+ groupTitle = "Weekend Hike",+ ),+ SmsThread(+ threadId = 3,+ address = "+14155550105",+ displayName = null,+ snippet = "Your package arrives Thursday",+ timestampMillis = 1_785_550_000_000,+ unreadCount = 0,+ ),+ )++ private val contacts = listOf(+ CommunicateContact(id = 1, name = "Aisha Rahman", phoneNumber = "+14155550102", label = "Mobile"),+ CommunicateContact(id = 2, name = "Sam Whitfield", phoneNumber = "+14155550103", label = "Home"),+ CommunicateContact(id = 3, name = "Maya Chen", phoneNumber = "+14155550105", label = "Work"),+ )++ private val callLogs = listOf(+ CommunicateCallLogEntry(+ id = 1,+ displayName = "Aisha Rahman",+ phoneNumber = "+14155550102",+ type = CommunicateCallType.Incoming,+ timestampMillis = 1_785_566_000_000,+ durationSeconds = 184,+ ),+ CommunicateCallLogEntry(+ id = 2,+ displayName = null,+ phoneNumber = "+14155550109",+ type = CommunicateCallType.Missed,+ timestampMillis = 1_785_560_000_000,+ durationSeconds = 0,+ ),+ CommunicateCallLogEntry(+ id = 3,+ displayName = "Sam Whitfield",+ phoneNumber = "+14155550103",+ type = CommunicateCallType.Outgoing,+ timestampMillis = 1_785_550_000_000,+ durationSeconds = 62,+ ),+ )++ @PreviewTest+ @Preview(name = "1-messages", device = PHONE, group = "phone", showSystemUi = true)+ @Composable+ fun Preview1Messages() {+ ChromePreview(selectedTab = 0)+ }++ @PreviewTest+ @Preview(name = "2-dialer", device = PHONE, group = "phone", showSystemUi = true)+ @Composable+ fun Preview2Dialer() {+ ChromePreview(selectedTab = 1)+ }++ @PreviewTest+ @Preview(name = "3-call-logs", device = PHONE, group = "phone", showSystemUi = true)+ @Composable+ fun Preview3CallLogs() {+ ChromePreview(selectedTab = 2)+ }++ @Composable+ private fun MessagesContent() {+ MessagesListContent(+ threads = threads,+ onOpenThread = {},+ onDeleteThread = {},+ )+ }++ @Composable+ private fun DialerContentTab() {+ DialerContent(+ contacts = contacts,+ onPlace = {},+ )+ }++ @Composable+ private fun CallLogsContentTab() {+ CallLogsContent(+ entries = callLogs,+ onCall = {},+ onDelete = {},+ )+ }++ /**+ * The app's real tab chrome around preview screen content: the same+ * [TabbedPagerScaffold] with the same Messages/Dialer/Call-logs tabs+ * `CommunicateTabs` declares. Only the selected tab is literal.+ */+ @Composable+ private fun ChromePreview(selectedTab: Int) {+ DynamicTheme(darkTheme = true) {+ val tabs = listOf(+ PagerTab("Messages", { IconSms() }) { MessagesContent() },+ PagerTab("Dialer", { IconCall() }) { DialerContentTab() },+ PagerTab("Call logs", { IconHistory() }) { CallLogsContentTab() },+ )+ TabbedPagerScaffold(+ tabs = tabs,+ pagerState = rememberPagerState(initialPage = selectedTab, pageCount = { tabs.size }),+ tabStyle = TabStyle.BottomNav,+ )+ }+ }+}
library/ml/src/main/rust/examples/dump_conv_shapes.rs
diff --git a/library/ml/src/main/rust/examples/dump_conv_shapes.rs b/library/ml/src/main/rust/examples/dump_conv_shapes.rsnew file mode 100644index 0000000000..571d93b67e--- /dev/null+++ b/library/ml/src/main/rust/examples/dump_conv_shapes.rs@@ -0,0 +1,107 @@+//! Conv geometry inventory for the vision nets, on the host (no device needed).+//!+//! ```text+//! cargo run --offline -p modelrunner --example dump_conv_shapes -- path/to/assets+//! ```+//!+//! Prints every `Kind::Conv` dispatch's geometry and MACs, hottest first, so the+//! tiled spatial-conv work can pick tile sizes against the real shapes.+use modelrunner::nets::{+ maia, mobilefacenet, modnet, ppocr_det, ppocr_rec, scrfd, selfie, tinyclip, u2netp, Kind,+ Op, Plan,+};+use modelrunner::post::ocr::REC_WIDTH;+use modelrunner::weights::{graph, Weights};++fn main() {+ let dir = std::env::args()+ .nth(1)+ .or_else(|| std::env::var("MODELRUNNER_VISION").ok())+ .unwrap_or_else(|| ".".into());+ let mut plans: Vec<(String, Plan)> = Vec::new();+ let mut open = |name: &str, file: &str, graph_id: u32, build: &dyn Fn(&Weights) -> Result<Plan, String>| {+ let path = format!("{dir}/{file}");+ match std::fs::read(&path) {+ Ok(bytes) => match Weights::parse(&bytes, graph_id) {+ Ok(w) => match build(&w) {+ Ok(plan) => plans.push((name.to_string(), plan)),+ Err(e) => println!("{name}: build failed: {e}"),+ },+ Err(e) => println!("{name}: parse failed: {e}"),+ },+ Err(e) => println!("{name}: cannot read {path}: {e}"),+ }+ };+ open("selfie", "selfie_segmentation.maml", graph::SELFIE, &|w| selfie::build(w));+ open("modnet", "modnet.maml", graph::MODNET, &|w| modnet::build(w));+ open("u2netp", "u2netp.maml", graph::U2NETP, &|w| u2netp::build(w));+ open("scrfd", "scrfd_500m.maml", graph::SCRFD, &|w| {+ scrfd::build(w, scrfd::LONG_SIDE, scrfd::LONG_SIDE)+ });+ open("mbf", "w600k_mbf.maml", graph::MOBILEFACENET, &|w| mobilefacenet::build(w));+ open("det", "ppocr_det.maml", graph::PPOCR_DET, &|w| {+ ppocr_det::build(w, ppocr_det::LONG_SIDE, ppocr_det::LONG_SIDE)+ });+ open("rec", "ppocr_rec.maml", graph::PPOCR_REC, &|w| ppocr_rec::build(w, REC_WIDTH));+ open("clip_image", "clip/tinyclip.maml", graph::TINYCLIP, &|w| {+ tinyclip::build(w, tinyclip::Mode::Image)+ });+ open("maia", "maia3-5m.maml", graph::MAIA, &|w| maia::build(w));++ // (net, step, out_c, out_h, out_w, in_c, kh, kw, stride, dil, group, act, gmac)+ let mut rows: Vec<(String, usize, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, f64)> =+ Vec::new();+ for (name, plan) in &plans {+ for (step, op) in plan.ops.iter().enumerate() {+ let Op::Dispatch { kind: Kind::Conv, push, .. } = op else { continue };+ let macs = push.out_c as u64 * push.out_h as u64 * push.out_w as u64+ * (push.in_c as u64 / push.group as u64)+ * push.kh as u64+ * push.kw as u64;+ rows.push((+ name.to_string(),+ step,+ push.out_c,+ push.out_h,+ push.out_w,+ push.in_c,+ push.kh,+ push.kw,+ push.stride_h,+ push.dil_h,+ push.group,+ push.act,+ macs as f64 / 1e9,+ ));+ }+ }+ rows.sort_by(|a, b| b.12.total_cmp(&a.12));+ println!(+ " {:<10} {:>4} {:>9} {:>11} {:>9} {:>3} {:>2} {:>2} {:>3} {:>7}",+ "net", "step", "out_cxhxw", "in_c", "kxk", "s", "d", "g", "act", "GMAC"+ );+ let mut total = 0.0;+ for (name, step, oc, oh, ow, ic, kh, kw, s, d, g, act, gmac) in &rows {+ println!(+ " {name:<10} {step:>4} {oc:>4}x{oh:<4}x{ow:<4} {ic:>6} {kh:>2}x{kw:<2} {s:>2} {d:>2} {g:>4} {act:>3} {gmac:>7.3}",+ );+ total += gmac;+ }+ println!("total untiled Conv GMAC: {total:.2}");+ // Per-net dense (group==1) vs grouped/depthwise GMAC, for ranking the work.+ // rows entries: (name, step, oc, oh, ow, ic, kh, kw, s, d, g, act, gmac)+ let mut per_net: std::collections::BTreeMap<String, (f64, f64)> =+ std::collections::BTreeMap::new();+ for r in &rows {+ let entry = per_net.entry(r.0.clone()).or_default();+ if r.10 == 1 {+ entry.0 += r.12;+ } else {+ entry.1 += r.12;+ }+ }+ println!("per net (dense, grouped) GMAC:");+ for (name, (dense, grouped)) in &per_net {+ println!(" {name:<10} dense {dense:>7.3} grouped {grouped:>7.3}");+ }+}
library/ml/src/main/rust/examples/profile_vision.rs
diff --git a/library/ml/src/main/rust/examples/profile_vision.rs b/library/ml/src/main/rust/examples/profile_vision.rsnew file mode 100644index 0000000000..a28858bd32--- /dev/null+++ b/library/ml/src/main/rust/examples/profile_vision.rs@@ -0,0 +1,369 @@+//! Per-model wall time, per-kind GPU time and output checksums for the vision nets.+//!+//! ```text+//! cargo run --release -p modelrunner --example profile_vision -- all path/to/assets+//! adb shell MODELRUNNER_TIMESTAMPS=1 /data/local/tmp/maml/vision/profile_vision all /data/local/tmp/maml/vision+//! ```+//!+//! `which` is one of `all`, `selfie`, `modnet`, `u2netp`, `scrfd`, `mbf`, `det`, `rec`,+//! `clip_image`, `clip_text`, `maia`. `dir` holds the `.maml` files under their asset+//! names (`selfie_segmentation.maml`, `modnet.maml`, `u2netp.maml`, `scrfd_500m.maml`,+//! `w600k_mbf.maml`, `ppocr_det.maml`, `ppocr_rec.maml`, `clip/tinyclip.maml`,+//! `maia3-5m.maml`); it defaults to `MODELRUNNER_VISION` or the current directory.+//!+//! Timestamps need `MODELRUNNER_TIMESTAMPS=1`; without it only wall times and checksums+//! print. Measure the two in separate runs. The checksum is the whole-output f64 sum,+//! printed so two builds can be compared for identical output.+use std::collections::BTreeMap;+use std::time::Instant;++use modelrunner::nets::{+ maia, mobilefacenet, modnet, ppocr_det, ppocr_rec, scrfd, selfie, tinyclip, u2netp, Plan,+};+use modelrunner::post::ocr::REC_WIDTH;+use modelrunner::preprocess::{RESCALE_ONLY, PPOCR_REC};+use modelrunner::vulkan::context;+use modelrunner::vulkan::reshape::Reshaped;+use modelrunner::vulkan::run::Net;+use modelrunner::weights::{graph, Offsets, Weights};++fn main() {+ let args: Vec<String> = std::env::args().skip(1).collect();+ let which = args.first().map(String::as_str).unwrap_or("all");+ let dir = args+ .get(1)+ .map(String::as_str)+ .map(str::to_owned)+ .or_else(|| std::env::var("MODELRUNNER_VISION").ok())+ .unwrap_or_else(|| ".".into());+ let models: &[(&str, &str, u32)] = &[+ ("selfie", "selfie_segmentation.maml", 5),+ ("modnet", "modnet.maml", 3),+ ("u2netp", "u2netp.maml", 2),+ ("scrfd", "scrfd_500m.maml", 3),+ ("mbf", "w600k_mbf.maml", 5),+ ("det", "ppocr_det.maml", 2),+ ("rec", "ppocr_rec.maml", 5),+ ("clip_image", "clip/tinyclip.maml", 3),+ ("clip_text", "clip/tinyclip.maml", 5),+ ("maia", "maia3-5m.maml", 3),+ ];+ let mut failed = false;+ for (name, file, passes) in models {+ if which != "all" && which != *name {+ continue;+ }+ let path = format!("{dir}/{file}");+ println!("=== {name} ({path}) ===");+ let result = match *name {+ "selfie" => profile_selfie(&path, *passes),+ "modnet" => profile_modnet(&path, *passes),+ "u2netp" => profile_u2netp(&path, *passes),+ "scrfd" => profile_scrfd(&path, *passes),+ "mbf" => profile_mbf(&path, *passes),+ "det" => profile_det(&path, *passes),+ "rec" => profile_rec(&path, *passes),+ "clip_image" => profile_clip_image(&path, *passes),+ "clip_text" => profile_clip_text(&path, *passes),+ "maia" => profile_maia(&path, *passes),+ other => Err(format!("unknown model {other:?}")),+ };+ if let Err(why) = result {+ println!("failed: {why}");+ failed = true;+ }+ println!();+ }+ if failed {+ std::process::exit(1);+ }+}++/// Deterministic photo-range input: the same ramp `scripts/ml/onnx_parity.py` feeds.+///+/// A full-range sawtooth in [-0.5, 0.5), exercising every activation's range rather+/// than saturating the segmenters' sigmoids to one end. Free of transcendentals so+/// both sides of a parity comparison read the same bytes.+fn pattern(len: usize) -> Vec<f32> {+ (0..len).map(|i| (i as u64 * 37 % 255) as f32 / 255.0 - 0.5).collect()+}++/// A bright centred blob on a dark field — structurally nothing like [`pattern`].+///+/// Matches `nets::reference`'s `blob` so the response check compares the same pair.+/// Layout is channel-major `[c, h, w]`, the order every plan input uses.+fn blob(channels: usize, height: usize, width: usize) -> Vec<f32> {+ let mut values = Vec::with_capacity(channels * height * width);+ let (cy, cx) = (height as f32 / 2.0, width as f32 / 2.0);+ let radius = height.min(width) as f32 / 3.0;+ for c in 0..channels {+ for y in 0..height {+ for x in 0..width {+ let (dy, dx) = (y as f32 - cy, x as f32 - cx);+ let inside = (dy * dy + dx * dx).sqrt() < radius;+ values.push(if inside { 0.9 - c as f32 * 0.2 } else { 0.05 });+ }+ }+ }+ values+}++fn load(path: &str, graph_id: u32) -> Result<Weights, String> {+ let bytes = std::fs::read(path).map_err(|e| format!("cannot read {path}: {e}"))?;+ Weights::parse(&bytes, graph_id)+}++/// Time `passes` inferences after one warm-up, then print the kinds table and checksums.+///+/// Runs `input_b` once after the timed passes and reports the peak per-element+/// response between the two inputs. Segmentation masks are near-zero on synthetic+/// input even when correct — see `nets::reference::assert_usable_mask` — so the+/// response, not the checksum, is what distinguishes a net that answers from one+/// that cannot.+fn report(+ label: &str,+ net: &mut Net,+ input: &[f32],+ input_b: &[f32],+ passes: u32,+) -> Result<(), String> {+ let mut ms = Vec::new();+ let mut last: Vec<Vec<f32>> = Vec::new();+ net.infer_raw(input)?;+ for _ in 0..passes {+ let t = Instant::now();+ last = net.infer_raw(input)?;+ ms.push(since(t));+ }+ println!("infer {}", stats(&ms));+ print_checksums(&last);+ let other = net.infer_raw(input_b)?;+ for (a, b) in last.iter().zip(other.iter()) {+ let response = a.iter().zip(b.iter()).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max);+ println!("response peak {response:.6}");+ }+ net.infer_raw(input)?;+ print_kinds(label, net);+ Ok(())+}++fn report_many(+ label: &str,+ net: &mut Net,+ inputs: &[&[f32]],+ passes: u32,+) -> Result<(), String> {+ let mut ms = Vec::new();+ net.infer_raw_many(inputs)?;+ for _ in 0..passes {+ let t = Instant::now();+ let out = net.infer_raw_many(inputs)?;+ ms.push(since(t));+ if ms.len() == passes as usize {+ print_checksums(&out);+ }+ }+ println!("infer {}", stats(&ms));+ net.infer_raw_many(inputs)?;+ print_kinds(label, net);+ Ok(())+}++fn print_checksums(out: &[Vec<f32>]) {+ for (i, binding) in out.iter().enumerate() {+ let sum: f64 = binding.iter().map(|&v| f64::from(v)).sum();+ let max: f32 = binding.iter().fold(0.0f32, |a, &v| a.max(v.abs()));+ println!("output[{i}] len {:>8} checksum {sum:.6} maxabs {max:.6}", binding.len());+ }+}++fn profile_selfie(path: &str, passes: u32) -> Result<(), String> {+ let weights = load(path, graph::SELFIE)?;+ let context = context::shared()?;+ let started = Instant::now();+ let plan = selfie::build(&weights)?;+ let mut net = Net::new(context, plan, &weights, RESCALE_ONLY)?;+ println!("load {:>8.1} ms (upload + first record)", since(started));+ let input = pattern(3 * selfie::SIZE as usize * selfie::SIZE as usize);+ let input_b = blob(3, selfie::SIZE as usize, selfie::SIZE as usize);+ report("selfie", &mut net, &input, &input_b, passes)+}++fn profile_modnet(path: &str, passes: u32) -> Result<(), String> {+ let weights = load(path, graph::MODNET)?;+ let context = context::shared()?;+ let started = Instant::now();+ let plan = modnet::build(&weights)?;+ let mut net = Net::new(context, plan, &weights, RESCALE_ONLY)?;+ println!("load {:>8.1} ms (upload + first record)", since(started));+ let input = pattern(3 * modnet::SIZE as usize * modnet::SIZE as usize);+ let input_b = blob(3, modnet::SIZE as usize, modnet::SIZE as usize);+ report("modnet", &mut net, &input, &input_b, passes)+}++fn profile_u2netp(path: &str, passes: u32) -> Result<(), String> {+ let weights = load(path, graph::U2NETP)?;+ let context = context::shared()?;+ let started = Instant::now();+ let plan = u2netp::build(&weights)?;+ let mut net = Net::new(context, plan, &weights, RESCALE_ONLY)?;+ println!("load {:>8.1} ms (upload + first record)", since(started));+ let input = pattern(3 * u2netp::SIZE as usize * u2netp::SIZE as usize);+ let input_b = blob(3, u2netp::SIZE as usize, u2netp::SIZE as usize);+ report("u2netp", &mut net, &input, &input_b, passes)+}++fn profile_scrfd(path: &str, passes: u32) -> Result<(), String> {+ let weights = load(path, graph::SCRFD)?;+ let context = context::shared()?;+ let started = Instant::now();+ // The bridge builds at the fixed LONG_SIDE square; profile that.+ let plan = scrfd::build(&weights, scrfd::LONG_SIDE, scrfd::LONG_SIDE)?;+ let mut net = Net::new(context, plan, &weights, RESCALE_ONLY)?;+ println!("load {:>8.1} ms (upload + first record)", since(started));+ let side = scrfd::LONG_SIDE as usize;+ let input = pattern(3 * side * side);+ let input_b = blob(3, side, side);+ report("scrfd", &mut net, &input, &input_b, passes)+}++fn profile_mbf(path: &str, passes: u32) -> Result<(), String> {+ let weights = load(path, graph::MOBILEFACENET)?;+ let context = context::shared()?;+ let started = Instant::now();+ let plan = mobilefacenet::build(&weights)?;+ let mut net = Net::new(context, plan, &weights, RESCALE_ONLY)?;+ println!("load {:>8.1} ms (upload + first record)", since(started));+ let input = pattern(3 * mobilefacenet::SIZE as usize * mobilefacenet::SIZE as usize);+ let input_b = blob(3, mobilefacenet::SIZE as usize, mobilefacenet::SIZE as usize);+ report("mbf", &mut net, &input, &input_b, passes)+}++fn profile_det(path: &str, passes: u32) -> Result<(), String> {+ let weights = load(path, graph::PPOCR_DET)?;+ let context = context::shared()?;+ let started = Instant::now();+ // The bridge builds at the fixed LONG_SIDE square; profile that.+ let plan = ppocr_det::build(&weights, ppocr_det::LONG_SIDE, ppocr_det::LONG_SIDE)?;+ let mut net = Net::new(context, plan, &weights, RESCALE_ONLY)?;+ println!("load {:>8.1} ms (upload + first record)", since(started));+ let side = ppocr_det::LONG_SIDE as usize;+ let input = pattern(3 * side * side);+ let input_b = blob(3, side, side);+ report("det", &mut net, &input, &input_b, passes)+}++fn profile_rec(path: &str, passes: u32) -> Result<(), String> {+ let weights = load(path, graph::PPOCR_REC)?;+ let context = context::shared()?;+ let started = Instant::now();+ // The bridge builds at the fixed REC_WIDTH; profile that.+ let plan = ppocr_rec::build(&weights, REC_WIDTH)?;+ let mut net = Net::new(context, plan, &weights, PPOCR_REC)?;+ println!("load {:>8.1} ms (upload + first record)", since(started));+ let input = pattern(3 * ppocr_rec::HEIGHT as usize * REC_WIDTH as usize);+ let input_b = blob(3, ppocr_rec::HEIGHT as usize, REC_WIDTH as usize);+ report("rec", &mut net, &input, &input_b, passes)+}++fn tinyclip_plan(offsets: &Offsets, mode: tinyclip::Mode) -> Result<Plan, String> {+ tinyclip::build(offsets, mode)+}++fn profile_clip_image(path: &str, passes: u32) -> Result<(), String> {+ let weights = load(path, graph::TINYCLIP)?;+ let context = context::shared()?;+ let started = Instant::now();+ let mut nets = Reshaped::new(context, &weights, tinyclip::Mode::Image, tinyclip_plan)?;+ println!("load {:>8.1} ms (upload + first record)", since(started));+ let side = tinyclip::IMAGE_SIZE as usize;+ let input = pattern(3 * side * side);+ let input_b = blob(3, side, side);+ let net = nets.at(tinyclip::Mode::Image)?;+ report("clip_image", net, &input, &input_b, passes)+}++fn profile_clip_text(path: &str, passes: u32) -> Result<(), String> {+ let weights = load(path, graph::TINYCLIP)?;+ let context = context::shared()?;+ let started = Instant::now();+ // `<|startoftext|>`, three pieces, `<|endoftext|>`: a typical short query.+ let ids: Vec<u32> = vec![49406, 1234, 5678, 9012, 49407];+ let embedded = tinyclip::embed_positions(weights.reader(), &ids)?;+ let len = ids.len() as u32;+ let mut nets = Reshaped::new(context, &weights, tinyclip::Mode::Text { len }, tinyclip_plan)?;+ println!("load {:>8.1} ms (upload + first record)", since(started));+ let net = nets.at(tinyclip::Mode::Text { len })?;+ report_many("clip_text", net, &[&embedded], passes)+}++fn profile_maia(path: &str, passes: u32) -> Result<(), String> {+ let weights = load(path, graph::MAIA)?;+ let context = context::shared()?;+ let started = Instant::now();+ let plan = maia::build(&weights)?;+ let mut net = Net::new(context, plan, &weights, RESCALE_ONLY)?;+ println!("load {:>8.1} ms (upload + first record)", since(started));+ // A sparse opening-like board: a few pieces on their squares, both sides at 1500.+ let mut planes = vec![0.0f32; maia::PLANES as usize * maia::SQUARES as usize];+ for (plane, square) in [(5, 12), (5, 52), (4, 1), (4, 57), (11, 4), (11, 60)] {+ planes[plane * maia::SQUARES as usize + square] = 1.0;+ }+ let elo = maia::elo_embedding(weights.reader(), 1500.0)?;+ let tokens = maia::tokens(&planes, &elo, &elo)?;+ report_many("maia", &mut net, &[&tokens], passes)+}++fn print_kinds(label: &str, net: &Net) {+ let times = match net.op_times() {+ Ok(times) => times,+ Err(why) => {+ println!("{label}: {why}");+ return;+ }+ };+ let mut kinds: BTreeMap<String, (usize, f64)> = BTreeMap::new();+ let (mut total, mut gaps) = (0.0, 0.0);+ for (name, us, gap) in × {+ let kind = name.split(": ").nth(1).unwrap_or(name).to_string();+ let entry = kinds.entry(kind).or_default();+ entry.0 += 1;+ entry.1 += us;+ total += us;+ gaps += gap;+ }+ let mut rows: Vec<_> = kinds.into_iter().collect();+ rows.sort_by(|a, b| b.1 .1.total_cmp(&a.1 .1));+ println!();+ println!("{label}: {} dispatches, {:.2} ms in shaders, {:.2} ms in gaps", times.len(), total / 1e3, gaps / 1e3);+ println!(" {:<22} {:>6} {:>10} {:>10}", "kind", "count", "total ms", "mean us");+ for (kind, (count, us)) in rows {+ println!(" {kind:<22} {count:>6} {:>10.3} {:>10.1}", us / 1e3, us / count as f64);+ }+ let top: usize = std::env::var("MODELRUNNER_TOP").ok().and_then(|v| v.parse().ok()).unwrap_or(0);+ let mut slowest: Vec<_> = times.iter().collect();+ slowest.sort_by(|a, b| b.1.total_cmp(&a.1));+ for (name, us, _) in slowest.into_iter().take(top) {+ println!(" top {name:<30} {:>10.3} ms", us / 1e3);+ }+}++fn since(since: Instant) -> f64 {+ since.elapsed().as_secs_f64() * 1e3+}++fn stats(values: &[f64]) -> String {+ if values.is_empty() {+ return "n/a".into();+ }+ let mut sorted = values.to_vec();+ sorted.sort_by(f64::total_cmp);+ let mean = sorted.iter().sum::<f64>() / sorted.len() as f64;+ format!(+ "mean {mean:>8.2} ms median {:>8.2} min {:>8.2} max {:>8.2} (n={})",+ sorted[sorted.len() / 2],+ sorted[0],+ sorted[sorted.len() - 1],+ sorted.len()+ )+}
metadata_data/photos/communicate/phone/1.png
diff --git a/metadata_data/photos/communicate/phone/1.png b/metadata_data/photos/communicate/phone/1.pngindex 10c47bba3f..7643fb72a6 100644Binary files a/metadata_data/photos/communicate/phone/1.png and b/metadata_data/photos/communicate/phone/1.png differ
metadata_data/photos/communicate/phone/2.png
diff --git a/metadata_data/photos/communicate/phone/2.png b/metadata_data/photos/communicate/phone/2.pngindex d2daf65007..59e9529302 100644Binary files a/metadata_data/photos/communicate/phone/2.png and b/metadata_data/photos/communicate/phone/2.png differ
metadata_data/photos/communicate/phone/3.png
diff --git a/metadata_data/photos/communicate/phone/3.png b/metadata_data/photos/communicate/phone/3.pngindex 80685cbacc..da876b488c 100644Binary files a/metadata_data/photos/communicate/phone/3.png and b/metadata_data/photos/communicate/phone/3.png differ
metadata_data/photos/communicate/phone/4.png
diff --git a/metadata_data/photos/communicate/phone/4.png b/metadata_data/photos/communicate/phone/4.pngnew file mode 100644index 0000000000..10c47bba3fBinary files /dev/null and b/metadata_data/photos/communicate/phone/4.png differ
metadata_data/photos/communicate/phone/5.png
diff --git a/metadata_data/photos/communicate/phone/5.png b/metadata_data/photos/communicate/phone/5.pngnew file mode 100644index 0000000000..d2daf65007Binary files /dev/null and b/metadata_data/photos/communicate/phone/5.png differ
metadata_data/photos/communicate/phone/6.png
diff --git a/metadata_data/photos/communicate/phone/6.png b/metadata_data/photos/communicate/phone/6.pngnew file mode 100644index 0000000000..80685cbaccBinary files /dev/null and b/metadata_data/photos/communicate/phone/6.png differ