用ExecuTorch的C++运行库在端侧运行已导出的LLM
ExecuTorch的C++运行库为已导出为.pte格式的LLM提供文本生成的高层接口,统一处理分词、推理与逐词生成。导出时需写入动态形状支持和最大序列长度等元数据,运行库通过IRunner接口与统一的分词器接口组织生成流程,并建议在正式推理前先做预热运行。
## C++ 运行 LLMS[#](<https://docs.pytorch.org/executorch/stable/llm/run-with-c-plus-plus.html#running-llms-with-c>) 本指南解释如何使用 ExecuTorch 的 C++ 运行程序库来运行 LLM 已导出到 `.pte` 格式。运行库提供高级的 API ,用于文本生成和LLMS,处理符号化,推论,和符号生成。 ## 先决条件[#](<https://docs.pytorch.org/executorch/stable/llm/run-with-c-plus-plus.html#prerequisites>) 在开始前,请务必做到: 1. 一个模型导出到 `.pte` 使用该格式 `export_llm` API 中描述 [从框中导出流行的 LLMs](<https://docs.pytorch.org/executorch/stable/llm/export-llm.html>) 或 时 间 [导出自定义 LLMS](<https://docs.pytorch.org/executorch/stable/llm/export-custom-llm.html>). - 也请参见 [模型元数据](<https://docs.pytorch.org/executorch/stable/llm/run-with-c-plus-plus.html#model-metadata>) 用于将重要元数据序列化为 `.pte`. 2. 与您的模型兼容的标识器文件 - 对于 HuggingFace 表示器,这是 JSON 文件 `tokenizer.json` - 对于SentencePiece 表示器,这是一个 `tokenizer.model` 文件,通常与加权文件并存 3. CMake 和 C++ 编译器已安装 - CMake 版本 3.26 或更高 - g++ 或 clang 编译器 ## 模型元数据[#](<https://docs.pytorch.org/executorch/stable/llm/run-with-c-plus-plus.html#model-metadata>) 元数据包括了导出步骤中要包含的几个重要配置参数,这些参数将由导出程序库使用: 1. **`enable_dynamic_shape`**: 模型是否支持动态输入形状 2. **`max_seq_len`**: 模型可以处理的最大序列长度 3. **`max_context_len`**: KV缓存的最大上下文长度 4. **`use_kv_cache`**: 该模型是否使用 KV 缓存高效生成 5. **`get_bos_id`**: 序列开始符号 ID 6. **`get_eos_ids`**: 序列结束代号 ### 导出时添加元数据[#](<https://docs.pytorch.org/executorch/stable/llm/run-with-c-plus-plus.html#adding-metadata-during-export>) 为了确保您的模型具有必要的元数据,您可以在导出时使用 `metadata` 导出配置中的参数 : ``` # export_llm python -m extension.llm.export.export_llm \ --config path/to/config.yaml \ +base.metadata='{"get_bos_id":128000, "get_eos_ids":[128009, 128001], "get_max_context_len":4096}' ``` ## 建设运行者库[#](<https://docs.pytorch.org/executorch/stable/llm/run-with-c-plus-plus.html#building-the-runner-library>) ExecuTorch LLM 跑步库可以使用 CMake 构建。 要将其整合到您的项目中: 1. 在您的 CMake 计划中添加 ExecuTorch 作为依赖性 2. 启用所需的组件( extension_module , extension_tensor 等) 3. 将您的申请与 `extension_llm_runner` 图书馆 以下是CMake配置的简化例子: ``` # Enable required components set_overridable_option(EXECUTORCH_BUILD_EXTENSION_MODULE ON) set_overridable_option(EXECUTORCH_BUILD_EXTENSION_TENSOR ON) set_overridable_option(EXECUTORCH_BUILD_EXTENSION_LLM_RUNNER ON) # Add ExecuTorch as a dependency add_subdirectory(executorch) # Link against the LLM runner library target_link_libraries(your_app PRIVATE extension_llm_runner) ``` ## 建造Llama跑车[#](<https://docs.pytorch.org/executorch/stable/llm/run-with-c-plus-plus.html#building-the-llama-runner>) ExecuTorch提供了Llama 模型的 C++ 运行器在 [`examples/models/llama`](<https://github.com/pytorch/executorch/blob/main/examples/models/llama/README.md#step-3-run-on-your-computer-to-validate>) 目录。该运行器演示如何使用 LLM 运行导出到该目录的 Llama 模型 `.pte` 格式。 请注意,这个跑步库并不限于Llama型号,并且可以使用任何已导出到该型号的仅文本解码器的LLM型号. `.pte`. ## 基本用法示例[#](<https://docs.pytorch.org/executorch/stable/llm/run-with-c-plus-plus.html#basic-usage-example>) 以下是使用跑车的简单例子: ``` #include <executorch/extension/llm/runner/text_llm_runner.h> using namespace executorch::extension::llm; int main() { // Load tokenizer and create runner auto tokenizer = load_tokenizer("path/to/tokenizer.json", nullptr, std::nullopt, 0, 0); auto runner = create_text_llm_runner("path/to/model.pte", std::move(tokenizer)); // Load the model runner->load(); // Configure generation GenerationConfig config; config.max_new_tokens = 100; config.temperature = 0.8f; // Generate text with streaming output runner->generate("Hello, world!", config, [](const std::string& token) { std::cout << token << std::flush; }, nullptr); return 0; } ``` ## 运行者 API 架构[#](<https://docs.pytorch.org/executorch/stable/llm/run-with-c-plus-plus.html#the-runner-api-architecture>) ExecuTorch LLM跑车库的设计采用了模块化架构,将文本生成管道的不同组件之间的关切区分开来. ### IRunner 接口[#](<https://docs.pytorch.org/executorch/stable/llm/run-with-c-plus-plus.html#irunner-interface>) 那个... `IRunner` 接口( E)`irunner.h`)定义了 LLM 文本生成的核心功能。这个接口充当了与 LLM 模型交互的主要抽象 : ``` class IRunner { public: virtual ~IRunner() = default; virtual bool is_loaded() const = 0; virtual runtime::Error load() = 0; virtual runtime::Error generate(...) = 0; virtual runtime::Error generate_from_pos(...) = 0; virtual void stop() = 0; }; ``` 让我们详细研究每一种方法: ``` bool is_loaded() const ``` 检查模型和所有必要的资源是否已经装入内存并准备进行推断。这种方法在尝试生成文本之前对验证运行者的状态很有用 。 ``` runtime::Error load() ``` 装入模型并准备推论。其中包括: - 装入模型重量 `.pte` 文件 - 初始化任何必要的缓冲或缓存 - 准备执行环境 这种方法在任何一代人尝试之前都应该使用。它返回一个 `Error` 显示成功或失败的对象。 ``` runtime::Error generate( const std::string& prompt, const GenerationConfig& config, std::function<void(const std::string&)> token_callback, std::function<void(const Stats&)> stats_callback) ``` 文本生成的主要方法。 它需要: - `prompt`: 从 - `config`: 控制生成过程的配置参数 - `token_callback`: 接收每个生成的令牌作为字符串的调用函数 - `stats_callback`: 生成完成后接收性能统计的调用函数 符号回调是每个符号生成时的调用,允许流出输出。 数据回调提供代代完成后的详细性能度量。 ``` runtime::Error generate_from_pos( const std::string& prompt, int64_t start_pos, const GenerationConfig& config, std::function<void(const std::string&)> token_callback, std::function<void(const Stats&)> stats_callback) ``` 高级版本 `generate()` 允许从 KV 缓存中的特定位置启动生成。这对来自先前状态的连续生成很有用。 ``` void stop() ``` 立即停止生成循环。 通常从另一个线程中调用来中断一个长期运行的生成 。 ### GenerationConfig 结构[#](<https://docs.pytorch.org/executorch/stable/llm/run-with-c-plus-plus.html#generationconfig-structure>) 那个... `GenerationConfig` 结构控制生成过程的各个方面: ``` struct GenerationConfig { bool echo = true; // Whether to echo the input prompt in the output int32_t max_new_tokens = -1; // Maximum number of new tokens to generate bool warming = false; // Whether this is a warmup run int32_t seq_len = -1; // Maximum number of total tokens float temperature = 0.8f; // Temperature for sampling int32_t num_bos = 0; // Number of BOS tokens to add int32_t num_eos = 0; // Number of EOS tokens to add // Helper method to resolve the actual max_new_tokens based on constraints int32_t resolve_max_new_tokens(int64_t max_context_len, int64_t num_tokens_occupied) const; }; ``` 那个... `resolve_max_new_tokens` 方法处理根据下列条件决定可以产生多少个令牌的逻辑: - 模型的最大上下文长度 - 上下文窗口中已占用的符号位置数 - 用户指定的最大序列长度和最大新令牌 ### 执行构成部分[#](<https://docs.pytorch.org/executorch/stable/llm/run-with-c-plus-plus.html#implementation-components>) 跑步图书馆由几个专业部分组成,共同工作: #### TextLLMRunner[#](<https://docs.pytorch.org/executorch/stable/llm/run-with-c-plus-plus.html#textllmrunner>) 《公约》的主要执行情况 `IRunner` 界面,用于调节文本生成过程。它管理: 1. 输入文本的切换 2. 预填 KV 缓存, 并带有快速符号 3. 逐个生成新符号 4. 收集业绩统计 #### TextPrefiller[#](<https://docs.pytorch.org/executorch/stable/llm/run-with-c-plus-plus.html#textprefiller>) 负责处理初始的提示符并填充 KV 缓存。 关键特性 : - 高效处理大提示 - 处理动态序列长度 - 支持对性能优化进行并行的预填 #### TextTokenGenerator[#](<https://docs.pytorch.org/executorch/stable/llm/run-with-c-plus-plus.html#texttokengenerator>) 以自动递减的方式逐个生成新符号。 它 : - 管理符号生成循环 - 应用基于温度的取样 - 检测 end-of-sequence 条件 - 生成的符号流出 #### TextDecoderRunner[#](<https://docs.pytorch.org/executorch/stable/llm/run-with-c-plus-plus.html#textdecoderrunner>) 与 ExecuTorch 模块的接口来运行模型向前传。 它 : - 管理模型的投入和产出 - 处理 KV 缓存更新 - 通过采样将登录转换为符号 ## 切换器支持[#](<https://docs.pytorch.org/executorch/stable/llm/run-with-c-plus-plus.html#tokenizer-support>) 运行库通过一个统一的接口支持多个指示器格式 : ``` std::unique_ptr<tokenizers::Tokenizer> tokenizer = load_tokenizer( tokenizer_path, // Path to tokenizer file nullptr, // Optional special tokens std::nullopt, // Optional regex pattern (for TikToken) 0, // BOS token index 0 // EOS token index ); ``` 支持的符号格式包括: 1. **HuggingFace 调试器**: JSON 格式代号器 2. **SentencePiece**: `.model` 格式标识符 3. **TikToken**: BPE 表示器 4. **拉玛2c**: BPE 表示器,使用Llama2.c格式 对于自定义的标识器,您可以在 [meta-pytorch/tokenizers](<https://github.com/meta-pytorch/tokenizers>) 存储器。 ## 其他APIs 软件[#](<https://docs.pytorch.org/executorch/stable/llm/run-with-c-plus-plus.html#other-apis>) ### 模型温暖[#](<https://docs.pytorch.org/executorch/stable/llm/run-with-c-plus-plus.html#model-warmup>) 为了更准确的时间安排和最佳的表现,您应该在实际推断前先进行热身测试: ``` runner->warmup("Hello world", 10); // Generate 10 tokens as warmup ``` 热身期间: 1. 特别的 `GenerationConfig` 创建方式为: - `echo = false`: 输出中未包含提示 - `warming = true`: 表示这是热身跑步 - `max_new_tokens`: 设定为要生成的指定符号数 2. 该模型贯穿了整个一代的输油管: - 正在装入模型( 如果尚未装入) - 启动提示( T) - 预填 KV 缓存 - 生成指定的令牌数 3. 热身期间的特殊行为 : - 未向控制台显示托肯斯 - 跑步日志“做热跑......”和“温跑完毕!” 4. 热身后: - 那个... `Stats` 对象重置以清除性能度量度 - 模型仍然装满,可以进行实际推论 暖化对于精确的基准制定特别重要,因为第一个推论往往包括一次性初始化费用,这些成本将扭曲性能测量。 ### 内存使用监测[#](<https://docs.pytorch.org/executorch/stable/llm/run-with-c-plus-plus.html#memory-usage-monitoring>) 您可以用此监视内存使用情况 `Stats` 对象 : ``` std::cout << "RSS after loading: " << get_rss_bytes() / 1024.0 / 1024.0 << " MiB" << std::endl; ```
查看原始来源