# ExecuTorch

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

使用 [optimum-executorch](https://huggingface.co/docs/optimum-executorch/en/index) 库导出 Transformers 模型。

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

```py
from transformers import AutoTokenizer
from optimum.executorch import ExecuTorchModelForCausalLM

model = ExecuTorchModelForCausalLM.from_pretrained(
    "HuggingFaceTB/SmolLM2-135M-Instruct",
    recipe="xnnpack",
)
model.save_pretrained("./smollm2_exported")
tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct")
```

## Transformers 集成

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

1. [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 以 safetensors 格式加载模型权重。
2. Optimum 会应用图优化并运行 [torch.export](https://docs.pytorch.org/docs/stable/export.html)，以生成针对您的硬件后端的 `model.pte` 文件。
3. [AutoTokenizer](/docs/transformers/main/zh/model_doc/auto#transformers.AutoTokenizer) 或 [AutoProcessor](/docs/transformers/main/zh/model_doc/auto#transformers.AutoProcessor) 会加载分词器或处理器文件，并在推理阶段运行。
4. 在运行时，C++ 运行器类会在 ExecuTorch 运行时上执行 `.pte` 文件。

```c++
#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;
}
```

## 资源

- [ExecuTorch](https://docs.pytorch.org/executorch/stable/index.html) 文档
- [torch.export](https://docs.pytorch.org/docs/stable/export.html) 文档
- [导出到生产环境](../serialization#executorch)指南

