Android 適用的 LLM 推論指南

,瞭解如何調查及移除這項存取權。

透過 LLM Inference API,您可以在裝置上完全執行大型語言模型 (LLM) 可用來執行多種工作 例如生成文字、以自然語言格式擷取資訊 總結文件內容這項工作內建支援 文字轉文字大型語言模型,方便你在裝置上套用 建構生成式 AI 模型

這項工作支援 Gemma 2B,位於 都以相同的研究為基礎建構而成的輕量級開放式模型系列 和技術建立 Gemini 模型 也支援下列外部模型: Phi-2Falcon-RW-1BStableLM-3B、 以及透過 AI Edge 匯出的所有模型

進一步瞭解功能、模型和設定選項 請參閱總覽

程式碼範例

本指南以範例說明 Android 基本的文字生成應用程式。個人中心 可以做為您 Android 應用程式的起點, 做出決定範例程式碼 GitHub

下載程式碼

以下說明如何建立範例的本機副本 git 指令列工具編寫程式碼。

如要下載範例程式碼,請按照下列步驟操作:

  1. 使用下列指令複製 git 存放區:
    git clone https://github.com/google-ai-edge/mediapipe-samples
    
  2. 您也可以設定 Git 執行個體來使用稀疏結帳功能, 只有 LLM Inference API 範例應用程式的檔案:
    cd mediapipe
    git sparse-checkout init --cone
    git sparse-checkout set examples/llm_inference/android
    

建立範例程式碼的本機版本後,您可以匯入專案 然後執行應用程式如需操作說明,請參閱 Android

設定

本節說明設定開發環境的重要步驟,以及 特別適合使用 LLM Inference API如需 設定開發環境以使用 MediaPipe 工作,包括: 平台版本需求,請參閱這份指南 Android

依附元件

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

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

型號

MediaPipe LLM Inference API 需要經過訓練的文字轉文字語言模型, 與這個任務相容下載模型後,請安裝 並將模型推送至 Android 裝置如果您使用模型 就必須將模型轉換為與 Gemma 相容的格式 MediaPipe。

如要進一步瞭解可用於 LLM Inference API 的可用訓練模型,請參閱任務 總覽的「模型」一節

下載模型

在初始化 LLM Inference API 之前,請先下載其中一個支援的模型,然後 將檔案儲存在專案目錄中:

  • Gemma 2B: 這是一系列最先進的開放式模型之一,以 研究和技術有助於打造 Gemini 模型。適用於各種 像是回答問題、摘要 。
  • Phi-2:27 億參數 Transformer 模型,最適合用於問答、聊天和程式碼 格式。
  • Falcon-RW-1B:10 億 參數因解碼器而僅限解碼器的模型 RefinedWeb
  • StableLM-3B:3 以 1 兆美元預先訓練的 10 兆種僅限解碼器語言模型 種類繁多的英文和程式碼資料集

或者,您也可以透過上述方法,使用 AI 邊緣區塊

建議使用 Gemma 2B (可從 Kaggle 取得) 型號 且該格式與 LLM Inference API 相容如果您使用 如果是另一個 LLM,您需要將模型轉換為 適用於 MediaPipe 的格式。如要進一步瞭解 Gemma 2B,請參閱 Gemma 網站。如要進一步瞭解 請參閱工作總覽的「模型」一節

將模型轉換為 MediaPipe 格式

原生模型轉換

如果使用外部 LLM (Phi-2、Falcon 或 StableLM) 或非 Kaggle, Gemma 版本,並使用轉換指令碼將模型格式化 與 MediaPipe 相容

模型轉換程序需要 MediaPipe PyPI 套件。轉換 0.10.11 之後的所有 MediaPipe 套件都能提供指令碼。

透過下列指令安裝及匯入依附元件:

$ python3 -m pip install mediapipe

使用 genai.converter 程式庫轉換模型:

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

config = converter.ConversionConfig(
  input_ckpt=INPUT_CKPT,
  ckpt_format=CKPT_FORMAT,
  model_type=MODEL_TYPE,
  backend=BACKEND,
  output_dir=OUTPUT_DIR,
  combine_file_only=False,
  vocab_model_file=VOCAB_MODEL_FILE,
  output_tflite_file=OUTPUT_TFLITE_FILE,
)

converter.convert_checkpoint(config)

