在安卓设备上通过 ExecuTorch 运行大语言模型

ExecuTorch 通过 executorch-android AAR 提供实验性 Java/Kotlin 接口,用于在安卓端加载 .pte 模型与分词器、配置生成参数、流式生成 token,并支持图像与音频多模态预填充。

## 在 Android 上运行 LLMS[#](<https://docs.pytorch.org/executorch/stable/llm/run-on-android.html#running-llms-on-android>) ExecuTorch 的 LLM 特定运行时间组件提供实验 Java API,可以从 Java 或 Kotlin 调用,绕 C++ LLM 运行时间。这些API 可以通过 `executorch-android` AAR. ## 先决条件[#](<https://docs.pytorch.org/executorch/stable/llm/run-on-android.html#prerequisites>) 确定您已准备好模型和标定器文件, 详情请见: [C++ 运行 LLMS](<https://docs.pytorch.org/executorch/stable/llm/run-with-c-plus-plus.html>) 向导。 添加以下内容: `executorch-android` 库到您的应用程序,参见 [在Android上使用 ExecuTorch 软件](<https://docs.pytorch.org/executorch/stable/using-executorch-android.html>). LLM 跑步类被捆绑在与通用型相同的AAR内. `Module` API. ## 运行时间 API[#](<https://docs.pytorch.org/executorch/stable/llm/run-on-android.html#runtime-api>) 一经. `executorch-android` AAR在你的类号上,你可以从中导入LLM的跑步类. `org.pytorch.executorch.extension.llm` 软件包。从Java和Kotlin中都可以调用运行程序;本指南的其余部分包括Java和Kotlin两个实例,每个片段都有。 ### 导入[#](<https://docs.pytorch.org/executorch/stable/llm/run-on-android.html#importing>) 爪哇语 : ``` import org.pytorch.executorch.extension.llm.LlmModule; import org.pytorch.executorch.extension.llm.LlmModuleConfig; import org.pytorch.executorch.extension.llm.LlmGenerationConfig; import org.pytorch.executorch.extension.llm.LlmCallback; // Only needed for the multimodal ByteBuffer paths in the Images section. import java.nio.ByteBuffer; import java.nio.ByteOrder; ``` 科特林: 科特林: 科特林: ``` import org.pytorch.executorch.extension.llm.LlmModule import org.pytorch.executorch.extension.llm.LlmModuleConfig import org.pytorch.executorch.extension.llm.LlmGenerationConfig import org.pytorch.executorch.extension.llm.LlmCallback // Only needed for the multimodal ByteBuffer paths in the Images section. import java.nio.ByteBuffer import java.nio.ByteOrder ``` ### LlmModule[#](<https://docs.pytorch.org/executorch/stable/llm/run-on-android.html#llmmodule>) 那个... `LlmModule` class 提供了一个简单的界面,从 Java 和 Kotlin 中可以使用,用于装入文本生成模型,配置其表达器,生成令牌流,并停止执行。它也支持在文本提示的同时接受图像和音频输入的多式联运模型。 这个API是实验性的,可以改变. #### 初始化[#](<https://docs.pytorch.org/executorch/stable/llm/run-on-android.html#initialization>) 创建一个 `LlmModule` 通过指定您序列模型的路径( R) :`.pte`)和标识符文件。对于只使用文本的模型,简单的构建器就足够了: 爪哇语 : ``` LlmModule module = new LlmModule( "/data/local/tmp/llama-3.2-instruct.pte", "/data/local/tmp/tokenizer.model", 0.8f); ``` 科特林: 科特林: 科特林: ``` val module = LlmModule( "/data/local/tmp/llama-3.2-instruct.pte", "/data/local/tmp/tokenizer.model", 0.8f ) ``` 对于更细的控制(多模式型号,BOS / EOS处理,补充数据文件,负载模式),使用 `LlmModuleConfig` 与流畅的建筑者: 爪哇语 : ``` LlmModuleConfig config = LlmModuleConfig.create() .modulePath("/data/local/tmp/llama-3.2-instruct.pte") .tokenizerPath("/data/local/tmp/tokenizer.model") .temperature(0.8f) .modelType(LlmModuleConfig.MODEL_TYPE_TEXT) .loadMode(LlmModuleConfig.LOAD_MODE_MMAP) .build(); LlmModule module = new LlmModule(config); ``` 科特林: 科特林: 科特林: ``` val config = LlmModuleConfig.create() .modulePath("/data/local/tmp/llama-3.2-instruct.pte") .tokenizerPath("/data/local/tmp/tokenizer.model") .temperature(0.8f) .modelType(LlmModuleConfig.MODEL_TYPE_TEXT) .loadMode(LlmModuleConfig.LOAD_MODE_MMAP) .build() val module = LlmModule(config) ``` 可用负载模式为 `LOAD_MODE_FILE`, `LOAD_MODE_MMAP` (违约), `LOAD_MODE_MMAP_USE_MLOCK`,以及 `LOAD_MODE_MMAP_USE_MLOCK_IGNORE_ERRORS`。可用的模型类型是: `MODEL_TYPE_TEXT` 财务报告和财务报告 `MODEL_TYPE_TEXT_VISION` (单位:千美元) `MODEL_TYPE_MULTIMODAL` 常数是当前用于 `MODEL_TYPE_TEXT_VISION` ,并选择相同的运行时路径)。 构造本身是轻量级的,不会立即加载程序数据. #### 正在装入[#](<https://docs.pytorch.org/executorch/stable/llm/run-on-android.html#loading>) 在生成前明确加载该模型,以避免在您第一次加载期间支付载荷成本 `generate` 打电话。 爪哇语 : ``` int status = module.load(); if (status != 0) { // Handle load failure (status is an ExecuTorch runtime error code). } ``` 科特林: 科特林: 科特林: ``` val status = module.load() if (status != 0) { // Handle load failure (status is an ExecuTorch runtime error code). } ``` 如果你跳过这个步骤, 模型在第一个被懒散地装上 `generate` 打电话。 #### 正在生成[#](<https://docs.pytorch.org/executorch/stable/llm/run-on-android.html#generating>) 通过传递一个字段从文字提示生成符号 `LlmCallback` 当生成完成时,同样的调回也会收到一个JSON编码统计字符串。 爪哇语 : ``` LlmCallback callback = new LlmCallback() { @Override public void onResult(String token) { // Called once per generated token. Append to your UI buffer here. System.out.print(token); } @Override public void onStats(String statsJson) { // Called once when generation finishes. See extension/llm/runner/stats.h // for the field definitions. System.out.println("\n" + statsJson); } @Override public void onError(int errorCode, String message) { // Called if the runtime reports an error during generation. } }; module.generate("Once upon a time", callback); ``` 科特林: 科特林: 科特林: ``` val callback = object : LlmCallback { override fun onResult(token: String) { // Called once per generated token. Append to your UI buffer here. print(token) } override fun onStats(statsJson: String) { // Called once when generation finishes. See extension/llm/runner/stats.h // for the field definitions. println("\n$statsJson") } override fun onError(errorCode: Int, message: String) { // Called if the runtime reports an error during generation. } } module.generate("Once upon a time", callback) ``` 用于完全控制生成参数,使用 `LlmGenerationConfig`: 爪哇语 : ``` LlmGenerationConfig genConfig = LlmGenerationConfig.create() .seqLen(2048) .temperature(0.8f) .echo(false) .build(); module.generate("Once upon a time", genConfig, callback); ``` 科特林: 科特林: 科特林: ``` val genConfig = LlmGenerationConfig.create() .seqLen(2048) .temperature(0.8f) .echo(false) .build() module.generate("Once upon a time", genConfig, callback) ``` `LlmGenerationConfig` 曝光情况 `echo`, `maxNewTokens`, `seqLen`, `temperature`, `numBos`, `numEos`,以及 `warming`。默认值匹配 C++ `GenerationConfig` 记录 [C++ 运行 LLMS](<https://docs.pytorch.org/executorch/stable/llm/run-with-c-plus-plus.html>). #### 停止生成[#](<https://docs.pytorch.org/executorch/stable/llm/run-on-android.html#stopping-generation>) 如果你需要打断一个 长期运行的一代,打电话 `stop()` 从另一个线程(或从内部) `onResult` 回拨: 爪哇语 : ``` module.stop(); ``` 科特林: 科特林: 科特林: ``` module.stop() ``` 世代也同步运行在调用线条上, 所以要确保您引用 `generate()` 离主线(例如,在 `HandlerThread` 或通过 `java.util.concurrent.Executor`). #### 重设[#](<https://docs.pytorch.org/executorch/stable/llm/run-on-android.html#resetting>) 要从 KV 缓存中清除预填的符号,并将起始位置重置到 0 ,请打电话: 爪哇语 : ``` module.resetContext(); ``` 科特林: 科特林: 科特林: ``` module.resetContext() ``` 这相当于 `reset()` 在iOS跑车和 `reset()` 打开 C++ `IRunner`. ### 多式联运输入[#](<https://docs.pytorch.org/executorch/stable/llm/run-on-android.html#multimodal-inputs>) 对于被宣布为 `MODEL_TYPE_TEXT_VISION` (`MODEL_TYPE_MULTIMODAL` 目前是一个别名,图像和音频数据是通过专用的预填方法提供的。在预填所有模式后,调用 `generate()` ,并提示文本生成响应。 #### 图像[#](<https://docs.pytorch.org/executorch/stable/llm/run-on-android.html#images>) CHW 订单中的 Raw uint8 像素数据可以作为 `int[]`,或作为直接 `ByteBuffer` 以避开 JNI 数组副本 : 爪哇语 : ``` // As int[] int[] pixels = ...; // length == channels * height * width module.prefillImages(pixels, /*width=*/336, /*height=*/336, /*channels=*/3); // As direct ByteBuffer (preferred for large images) byte[] rawBytes = ...; // length == channels * height * width ByteBuffer buffer = ByteBuffer.allocateDirect(3 * 336 * 336); buffer.put(rawBytes); // Rewind so the JNI side reads from position 0. buffer.rewind(); module.prefillImages(buffer, 336, 336, 3); ``` 科特林: 科特林: 科特林: ``` // As IntArray val pixels: IntArray = ... // length == channels * height * width module.prefillImages(pixels, /* width = */ 336, /* height = */ 336, /* channels = */ 3) // As direct ByteBuffer (preferred for large images) val rawBytes: ByteArray = ... // length == channels * height * width val buffer = ByteBuffer.allocateDirect(3 * 336 * 336).apply { put(rawBytes) rewind() } module.prefillImages(buffer, 336, 336, 3) ``` 也支持预先正常的浮点像素数据,两者都作为 `float[]` 并作为一个直接 `ByteBuffer` 以本地字节顺序排列 。 `float[]` 超载是 `prefillImages`时, `ByteBuffer` 路径是 `prefillNormalizedImage` (名称反映了基础的JNI绑定,不可互换). 爪哇语 : ``` float[] normalized = ...; // length == channels * height * width module.prefillImages(normalized, 336, 336, 3); ByteBuffer floatBuffer = ByteBuffer .allocateDirect(3 * 336 * 336 * Float.BYTES) .order(ByteOrder.nativeOrder()); // fill floatBuffer with normalized values, then rewind before the call: floatBuffer.rewind(); module.prefillNormalizedImage(floatBuffer, 336, 336, 3); ``` 科特林: 科特林: 科特林: ``` val normalized: FloatArray = ... // length == channels * height * width module.prefillImages(normalized, 336, 336, 3) val floatBuffer: ByteBuffer = ByteBuffer .allocateDirect(3 * 336 * 336 * Float.SIZE_BYTES) .order(ByteOrder.nativeOrder()) // fill floatBuffer with normalized values, then rewind before the call: floatBuffer.rewind() module.prefillNormalizedImage(floatBuffer, 336, 336, 3) ``` #### 音频[#](<https://docs.pytorch.org/executorch/stable/llm/run-on-android.html#audio>) 预处理的音频功能(例如Whisper预处理器制作的mel光谱)可以提供为: `byte[]` 或 时 间 `float[]`: 爪哇语 : ``` module.prefillAudio(features, /*batchSize=*/1, /*nBins=*/128, /*nFrames=*/3000); ``` 科特林: 科特林: 科特林: ``` module.prefillAudio(features, /* batchSize = */ 1, /* nBins = */ 128, /* nFrames = */ 3000) ``` 可用原始音频样本提供 `prefillRawAudio`: 爪哇语 : ``` module.prefillRawAudio(samples, /*batchSize=*/1, /*nChannels=*/1, /*nSamples=*/16000); ``` 科特林: 科特林: 科特林: ``` module.prefillRawAudio(samples, /* batchSize = */ 1, /* nChannels = */ 1, /* nSamples = */ 16000) ``` #### 以多式联运预补生成[#](<https://docs.pytorch.org/executorch/stable/llm/run-on-android.html#generating-with-multimodal-prefill>) 预填每个模式后, 运行 `generate()` 如往常一样,在文字提示下: 爪哇语 : ``` module.prefillImages(pixels, 336, 336, 3); module.generate("What's in this image?", callback); ``` 科特林: 科特林: 科特林: ``` module.prefillImages(pixels, 336, 336, 3) module.generate("What's in this image?", callback) ``` 对于文本视觉模型,一个方便超载接受图像并一起提示: 爪哇语 : ``` module.generate( pixels, /*width=*/336, /*height=*/336, /*channels=*/3, "What's in this image?", /*seqLen=*/768, callback, /*echo=*/false); ``` 科特林: 科特林: 科特林: ``` module.generate( pixels, /* width = */ 336, /* height = */ 336, /* channels = */ 3, "What's in this image?", /* seqLen = */ 768, callback, /* echo = */ false ) ``` ## 演示[#](<https://docs.pytorch.org/executorch/stable/llm/run-on-android.html#demo>) 见 [Llama Android 演示应用软件](<https://github.com/meta-pytorch/executorch-examples/tree/main/llm/android/LlamaDemo>) 输入 `executorch-examples` 用于一个 end-to-end 电线项目 `LlmModule`, `LlmCallback`和 a 键 `HandlerThread` 进入聊天的UI。

查看原始来源