เริ่มต้นใช้งาน LiteRT

คู่มือนี้จะแนะนำกระบวนการเรียกใช้โมเดล LiteRT (ย่อมาจาก Lite Runtime) ในอุปกรณ์เพื่อทำการคาดการณ์ตามข้อมูลที่ป้อน ซึ่งทำได้ด้วยตัวแปล LiteRT ซึ่งใช้การจัดลำดับกราฟแบบคงที่และตัวจัดสรรหน่วยความจำที่กำหนดเอง (แบบไดนามิกน้อยกว่า) เพื่อให้มั่นใจว่าเวลาในการโหลด การเริ่มต้น และการดำเนินการจะน้อยที่สุด

โดยปกติแล้ว การอนุมาน LiteRT จะมีขั้นตอนดังนี้

  1. การโหลดโมเดล: โหลด.tfliteโมเดลลงในหน่วยความจำ ซึ่งมี กราฟการดำเนินการของโมเดล

  2. การเปลี่ยนรูปแบบข้อมูล: เปลี่ยนรูปแบบข้อมูลนำเข้าเป็นรูปแบบและมิติข้อมูลที่คาดไว้ โดยทั่วไปแล้ว ข้อมูลอินพุตดิบสำหรับโมเดลจะไม่ตรงกับรูปแบบข้อมูลอินพุตที่โมเดลคาดไว้ เช่น คุณอาจต้องปรับขนาด รูปภาพหรือเปลี่ยนรูปแบบรูปภาพให้เข้ากันได้กับโมเดล

  3. การเรียกใช้การอนุมาน: เรียกใช้โมเดล LiteRT เพื่อทำการคาดการณ์ ขั้นตอนนี้เกี่ยวข้องกับการใช้ LiteRT API เพื่อเรียกใช้โมเดล ซึ่งเกี่ยวข้องกับขั้นตอนต่างๆ เช่น การสร้างอินเทอร์พรีเตอร์และการจัดสรรเทนเซอร์

  4. การตีความเอาต์พุต: ตีความเทนเซอร์เอาต์พุตในลักษณะที่มีความหมาย ซึ่งมีประโยชน์ในแอปพลิเคชันของคุณ เช่น โมเดลอาจแสดงผลเฉพาะ รายการความน่าจะเป็น คุณต้องเป็นผู้เชื่อมโยงความน่าจะเป็นกับหมวดหมู่ที่เกี่ยวข้อง และจัดรูปแบบเอาต์พุต

คู่มือนี้อธิบายวิธีเข้าถึงอินเทอร์พรีเตอร์ LiteRT และทำการอนุมานโดยใช้ C++, Java และ Python

แพลตฟอร์มที่รองรับ

API การอนุมานของ TensorFlow มีให้ใช้งานในแพลตฟอร์มอุปกรณ์เคลื่อนที่และอุปกรณ์ฝังตัวที่ใช้กันมากที่สุด เช่น Android, iOS และ Linux ในภาษาโปรแกรมหลายภาษา

ในกรณีส่วนใหญ่ การออกแบบ API จะแสดงให้เห็นว่าเราให้ความสำคัญกับประสิทธิภาพมากกว่าความสะดวกในการใช้งาน LiteRT ออกแบบมาเพื่อการอนุมานที่รวดเร็วในอุปกรณ์ขนาดเล็ก ดังนั้น API จึงหลีกเลี่ยง การคัดลอกที่ไม่จำเป็นเพื่อแลกกับความสะดวก

ในไลบรารีทั้งหมด API ของ LiteRT ช่วยให้คุณโหลดโมเดล ป้อนอินพุต และ ดึงข้อมูลเอาต์พุตการอนุมานได้

แพลตฟอร์ม Android

ใน Android คุณสามารถทำการอนุมาน LiteRT ได้โดยใช้ Java หรือ C++ API Java API มอบความสะดวกและสามารถใช้ได้โดยตรงภายในคลาส Activity ของ Android API ของ C++ มีความยืดหยุ่นและรวดเร็วกว่า แต่คุณอาจต้องเขียน Wrapper ของ JNI เพื่อย้ายข้อมูลระหว่างเลเยอร์ Java และ C++

ดูข้อมูลเพิ่มเติมได้ที่ส่วน C++ และ Java หรือ ทำตามการเริ่มต้นใช้งาน Android อย่างรวดเร็ว

แพลตฟอร์ม iOS