如要轉換 LoRA 模型,ConversionConfig 應指定基礎模型 以及額外的 LoRA 選項請注意,自 API 以來 支援搭配 GPU 進行 LoRA 推論,後端必須設為 'gpu'

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_TFLITE_FILE,
)

converter.convert_checkpoint(config)

轉換工具會輸出兩個 TFLite Flatbuffer 檔案,一個用於基礎模型 另一個則是 LoRA 模型

參數 說明 接受的值
input_ckpt model.safetensorspytorch.bin 檔案的路徑。請注意,模型安全張量格式有時會分割為多個檔案,例如model-00001-of-00003.safetensorsmodel-00001-of-00003.safetensors。您可以指定檔案模式,例如 model*.safetensors 路徑
ckpt_format 模型檔案格式。 {"安全張量", "pytorch"}
model_type 正在轉換的 LLM, {"PHI_2", "FALCON_RW_1B", "STABLELM_4E1T_3B", "GEMMA_2B"}
backend 用來執行模型的處理器 (委派)。 {"cpu", "gpu"}
output_dir 代管各圖層權重檔案的輸出目錄路徑。 路徑
output_tflite_file 輸出檔案的路徑。例如「model_cpu.bin」或「model_gpu.bin」這個檔案僅與 LLM Inference API 相容,無法做為一般的「tflite」檔案使用。 路徑
vocab_model_file 儲存 tokenizer.jsontokenizer_config.json 個檔案。如果是 Gemma,請指向單一 tokenizer.model 檔案。 路徑
lora_ckpt 儲存 LoRA 轉接器權重的 LoRA 安全張量檔案路徑。 路徑
lora_rank 代表 LoRA ckpt 排名的整數。必須填寫此欄位,才能轉換 lora 權重。如未提供,則轉換器會假設沒有 LoRA 權重。注意:只有 GPU 後端支援 LoRA。 整數
lora_output_tflite_file LoRA 權重的輸出 tflite 檔案名稱。 路徑

AI Edge 模型轉換

