Android 適用的 LLM 推論指南

您可以使用 LLM 推論 API,在 Android 應用程式中完全透過裝置端執行大型語言模型 (LLM),藉此執行各種工作,例如生成文字、以自然語言形式檢索資訊,以及製作文件摘要。這項工作內建支援多個文字轉文字大型語言模型,因此您可以在 Android 應用程式中套用最新的裝置端生成式 AI 模型。

如要快速將 LLM Inference API 新增至 Android 應用程式,請按照快速入門導覽課程操作。如需執行 LLM Inference API 的 Android 應用程式基本範例,請參閱範例應用程式。如要深入瞭解 LLM 推論 API 的運作方式,請參閱「設定選項」、「模型轉換」和「LoRA 微調」章節。

如要查看這項工作實際運作情形,請參閱 MediaPipe Studio 示範。 如要進一步瞭解這項工作的能力、模型和設定選項,請參閱總覽

快速入門導覽課程

請按照下列步驟,將 LLM Inference API 新增至 Android 應用程式。 LLM Inference API 專為高階 Android 裝置 (例如 Pixel 8 和 Samsung S23 以上機型) 最佳化,無法穩定支援裝置模擬器。

新增依附元件

LLM Inference API 使用 com.google.mediapipe:tasks-genai 程式庫。將這個依附元件新增至 Android 應用程式的 build.gradle 檔案:

dependencies {
    implementation 'com.google.mediapipe:tasks-genai:0.10.27'
}

下載模型

Hugging Face 下載 4 位元量化格式的 Gemma-3 1B。如要進一步瞭解可用模型,請參閱模型說明文件

output_path 資料夾的內容推送到 Android 裝置。

$ adb shell rm -r /data/local/tmp/llm/ # Remove any previously loaded models
$ adb shell mkdir -p /data/local/tmp/llm/
$ adb push output_path /data/local/tmp/llm/model_version.task

初始化工作

使用基本設定選項初始化工作:

// Set the configuration options for the LLM Inference task
val taskOptions = LlmInferenceOptions.builder()
        .setModelPath('/data/local/tmp/llm/model_version.task')
        .setMaxTopK(64)
        .build()

// Create an instance of the LLM Inference task
llmInference = LlmInference.createFromOptions(context, taskOptions)

執行工作

使用 generateResponse() 方法生成文字回覆。這會產生單一生成的回覆。

val result = llmInference.generateResponse(inputPrompt)
logger.atInfo().log("result: $result")

如要串流回應,請使用 generateResponseAsync() 方法。

val options = LlmInference.LlmInferenceOptions.builder()
  ...
  .setResultListener { partialResult, done ->
    logger.atInfo().log("partial result: $partialResult")
  }
  .build()

llmInference.generateResponseAsync(inputPrompt)

應用程式範例

如要查看 LLM 推論 API 的實際運作情形,並探索各種裝置端生成式 AI 功能,請參閱 Google AI Edge Gallery 應用程式

Google AI Edge Gallery 是開放原始碼的 Android 應用程式,可做為開發人員的互動式遊樂場。當中包含:

  • 使用 LLM Inference API 執行各種工作的實用範例,包括:
    • 詢問圖片:上傳圖片並提出相關問題。取得說明、解決問題或辨識物體。
    • 提示實驗室:摘要、重寫、生成程式碼,或使用任意格式的提示,探索單輪 LLM 用途。
    • AI Chat:進行多輪對話。
  • 從 Hugging Face LiteRT 社群和官方 Google 版本 (例如 Gemma 3N) 探索、下載及實驗各種 LiteRT 最佳化模型。
  • 不同模型在裝置上的即時效能基準 (首次產生權杖的時間、解碼速度等)。
  • 如何匯入及測試自訂 .litertlm.task 模型。

這個應用程式可協助您瞭解 LLM Inference API 的實際導入方式,以及裝置端生成式 AI 的潛力。瀏覽原始碼,並從 Google AI Edge Gallery GitHub 存放區下載應用程式。