ใน iOS, LiteRT จะพร้อมใช้งานในไลบรารี Swift และ Objective-C ของ iOS คุณยังใช้ C API ในโค้ด Objective-C ได้โดยตรงด้วย

ดูส่วน Swift, Objective-C และ C API หรือทำตามการเริ่มต้นใช้งาน iOS อย่างรวดเร็ว

แพลตฟอร์ม Linux

ในแพลตฟอร์ม Linux คุณสามารถเรียกใช้การอนุมานโดยใช้ LiteRT API ที่มีใน C++

โหลดและเรียกใช้โมเดล

การโหลดและเรียกใช้โมเดล LiteRT มีขั้นตอนดังนี้

  1. โหลดโมเดลลงในหน่วยความจำ
  2. การสร้าง Interpreter โดยอิงตามโมเดลที่มีอยู่
  3. การตั้งค่าเทนเซอร์อินพุต
  4. การเรียกใช้การอนุมาน
  5. แสดงค่า Tensor

Android (Java)

Java API สำหรับการเรียกใช้การอนุมานด้วย LiteRT ออกแบบมาเพื่อใช้กับ Android เป็นหลัก จึงพร้อมใช้งานเป็นทรัพยากร Dependency ของไลบรารี Android ดังนี้ com.google.ai.edge.litert

ใน Java คุณจะใช้คลาส Interpreter เพื่อโหลดโมเดลและขับเคลื่อนการอนุมานโมเดล ในหลายๆ กรณี นี่อาจเป็น API เดียวที่คุณต้องการ

คุณเริ่มต้น Interpreter ได้โดยใช้ไฟล์ FlatBuffers (.tflite) ดังนี้

public Interpreter(@NotNull File modelFile);

หรือใช้ MappedByteBuffer

public Interpreter(@NotNull MappedByteBuffer mappedByteBuffer);

ในทั้ง 2 กรณี คุณต้องระบุโมเดล LiteRT ที่ถูกต้องหรือ API จะแสดงข้อผิดพลาด IllegalArgumentException หากคุณใช้ MappedByteBuffer เพื่อเริ่มต้น Interpreter คุณต้องคงค่าเดิมไว้ตลอดอายุการใช้งานของ Interpreter

วิธีที่แนะนำในการเรียกใช้การอนุมานในโมเดลคือการใช้ลายเซ็น ซึ่งพร้อมใช้งาน สำหรับโมเดลที่แปลงตั้งแต่ TensorFlow 2.5 เป็นต้นไป

try (Interpreter interpreter = new Interpreter(file_of_tensorflowlite_model)) {
  Map<String, Object> inputs = new HashMap<>();
  inputs.put("input_1", input1);
  inputs.put("input_2", input2);
  Map<String, Object> outputs = new HashMap<>();
  outputs.put("output_1", output1);
  interpreter.runSignature(inputs, outputs, "mySignature");
}

เมธอด runSignature รับอาร์กิวเมนต์ 3 รายการ ดังนี้

  • อินพุต : แมปสำหรับอินพุตจากชื่ออินพุตในลายเซ็นไปยังออบเจ็กต์อินพุต

  • เอาต์พุต : แมปสำหรับการแมปเอาต์พุตจากชื่อเอาต์พุตในลายเซ็นไปยังข้อมูลเอาต์พุต

  • ชื่อลายเซ็น (ไม่บังคับ): ชื่อลายเซ็น (ปล่อยว่างไว้ได้หากโมเดลมีลายเซ็นเดียว)

อีกวิธีในการเรียกใช้การอนุมานเมื่อโมเดลไม่มีลายเซ็นที่กำหนด เพียงโทรหา Interpreter.run() เช่น

try (Interpreter interpreter = new Interpreter(file_of_a_tensorflowlite_model)) {
  interpreter.run(input, output);
}

run() รับอินพุตเพียงรายการเดียวและแสดงผลลัพธ์เพียงรายการเดียว ดังนั้นหากโมเดลมีอินพุตหรือเอาต์พุตหลายรายการ ให้ใช้สิ่งต่อไปนี้แทน

interpreter.runForMultipleInputsOutputs(inputs, map_of_indices_to_outputs);

ในกรณีนี้ รายการแต่ละรายการใน inputs จะสอดคล้องกับอินพุตเทนเซอร์ และ map_of_indices_to_outputs จะเชื่อมโยงดัชนีของเอาต์พุตเทนเซอร์กับข้อมูลเอาต์พุตที่สอดคล้องกัน