如果您使用的 LLM 對應至透過 AI Edge 對應至 TFLite 模型,請使用 組合指令碼來建立工作套件。套裝程序會封裝 具備額外中繼資料 (例如Tokenizer 參數 執行端對端推論

模型組合程序需要 MediaPipe PyPI 套件。轉換 0.10.14 之後的所有 MediaPipe 套件都能提供指令碼。

透過下列指令安裝及匯入依附元件:

$ python3 -m pip install mediapipe

使用 genai.bundler 程式庫封裝模型:

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

config = bundler.BundleConfig(
    tflite_model=TFLITE_MODEL,
    tokenizer_model=TOKENIZER_MODEL,
    start_token=START_TOKEN,
    stop_tokens=STOP_TOKENS,
    output_filename=OUTPUT_FILENAME,
    enable_bytes_to_unicode_mapping=ENABLE_BYTES_TO_UNICODE_MAPPING,
)
bundler.create_bundle(config)
參數 說明 接受的值
tflite_model AI Edge 匯出的 TFLite 模型的路徑。 路徑
tokenizer_model SentencePiece 權杖化工具模型的路徑。 路徑
start_token 適用於特定模型的起始權杖。起始權杖必須出現在 提供的符記化模型 STRING
stop_tokens 模型專屬的停止權杖。停止權杖必須在 提供的符記化模型 清單 [STRING]
output_filename 輸出工作套件檔案的名稱。 路徑

將模型推送至裝置

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.bin

建立工作

MediaPipe LLM Inference API 會使用 createFromOptions() 函式來設定 工作。createFromOptions() 函式可接受設定值 只要設定成「自動重新啟動」 和「在主機維護期間」選項即可如要進一步瞭解設定選項,請參閱設定 選項

下列程式碼會使用基本設定選項初始化工作:

// Set the configuration options for the LLM Inference task
val options = LlmInferenceOptions.builder()
        .setModelPATH('/data/local/.../')
        .setMaxTokens(1000)
        .setTopK(40)
        .setTemperature(0.8)
        .setRandomSeed(101)
        .build()

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

設定選項

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

選項名稱 說明 值範圍 預設值
modelPath 儲存模型在專案目錄中的模型路徑。 路徑 不適用
maxTokens 模型可處理的符記數量上限 (輸入符記 + 輸出符記)。 整數 512
topK 模型在產生各步驟時考慮的符記數量。 將預測範圍限制在可能性前 K 高的符記。 整數 40
temperature 在產生過程中出現的隨機程度。更高 就能提高生成文字的創造力 較低的隨機性參數會產生較容易預測的生成器 浮點值 0.8
randomSeed 文字產生時使用的隨機種子。 整數 0
loraPath 裝置上 LoRA 模型的絕對路徑。注意:這項功能僅適用於 GPU 型號。 路徑 不適用
resultListener 設定結果事件監聽器,以非同步方式接收結果。 只有在使用非同步產生方法時適用。 不適用 不適用
errorListener 設定選用的錯誤事件監聽器。 不適用 不適用

準備資料

LLM Inference API 接受下列輸入內容:

  • prompt (字串):問題或提示。
val inputPrompt = "Compose an email to remind Brett of lunch plans at noon on Saturday."

執行工作

使用 generateResponse() 方法產生輸入內容的文字回應 如上一節 (inputPrompt) 中提供的文字。這樣就會產生 生成的回覆

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 Inference API 會傳回 LlmInferenceResult,其中包含產生的 回應文字。

Here's a draft you can use:

Subject: Lunch on Saturday Reminder

Hi Brett,

Just a quick reminder about our lunch plans this Saturday at noon.
Let me know if that still works for you.

Looking forward to it!

Best,
[Your Name]

自訂 LoRA 模型

您可以將 Mediapipe LLM 推論 API 設為支援低階調整 (LoRA) 這適合用於大型語言模型開發人員只要使用經過微調的 LoRA 模型 以符合成本效益的訓練程序,自訂 LLM 的行為。

支援 LLM Inference API 的 LoRA 支援 Gemma-2B 和 Phi-2 模型 ,且 LoRA 權重僅適用於注意力層這個 初始實作的用意是供未來開發的實驗性 API 並計劃在未來支援更多模型和各種圖層類型 更新。

準備 LoRA 模型

按照 HuggingFace 的操作說明,在自己的資料集內使用支援的模型類型 Gemma-2B 或 Phi-2 訓練微調的 LoRA 模型。HuggingFace 同時提供 Gemma-2B 和 Phi-2 模型,並採用安全張量格式。由於 LLM Inference API 僅支援注意力層的 LoRA,因此只有在建立 LoraConfig 時指定注意力層,如下所示:

# For Gemma-2B
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"],
)

為了進行測試,HuggingFace 提供公開且經過微調的 LoRA 模型,這些模型與 LLM Inference API 相容。例如,Gemma-2B 的 monsterapi/gemma-2b-lora-maths-orca-200k,而 Phi-2 代表 lole25/phi-2-sft-ultrachat-lora

在準備的資料集訓練及儲存模型後,您會取得一個 adapter_model.safetensors 檔案,其中包含經過微調的 LoRA 模型權重。安全張量檔案是模型轉換中使用的 LoRA 檢查點,

接下來,您必須使用 MediaPipe Python 套件,將模型權重轉換為 TensorFlow Lite Flatbuffer。ConversionConfig 應指定基本模型選項及其他 LoRA 選項。請注意,由於 API 只支援使用 GPU 進行 LoRA 推論,因此後端必須設為 'gpu'

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_TFLITE_FILE,
)

converter.convert_checkpoint(config)

轉換工具會輸出兩個 TFLite Flatbuffer 檔案,一個用於基礎模型 另一個則是 LoRA 模型

LoRA 模型推論

Web、Android 和 iOS LLM Inference API 已更新,現在支援 LoRA 模型推論。網頁支援動態 LoRA,該架構可在執行階段切換不同的 LoRA 模型。Android 和 iOS 支援靜態 LoRA,在任務生命週期中使用相同的 LoRA 權重。

Android 支援在初始化期間使用靜態 LoRA。如要載入 LoRA 模型,使用者須指定 LoRA 模型路徑和基本 LLM。

// Set the configuration options for the LLM Inference task
val options = LlmInferenceOptions.builder()
        .setModelPath('<path to base model>')
        .setMaxTokens(1000)
        .setTopK(40)
        .setTemperature(0.8)
        .setRandomSeed(101)
        .setLoraPath('<path to LoRA model>')
        .build()

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

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