設定選項

請使用下列設定選項設定 Android 應用程式:

選項名稱 說明 值範圍 預設值
modelPath 模型在專案目錄中的儲存路徑。 路徑 不適用
maxTokens 模型可處理的權杖數量上限 (輸入權杖 + 輸出權杖)。 整數 512
topK 模型在生成過程的每個步驟中會考量的權杖數量。 將預測結果限制為機率最高的 k 個符記。 整數 40
temperature 生成期間導入的隨機程度。溫度越高,生成的文字就越有創意;溫度越低,生成的文字就越可預測。 浮點值 0.8
randomSeed 文字生成期間使用的隨機種子。 整數 0
loraPath 裝置本機上 LoRA 模型的絕對路徑。注意:這項功能僅適用於 GPU 型號。 路徑 不適用
resultListener 設定結果事件監聽器,以非同步方式接收結果。 僅適用於使用非同步生成方法。 不適用 不適用
errorListener 設定選用的錯誤監聽器。 不適用 不適用

多模態提示

LLM Inference API Android API 支援多模態提示,可搭配接受文字、圖片和音訊輸入內容的模型使用。啟用多模態功能後,使用者可以在提示中加入圖片和文字,或是音訊和文字。接著,LLM 就會提供文字回覆。

如要開始使用,請使用與 MediaPipe 相容的 Gemma 3n 變體:

詳情請參閱 Gemma-3n 說明文件

請按照下列步驟,為 LLM Inference API 啟用圖片或音訊輸入功能。

輸入圖片

如要在提示中提供圖片,請先將輸入圖片或影格轉換為 com.google.mediapipe.framework.image.MPImage 物件,再傳遞至 LLM 推論 API:

import com.google.mediapipe.framework.image.BitmapImageBuilder
import com.google.mediapipe.framework.image.MPImage

// Convert the input Bitmap object to an MPImage object to run inference
val mpImage = BitmapImageBuilder(image).build()

如要為 LLM 推論 API 啟用影像支援功能,請在 Graph 選項中將 EnableVisionModality 設定選項設為 true

LlmInferenceSession.LlmInferenceSessionOptions sessionOptions =
  LlmInferenceSession.LlmInferenceSessionOptions.builder()
    ...
    .setGraphOptions(GraphOptions.builder().setEnableVisionModality(true).build())
    .build();

每個工作階段最多可上傳 10 張圖片。

LlmInferenceOptions options = LlmInferenceOptions.builder()
  ...
  .setMaxNumImages(10)
  .build();

以下是 LLM 推論 API 的實作範例,可處理影像和文字輸入內容:

MPImage image = getImageFromAsset(BURGER_IMAGE);

LlmInferenceSession.LlmInferenceSessionOptions sessionOptions =
  LlmInferenceSession.LlmInferenceSessionOptions.builder()
    .setTopK(10)
    .setTemperature(0.4f)
    .setGraphOptions(GraphOptions.builder().setEnableVisionModality(true).build())
    .build();

try (LlmInference llmInference =
    LlmInference.createFromOptions(ApplicationProvider.getApplicationContext(), options);
  LlmInferenceSession session =
    LlmInferenceSession.createFromOptions(llmInference, sessionOptions)) {
  session.addQueryChunk("Describe the objects in the image.");
  session.addImage(image);
  String result = session.generateResponse();
}

音訊輸入

在 LlmInferenceOptions 中啟用音訊支援

val inferenceOptions = LlmInference.LlmInferenceOptions.builder()
  ...
  .setAudioModelOptions(AudioModelOptions.builder().build())
  .build()

在 sessionOptions 中啟用音訊支援

    val sessionOptions =  LlmInferenceSessionOptions.builder()
      ...
      .setGraphOptions(GraphOptions.builder().setEnableAudioModality(true).build())
      .build()

在推論期間傳送音訊資料。 注意:音訊必須是單聲道,格式為 .wav


