refactor: migrate TensorFlow Lite to LiteRT
This commit is contained in:
1 parent
4bb567c7c1
commit
bbca4b845d
8 files changed
+249
-247
No files matched your search
@@ -234,9 +234,8 @@ dependencies {
|
||||
debugImplementation(libs.androidx.ui.tooling)
|
||||
debugImplementation(libs.androidx.ui.test.manifest)
|
||||
|
||||
// TensorFlow Lite for Depth Estimator
|
||||
implementation("org.tensorflow:tensorflow-lite:2.17.0")
|
||||
implementation("org.tensorflow:tensorflow-lite-gpu:2.17.0")
|
||||
implementation("org.tensorflow:tensorflow-lite-gpu-api:2.17.0")
|
||||
implementation("org.tensorflow:tensorflow-lite-support:0.5.0")
|
||||
// LiteRT: Interpreter for CPU models, CompiledModel for GPU-accelerated models
|
||||
implementation("com.google.ai.edge.litert:litert:2.3.2")
|
||||
implementation("com.google.ai.edge.litert:litert-gpu:2.3.2")
|
||||
implementation("com.google.ai.edge.litert:litert-support:2.3.2")
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import android.graphics.Paint
|
||||
import android.graphics.RectF
|
||||
import org.tensorflow.lite.DataType
|
||||
import org.tensorflow.lite.Interpreter
|
||||
import org.tensorflow.lite.support.common.FileUtil
|
||||
import com.google.ai.edge.litert.support.common.FileUtil
|
||||
import java.io.Closeable
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
@@ -10,15 +10,13 @@ import com.hinnka.mycamera.utils.PLog
|
||||
import com.hinnka.mycamera.utils.StartupTrace
|
||||
import org.tensorflow.lite.DataType
|
||||
import org.tensorflow.lite.Interpreter
|
||||
import org.tensorflow.lite.nnapi.NnApiDelegate
|
||||
import org.tensorflow.lite.Tensor
|
||||
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer
|
||||
import com.google.ai.edge.litert.support.tensorbuffer.TensorBuffer
|
||||
import java.io.FileInputStream
|
||||
import java.nio.ByteBuffer
|
||||
|
||||
class DepthEstimator(context: Context) {
|
||||
private var interpreter: Interpreter? = null
|
||||
private var nnApiDelegate: NnApiDelegate? = null
|
||||
private var isInitialized = false
|
||||
private var inputWidth = 518
|
||||
private var inputHeight = 518
|
||||
@@ -43,53 +41,18 @@ class DepthEstimator(context: Context) {
|
||||
)
|
||||
}
|
||||
}
|
||||
val delegateCache = MlDelegateCacheFactory.create(
|
||||
context = context,
|
||||
tag = TAG,
|
||||
cacheName = "depth_estimator",
|
||||
modelAssetName = modelFile.name,
|
||||
modelSizeBytes = modelBuffer.capacity(),
|
||||
modelFingerprint = DepthModelManager.installedModelFingerprint(context)
|
||||
)
|
||||
|
||||
// The GPU delegate is deliberately not used: this model can compile but
|
||||
// produce a constant map on affected Qualcomm GLES drivers.
|
||||
PLog.d(TAG, "Depth model: trying NNAPI first")
|
||||
try {
|
||||
val nnApiOptions = Interpreter.Options()
|
||||
nnApiDelegate = StartupTrace.measure("DepthEstimator.NnApiDelegate()") {
|
||||
val delegateOptions = NnApiDelegate.Options()
|
||||
delegateCache?.let {
|
||||
delegateOptions
|
||||
.setCacheDir(it.directory.absolutePath)
|
||||
.setModelToken(it.modelToken)
|
||||
}
|
||||
NnApiDelegate(delegateOptions)
|
||||
}
|
||||
StartupTrace.measure("DepthEstimator.nnApiOptions.addDelegate") {
|
||||
nnApiOptions.addDelegate(nnApiDelegate)
|
||||
}
|
||||
interpreter = StartupTrace.measure("DepthEstimator.Interpreter(NNAPI)") {
|
||||
Interpreter(modelBuffer, nnApiOptions)
|
||||
}
|
||||
isInitialized = true
|
||||
PLog.d(TAG, "Using NNAPI (NPU) for depth model")
|
||||
} catch (e: Exception) {
|
||||
PLog.w(TAG, "Failed to initialize NNAPI delegate, falling back to CPU", e)
|
||||
nnApiDelegate?.close()
|
||||
nnApiDelegate = null
|
||||
}
|
||||
|
||||
// Fallback to CPU
|
||||
if (!isInitialized) {
|
||||
val cpuOptions = Interpreter.Options()
|
||||
cpuOptions.setNumThreads(4)
|
||||
interpreter = StartupTrace.measure("DepthEstimator.Interpreter(CPU)") {
|
||||
Interpreter(modelBuffer, cpuOptions)
|
||||
}
|
||||
isInitialized = true
|
||||
PLog.d(TAG, "Using CPU for depth model")
|
||||
// LiteRT 2.x no longer provides the NNAPI delegate. The GPU accelerator is
|
||||
// deliberately not used: this model can compile but produce a constant map
|
||||
// on affected Qualcomm drivers. XNNPACK runs every supported depth contract,
|
||||
// including quantized inputs and multi-output graphs.
|
||||
val cpuOptions = Interpreter.Options()
|
||||
.setNumThreads(CPU_THREADS)
|
||||
.setUseXNNPACK(true)
|
||||
interpreter = StartupTrace.measure("DepthEstimator.Interpreter(CPU)") {
|
||||
Interpreter(modelBuffer, cpuOptions)
|
||||
}
|
||||
isInitialized = true
|
||||
PLog.d(TAG, "Using CPU/XNNPACK for depth model threads=$CPU_THREADS")
|
||||
|
||||
interpreter?.let {
|
||||
applyModelContract(it, inspectDepthModelContract(it))
|
||||
@@ -336,12 +299,11 @@ class DepthEstimator(context: Context) {
|
||||
fun close() {
|
||||
interpreter?.close()
|
||||
interpreter = null
|
||||
nnApiDelegate?.close()
|
||||
nnApiDelegate = null
|
||||
isInitialized = false
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "DepthEstimator"
|
||||
private const val CPU_THREADS = 4
|
||||
}
|
||||
}
|
||||
@@ -12,13 +12,10 @@ import kotlinx.coroutines.awaitAll
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import com.google.ai.edge.litert.CompiledModel
|
||||
import com.google.ai.edge.litert.support.common.FileUtil
|
||||
import com.google.ai.edge.litert.support.tensorbuffer.TensorBuffer
|
||||
import org.tensorflow.lite.Interpreter
|
||||
import org.tensorflow.lite.gpu.CompatibilityList
|
||||
import org.tensorflow.lite.gpu.GpuDelegate
|
||||
import org.tensorflow.lite.gpu.GpuDelegateFactory
|
||||
import org.tensorflow.lite.nnapi.NnApiDelegate
|
||||
import org.tensorflow.lite.support.common.FileUtil
|
||||
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer
|
||||
import java.nio.ByteBuffer
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
@@ -26,12 +23,10 @@ import java.util.concurrent.atomic.AtomicLong
|
||||
class DnCNNDenoiseEstimator(
|
||||
context: Context,
|
||||
private val modelAssetName: String = MODEL_DNCNN,
|
||||
private val backend: Backend = Backend.AUTO
|
||||
) {
|
||||
private var interpreter: Interpreter? = null
|
||||
private val extraCpuInterpreters = mutableListOf<Interpreter>()
|
||||
private var gpuDelegate: GpuDelegate? = null
|
||||
private var nnApiDelegate: NnApiDelegate? = null
|
||||
private var gpuModel: LiteRtGpuModel? = null
|
||||
private var isInitialized = false
|
||||
private var activeBackend = "none"
|
||||
private var cpuWorkerCount = 1
|
||||
@@ -42,6 +37,9 @@ class DnCNNDenoiseEstimator(
|
||||
private var outputHeight = 256
|
||||
private var inputChannelsFirst = false
|
||||
private var outputChannelsFirst = false
|
||||
private var isRgbModel = false
|
||||
private var outputShape = intArrayOf(1, 256, 256, 1)
|
||||
private var outputDataType = org.tensorflow.lite.DataType.FLOAT32
|
||||
private val interpreterMutex = Mutex()
|
||||
|
||||
init {
|
||||
@@ -49,76 +47,35 @@ class DnCNNDenoiseEstimator(
|
||||
val modelFile = StartupTrace.measure("DnCNNDenoiseEstimator.loadMappedFile") {
|
||||
FileUtil.loadMappedFile(context, modelAssetName)
|
||||
}
|
||||
// Tensor dimensions are read from the plain interpreter: the compiled model
|
||||
// exposes buffer sizes but not shapes.
|
||||
Interpreter(modelFile, Interpreter.Options().setUseXNNPACK(false)).use(::updateTensorDimensions)
|
||||
val elementCount = inputWidth * inputHeight * if (isRgbModel) 3 else 1
|
||||
|
||||
val delegateCache = MlDelegateCacheFactory.create(
|
||||
context = context,
|
||||
tag = TAG,
|
||||
cacheName = "dncnn_denoise",
|
||||
cacheName = "dncnn_denoise_litert",
|
||||
modelAssetName = modelAssetName,
|
||||
modelSizeBytes = modelFile.capacity()
|
||||
)
|
||||
|
||||
if (backend == Backend.AUTO || backend == Backend.GPU) {
|
||||
val compatList = StartupTrace.measure("DnCNNDenoiseEstimator.CompatibilityList()") {
|
||||
CompatibilityList()
|
||||
}
|
||||
val gpuOptions = Interpreter.Options()
|
||||
gpuDelegate = StartupTrace.measure("DnCNNDenoiseEstimator.GpuDelegate()") {
|
||||
val delegateOptions = if (compatList.isDelegateSupportedOnThisDevice) {
|
||||
compatList.bestOptionsForThisDevice
|
||||
} else {
|
||||
GpuDelegateFactory.Options()
|
||||
}
|
||||
delegateCache?.let {
|
||||
delegateOptions.setSerializationParams(
|
||||
it.directory.absolutePath,
|
||||
it.modelToken
|
||||
)
|
||||
}
|
||||
GpuDelegate(delegateOptions)
|
||||
}
|
||||
StartupTrace.measure("DnCNNDenoiseEstimator.gpuOptions.addDelegate") {
|
||||
gpuOptions.addDelegate(gpuDelegate)
|
||||
}
|
||||
try {
|
||||
interpreter = StartupTrace.measure("DnCNNDenoiseEstimator.Interpreter(GPU)") {
|
||||
Interpreter(modelFile, gpuOptions)
|
||||
}
|
||||
isInitialized = true
|
||||
activeBackend = "GPU"
|
||||
PLog.d(TAG, "Using GPU Delegate for DnCNN Denoise: $modelAssetName")
|
||||
} catch (e: Exception) {
|
||||
PLog.w(TAG, "Failed to initialize GPU delegate, falling back to ${if (backend == Backend.AUTO) "NNAPI" else "CPU"}", e)
|
||||
gpuDelegate?.close()
|
||||
gpuDelegate = null
|
||||
}
|
||||
}
|
||||
|
||||
if (backend == Backend.AUTO && !isInitialized) {
|
||||
val nnApiOptions = Interpreter.Options()
|
||||
nnApiDelegate = StartupTrace.measure("DnCNNDenoiseEstimator.NnApiDelegate()") {
|
||||
val delegateOptions = NnApiDelegate.Options()
|
||||
delegateCache?.let {
|
||||
delegateOptions
|
||||
.setCacheDir(it.directory.absolutePath)
|
||||
.setModelToken(it.modelToken)
|
||||
}
|
||||
NnApiDelegate(delegateOptions)
|
||||
}
|
||||
StartupTrace.measure("DnCNNDenoiseEstimator.nnApiOptions.addDelegate") {
|
||||
nnApiOptions.addDelegate(nnApiDelegate)
|
||||
}
|
||||
try {
|
||||
interpreter = StartupTrace.measure("DnCNNDenoiseEstimator.Interpreter(NNAPI)") {
|
||||
Interpreter(modelFile, nnApiOptions)
|
||||
}
|
||||
isInitialized = true
|
||||
activeBackend = "NNAPI"
|
||||
PLog.d(TAG, "Using NNAPI (NPU) for DnCNN Denoise: $modelAssetName")
|
||||
} catch (e: Exception) {
|
||||
PLog.w(TAG, "Failed to initialize NNAPI delegate, falling back to CPU", e)
|
||||
nnApiDelegate?.close()
|
||||
nnApiDelegate = null
|
||||
try {
|
||||
gpuModel = StartupTrace.measure("DnCNNDenoiseEstimator.CompiledModel(GPU)") {
|
||||
LiteRtGpuModel.fromAsset(
|
||||
context = context,
|
||||
assetName = modelAssetName,
|
||||
cache = delegateCache,
|
||||
precision = CompiledModel.GpuOptions.Precision.DEFAULT,
|
||||
inputElementCount = elementCount,
|
||||
outputElementCount = outputWidth * outputHeight * if (isRgbModel) 3 else 1,
|
||||
)
|
||||
}
|
||||
isInitialized = true
|
||||
activeBackend = "GPU"
|
||||
PLog.d(TAG, "Using LiteRT GPU for DnCNN Denoise: $modelAssetName")
|
||||
} catch (e: Exception) {
|
||||
PLog.w(TAG, "Failed to initialize LiteRT GPU, falling back to CPU", e)
|
||||
}
|
||||
|
||||
// Fallback to CPU
|
||||
@@ -128,13 +85,6 @@ class DnCNNDenoiseEstimator(
|
||||
interpreter = StartupTrace.measure("DnCNNDenoiseEstimator.Interpreter(CPU)") {
|
||||
Interpreter(modelFile, cpuOptions)
|
||||
}
|
||||
if (backend == Backend.CPU && cpuWorkerCount > 1) {
|
||||
repeat(cpuWorkerCount - 1) { index ->
|
||||
extraCpuInterpreters += StartupTrace.measure("DnCNNDenoiseEstimator.Interpreter(CPU worker ${index + 2})") {
|
||||
Interpreter(modelFile, createCpuOptions(cpuThreadsPerInterpreter))
|
||||
}
|
||||
}
|
||||
}
|
||||
isInitialized = true
|
||||
activeBackend = "CPU"
|
||||
PLog.d(
|
||||
@@ -143,23 +93,14 @@ class DnCNNDenoiseEstimator(
|
||||
)
|
||||
}
|
||||
|
||||
interpreter?.let {
|
||||
updateTensorDimensions(it)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Error initializing DnCNNDenoiseEstimator: $modelAssetName", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun configureCpuParallelism() {
|
||||
val availableProcessors = Runtime.getRuntime().availableProcessors().coerceAtLeast(1)
|
||||
if (backend == Backend.CPU) {
|
||||
cpuWorkerCount = availableProcessors.coerceIn(2, 4)
|
||||
cpuThreadsPerInterpreter = (availableProcessors / cpuWorkerCount).coerceAtLeast(1)
|
||||
} else {
|
||||
cpuWorkerCount = 1
|
||||
cpuThreadsPerInterpreter = 4
|
||||
}
|
||||
cpuWorkerCount = 1
|
||||
cpuThreadsPerInterpreter = 4
|
||||
}
|
||||
|
||||
private fun createCpuOptions(numThreads: Int): Interpreter.Options {
|
||||
@@ -172,6 +113,9 @@ class DnCNNDenoiseEstimator(
|
||||
private fun updateTensorDimensions(interpreter: Interpreter) {
|
||||
val inputShape = interpreter.getInputTensor(0).shape()
|
||||
val outputShape = interpreter.getOutputTensor(0).shape()
|
||||
this.outputShape = outputShape
|
||||
outputDataType = interpreter.getOutputTensor(0).dataType()
|
||||
isRgbModel = inputShape.last() == 3 || (inputShape.size == 4 && inputShape[1] == 3)
|
||||
|
||||
// typically [1, 1, H, W] or [1, H, W, 1]
|
||||
inputChannelsFirst = inputShape.size == 4 && (inputShape[1] == 1 || inputShape[1] == 3)
|
||||
@@ -244,17 +188,13 @@ class DnCNNDenoiseEstimator(
|
||||
* [strength] (0.0 to 1.0) controls the blending with the original image.
|
||||
*/
|
||||
suspend fun denoise(inputBitmap: Bitmap, strength: Float = 1.0f): Bitmap? {
|
||||
if (!isInitialized || interpreter == null) {
|
||||
if (!isInitialized) {
|
||||
PLog.e(TAG, "DnCNNDenoiseEstimator is not initialized")
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
val inputTensor = interpreter!!.getInputTensor(0)
|
||||
val outputTensor = interpreter!!.getOutputTensor(0)
|
||||
val outputDataType = outputTensor.dataType()
|
||||
|
||||
val isRgb = inputTensor.shape().last() == 3 || (inputChannelsFirst && inputTensor.shape()[1] == 3)
|
||||
val isRgb = isRgbModel
|
||||
val channels = if (isRgb) 3 else 1
|
||||
val buffer = LargeDirectBuffer.allocate(
|
||||
inputWidth.toLong() * inputHeight.toLong() * channels.toLong() * 4L,
|
||||
@@ -264,13 +204,11 @@ class DnCNNDenoiseEstimator(
|
||||
|
||||
preprocessNative(inputBitmap, 0, 0, inputWidth, inputHeight, buffer, isRgb, inputChannelsFirst)
|
||||
|
||||
val outputBuffer = TensorBuffer.createFixedSize(outputTensor.shape(), outputDataType)
|
||||
val outputBuffer = TensorBuffer.createFixedSize(outputShape, outputDataType)
|
||||
|
||||
StartupTrace.measure("DnCNNDenoiseEstimator.Interpreter.run") {
|
||||
StartupTrace.measure("DnCNNDenoiseEstimator.run") {
|
||||
interpreterMutex.withLock {
|
||||
buffer.rewind()
|
||||
outputBuffer.buffer.rewind()
|
||||
interpreter?.run(buffer, outputBuffer.buffer)
|
||||
runInference(buffer, outputBuffer.buffer)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -314,7 +252,7 @@ class DnCNNDenoiseEstimator(
|
||||
strength: Float = 1.0f,
|
||||
onProgress: ((Float) -> Unit)? = null
|
||||
): Bitmap? = coroutineScope {
|
||||
if (!isInitialized || interpreter == null) {
|
||||
if (!isInitialized) {
|
||||
PLog.e(TAG, "DnCNNDenoiseEstimator is not initialized")
|
||||
return@coroutineScope null
|
||||
}
|
||||
@@ -330,11 +268,8 @@ class DnCNNDenoiseEstimator(
|
||||
val totalSteps = ((height + strideY - 1) / strideY) * ((width + strideX - 1) / strideX)
|
||||
var completedSteps = 0
|
||||
|
||||
val inputTensor = interpreter!!.getInputTensor(0)
|
||||
val outputTensor = interpreter!!.getOutputTensor(0)
|
||||
val isRgb = inputTensor.shape().last() == 3 || (inputChannelsFirst && inputTensor.shape()[1] == 3)
|
||||
val isRgb = isRgbModel
|
||||
val channels = if (isRgb) 3 else 1
|
||||
val outputDataType = outputTensor.dataType()
|
||||
var preprocessMs = 0L
|
||||
var inferenceMs = 0L
|
||||
var postprocessMs = 0L
|
||||
@@ -389,7 +324,7 @@ class DnCNNDenoiseEstimator(
|
||||
inputWidth.toLong() * inputHeight.toLong() * channels.toLong() * 4L,
|
||||
"DnCNN worker input"
|
||||
) ?: throw OutOfMemoryError("Failed to allocate DnCNN worker input buffer")
|
||||
val outBuffer = TensorBuffer.createFixedSize(outputTensor.shape(), outputDataType)
|
||||
val outBuffer = TensorBuffer.createFixedSize(outputShape, outputDataType)
|
||||
try {
|
||||
while (true) {
|
||||
val patchIndex = nextPatch.getAndIncrement()
|
||||
@@ -440,7 +375,7 @@ class DnCNNDenoiseEstimator(
|
||||
inputWidth.toLong() * inputHeight.toLong() * channels.toLong() * 4L,
|
||||
"DnCNN patch input"
|
||||
) ?: return@coroutineScope null
|
||||
val outBuffer = TensorBuffer.createFixedSize(outputTensor.shape(), outputDataType)
|
||||
val outBuffer = TensorBuffer.createFixedSize(outputShape, outputDataType)
|
||||
|
||||
try {
|
||||
for (task in patchTasks) {
|
||||
@@ -449,11 +384,9 @@ class DnCNNDenoiseEstimator(
|
||||
preprocessMs += SystemClock.elapsedRealtime() - stageStartMs
|
||||
|
||||
stageStartMs = SystemClock.elapsedRealtime()
|
||||
StartupTrace.measure("DnCNNDenoiseEstimator.Interpreter.run") {
|
||||
StartupTrace.measure("DnCNNDenoiseEstimator.run") {
|
||||
interpreterMutex.withLock {
|
||||
buffer.rewind()
|
||||
outBuffer.buffer.rewind()
|
||||
interpreter?.run(buffer, outBuffer.buffer)
|
||||
runInference(buffer, outBuffer.buffer)
|
||||
}
|
||||
}
|
||||
inferenceMs += SystemClock.elapsedRealtime() - stageStartMs
|
||||
@@ -487,13 +420,25 @@ class DnCNNDenoiseEstimator(
|
||||
return@coroutineScope resultBitmap
|
||||
}
|
||||
|
||||
/** Runs one patch on the active backend; both buffers hold FLOAT32 tensors. */
|
||||
private fun runInference(input: ByteBuffer, output: ByteBuffer) {
|
||||
input.rewind()
|
||||
output.rewind()
|
||||
val gpu = gpuModel
|
||||
if (gpu != null) {
|
||||
val inputValues = FloatArray(input.capacity() / Float.SIZE_BYTES)
|
||||
input.asFloatBuffer().get(inputValues)
|
||||
output.asFloatBuffer().put(gpu.run(inputValues))
|
||||
} else {
|
||||
interpreter?.run(input, output)
|
||||
}
|
||||
}
|
||||
|
||||
fun close() {
|
||||
interpreter?.close()
|
||||
interpreter = null
|
||||
gpuDelegate?.close()
|
||||
gpuDelegate = null
|
||||
nnApiDelegate?.close()
|
||||
nnApiDelegate = null
|
||||
gpuModel?.close()
|
||||
gpuModel = null
|
||||
extraCpuInterpreters.forEach { it.close() }
|
||||
extraCpuInterpreters.clear()
|
||||
isInitialized = false
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.hinnka.mycamera.ml
|
||||
|
||||
import android.content.Context
|
||||
import com.google.ai.edge.litert.Accelerator
|
||||
import com.google.ai.edge.litert.CompiledModel
|
||||
import com.google.ai.edge.litert.TensorBuffer
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* A single-input, single-output FLOAT32 model compiled for the LiteRT GPU accelerator.
|
||||
*
|
||||
* The tensor contract (shape, layout, element type) is validated by the caller with the
|
||||
* plain interpreter before compiling; this class checks the element counts it exchanges.
|
||||
* Instances are not thread-safe and must be created, run and closed on one thread.
|
||||
*/
|
||||
internal class LiteRtGpuModel private constructor(
|
||||
private val model: CompiledModel,
|
||||
private val inputElementCount: Int,
|
||||
private val outputElementCount: Int,
|
||||
) : AutoCloseable {
|
||||
private val inputBuffers: List<TensorBuffer>
|
||||
private val outputBuffers: List<TensorBuffer>
|
||||
|
||||
init {
|
||||
var inputs: List<TensorBuffer> = emptyList()
|
||||
var outputs: List<TensorBuffer> = emptyList()
|
||||
try {
|
||||
inputs = model.createInputBuffers()
|
||||
outputs = model.createOutputBuffers()
|
||||
check(inputs.size == 1 && outputs.size == 1) {
|
||||
"LiteRT GPU model requires one input and one output, " +
|
||||
"actual inputs=${inputs.size} outputs=${outputs.size}"
|
||||
}
|
||||
} catch (error: Throwable) {
|
||||
inputs.forEach(TensorBuffer::close)
|
||||
outputs.forEach(TensorBuffer::close)
|
||||
model.close()
|
||||
throw error
|
||||
}
|
||||
inputBuffers = inputs
|
||||
outputBuffers = outputs
|
||||
}
|
||||
|
||||
fun run(input: FloatArray): FloatArray {
|
||||
require(input.size == inputElementCount) {
|
||||
"Unexpected input size: ${input.size}, expected $inputElementCount"
|
||||
}
|
||||
inputBuffers[0].writeFloat(input)
|
||||
model.run(inputBuffers, outputBuffers)
|
||||
val output = outputBuffers[0].readFloat()
|
||||
check(output.size == outputElementCount) {
|
||||
"Unexpected output size: ${output.size}, expected $outputElementCount"
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
inputBuffers.forEach(TensorBuffer::close)
|
||||
outputBuffers.forEach(TensorBuffer::close)
|
||||
model.close()
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun fromAsset(
|
||||
context: Context,
|
||||
assetName: String,
|
||||
cache: MlDelegateCache?,
|
||||
precision: CompiledModel.GpuOptions.Precision,
|
||||
inputElementCount: Int,
|
||||
outputElementCount: Int,
|
||||
): LiteRtGpuModel {
|
||||
val model = CompiledModel.create(context.assets, assetName, gpuOptions(cache, precision), null)
|
||||
return LiteRtGpuModel(model, inputElementCount, outputElementCount)
|
||||
}
|
||||
|
||||
fun fromFile(
|
||||
file: File,
|
||||
cache: MlDelegateCache?,
|
||||
precision: CompiledModel.GpuOptions.Precision,
|
||||
inputElementCount: Int,
|
||||
outputElementCount: Int,
|
||||
): LiteRtGpuModel {
|
||||
val model = CompiledModel.create(file.absolutePath, gpuOptions(cache, precision), null)
|
||||
return LiteRtGpuModel(model, inputElementCount, outputElementCount)
|
||||
}
|
||||
|
||||
/**
|
||||
* [precision] is part of the compiled program, so callers must use a cache name
|
||||
* that is distinct per precision.
|
||||
*/
|
||||
private fun gpuOptions(
|
||||
cache: MlDelegateCache?,
|
||||
precision: CompiledModel.GpuOptions.Precision,
|
||||
): CompiledModel.Options {
|
||||
return CompiledModel.Options(Accelerator.GPU).apply {
|
||||
gpuOptions = CompiledModel.GpuOptions(
|
||||
precision = precision,
|
||||
serializationDir = cache?.directory?.absolutePath,
|
||||
modelCacheKey = cache?.modelToken,
|
||||
serializeProgramCache = cache != null,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,10 +7,10 @@ import android.graphics.ColorSpace
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Rect
|
||||
import android.os.SystemClock
|
||||
import com.hinnka.mycamera.utils.LargeDirectBuffer
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import java.io.FileInputStream
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.FloatBuffer
|
||||
import java.nio.channels.FileChannel
|
||||
import java.util.concurrent.Executors
|
||||
import kotlinx.coroutines.CancellationException
|
||||
@@ -19,16 +19,14 @@ import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withContext
|
||||
import com.google.ai.edge.litert.CompiledModel
|
||||
import org.tensorflow.lite.DataType
|
||||
import org.tensorflow.lite.Interpreter
|
||||
import org.tensorflow.lite.gpu.CompatibilityList
|
||||
import org.tensorflow.lite.gpu.GpuDelegate
|
||||
import org.tensorflow.lite.gpu.GpuDelegateFactory
|
||||
|
||||
/**
|
||||
* Owns the bundled U2NetP interpreter on one thread for its complete lifetime.
|
||||
* The GPU delegate is preferred; the CPU / XNNPACK interpreter replaces it when
|
||||
* the device does not support it, it fails to build, or a GPU inference fails.
|
||||
* Owns the bundled U2NetP model on one thread for its complete lifetime.
|
||||
* The LiteRT GPU compiled model is preferred; the CPU / XNNPACK interpreter replaces
|
||||
* it when the GPU accelerator is unavailable, fails to compile, or a GPU inference fails.
|
||||
*/
|
||||
object SharedSubjectMaskEstimator {
|
||||
private const val TAG = "SharedSubjectMaskEstimator"
|
||||
@@ -44,17 +42,35 @@ object SharedSubjectMaskEstimator {
|
||||
Thread(runnable, TAG).apply { isDaemon = true }
|
||||
}.asCoroutineDispatcher()
|
||||
|
||||
private class LoadedModel(val interpreter: Interpreter, val gpuDelegate: GpuDelegate?) {
|
||||
val backend: String get() = if (gpuDelegate != null) "GPU" else "CPU/XNNPACK"
|
||||
private sealed interface LoadedModel {
|
||||
val backend: String
|
||||
val isGpu: Boolean
|
||||
fun run(input: FloatArray): FloatArray
|
||||
fun close()
|
||||
}
|
||||
|
||||
fun close() {
|
||||
interpreter.close()
|
||||
gpuDelegate?.close()
|
||||
private class GpuModel(private val runner: LiteRtGpuModel) : LoadedModel {
|
||||
override val backend = "GPU"
|
||||
override val isGpu = true
|
||||
override fun run(input: FloatArray): FloatArray = runner.run(input)
|
||||
override fun close() = runner.close()
|
||||
}
|
||||
|
||||
private class CpuModel(private val interpreter: Interpreter) : LoadedModel {
|
||||
override val backend = "CPU/XNNPACK"
|
||||
override val isGpu = false
|
||||
|
||||
override fun run(input: FloatArray): FloatArray {
|
||||
val values = FloatArray(MODEL_SIZE * MODEL_SIZE)
|
||||
interpreter.run(FloatBuffer.wrap(input), FloatBuffer.wrap(values))
|
||||
return values
|
||||
}
|
||||
|
||||
override fun close() = interpreter.close()
|
||||
}
|
||||
|
||||
// Access, including initialization and destruction, is confined to the dispatcher:
|
||||
// the GPU delegate must be created, run and closed on one thread.
|
||||
// the GPU model is created, run and closed on one thread.
|
||||
private var model: LoadedModel? = null
|
||||
private var gpuDisabled = false
|
||||
|
||||
@@ -107,7 +123,7 @@ object SharedSubjectMaskEstimator {
|
||||
*/
|
||||
private fun infer(context: Context, inputBitmap: Bitmap, crop: DepthSubjectCropPlanner.Crop): SubjectMask {
|
||||
val loaded = model ?: createModel(context).also { model = it }
|
||||
if (loaded.gpuDelegate == null) return runInference(loaded, inputBitmap, crop)
|
||||
if (!loaded.isGpu) return runInference(loaded, inputBitmap, crop)
|
||||
return try {
|
||||
runInference(loaded, inputBitmap, crop)
|
||||
} catch (error: Exception) {
|
||||
@@ -138,50 +154,44 @@ object SharedSubjectMaskEstimator {
|
||||
setNumThreads(CPU_THREADS)
|
||||
setUseXNNPACK(true)
|
||||
}
|
||||
val loaded = LoadedModel(Interpreter(modelBuffer, options), null)
|
||||
val interpreter = Interpreter(modelBuffer, options)
|
||||
try {
|
||||
validateTensors(loaded.interpreter)
|
||||
validateTensors(interpreter)
|
||||
} catch (error: Throwable) {
|
||||
loaded.close()
|
||||
interpreter.close()
|
||||
throw error
|
||||
}
|
||||
val loaded = CpuModel(interpreter)
|
||||
logReady(loaded, startedAt)
|
||||
return loaded
|
||||
}
|
||||
|
||||
/** The GPU interpreter, or null when the delegate is unsupported or fails to build / validate. */
|
||||
/** The GPU compiled model, or null when the accelerator is unavailable or fails to compile / validate. */
|
||||
private fun createGpuModel(context: Context, modelBuffer: ByteBuffer): LoadedModel? {
|
||||
val compatibility = CompatibilityList()
|
||||
try {
|
||||
val delegateOptions = if (compatibility.isDelegateSupportedOnThisDevice) {
|
||||
compatibility.bestOptionsForThisDevice
|
||||
} else {
|
||||
GpuDelegateFactory.Options()
|
||||
}
|
||||
MlDelegateCacheFactory.create(
|
||||
return try {
|
||||
// The tensor contract is checked on the plain interpreter: the compiled model
|
||||
// exposes buffer sizes but not shapes or element types.
|
||||
Interpreter(modelBuffer, Interpreter.Options().setUseXNNPACK(false)).use(::validateTensors)
|
||||
val cache = MlDelegateCacheFactory.create(
|
||||
context = context,
|
||||
tag = TAG,
|
||||
cacheName = "u2netp_subject_mask",
|
||||
cacheName = "u2netp_subject_mask_litert",
|
||||
modelAssetName = MODEL_ASSET,
|
||||
modelSizeBytes = modelBuffer.capacity(),
|
||||
)?.let { cache ->
|
||||
delegateOptions.setSerializationParams(cache.directory.absolutePath, cache.modelToken)
|
||||
}
|
||||
var delegate: GpuDelegate? = null
|
||||
var interpreter: Interpreter? = null
|
||||
return try {
|
||||
delegate = GpuDelegate(delegateOptions)
|
||||
interpreter = Interpreter(modelBuffer, Interpreter.Options().addDelegate(delegate))
|
||||
validateTensors(interpreter)
|
||||
LoadedModel(interpreter, delegate)
|
||||
} catch (error: Exception) {
|
||||
PLog.w(TAG, "U2NetP GPU delegate unavailable; using CPU/XNNPACK", error)
|
||||
interpreter?.close()
|
||||
delegate?.close()
|
||||
null
|
||||
}
|
||||
} finally {
|
||||
compatibility.close()
|
||||
)
|
||||
GpuModel(
|
||||
LiteRtGpuModel.fromAsset(
|
||||
context = context,
|
||||
assetName = MODEL_ASSET,
|
||||
cache = cache,
|
||||
precision = CompiledModel.GpuOptions.Precision.DEFAULT,
|
||||
inputElementCount = MODEL_SIZE * MODEL_SIZE * CHANNEL_COUNT,
|
||||
outputElementCount = MODEL_SIZE * MODEL_SIZE,
|
||||
)
|
||||
)
|
||||
} catch (error: Exception) {
|
||||
PLog.w(TAG, "U2NetP GPU accelerator unavailable; using CPU/XNNPACK", error)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,12 +212,9 @@ object SharedSubjectMaskEstimator {
|
||||
}
|
||||
|
||||
private fun logReady(loaded: LoadedModel, startedAt: Long) {
|
||||
val input = loaded.interpreter.getInputTensor(0)
|
||||
val output = loaded.interpreter.getOutputTensor(0)
|
||||
PLog.d(TAG, "U2NetP ready: backend=${loaded.backend}" +
|
||||
(if (loaded.gpuDelegate == null) " threads=$CPU_THREADS" else "") +
|
||||
" input=${input.shape().contentToString()} output=${output.shape().contentToString()} " +
|
||||
"init=${SystemClock.elapsedRealtime() - startedAt}ms")
|
||||
(if (!loaded.isGpu) " threads=$CPU_THREADS" else "") +
|
||||
" init=${SystemClock.elapsedRealtime() - startedAt}ms")
|
||||
}
|
||||
|
||||
private fun runInference(
|
||||
@@ -217,8 +224,6 @@ object SharedSubjectMaskEstimator {
|
||||
): SubjectMask {
|
||||
val startedAt = SystemClock.elapsedRealtime()
|
||||
var guide: Bitmap? = null
|
||||
var inputBytes: ByteBuffer? = null
|
||||
var outputBytes: ByteBuffer? = null
|
||||
try {
|
||||
// Resize and color-convert in one draw; never allocate a full-size SDR copy.
|
||||
val resized = Bitmap.createBitmap(
|
||||
@@ -240,29 +245,17 @@ object SharedSubjectMaskEstimator {
|
||||
}
|
||||
val inputScale = maximumChannel.coerceAtLeast(1).toFloat()
|
||||
val pixelCount = MODEL_SIZE * MODEL_SIZE
|
||||
val inputBuffer = LargeDirectBuffer.allocate(
|
||||
pixelCount.toLong() * CHANNEL_COUNT * Float.SIZE_BYTES, "U2NetP input",
|
||||
) ?: throw IllegalStateException("Unable to allocate U2NetP input buffer")
|
||||
inputBytes = inputBuffer
|
||||
val outputBuffer = LargeDirectBuffer.allocate(
|
||||
pixelCount.toLong() * Float.SIZE_BYTES, "U2NetP output",
|
||||
) ?: throw IllegalStateException("Unable to allocate U2NetP output buffer")
|
||||
outputBytes = outputBuffer
|
||||
val input = inputBuffer.asFloatBuffer()
|
||||
val output = outputBuffer.asFloatBuffer()
|
||||
val input = FloatArray(pixelCount * CHANNEL_COUNT)
|
||||
var inputIndex = 0
|
||||
for (pixel in pixels) {
|
||||
input.put((((pixel ushr 16) and 0xff) / inputScale - INPUT_MEAN[0]) / INPUT_STD[0])
|
||||
input.put((((pixel ushr 8) and 0xff) / inputScale - INPUT_MEAN[1]) / INPUT_STD[1])
|
||||
input.put(((pixel and 0xff) / inputScale - INPUT_MEAN[2]) / INPUT_STD[2])
|
||||
input[inputIndex++] = (((pixel ushr 16) and 0xff) / inputScale - INPUT_MEAN[0]) / INPUT_STD[0]
|
||||
input[inputIndex++] = (((pixel ushr 8) and 0xff) / inputScale - INPUT_MEAN[1]) / INPUT_STD[1]
|
||||
input[inputIndex++] = ((pixel and 0xff) / inputScale - INPUT_MEAN[2]) / INPUT_STD[2]
|
||||
}
|
||||
input.rewind()
|
||||
output.rewind()
|
||||
val runStartedAt = SystemClock.elapsedRealtime()
|
||||
loaded.interpreter.run(input, output)
|
||||
val values = loaded.run(input)
|
||||
val runFinishedAt = SystemClock.elapsedRealtime()
|
||||
output.rewind()
|
||||
val values = FloatArray(pixelCount)
|
||||
output.get(values)
|
||||
check(values.size == pixelCount) { "Unexpected U2NetP output size: ${values.size}" }
|
||||
var minimum = Float.POSITIVE_INFINITY
|
||||
var maximum = Float.NEGATIVE_INFINITY
|
||||
for ((index, value) in values.withIndex()) {
|
||||
@@ -287,8 +280,6 @@ object SharedSubjectMaskEstimator {
|
||||
crop.right.toFloat() / inputBitmap.width, crop.bottom.toFloat() / inputBitmap.height,
|
||||
))
|
||||
} finally {
|
||||
LargeDirectBuffer.free(outputBytes)
|
||||
LargeDirectBuffer.free(inputBytes)
|
||||
guide?.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import com.hinnka.mycamera.processor.PhotonCoreImagingTuning
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import org.tensorflow.lite.DataType
|
||||
import org.tensorflow.lite.Interpreter
|
||||
import org.tensorflow.lite.support.common.FileUtil
|
||||
import com.google.ai.edge.litert.support.common.FileUtil
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import kotlin.math.abs
|
||||
|
||||
@@ -6,7 +6,7 @@ import com.hinnka.mycamera.preview.PortraitMaskSnapshot
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import org.tensorflow.lite.DataType
|
||||
import org.tensorflow.lite.Interpreter
|
||||
import org.tensorflow.lite.support.common.FileUtil
|
||||
import com.google.ai.edge.litert.support.common.FileUtil
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
|
||||
Reference in new issue
Block a user