Khunndev Cursor commited on
Commit
d64e218
·
1 Parent(s): 06bdaca

Prevent renderer OOM crash on low-memory devices (offload heavy jobs to server, cap result canvas, lighter warmup)

Browse files
frontend/src/App.tsx CHANGED
@@ -1,6 +1,6 @@
1
  import { useEffect, useRef, useState } from 'react'
2
  import { assignDiameterGroups, countByGroup } from './lib/clustering'
3
- import { getActiveBackend, loadModel, runDetection } from './lib/inference'
4
  import { isServerDetectAvailable, serverDetect } from './lib/serverDetect'
5
  import { t } from './lib/i18n'
6
  import type { Detection, DiameterGroup, Lang } from './lib/types'
@@ -134,7 +134,14 @@ export default function App() {
134
  try {
135
  let dets: Detection[]
136
 
137
- if (engine === 'server') {
 
 
 
 
 
 
 
138
  if (!imageFile) throw new Error('Image unavailable for server detection')
139
  dets = await detectServer(imageFile)
140
  } else {
 
1
  import { useEffect, useRef, useState } from 'react'
2
  import { assignDiameterGroups, countByGroup } from './lib/clustering'
3
+ import { getActiveBackend, isLowMemoryDevice, loadModel, runDetection } from './lib/inference'
4
  import { isServerDetectAvailable, serverDetect } from './lib/serverDetect'
5
  import { t } from './lib/i18n'
6
  import type { Detection, DiameterGroup, Lang } from './lib/types'
 
134
  try {
135
  let dets: Detection[]
136
 
137
+ // Big photos on low-memory phones can crash the browser tab (renderer OOM)
138
+ // during local inference. When the server fallback is reachable, offload
139
+ // these heavy jobs to it instead of risking a crash.
140
+ const megapixels = (imageDims.w * imageDims.h) / 1_000_000
141
+ const offloadHeavy =
142
+ engine === 'local' && serverAvailable && !!imageFile && isLowMemoryDevice() && megapixels >= 4
143
+
144
+ if (engine === 'server' || offloadHeavy) {
145
  if (!imageFile) throw new Error('Image unavailable for server detection')
146
  dets = await detectServer(imageFile)
147
  } else {
frontend/src/components/ResultCanvas.tsx CHANGED
@@ -5,8 +5,24 @@
5
  * Tap during animation to skip to the final frame.
6
  */
7
  import { useEffect, useRef, useState } from 'react'
 
8
  import type { Detection, DiameterGroup, ToolMode } from '../lib/types'
9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  // ---------------------------------------------------------------------------
11
  // helpers
12
  // ---------------------------------------------------------------------------
@@ -178,12 +194,17 @@ export function ResultCanvas({
178
  const ctx = canvas.getContext('2d')
179
  if (!ctx) return
180
 
181
- // Draw at full natural resolution — CSS width:100% scales it down visually.
182
- // This keeps the photo and circles crisp on all screen densities.
 
 
183
  const displayW = canvas.parentElement?.clientWidth ?? image.naturalWidth
184
- const displayPx = displayW / image.naturalWidth // CSS px per canvas px
185
- canvas.width = image.naturalWidth
186
- canvas.height = image.naturalHeight
 
 
 
187
 
188
  onCanvasReady?.(canvas)
189
 
@@ -203,8 +224,8 @@ export function ResultCanvas({
203
  if (startTs === null) startTs = ts
204
  const elapsed = skipRef.current ? totalMs + 1 : ts - startTs
205
 
206
- ctx!.clearRect(0, 0, canvas.width, canvas.height)
207
- ctx!.drawImage(image, 0, 0, canvas.width, canvas.height)
208
 
209
  let visibleCount = 0
210
 
@@ -237,8 +258,8 @@ export function ResultCanvas({
237
  rafRef.current = requestAnimationFrame(frame)
238
  } else {
239
  // final static redraw with all circles fully complete
240
- ctx!.clearRect(0, 0, canvas.width, canvas.height)
241
- ctx!.drawImage(image, 0, 0, canvas.width, canvas.height)
242
  sorted.forEach(({ d, origIdx }) => {
243
  const group = groups.find((g) => g.id === d.groupId) ?? groups[0]
244
  const color = group?.color ?? '#ef4444'
@@ -273,16 +294,21 @@ export function ResultCanvas({
273
  const ctx = canvas.getContext('2d')
274
  if (!ctx) return
275
 
276
- // Ensure canvas is still at full natural resolution after animation
277
- if (canvas.width !== image.naturalWidth) {
278
- canvas.width = image.naturalWidth
279
- canvas.height = image.naturalHeight
 
 
 
 
280
  }
281
- const displayW = canvas.parentElement?.clientWidth ?? image.naturalWidth
282
- const displayPx = displayW / image.naturalWidth
 
283
 
284
- ctx.clearRect(0, 0, canvas.width, canvas.height)
285
- ctx.drawImage(image, 0, 0, canvas.width, canvas.height)
286
 
287
  const dense = detections.length > 300
288
  const showLabels = detections.length <= 3000
@@ -324,14 +350,18 @@ export function ResultCanvas({
324
  const ctx = canvas.getContext('2d')
325
  if (!ctx) return
326
 
327
- const displayW = canvas.parentElement?.clientWidth ?? image.naturalWidth
328
- const displayPx = displayW / image.naturalWidth
 
 
 
329
  const dense = detections.length > 300
330
  const showLabels = detections.length <= 3000
331
  const minR = (dense ? 5 : 7) / displayPx
332
 
333
- ctx.clearRect(0, 0, canvas.width, canvas.height)
334
- ctx.drawImage(image, 0, 0, canvas.width, canvas.height)
 
335
 
336
  detections.forEach((d, idx) => {
337
  const group = groups.find((g) => g.id === d.groupId) ?? groups[0]
 
5
  * Tap during animation to skip to the final frame.
6
  */
7
  import { useEffect, useRef, useState } from 'react'
8
+ import { isLowMemoryDevice } from '../lib/inference'
9
  import type { Detection, DiameterGroup, ToolMode } from '../lib/types'
10
 
11
+ /**
12
+ * Render scale for the result canvas.
13
+ *
14
+ * Drawing the photo at full resolution (e.g. a 12 MP phone photo => ~48 MB
15
+ * canvas, redrawn every animation frame) can crash the tab on low-RAM devices.
16
+ * We cap the canvas buffer size and use ctx.setTransform() so all detection
17
+ * coordinate math can stay in natural pixels. Capable devices keep near-full
18
+ * resolution so the result stays crisp.
19
+ */
20
+ function computeRenderScale(naturalW: number, naturalH: number): number {
21
+ const longSide = Math.max(naturalW, naturalH)
22
+ const cap = isLowMemoryDevice() ? 2200 : 4096
23
+ return Math.min(1, cap / longSide)
24
+ }
25
+
26
  // ---------------------------------------------------------------------------
27
  // helpers
28
  // ---------------------------------------------------------------------------
 
194
  const ctx = canvas.getContext('2d')
195
  if (!ctx) return
196
 
197
+ // Canvas buffer is capped on low-memory devices; ctx.setTransform(rs,rs)
198
+ // lets all drawing below keep using natural-pixel coordinates. CSS
199
+ // width:100% then scales the buffer to the display width.
200
+ const rs = computeRenderScale(image.naturalWidth, image.naturalHeight)
201
  const displayW = canvas.parentElement?.clientWidth ?? image.naturalWidth
202
+ const displayPx = displayW / image.naturalWidth // CSS px per natural px
203
+ const natW = image.naturalWidth
204
+ const natH = image.naturalHeight
205
+ canvas.width = Math.round(natW * rs)
206
+ canvas.height = Math.round(natH * rs)
207
+ ctx.setTransform(rs, 0, 0, rs, 0, 0)
208
 
209
  onCanvasReady?.(canvas)
210
 
 
224
  if (startTs === null) startTs = ts
225
  const elapsed = skipRef.current ? totalMs + 1 : ts - startTs
226
 
227
+ ctx!.clearRect(0, 0, natW, natH)
228
+ ctx!.drawImage(image, 0, 0, natW, natH)
229
 
230
  let visibleCount = 0
231
 
 
258
  rafRef.current = requestAnimationFrame(frame)
259
  } else {
260
  // final static redraw with all circles fully complete
261
+ ctx!.clearRect(0, 0, natW, natH)
262
+ ctx!.drawImage(image, 0, 0, natW, natH)
263
  sorted.forEach(({ d, origIdx }) => {
264
  const group = groups.find((g) => g.id === d.groupId) ?? groups[0]
265
  const color = group?.color ?? '#ef4444'
 
294
  const ctx = canvas.getContext('2d')
295
  if (!ctx) return
296
 
297
+ // Keep the (capped) canvas buffer in sync with the image.
298
+ const rs = computeRenderScale(image.naturalWidth, image.naturalHeight)
299
+ const natW = image.naturalWidth
300
+ const natH = image.naturalHeight
301
+ const scaledW = Math.round(natW * rs)
302
+ if (canvas.width !== scaledW) {
303
+ canvas.width = scaledW
304
+ canvas.height = Math.round(natH * rs)
305
  }
306
+ const displayW = canvas.parentElement?.clientWidth ?? natW
307
+ const displayPx = displayW / natW
308
+ ctx.setTransform(rs, 0, 0, rs, 0, 0)
309
 
310
+ ctx.clearRect(0, 0, natW, natH)
311
+ ctx.drawImage(image, 0, 0, natW, natH)
312
 
313
  const dense = detections.length > 300
314
  const showLabels = detections.length <= 3000
 
350
  const ctx = canvas.getContext('2d')
351
  if (!ctx) return
352
 
353
+ const rs = computeRenderScale(image.naturalWidth, image.naturalHeight)
354
+ const natW = image.naturalWidth
355
+ const natH = image.naturalHeight
356
+ const displayW = canvas.parentElement?.clientWidth ?? natW
357
+ const displayPx = displayW / natW
358
  const dense = detections.length > 300
359
  const showLabels = detections.length <= 3000
360
  const minR = (dense ? 5 : 7) / displayPx
361
 
362
+ ctx.setTransform(rs, 0, 0, rs, 0, 0)
363
+ ctx.clearRect(0, 0, natW, natH)
364
+ ctx.drawImage(image, 0, 0, natW, natH)
365
 
366
  detections.forEach((d, idx) => {
367
  const group = groups.find((g) => g.id === d.groupId) ?? groups[0]
frontend/src/lib/inference.ts CHANGED
@@ -33,6 +33,18 @@ function resolveThreadCount(): number {
33
  ort.env.wasm.numThreads = resolveThreadCount()
34
  ort.env.wasm.simd = true
35
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  // WebGPU often *creates* a session on cheap Android GPUs but then throws at
37
  // run() time. We pre-check for a usable adapter and additionally warm up each
38
  // session so a broken backend is rejected before we depend on it.
@@ -60,6 +72,9 @@ const MODEL_WARMUP_SIZE: Record<string, number> = {
60
 
61
  let sessionCache = new Map<string, Promise<ort.InferenceSession>>()
62
  let activeBackend = 'loading'
 
 
 
63
 
64
  async function warmUp(session: ort.InferenceSession, size: number): Promise<void> {
65
  const dummy = new ort.Tensor('float32', new Float32Array(3 * size * size), [1, 3, size, size])
@@ -83,8 +98,12 @@ async function createSession(modelUrl: string): Promise<ort.InferenceSession> {
83
  executionProviders: backend.providers,
84
  graphOptimizationLevel: 'all',
85
  })
86
- // Validate the backend actually runs — catches GPUs that init but fail at run().
87
- await warmUp(session, warmSize)
 
 
 
 
88
  activeBackend = backend.name
89
  return session
90
  } catch (err) {
 
33
  ort.env.wasm.numThreads = resolveThreadCount()
34
  ort.env.wasm.simd = true
35
 
36
+ // Device memory in GB (Chrome/Android only; capped at 8, undefined elsewhere).
37
+ export function getDeviceMemoryGB(): number | undefined {
38
+ const m = (navigator as unknown as { deviceMemory?: number }).deviceMemory
39
+ return typeof m === 'number' && m > 0 ? m : undefined
40
+ }
41
+
42
+ // Heuristic for memory-constrained devices (typical low-price Android phones).
43
+ export function isLowMemoryDevice(): boolean {
44
+ const m = getDeviceMemoryGB()
45
+ return m !== undefined && m <= 4
46
+ }
47
+
48
  // WebGPU often *creates* a session on cheap Android GPUs but then throws at
49
  // run() time. We pre-check for a usable adapter and additionally warm up each
50
  // session so a broken backend is rejected before we depend on it.
 
72
 
73
  let sessionCache = new Map<string, Promise<ort.InferenceSession>>()
74
  let activeBackend = 'loading'
75
+ // Once a backend has proven it can actually run inference we don't warm up
76
+ // subsequent (larger) models — a 1024 warmup is heavy and risks OOM on phones.
77
+ let backendValidated = false
78
 
79
  async function warmUp(session: ort.InferenceSession, size: number): Promise<void> {
80
  const dummy = new ort.Tensor('float32', new Float32Array(3 * size * size), [1, 3, size, size])
 
98
  executionProviders: backend.providers,
99
  graphOptimizationLevel: 'all',
100
  })
101
+ // Validate the backend can actually run (catches GPUs that init but fail
102
+ // at run()) — but only once, to avoid a costly large-model warmup.
103
+ if (!backendValidated) {
104
+ await warmUp(session, warmSize)
105
+ backendValidated = true
106
+ }
107
  activeBackend = backend.name
108
  return session
109
  } catch (err) {