java.lang.IllegalArgumentException: невозможно скопировать из тензора TensorFlowLite (StatefulPartitionedCall:8) с 393216 байтами в буфер Java с 512 байт.
Я взял модель головы gpt2 с обнимающего лица и преобразовал ее в tensorflowlite, прикрепил файл модели в папку ресурсов Android и попытался загрузить модель gpt2 в android. здесь входные данные должны быть строкой, которые передаются в функцию генерации текста и хотят вернуть выходные данные в качестве ответа. Я прикрепил свой код и форму входных данных выше. Я получаю вышеуказанную ошибку при запросе ответа из файла loadModel.
Подробности входной_модели
[{'name' : 'serving_default_input_1:0', 'index': 0, 'shape': массив([1, 64], dtype=int32), 'shape_signature': массив([1, 64], dtype=int32), 'dtype': , 'quantization': (0.0, 0), 'quantization_parameters': {'scales': array([], dtype=float32), 'zero_points' : array([], dtype=int32), 'quantized_dimension': 0}, 'sparsity_parameters': {}}]
LoadModel.kt
Код: Выделить всё
class LoadModel(context: Context) {
private var tflite: Interpreter? = null
init {
try {
tflite = Interpreter(loadModelFile(context, "gpt2_model.tflite"))
} catch (e: Exception) {
e.printStackTrace()
}
}
@Throws(Exception::class)
private fun loadModelFile(context: Context, modelName: String): MappedByteBuffer {
val fileInputStream = FileInputStream(context.assets.openFd(modelName).fileDescriptor)
val fileChannel = fileInputStream.channel
val startOffset = context.assets.openFd(modelName).startOffset
val declaredLength = context.assets.openFd(modelName).declaredLength
return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength)
}
fun generateText(inputText: String): String {
// Prepare input tensor
val inputBuffer = ByteBuffer.allocateDirect(64 * 4) // 64 tokens * 4 bytes each
inputBuffer.order(ByteOrder.nativeOrder())
var tokens = tokenize(inputText) // Implement your tokenizer
if (tokens.size > 64) {
tokens = Arrays.copyOfRange(tokens, 0, 64) // Truncate to 64 tokens
}
for (token in tokens) {
inputBuffer.putInt(token)
}
System.out.println("Number of tokens: " + tokens.size);
val paddingToken = 0
for (i in tokens.size..63) {
inputBuffer.putInt(paddingToken)
}
// Prepare output tensor
val outputBuffer = ByteBuffer.allocateDirect(128 * 4) // Adjust buffer size if needed
outputBuffer.order(ByteOrder.nativeOrder())
// Run inference
tflite!!.run(inputBuffer, outputBuffer)
// Decode the output tensor into text (you may need a detokenizer here)
val outputText = detokenize(outputBuffer) // Implement this method for your tokenizer logic
return outputText
}
private fun tokenize(inputText: String): IntArray {
// Implement your tokenizer logic to convert text into tokens (int array)
// This is specific to your GPT-2 tokenizer
return intArrayOf()
}
private fun detokenize(outputBuffer: ByteBuffer): String {
// Implement your detokenizer logic to convert tokens (int array) back into text
return "Generated text"
}
fun close() {
if (tflite != null) {
tflite!!.close() // Properly release TensorFlow Lite interpreter resources
tflite = null
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... ndroid-app