# MLX

[MLX](https://ml-explore.github.io/mlx/build/html/index.html)は、Apple silicon向けの機械学習用アレイフレームワークであり、CUDAでも動作します。Apple siliconでは、CPUとGPU間のデータコピーを回避するために、アレイは共有メモリに保持されます。遅延計算により、グラフの操作と最適化が可能になります。[safetensors](https://huggingface.co/docs/safetensors/en/index)のネイティブサポートにより、Transformersの言語モデルをMLX上で直接実行できます。

[mlx-lm](https://github.com/ml-explore/mlx-lm) ライブラリをインストールします。

```bash
pip install mlx-lm transformers
```

モデルアーキテクチャが[サポート](https://huggingface.co/mlx-community/models)されている限り、Hubから任意のTransformers言語モデルを読み込むことができます。重みの変換は不要です。

```py
from mlx_lm import load, generate

model, tokenizer = load("openai/gpt-oss-20b")
output = generate(
    model,
    tokenizer,
    prompt="The capital of France is",
    max_tokens=100,
)
print(output)
```

## Transformers の統合

- [mlx_lm.load](https://github.com/ml-explore/mlx-lm?tab=readme-ov-file#python-api) は safetensor 形式の重みを読み込み、モデルとトークナイザーを返します。
- MLX は、テンソル名をキーとする重み配列を読み込み、MLX の [nn.Module](https://ml-explore.github.io/mlx/build/html/python/nn/module.html#) パラメータツリーにマッピングします。これは Transformers のチェックポイントの構成方法と一致しています。

> [!TIP]
> MLX Transformersの統合は双方向です。Transformersも、HubからMLXの重みをロードして実行できます。

## リソース

- [MLX](https://ml-explore.github.io/mlx/build/html/index.html)ドキュメント
- MLX LLMの実装を含む[mlx-lm](https://github.com/ml-explore/mlx-lm)リポジトリ
- VLMの実装を含むコミュニティライブラリ[mlx-vlm](https://github.com/Blaizzy/mlx-vlm)

