The dataset could not be loaded because the splits use different data file formats, which is not supported. Read more about the splits configuration. Click for more details.
Error code: FileFormatMismatchBetweenSplitsError
Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.
MLX
Quickstart | Installation | Documentation | Examples
MLX is an array framework for machine learning on Apple silicon, brought to you by Apple machine learning research.
Some key features of MLX include:
Familiar APIs: MLX has a Python API that closely follows NumPy. MLX also has fully featured C++, C, and Swift APIs, which closely mirror the Python API. MLX has higher-level packages like
mlx.nnandmlx.optimizerswith APIs that closely follow PyTorch to simplify building more complex models.Composable function transformations: MLX supports composable function transformations for automatic differentiation, automatic vectorization, and computation graph optimization.
Lazy computation: Computations in MLX are lazy. Arrays are only materialized when needed.
Dynamic graph construction: Computation graphs in MLX are constructed dynamically. Changing the shapes of function arguments does not trigger slow compilations, and debugging is simple and intuitive.
Multi-device: Operations can run on any of the supported devices (currently the CPU and the GPU).
Unified memory: A notable difference from MLX and other frameworks is the unified memory model. Arrays in MLX live in shared memory. Operations on MLX arrays can be performed on any of the supported device types without transferring data.
MLX is designed by machine learning researchers for machine learning researchers. The framework is intended to be user-friendly, but still efficient to train and deploy models. The design of the framework itself is also conceptually simple. We intend to make it easy for researchers to extend and improve MLX with the goal of quickly exploring new ideas.
The design of MLX is inspired by frameworks like NumPy, PyTorch, Jax, and ArrayFire.
Examples
The MLX examples repo has a variety of examples, including:
- Transformer language model training.
- Large-scale text generation with LLaMA and finetuning with LoRA.
- Generating images with Stable Diffusion.
- Speech recognition with OpenAI's Whisper.
Quickstart
See the quick start guide in the documentation.
Installation
MLX is available on PyPI. To install MLX on macOS, run:
pip install mlx
To install the CUDA backend on Linux, run:
pip install mlx[cuda]
To install a CPU-only Linux package, run:
pip install mlx[cpu]
Checkout the documentation for more information on building the C++ and Python APIs from source.
ファインチューニング手法: LoRAとPRT
このリポジトリでは、Apple Silicon上で効率的にLLMをファインチューニングするための2つの手法を実装・提供しています。
LoRA (Low-Rank Adaptation)
概要
LoRAは、元のモデルの重みを変更せずに、低ランク行列を追加することでファインチューニングを行う手法です。メモリ効率が良く、複数のタスク用アダプターを切り替えて使用できます。
アーキテクチャ
元の計算: output = W × input
LoRA適用: output = (W + B × A) × input
W: 元の重み行列(固定、変更されない)
A, B: 低ランク行列(学習される)
rank: 低ランクの次元数(通常4-16)
特徴:
- 更新パラメータ: 全パラメータの0.1-1%(低ランク行列のみ)
- メモリ使用量: 小さい(モデルサイズの1.2-1.5倍)
- 保存容量: 非常に小さい(元のモデルの0.1-1%)
- 学習時間: 短い
- 性能: Full Fine-tuningに近い
実装方法
基本的な使い方:
# 仮想環境を有効化
source .venv/bin/activate
# LoRAファインチューニング
python -m mlx_lm lora \
--model ./models/tinyllama-1.1b \
--train --data ./finetune_data \
--num-layers 8 \
--lora-r 8 \
--learning-rate 1e-4 \
--iters 30
推奨パラメータ:
--lora-r: 8(低ランクの次元数)--num-layers: 8(適用する層数、TinyLlamaの場合は全22層中8層)--learning-rate: 1e-4--iters: 30
学習済みアダプターでの推論:
python -m mlx_lm chat \
--model ./models/tinyllama-1.1b \
--adapter-path ./adapters \
--prompt "### Instruction: 日本の首都はどこですか?\n### Response:"
アーキテクチャの詳細
TinyLlama-1.1Bでの実装例:
- モデル: TinyLlama-1.1B-Chat-v1.0
- LoRA適用層数: 8層(全22層中)
- LoRA rank: 8
- LoRA scale: 20.0
- 更新パラメータ: 約0.209%(2.294M/1100.048M)
- アダプターサイズ: 約8.8MB(元のモデルの0.44%)
パフォーマンス:
- トレーニング速度: 約5-6 it/sec
- トークン速度: 約250-300 tokens/sec
- ピークメモリ: 約2.4-2.5 GB
詳細は examples/prt_llm/README.md と knowledge/SLM_選定とファインチューニング手法と性能変化.md を参照してください。
PRT (Portable Reward Tuning)
概要
PRTは、ファインチューニングをreward最大化問題として再定式化し、rewardモデルを明示的に学習することで、異なるベースモデル間で再利用可能なファインチューニング手法です。論文「Portable Reward Tuning: Towards Reusable Fine-Tuning across Different Pretrained Models」(arXiv:2502.12776v1)に基づいています。
このリポジトリでの呼称(PRT1/2/3)
このREADMEでは、実装の違いを分かりやすくするために以下のように呼び分けます(いずれも「学習対象はRewardモデル」です)。
- PRT1: LinearのRewardヘッド(baseのhidden → vocabのreward logits):
examples/prt_llm/prt_llm.py - PRT2: Tiny Causal TransformerのRewardモデル(base hidden → 小型Transformer → vocab):
examples/prt_llm/prt_llm2.py - PRT3: Rewardモデルをベースモデルの完全コピー(別インスタンス)として学習:
examples/prt_llm/prt_llm_v3.py
アーキテクチャ
PRT1(Linear Reward Head)の基本構造:
Base Model (固定)
├── Transformer Layers (22層)
└── LM Head (Linear)
Reward Model (学習可能)
└── Reward Head (Linear)
├── Input: Base Modelのhidden states (2048次元)
└── Output: Reward logits (32000次元)
PRT合成:
v_θ = log softmax(base_logits) + reward_logits / λ
π_PRT = softmax(v_θ)
PRT2 (拡張版) - Tiny Causal Transformer Reward Model:
RewardTransformerRewardModel
├─ proj_in: Linear(2048 → 512)
├─ blocks: CausalTransformerBlock × L (L=2, default)
│ └─ block
│ ├─ norm1: RMSNorm(512)
│ ├─ attn: CausalSelfAttention(d=512, heads=8) + ALiBi
│ ├─ norm2: RMSNorm(512)
│ └─ mlp: SwiGLU FFN(512 → 2048 → 512)
├─ norm_out: RMSNorm(512)
└─ vocab_head: Linear(512 → 32000)
特徴:
- Base Modelのパラメータ: 完全に固定(変更されない)
- Reward Model: 独立したパラメータ(学習される)
- Portable性: 同じtokenizerを使用する異なるベースモデル間でrewardモデルを再利用可能
- 推論コスト(PRT1/2): Base Modelのforward passは1回のみ(効率的)
- パラメータ数: PRT1は約65M、PRT2は約26M(L=2の場合)
実装方法
PRT1(Linear Reward Head版)の使い方:
# 仮想環境を有効化
source .venv/bin/activate
# Rewardモデルの学習
python3 examples/prt_llm/prt_llm.py train \
--model ./models/tinyllama-1.1b \
--data ./finetune_data \
--output-dir ./prt_reward \
--learning-rate 1e-4 \
--iters 30 \
--lambda 1.0 \
--entropy-coeff 0.05
# PRTによる生成
python3 examples/prt_llm/prt_llm.py generate \
--model ./models/tinyllama-1.1b \
--reward ./prt_reward \
--prompt "### Instruction: 日本の首都はどこですか?\n### Response:" \
--max-tokens 100 \
--temp 0.7
PRT2(Tiny Transformer Reward版)の使い方:
# Rewardモデルの学習
python3 examples/prt_llm/prt_llm2.py train \
--model ./models/tinyllama-1.1b \
--data ./finetune_data \
--output-dir ./prt2_reward \
--lambda 1.0 \
--entropy-coeff 0.05 \
--reward-d-model 512 \
--reward-layers 2 \
--reward-heads 8 \
--reward-ffn-dim 2048
# PRT2による生成
python3 examples/prt_llm/prt_llm2.py generate \
--model ./models/tinyllama-1.1b \
--reward ./prt2_reward \
--prompt "### Instruction: 日本の首都はどこですか?\n### Response:" \
--max-tokens 100 \
--temp 0.7
損失関数
PRTの損失関数は以下の通りです:
# Algorithm 1 (論文準拠)
v_θ = log softmax(base_logits) + reward_logits / λ
π_PRT = softmax(v_θ)
loss = CE(π_PRT, y) + (-entropy_coeff * H(ρ_θ))
# ρ_θ = softmax(reward_logits) (reward-only分布)
# H(ρ_θ): Entropy正則化(崩壊防止)
パラメータ説明:
--lambda: KL正則化係数(デフォルト: 1.0)--entropy-coeff: Entropy正則化係数(デフォルト: 0.05)--reward-d-model: PRT2のTransformer次元(デフォルト: 512)--reward-layers: PRT2の層数(デフォルト: 2)
PRT vs LoRA の比較
| 観点 | LoRA | PRT1 | PRT2 | PRT3 |
|---|---|---|---|---|
| 更新パラメータ | 0.1-1% | 約6% | 約2.4% | ≈100%(Reward=Full Copy) |
| メモリ使用量 | 小さい | 中程度 | 中程度 | 大(モデル2本) |
| 学習時間 | 短い | 中程度 | やや長い | 長い |
| 保存容量 | 非常に小さい | 小さい | 小さい | 大 |
| Portable性 | なし(モデル依存) | あり(tokenizer一致が前提) | あり | あり |
| 推論速度 | 高速 | 高速 | 中速 | 低〜中(forward 2回) |
| 表現力 | 中程度 | 低(Linear) | 高(Transformer) | 高(Full Model) |
詳細は examples/prt_llm/README.md と knowledge/PRT_ネットワーク構造解説.md を参照してください。
PRT Implementation History & Architectures
開発の進展に伴い、PRTはその適用範囲をLLMからVLMへ、そして実験環境からHPC/実アプリケーションへと拡大してきました。以下に各バージョンの実装箇所と特徴を示します。
開発履歴一覧 (Version Summary):
| Ver | 環境 | モデル | LoRA | タスク | 実装箇所 (Path) | 特記事項 |
|---|---|---|---|---|---|---|
| PRT1 | Mac (MLX) | TinyLlama-1.1B | × | LLM | examples/prt_llm/prt_llm.py |
軽量Reward Head |
| PRT2 | Mac (MLX) | TinyLlama-1.1B | × | LLM | examples/prt_llm/prt_llm2.py |
高表現力Reward |
| PRT3 | Mac (MLX) | TinyLlama-1.1B | ◯ | LLM | examples/prt_llm/prt_llm_v3.py |
LLM標準 (Twin) |
| PRT4 | Mac (MLX) | DeepSeek-VL2 | ? | VLM | examples/prt_flickr30k |
Frozen (MoE負荷大) |
| PRT5 | Mac (MLX) | Qwen2-VL-2B | ◯ | VLM | examples/prt5_qwen2vl |
VLM標準 (Efficient) |
| PRT6 | Linux (PT) | Qwen2-VL-2B | ◯ | VLM | examples/prt6_pytorch |
PyTorch移植版 |
| PRT7 | HPC (Sing) | Qwen2-VL-2B | ◯ | VLM | examples/prt7_singularity |
コンテナ化 |
| PRT8 | Mac (MLX) | Qwen2-VL-2B | ◯ | VLM | examples/prt8_vlm |
汎用FW化 |
| PRT9 | Mac (MLX) | Qwen2-VL-2B | ◯ | DriveLM | examples/prt9_drivelm |
自動運転QA |
| PRT10 | Linux (PT) | Eagle2-1B | ◯ | DriveLM | examples/prt10_pytorch_drivelm |
(Conceptual/WIP) |
| PRT11 | Mac | Eagle2-1B | ◯ | DriveLM | examples/prt11_drivelm |
Mac実用版 (Active) |
| PRT12 | Any | Qwen2.5-VL | ◯ | General | examples/prt12_qwen25vl |
Transformers最小構成 (Wrapper) |
| PRT13 | Any | Qwen2.5-VL | ◯ | General | examples/prt13_qwen25vl |
Transformers標準設計 (Design A) |
以下に各フェーズの実装詳細を示します。
Phase 1: LLM Foundations (PRT1 - PRT3)
初期のPRTは、LLM(TinyLlama等)を対象に、Rewardモデルの構造を探索しました。
PRT1: Linear Reward Head
- 構造: ベースモデルの隠れ層から直接Linear層でRewardを計算。
- 特徴: 最も軽量だが、表現力が限定的。
- 実装:
examples/prt_llm/prt_llm.py
PRT2: Transformer Reward Model
- 構造: ベースモデルの隠れ層の上に、小さなTransformerブロックを追加。
- 特徴: 表現力と計算コストのバランスが良い。
- 実装:
examples/prt_llm/prt_llm2.py
PRT3: Twin Model Composition (Current Standard)
- 構造: Rewardモデルとして、ベースモデルと同じアーキテクチャのコピーを使用(別インスタンス)。
- 特徴: 最も表現力が高く、LoRA等の既存技術をそのまま適用可能。現在のPRTの標準形。
- 実装:
examples/prt_llm/prt_llm_v3.py
graph TD
subgraph PRT1 [PRT1: Linear]
B1[Base Model] --> H1[Hidden]
H1 --> L1[Linear Head]
L1 --> R1[Reward Logits]
end
subgraph PRT2 [PRT2: Tiny Transformer]
B2[Base Model] --> H2[Hidden]
H2 --> T2[Tiny Transformer]
T2 --> L2[Linear Head]
L2 --> R2[Reward Logits]
end
subgraph PRT3 [PRT3: Twin Model]
B3[Base Model] --> Log3[Base Logits]
RM3[Reward Model (Copy)] --> R3[Reward Logits]
Log3 -- "+" --> Sum
R3 -- "/ lambda" --> Sum
end
Phase 2: VLM Expansion on MLX (PRT4 - PRT5)
視覚情報を含むVLM(Vision-Language Model)への適用フェーズです。
PRT4: MoE VLM Experiment (Archived)
- 対象: DeepSeek-VL2 (Mixture-of-Experts)
- 結果: Mac M1でのMoE計算負荷とMLXの制約により開発凍結。
- ディレクトリ:
examples/prt_flickr30k
PRT5: Efficient VLM Tuning (Qwen2-VL)
- 対象: Qwen2-VL-2B-Instruct
- 構造: Vision Encoderからの特徴量を、BaseとRewardの両方のLLMに入力します。メモリ効率のためBaseは4bit量子化されています。
- 実装:
examples/prt5_qwen2vl
graph LR
Img[Image] --> V[Vision Encoder]
Txt[Text Prompt] --> Emb[Embedding]
V --> Concat
Emb --> Concat
Concat --> Base[Base LLM (4bit Frozen)]
Concat --> Reward[Reward LLM (LoRA Trainable)]
Base --> BL[Base Logits]
Reward --> RL[Reward Logits]
BL & RL --> PRT_Loss
Phase 3: Scaling to HPC (PRT6 - PRT7)
大学や研究所のHPC(スパコン)環境での学習を見据えたスケーリングフェーズです。
PRT6: PyTorch & Accelerate Port
- 内容: MLXの実装をPyTorch + Hugging Face Accelerateに移植。
- 目的: マルチGPU分散学習の実現。
- 実装:
examples/prt6_pytorch
PRT7: Singularity Containerization
- 内容: PRT6をSingularity (Apptainer) コンテナにパッケージング。
- 目的: 依存関係(CUDA, Libraries)の完全な再現性と、管理者権限のない共用スパコンでの実行。
- 実装:
examples/prt7_singularity
graph LR
subgraph HPC_Node [HPC Compute Node]
subgraph Singularity [Singularity Container (PRT7)]
Script[run_singularity.sh]
Env[Python venv / Dependencies]
Code[PRT6 PyTorch Code]
Script --> Env
Env --> Code
end
GPU[NVIDIA A100/H100 GPUs]
Code -.-> GPU
end
Phase 4: Generalization & Application (PRT8 - PRT9)
実用化に向けたリファクタリングと、複雑なタスクへの応用です。
PRT8: VLM Generalization Framework
- 内容: PRT5-7の知見を統合し、汎用的なVLM学習ライブラリとしてリファクタリング。
- 構造:
PRTForCausalLMクラスによるモデルの抽象化と、共通化されたデータハンドラ。 - 実装:
examples/prt8_vlm
PRT9: Autonomous Driving (DriveLM)
- 内容: 自動運転QAデータセット「DriveLM」への適用。
- 特徴: Preprocessによる特殊なJSON形式の変換と、高解像度画像の取り扱い。
- 実装:
examples/prt9_drivelm
graph TD
Raw[DriveLM Raw Data] --> Prep[preprocess_drivelm.py]
Prep --> JSONL[Formatted QA JSONL]
JSONL --> Load[DataLoader]
Img[High-Res Images] --> Load
subgraph PRT9_Training
Load --> PRT8[PRT8 Codebase]
Mod[Qwen2-VL-2B] -.-> PRT8
end
PRT8 --> ModelFile[Saved Model]
Phase 5: Real-World Adaptation & Challenges (PRT10 - PRT11)
実世界での運用(特にMacローカル環境やGPUリソースの制約)に向けた適応フェーズです。実装にあたり以下の「壁」がありました。
実装への壁 (Barriers):
- PyTorch環境: GPU環境の準備と依存関係の複雑さ。
- メモリ制約: フルファインチューニングは不可能。LoRAであってもVLM(Vision Model + LLM)はメモリ的に厳しい。
- タスクの変化: LLMからVLM(DriveLM)への移行。論文実装にあるViT(Vision Transformer)の実装が存在しないため、独自に構築する必要があった。
これらの課題を乗り越えるため、以下の2つのアプローチを実装しました。
| バージョン | 環境 | モデル | LoRA | タスク | ステータス |
|---|---|---|---|---|---|
| 論文実装 | PyTorch | LLM/(ViT) | QLoRA | Llama | (Reference) |
| PRT10 | PyTorch (GPU) | VLM | LoRA | DriveLM | 実装済み |
| PRT11 | Mac (Metal) | VLM | LoRA | DriveLM | 稼働中 (Code Exists) |
| (Future) | ? | VLM | Full FT | DriveLM | 未生成 |
PRT10: PyTorch VLM (LoRA)
- 環境: Linux / PyTorch / CUDA
- 特徴: PRT9のコンセプトをPyTorchネイティブ環境に移植。標準的なGPUサーバーでの学習を想定。
- 実装:
examples/prt10_pytorch_drivelm(Conceptual/WIP)
PRT11: Mac Metal VLM (LoRA)
- 環境: Mac M1/M2/M3 (Metal/MPS)
- 特徴:
nvidia/Eagle2-1Bモデルを採用し、MacBook Pro等のローカル環境で学習可能に最適化。- Dynamic Patching:
transformersライブラリやモデルのリモートコードに対し、実行時に動的にパッチを適用することで、FlashAttention非対応環境(Mac)での動作を強制。 - Memory Efficient: 1BクラスのモデルとLoRAを組み合わせることで、ユニファイドメモリ環境での動作を実現。
- 実装:
examples/prt11_drivelm/train_prt11.py
PRT12: Transformers Minimal Implementation
- 環境: Any (PyTorch + Transformers)
- 特徴:
mlxや複雑な依存関係を排除し、transformersとpeftのみで構成された最小実装。- Qwen2.5-VL を対象に、Algorithm 1 (学習) と Algorithm 2 (推論) のロジックをブラックボックスなしで実装。
- 教育的価値: PRTの動作原理(Logits合成)を理解するための参照実装として最適です。
- 実装:
examples/prt12_qwen25vl
PRT13: Transformers Standard Implementation (Design A)
- 環境: Any (PyTorch + Transformers)
- 特徴:
- PRTの「王道」とされる設計パターン(Design A)。
- 構成:
- Trainer継承:
PRTTrainerで学習ロジックをカプセル化し、標準エコシステム(SFT Trainer等)との親和性を確保。 - Generator分離:
PRTGeneratorで推論ロジックを独立させ、「モデルスワッピング実験(Baseモデルを入れ替えてAdapterのポータビリティを検証)」 を容易に。
- Trainer継承:
- 成果物: 純粋なLoRAアダプタのみ(モデルコード不要)。
- 実装:
examples/prt13_qwen25vl
PRT Architecture Details (Mechanism of Portability)
PRTの最大の利点である「ポータビリティ(学習時と推論時で異なるモデルサイズを扱える)」を実現するアーキテクチャの詳細です。
1. Core Concept: Logits Composition
PRTはモデル内部の隠れ層ではなく、最終出力である 「語彙空間(Logits)」 のレベルで結合を行います。これにより、モデルサイズ(7B vs 2B)が異なっていても、使用している「辞書(Tokenizer)」さえ同じであれば計算が可能になります。
2. Architecture: Training vs Inference
学習フェーズ (Training Phase): 計算コストを抑えるため、「小さなモデル同士」(2B + 2B)で学習を行います。
- Base Model (Reference): Qwen2-VL-2B (Frozen)
- Reward Model: Qwen2-VL-2B (Frozen) + LoRA Adapter (Trainable)
graph LR
Dataset --> Input
Input --> Base["Reference (2B)"]
Input --> Reward["Reward (2B)"]
subgraph RewardModel [Reward Model Composition]
Reward --> LoRA["LoRA Adapter (Trainable)"]
LoRA -.-> RewardOut[Logits]
end
Base -.-> Loss
RewardOut --> Loss
Loss --> Update["Update LoRA Params"]
style LoRA fill:#f96,stroke:#333,stroke-width:2px
style Base fill:#eee,stroke:#333,stroke-dasharray: 5 5
推論フェーズ (Inference Phase): 獲得したRewardモデル(2B + LoRA)を、「大きなモデル(7B)」 の推論プロセスに組み込みます。 重要な点として、Rewardモデルを7Bモデルに移植するわけではありません。Rewardモデルは2Bのまま独立して並走し、その出力を7Bモデルの出力に「加算」することで生成をガイドします。
- Base Model: Qwen2-VL-7B (Frozen) <-- ここだけ入れ替える
- Reward Model: Qwen2-VL-2B (Frozen) + LoRA Adapter (Frozen) <-- ずっと2Bのまま並走
- 操作: Logits Level Addition (出力の単純合成)
graph LR
Prompt --> Input
Input --> Base["Base (swapped to 7B)"]
Input --> Reward["Reward (stays 2B)"]
subgraph RewardComponents [Reward + LoRA]
Reward --> LoRA_Inf["LoRA Adapter (Frozen)"]
LoRA_Inf --> RewardLogits[Reward Logits]
end
Base --> BaseLogits[Base Logits]
BaseLogits -- "Log Probability" --> Add
RewardLogits -- "Reward (R/λ)" --> Add
Add["Compose (Logits Addition) v = log P + R/λ"] --> Output
style LoRA_Inf fill:#f96,stroke:#333,stroke-width:2px
このアーキテクチャにより、「学習コストは2B相当、推論能力は7B相当」 という効率的な運用が可能になります。
3. Full Fine-Tuning (Original PRT) vs LoRA
現在の実装 (train_prt5.py) はメモリ効率のため LoRA を使用していますが、論文通りの Full Fine-Tuning(全パラメータ学習)を行うことも可能です。
その場合はコードの以下の部分を変更します(ロジックやLoss関数は変更不要です)。
# train_prt5.py の変更イメージ
# Current (LoRA)
reward_model.freeze() # 1. 全体を凍結
apply_lora(reward_model) # 2. LoRA層のみ追加・学習
# Target (Full FT)
# reward_model.freeze() # 1. 凍結しない(または Unfreeze)
# apply_lora(reward_model) # 2. LoRAは適用しない(スキップ)
これにより、Optimizerはモデル全体のパラメータを学習対象として更新するようになります。
Contributing
Check out the contribution guidelines for more information on contributing to MLX. See the docs for more information on building from source, and running tests.
We are grateful for all of our contributors. If you contribute to MLX and wish to be acknowledged, please add your name to the list in your pull request.
Citing MLX
The MLX software suite was initially developed with equal contribution by Awni Hannun, Jagrit Digani, Angelos Katharopoulos, and Ronan Collobert. If you find MLX useful in your research and wish to cite it, please use the following BibTex entry:
@software{mlx2023,
author = {Awni Hannun and Jagrit Digani and Angelos Katharopoulos and Ronan Collobert},
title = {{MLX}: Efficient and flexible machine learning on Apple silicon},
url = {https://github.com/ml-explore},
version = {0.0},
year = {2023},
}
- Downloads last month
- 3