LLM Inference API 可讓您完全在裝置端針對 Android 應用程式執行大型語言模型 (LLM),方便您執行多種工作,例如產生文字、擷取自然語言格式的資訊,以及總結文件內容。這項工作提供多種文字轉文字大型語言模型的內建支援,方便您將最新的裝置端生成式 AI 模型套用至 Android 應用程式。
這項工作支援 Gemma 2B,這是一系列最先進的輕量開放模型的一部分,使用與建立 Gemini 模型相同的研究和技術建構而成。此外,也支援下列外部模型:Phi-2、Falcon-RW-1B 和 StableLM-3B,以及透過 AI Edge 匯出的所有模型。
如要進一步瞭解這項工作的功能、模型和設定選項,請參閱總覽。
程式碼範例
本指南為 Android 的基本文字產生應用程式提供範例。您可以將該應用程式做為開發 Android 應用程式的起點,或在修改現有應用程式時參照該應用程式。範例程式碼可託管於 GitHub。
下載程式碼
以下操作說明說明如何使用 git 指令列工具建立範例程式碼的本機副本。
如要下載範例程式碼,請按照下列步驟操作:
- 使用下列指令複製 Git 存放區:
git clone https://github.com/google-ai-edge/mediapipe-samples
- 您可以選擇將 Git 執行個體設為使用稀疏檢查,這樣您只有 LLM Inference API 範例應用程式的檔案:
cd mediapipe git sparse-checkout init --cone git sparse-checkout set examples/llm_inference/android
建立範例程式碼的本機版本後,您可以將專案匯入 Android Studio 並執行應用程式。如需操作說明,請參閱 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 的 350B 符記進行訓練。
- StableLM-3B:30 億
或者,您也可以使用透過 AI Edge Troch 對應及匯出的模型。
建議您使用與 LLM Inference API 相容的 Gemma 2B,前者可在 Kaggle 模型中找到。如果使用其他 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.safetensors 或 pytorch.bin 檔案的路徑。請注意,有時模型安全張量格式會分割為多個檔案,例如 model-00001-of-00003.safetensors 、model-00001-of-00003.safetensors 。您可以指定檔案模式,例如 model*.safetensors 。 |
PATH |
ckpt_format |
模型檔案格式。 | {"safetensors", "pytorch"} |
model_type |
要轉換的 LLM。 | {"PHI_2", "FALCON_RW_1B", "STABLELM_4E1T_3B", "GEMMA_2B"} |
backend |
用來執行模型的處理器 (委派)。 | {"cpu", "gpu"} |
output_dir |
託管個別圖層權重檔案的輸出目錄路徑。 | PATH |
output_tflite_file |
輸出檔案的路徑。例如「model_cpu.bin」或「model_gpu.bin」。這個檔案僅與 LLM Inference API 相容,無法做為一般的「tflite」檔案。 | PATH |
vocab_model_file |
儲存 tokenizer.json 和 tokenizer_config.json 檔案的目錄路徑。如為 Gemma,請指向單一 tokenizer.model 檔案。 |
PATH |
lora_ckpt |
用於儲存 LoRA 配接權重安全張量檔案的 LoRA 底座路徑。 | PATH |
lora_rank |
代表 LoRA 掛接位置的整數。如要轉換 lora 權重,此為必填屬性。如未提供,則轉換工具會假設沒有 LoRA 權重。注意:只有 GPU 後端支援 LoRA。 | 整數 |
lora_output_tflite_file |
輸出 LoRA 權重的 tflite 檔案名稱。 | PATH |
AI Edge 模型轉換
如果是透過 AI Edge 使用對應到 TFLite 模型的 LLM,請使用我們的套裝組合指令碼建立工作組合。組合程序會將對應的模型與其他中繼資料 (例如權杖化工具參數) 才能執行端對端推論
模型組合程序需要使用 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 模型的路徑。 | PATH |
tokenizer_model |
SentencePiece 權杖化工具模型的路徑。 | PATH |
start_token |
模型專屬起始權杖。啟動權杖必須存在於提供的權杖化工具模型中。 | STRING |
stop_tokens |
模型專屬的停止權杖。停止權杖必須存在於提供的權杖化工具模型中。 | 清單 [STRING] |
output_filename |
輸出工作組合檔案的名稱。 | PATH |
將模型推送至裝置
將 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 |
專案目錄中儲存模型的路徑。 | PATH | 不適用 |
maxTokens |
模型處理的符記數量上限 (輸入符記 + 輸出符記)。 | 整數 | 512 |
topK |
模型在產生每個步驟時考量的符記數量。將預測範圍限制在機率最高的前 K 個符記。設定 topK 時,您也必須設定 randomSeed 的值。 |
整數 | 40 |
temperature |
在產生過程中引入的隨機量。隨機性參數越高,生成文字就能發揮更多創意,而低溫則能產生更準確的生成結果。設定 temperature 時,您也必須設定 randomSeed 的值。 |
浮點值 | 0.8 |
randomSeed |
用來產生文字的隨機種子值。 | 整數 | 0 |
loraPath |
在裝置上本機的 LoRA 模型絕對路徑。注意:這項功能僅與 GPU 型號相容。 | PATH | 不適用 |
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 支援適用於 GPU 後端的 Gemma-2B 和 Phi-2 模型,而 LoRA 權重僅適用於注意力層。這項初始實作可做為日後開發的實驗性 API,並計畫在未來的更新中支援更多模型和不同類型層。
準備 LoRA 模型
請按照 HuggingFace 中的操作說明,使用自己的資料集類型 (Gemma-2B 或 Phi-2) 訓練經過微調的 LoRA 模型。Gemma-2B 和 Phi-2 機型皆以安全張量格式在 HuggingFace 中提供。由於 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 模型。例如 monsterapi/gemma-2b-lora-maths-orca-200k 代表 Gemma-2B,以及 lole25/phi-2-sft-ultrachat-lora 代表「Phi-2」。
使用準備好的資料集進行訓練並儲存模型後,您就會取得 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 模型推論。Web 支援動態 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()
方法。