Skip to content

Bug: GPU Delegate failure causes predictor to be null, inference completely fails without CPU fallback #419

@dmjtian

Description

@dmjtian

Search before asking

Project area

Plugin API

Bug

Bug Description

When TensorFlow Lite GPU Delegate fails at runtime (e.g., out of memory, unsupported operations), the Interpreter constructor throws an exception that is not caught. This causes the predictor to remain null, and all inference is skipped silently.

This issue was discovered while debugging Issue #413 - the CLASSIFY task showed FPS: 0.0 and 0 detections because the GPU Delegate failed to initialize.

Error Logs

E/YOLOView: java.lang.IllegalArgumentException: Internal error: Failed to apply delegate: Failed to build program executable - Out of host memory
E/YOLOView: TfLiteGpuDelegate Prepare: delegate is not initialized
E/YOLOView: Node number 517 (TfLiteGpuDelegateV2) failed to prepare.
W/YOLOView: predictor is null, skipping inference

Root Cause

In all Predictor classes (Classifier.kt, ObjectDetector.kt, Segmenter.kt, PoseEstimator.kt, ObbDetector.kt), the GPU Delegate is added in interpreterOptions, but if the Interpreter constructor fails at runtime, there's no try-catch to fall back to CPU mode:

// Current code - no fallback
interpreter = Interpreter(modelBuffer, interpreterOptions)  // Throws exception if GPU fails

Expected Behavior

When GPU Delegate fails, the code should automatically fall back to CPU inference instead of leaving predictor as null.

Suggested Fix

Wrap Interpreter creation in try-catch and retry with CPU-only options:

interpreter = try {
    Interpreter(modelBuffer, interpreterOptions)
} catch (e: Exception) {
    if (gpuDelegateRequested) {
        Log.w(TAG, "GPU delegate failed at runtime, falling back to CPU: ${e.message}")
        gpuDelegate?.close()
        val cpuOptions = Interpreter.Options().apply { setNumThreads(4) }
        Interpreter(modelBuffer, cpuOptions)
    } else {
        throw e
    }
}

Affected Files

- android/src/main/kotlin/com/ultralytics/yolo/Classifier.kt
- android/src/main/kotlin/com/ultralytics/yolo/ObjectDetector.kt
- android/src/main/kotlin/com/ultralytics/yolo/Segmenter.kt
- android/src/main/kotlin/com/ultralytics/yolo/PoseEstimator.kt
- android/src/main/kotlin/com/ultralytics/yolo/ObbDetector.kt

Related Issues

- #413 (CLASSIFY task not outputting results)


### Environment

### Environment

- Device: Redmi K60
- Flutter:  3.38.5
- Plugin version: latest main branch


### Minimal Reproducible Example

_No response_

### Additional

_No response_

### Are you willing to submit a PR?

- [x] Yes I'd like to help by submitting a PR!

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingenhancementNew feature or request

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions