# ExecuTorch

[ExecuTorch](https://docs.pytorch.org/executorch/stable/index.html) là một runtime nhẹ để suy luận mô hình trên các thiết bị biên. Nó xuất một mô hình PyTorch sang định dạng di động, biên dịch trước. Một runtime C++ nhỏ lập kế hoạch bộ nhớ và điều phối các thao tác đến các backend phần cứng cụ thể. Hành vi thực thi và bộ nhớ được xác định trước khi mô hình chạy trên thiết bị, do đó chi phí suy luận thấp.

Xuất mô hình Transformers bằng thư viện [optimum-executorch](https://huggingface.co/docs/optimum-executorch/en/index).

```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")
```

## Tích hợp Transformers

Quy trình xuất sử dụng một số thành phần của Transformers.

1. [from_pretrained()](/docs/transformers/main/vi/main_classes/model#transformers.PreTrainedModel.from_pretrained) tải trọng số mô hình ở định dạng safetensors.
2. Optimum áp dụng các tối ưu hóa đồ thị và chạy [torch.export](https://docs.pytorch.org/docs/stable/export.html) để tạo tệp `model.pte` nhắm đến backend phần cứng của bạn.
3. [AutoTokenizer](/docs/transformers/main/vi/model_doc/auto#transformers.AutoTokenizer) hoặc [AutoProcessor](/docs/transformers/main/vi/model_doc/auto#transformers.AutoProcessor) sẽ nạp các tệp tokenizer hoặc processor và chạy trong quá trình suy luận.
4. Vào thời điểm thực thi, một lớp runner C++ sẽ thực thi tệp `.pte` trên runtime ExecuTorch.

```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;
}
```

## Tài nguyên

- Tài liệu [ExecuTorch](https://docs.pytorch.org/executorch/stable/index.html)
- Tài liệu [torch.export](https://docs.pytorch.org/docs/stable/export.html)
- hướng dẫn [Xuất ra môi trường sản xuất](../serialization#executorch)

