# ExecuTorch

[ExecuTorch](https://docs.pytorch.org/executorch/stable/index.html)は、エッジデバイスでのモデル推論のための軽量ランタイムです。PyTorchモデルをポータブルなAOT（Ahead-of-Time）形式にエクスポートします。小型の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/ja/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/ja/model_doc/auto#transformers.AutoTokenizer) または [AutoProcessor](/docs/transformers/main/ja/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)ガイド