val audioData: ByteArray = ...
inferenceEngine.llmInferenceSession.addAudio(audioData)

以下是 LLM 推論 API 的實作範例,可處理音訊和文字輸入內容:

val audioData: ByteArray = ...
val inferenceOptions = LlmInference.LlmInferenceOptions.builder()
  ...
  .setAudioModelOptions(AudioModelOptions.builder().build())
  .build()
val sessionOptions =  LlmInferenceSessionOptions.builder()
  ...
  .setGraphOptions(GraphOptions.builder().setEnableAudioModality(true).build())
  .build()

LlmInference.createFromOptions(context, inferenceOptions).use { llmInference ->
  LlmInferenceSession.createFromOptions(llmInference, sessionOptions).use { session ->
    session.addQueryChunk("Transcribe the following speech segment:")
    session.addAudio(audioData)
    val result = session.generateResponse()
  }
}

LoRA 自訂

LLM Inference API 支援使用 PEFT (參數高效微調) 程式庫進行 LoRA (低秩調整) 微調。LoRA 微調功能會透過經濟實惠的訓練程序,自訂大型語言模型的行為,並根據新的訓練資料建立一小組可訓練的權重,而非重新訓練整個模型。

LLM Inference API 支援將 LoRA 權重新增至 Gemma-2 2BGemma 2BPhi-2 模型的注意力層。下載 safetensors 格式的模型。

基礎模型必須採用 safetensors 格式,才能建立 LoRA 權重。完成 LoRA 訓練後,您可以將模型轉換為 FlatBuffers 格式,以便在 MediaPipe 上執行。

準備 LoRA 權重

使用 PEFT 的 LoRA 方法指南,根據自己的資料集訓練微調的 LoRA 模型。

LLM Inference API 僅支援注意力層的 LoRA,因此請只在 LoraConfig 中指定注意力層:

# For Gemma
from peft import LoraConfig
config = LoraConfig(
    r=LORA_RANK,
    target_modules=["q_proj", "v_proj", "k_proj", "o_proj"],
)

# For Phi-2
config = LoraConfig(
    r=LORA_RANK,
    target_modules=["q_proj", "v_proj", "k_proj", "dense"],
)

使用準備好的資料集訓練模型並儲存後,微調的 LoRA 模型權重就會顯示在 adapter_model.safetensors 中。safetensors 檔案是模型轉換期間使用的 LoRA 檢查點。

模型轉換

使用 MediaPipe Python 套件將模型權重轉換為 Flatbuffer 格式。ConversionConfig 會指定基本模型選項,以及其他 LoRA 選項。

import mediapipe as mp
from mediapipe.tasks.python.genai import converter

config = converter.ConversionConfig(
  # Other params related to base model
  ...
  # Must use gpu backend for LoRA conversion
  backend='gpu',
  # LoRA related params
  lora_ckpt=LORA_CKPT,
  lora_rank=LORA_RANK,
  lora_output_tflite_file=LORA_OUTPUT_FILE,
)

converter.convert_checkpoint(config)

轉換工具會產生兩個 Flatbuffer 檔案,一個用於基本模型,另一個用於 LoRA 模型。

LoRA 模型推論

Android 支援初始化期間的靜態 LoRA。如要載入 LoRA 模型,請指定 LoRA 模型路徑和基礎 LLM。

// Set the configuration options for the LLM Inference task
val options = LlmInferenceOptions.builder()
        .setModelPath(BASE_MODEL_PATH)
        .setMaxTokens(1000)
        .setTopK(40)
        .setTemperature(0.8)
        .setRandomSeed(101)
        .setLoraPath(LORA_MODEL_PATH)
        .build()

// Create an instance of the LLM Inference task
llmInference = LlmInference.createFromOptions(context, options)

如要使用 LoRA 執行 LLM 推論,請使用與基礎模型相同的 generateResponse()generateResponseAsync() 方法。