ในทั้ง 2 กรณี ดัชนีเทนเซอร์ควรสอดคล้องกับค่าที่คุณระบุให้กับตัวแปลง LiteRT เมื่อสร้างโมเดล โปรดทราบว่าลำดับของเทนเซอร์ใน input ต้องตรงกับลำดับที่ระบุ ให้กับ LiteRT Converter

คลาส Interpreter ยังมีฟังก์ชันที่สะดวกสำหรับคุณในการรับดัชนีของอินพุตหรือเอาต์พุตของโมเดลโดยใช้ชื่อการดำเนินการ

public int getInputIndex(String opName);
public int getOutputIndex(String opName);

หาก opName ไม่ใช่การดำเนินการที่ถูกต้องในโมเดล ระบบจะแสดง IllegalArgumentException

นอกจากนี้ โปรดทราบว่า Interpreter เป็นเจ้าของทรัพยากร หากต้องการหลีกเลี่ยงการรั่วไหลของหน่วยความจำ คุณต้องปล่อย ทรัพยากรหลังการใช้งานโดยทำดังนี้

interpreter.close();

ดูโปรเจ็กต์ตัวอย่างที่ใช้ Java ได้ที่แอปตัวอย่างการตรวจหาออบเจ็กต์ใน Android

ประเภทข้อมูลที่สนับสนุน

หากต้องการใช้ LiteRT ประเภทข้อมูลของอินพุตและเอาต์พุตเทนเซอร์ต้องเป็นประเภทดั้งเดิมต่อไปนี้

  • float
  • int
  • long
  • byte

นอกจากนี้ยังรองรับประเภท String แต่มีการเข้ารหัสแตกต่างจาก ประเภทดั้งเดิม โดยเฉพาะอย่างยิ่ง รูปร่างของเทนเซอร์สตริงจะกำหนดจำนวน และการจัดเรียงสตริงในเทนเซอร์ โดยแต่ละองค์ประกอบจะเป็นสตริงที่มีความยาวผันแปร ในแง่นี้ ขนาด (ไบต์) ของเทนเซอร์ไม่สามารถ คำนวณจากรูปร่างและประเภทเพียงอย่างเดียวได้ และด้วยเหตุนี้จึงไม่สามารถระบุสตริงเป็นอาร์กิวเมนต์ ByteBuffer แบบแบนเดียวได้

หากใช้ข้อมูลประเภทอื่นๆ รวมถึงประเภทที่อยู่ในกรอบ เช่น Integer และ Float ระบบจะแสดง IllegalArgumentException

อินพุต

อินพุตแต่ละรายการควรเป็นอาร์เรย์หรืออาร์เรย์หลายมิติของประเภทข้อมูลพื้นฐานที่รองรับ หรือ ByteBuffer ดิบที่มีขนาดเหมาะสม หากอินพุตเป็น อาร์เรย์หรืออาร์เรย์หลายมิติ ระบบจะ ปรับขนาดเทนเซอร์อินพุตที่เชื่อมโยงโดยนัยให้มีขนาดเท่ากับอาร์เรย์ในเวลาอนุมาน หากอินพุตเป็น ByteBuffer ผู้เรียกใช้ควรปรับขนาดอินพุตที่เชื่อมโยง เทนเซอร์ด้วยตนเองก่อน (ผ่าน Interpreter.resizeInput()) ก่อนที่จะเรียกใช้การอนุมาน

เมื่อใช้ ByteBuffer ให้ใช้บัฟเฟอร์ไบต์โดยตรง เนื่องจากจะช่วยให้ Interpreter หลีกเลี่ยงการคัดลอกที่ไม่จำเป็นได้ หาก ByteBuffer เป็นบัฟเฟอร์ไบต์โดยตรง ลำดับของบัฟเฟอร์ต้องเป็น ByteOrder.nativeOrder() หลังจากใช้สำหรับการอนุมานโมเดลแล้ว จะต้องไม่มีการเปลี่ยนแปลงจนกว่าการอนุมานโมเดลจะเสร็จสิ้น

เอาต์พุต

เอาต์พุตแต่ละรายการควรเป็นอาร์เรย์หรืออาร์เรย์หลายมิติของ ประเภทดั้งเดิมที่รองรับ หรือ ByteBuffer ที่มีขนาดเหมาะสม โปรดทราบว่าโมเดลบางรุ่น มีเอาต์พุตแบบไดนามิก ซึ่งรูปร่างของเทนเซอร์เอาต์พุตอาจแตกต่างกันไปตาม อินพุต ไม่มีวิธีที่ตรงไปตรงมาในการจัดการปัญหานี้ด้วย Java Inference API ที่มีอยู่ แต่ส่วนขยายที่วางแผนไว้จะทำให้ทำได้

