Transformers documentation

ExecuTorch

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.24.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

ExecuTorch

ExecuTorch 是一个用于边缘设备模型推理的轻量级运行时。它将 PyTorch 模型导出为可移植的提前编译格式。一个小型的 C++ 运行时负责规划内存,并将操作分派到特定于硬件的后端。由于在模型于设备上运行之前,其执行和内存行为就已经确定,因此推理开销较低。

使用 optimum-executorch 库导出 Transformers 模型。

CLI
Python
optimum-cli export executorch \
    --model "HuggingFaceTB/SmolLM2-135M-Instruct" \
    --task "text-generation" \
    --recipe "xnnpack" \
    --output_dir="./smollm2_exported"

Transformers 集成

导出过程使用了多个 Transformers 组件。

  1. from_pretrained() 以 safetensors 格式加载模型权重。
  2. Optimum 会应用图优化并运行 torch.export,以生成针对您的硬件后端的 model.pte 文件。
  3. AutoTokenizer 或 AutoProcessor 会加载分词器或处理器文件,并在推理阶段运行。
  4. 在运行时,C++ 运行器类会在 ExecuTorch 运行时上执行 .pte 文件。
#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("The capital of France is", config,
    [](const std::string& token) { std::cout << token << std::flush; },
    nullptr);

  return 0;
}

资源

Update on GitHub