iOS (Swift)

Swift API พร้อมใช้งานใน TensorFlowLiteSwift Pod จาก Cocoapods

ก่อนอื่น คุณต้องนำเข้าโมดูล TensorFlowLite

import TensorFlowLite
// Getting model path
guard
  let modelPath = Bundle.main.path(forResource: "model", ofType: "tflite")
else {
  // Error handling...
}

do {
  // Initialize an interpreter with the model.
  let interpreter = try Interpreter(modelPath: modelPath)

  // Allocate memory for the model's input `Tensor`s.
  try interpreter.allocateTensors()

  let inputData: Data  // Should be initialized

  // input data preparation...

  // Copy the input data to the input `Tensor`.
  try self.interpreter.copy(inputData, toInputAt: 0)

  // Run inference by invoking the `Interpreter`.
  try self.interpreter.invoke()

  // Get the output `Tensor`
  let outputTensor = try self.interpreter.output(at: 0)

  // Copy output to `Data` to process the inference results.
  let outputSize = outputTensor.shape.dimensions.reduce(1, {x, y in x * y})
  let outputData =
        UnsafeMutableBufferPointer<Float32>.allocate(capacity: outputSize)
  outputTensor.data.copyBytes(to: outputData)

  if (error != nil) { /* Error handling... */ }
} catch error {
  // Error handling...
}

iOS (Objective-C)

Objective-C API พร้อมใช้งานใน LiteRTObjC Pod จาก Cocoapods

ก่อนอื่น คุณต้องนำเข้าโมดูล TensorFlowLiteObjC

@import TensorFlowLite;
NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"model"
                                                      ofType:@"tflite"];
NSError *error;

// Initialize an interpreter with the model.
TFLInterpreter *interpreter = [[TFLInterpreter alloc] initWithModelPath:modelPath
                                                                  error:&error];
if (error != nil) { /* Error handling... */ }

// Allocate memory for the model's input `TFLTensor`s.
[interpreter allocateTensorsWithError:&error];
if (error != nil) { /* Error handling... */ }

NSMutableData *inputData;  // Should be initialized
// input data preparation...

// Get the input `TFLTensor`
TFLTensor *inputTensor = [interpreter inputTensorAtIndex:0 error:&error];
if (error != nil) { /* Error handling... */ }

// Copy the input data to the input `TFLTensor`.
[inputTensor copyData:inputData error:&error];
if (error != nil) { /* Error handling... */ }

// Run inference by invoking the `TFLInterpreter`.
[interpreter invokeWithError:&error];
if (error != nil) { /* Error handling... */ }

// Get the output `TFLTensor`
TFLTensor *outputTensor = [interpreter outputTensorAtIndex:0 error:&error];
if (error != nil) { /* Error handling... */ }

// Copy output to `NSData` to process the inference results.
NSData *outputData = [outputTensor dataWithError:&error];
if (error != nil) { /* Error handling... */ }

C API ในโค้ด Objective-C

API ของ Objective-C ไม่รองรับผู้มอบสิทธิ์ หากต้องการใช้ผู้มอบสิทธิ์กับโค้ด Objective-C คุณต้องเรียกใช้ C API พื้นฐานโดยตรง

#include "tensorflow/lite/c/c_api.h"
TfLiteModel* model = TfLiteModelCreateFromFile([modelPath UTF8String]);
TfLiteInterpreterOptions* options = TfLiteInterpreterOptionsCreate();

// Create the interpreter.
TfLiteInterpreter* interpreter = TfLiteInterpreterCreate(model, options);

// Allocate tensors and populate the input tensor data.
TfLiteInterpreterAllocateTensors(interpreter);
TfLiteTensor* input_tensor =
    TfLiteInterpreterGetInputTensor(interpreter, 0);
TfLiteTensorCopyFromBuffer(input_tensor, input.data(),
                           input.size() * sizeof(float));

// Execute inference.
TfLiteInterpreterInvoke(interpreter);

// Extract the output tensor data.
const TfLiteTensor* output_tensor =
    TfLiteInterpreterGetOutputTensor(interpreter, 0);
TfLiteTensorCopyToBuffer(output_tensor, output.data(),
                         output.size() * sizeof(float));

// Dispose of the model and interpreter objects.
TfLiteInterpreterDelete(interpreter);
TfLiteInterpreterOptionsDelete(options);
TfLiteModelDelete(model);

C++

C++ API สำหรับการเรียกใช้การอนุมานด้วย LiteRT ใช้ได้กับแพลตฟอร์ม Android, iOS และ Linux C++ API ใน iOS จะใช้ได้เมื่อใช้ Bazel เท่านั้น

ใน C++ โมเดลจะจัดเก็บไว้ในคลาส FlatBufferModel โดยจะห่อหุ้มโมเดล LiteRT และคุณสามารถสร้างได้ 2 วิธี ขึ้นอยู่กับตำแหน่งที่จัดเก็บโมเดล

class FlatBufferModel {
  // Build a model based on a file. Return a nullptr in case of failure.
  static std::unique_ptr<FlatBufferModel> BuildFromFile(
      const char* filename,
      ErrorReporter* error_reporter);

  // Build a model based on a pre-loaded flatbuffer. The caller retains
  // ownership of the buffer and should keep it alive until the returned object
  // is destroyed. Return a nullptr in case of failure.
  static std::unique_ptr<FlatBufferModel> BuildFromBuffer(
      const char* buffer,
      size_t buffer_size,
      ErrorReporter* error_reporter);
};

ตอนนี้คุณมีโมเดลเป็นออบเจ็กต์ FlatBufferModel แล้ว คุณจึงเรียกใช้โมเดลได้ ด้วย Interpreter FlatBufferModel 1 รายการสามารถใช้พร้อมกันได้โดย Interpreter มากกว่า 1 คน

ส่วนสำคัญของ Interpreter API จะแสดงในข้อมูลโค้ดด้านล่าง โปรดทราบว่า

  • Tensor จะแสดงด้วยจำนวนเต็มเพื่อหลีกเลี่ยงการเปรียบเทียบสตริง (และการขึ้นอยู่กับไลบรารีสตริงแบบคงที่)
  • ต้องไม่เข้าถึงล่ามจากเธรดที่ทำงานพร้อมกัน
  • การจัดสรรหน่วยความจำสำหรับอินพุตและเอาต์พุตเทนเซอร์ต้องทริกเกอร์โดยการเรียกใช้ AllocateTensors() ทันทีหลังจากปรับขนาดเทนเซอร์

การใช้งาน LiteRT ที่ง่ายที่สุดด้วย C++ มีลักษณะดังนี้

// Load the model
std::unique_ptr<tflite::FlatBufferModel> model =
    tflite::FlatBufferModel::BuildFromFile(filename);

// Build the interpreter
tflite::ops::builtin::BuiltinOpResolver resolver;
std::unique_ptr<tflite::Interpreter> interpreter;
tflite::InterpreterBuilder(*model, resolver)(&interpreter);

// Resize input tensors, if needed.
interpreter->AllocateTensors();

float* input = interpreter->typed_input_tensor<float>(0);
// Fill `input`.

interpreter->Invoke();

float* output = interpreter->typed_output_tensor<float>(0);

ดูโค้ดตัวอย่างเพิ่มเติมได้ที่ minimal.cc และ label_image.cc

Python

Python API สำหรับการเรียกใช้การอนุมานจะใช้ Interpreter เพื่อโหลดโมเดลและเรียกใช้การอนุมาน

ติดตั้งแพ็กเกจ LiteRT

$ python3 -m pip install ai-edge-litert

นำเข้า Interpreter ของ LiteRT

from ai_edge_litert.interpreter import Interpreter
Interpreter = Interpreter(model_path=args.model.file)

ตัวอย่างต่อไปนี้แสดงวิธีใช้ตัวแปล Python เพื่อโหลดไฟล์ FlatBuffers (.tflite) และเรียกใช้การอนุมานด้วยข้อมูลอินพุตแบบสุ่ม

เราขอแนะนำให้ใช้ตัวอย่างนี้หากคุณกำลังแปลงจาก SavedModel ที่มี SignatureDef ที่กำหนด

class TestModel(tf.Module):
  def __init__(self):
    super(TestModel, self).__init__()

  @tf.function(input_signature=[tf.TensorSpec(shape=[1, 10], dtype=tf.float32)])
  def add(self, x):
    '''
    Simple method that accepts single input 'x' and returns 'x' + 4.
    '''
    # Name the output 'result' for convenience.
    return {'result' : x + 4}

SAVED_MODEL_PATH = 'content/saved_models/test_variable'
TFLITE_FILE_PATH = 'content/test_variable.tflite'

# Save the model
module = TestModel()
# You can omit the signatures argument and a default signature name will be
# created with name 'serving_default'.
tf.saved_model.save(
    module, SAVED_MODEL_PATH,
    signatures={'my_signature':module.add.get_concrete_function()})

# Convert the model using TFLiteConverter
converter = tf.lite.TFLiteConverter.from_saved_model(SAVED_MODEL_PATH)
tflite_model = converter.convert()
with open(TFLITE_FILE_PATH, 'wb') as f:
  f.write(tflite_model)

# Load the LiteRT model in LiteRT Interpreter
from ai_edge_litert.interpreter import Interpreter
interpreter = Interpreter(TFLITE_FILE_PATH)

# There is only 1 signature defined in the model,
# so it will return it by default.
# If there are multiple signatures then we can pass the name.
my_signature = interpreter.get_signature_runner()

# my_signature is callable with input as arguments.
output = my_signature(x=tf.constant([1.0], shape=(1,10), dtype=tf.float32))
# 'output' is dictionary with all outputs from the inference.
# In this case we have single output 'result'.
print(output['result'])

อีกตัวอย่างหนึ่งในกรณีที่โมเดลไม่ได้กำหนด SignatureDefs

import numpy as np
import tensorflow as tf

# Load the LiteRT model and allocate tensors.
from ai_edge_litert.interpreter import Interpreter
interpreter = Interpreter(TFLITE_FILE_PATH)
interpreter.allocate_tensors()

# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# Test the model on random input data.
input_shape = input_details[0]['shape']
input_data = np.array(np.random.random_sample(input_shape), dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], input_data)

interpreter.invoke()

# The function `get_tensor()` returns a copy of the tensor data.
# Use `tensor()` in order to get a pointer to the tensor.
output_data = interpreter.get_tensor(output_details[0]['index'])
print(output_data)

คุณสามารถรวมโค้ดกับ LiteRT Compiler เพื่อแปลงโมเดล Keras เป็นรูปแบบ LiteRT แล้วเรียกใช้ การอนุมานได้ ซึ่งเป็นอีกทางเลือกหนึ่งแทนการโหลดโมเดลเป็นไฟล์ .tflite ที่แปลงไว้ล่วงหน้า

import numpy as np
import tensorflow as tf

img = tf.keras.Input(shape=(64, 64, 3), name="img")
const = tf.constant([1., 2., 3.]) + tf.constant([1., 4., 4.])
val = img + const
out = tf.identity(val, name="out")

# Convert to LiteRT format
converter = tf.lite.TFLiteConverter.from_keras_model(tf.keras.models.Model(inputs=[img], outputs=[out]))
tflite_model = converter.convert()

# Load the LiteRT model and allocate tensors.
from ai_edge_litert.interpreter import Interpreter
interpreter = Interpreter(model_content=tflite_model)
interpreter.allocate_tensors()

# Continue to get tensors and so forth, as shown above...

ดูโค้ดตัวอย่าง Python เพิ่มเติมได้ที่ label_image.py

เรียกใช้การอนุมานด้วยโมเดลรูปร่างแบบไดนามิก

หากต้องการเรียกใช้โมเดลที่มีรูปร่างอินพุตแบบไดนามิก ให้ปรับขนาดรูปร่างอินพุต ก่อนเรียกใช้การอนุมาน ไม่เช่นนั้น รูปร่าง None ในโมเดล Tensorflow จะถูกแทนที่ด้วยตัวยึดตำแหน่ง 1 ในโมเดล LiteRT

ตัวอย่างต่อไปนี้แสดงวิธีปรับขนาดรูปร่างอินพุตก่อนเรียกใช้การอนุมานในภาษาต่างๆ ตัวอย่างทั้งหมดถือว่ารูปร่างอินพุต กำหนดเป็น [1/None, 10] และต้องปรับขนาดเป็น [3, 10]

ตัวอย่าง C++

// Resize input tensors before allocate tensors
interpreter->ResizeInputTensor(/*tensor_index=*/0, std::vector<int>{3,10});
interpreter->AllocateTensors();

ตัวอย่าง Python

# Load the LiteRT model in LiteRT Interpreter
from ai_edge_litert.interpreter import Interpreter
interpreter = Interpreter(model_path=TFLITE_FILE_PATH)

# Resize input shape for dynamic shape model and allocate tensor
interpreter.resize_tensor_input(interpreter.get_input_details()[0]['index'], [3, 10])
interpreter.allocate_tensors()

# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()