File size: 26,131 Bytes
09c07bd |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 |
# MLX
[**Quickstart**](#quickstart) | [**Installation**](#installation) |
[**Documentation**](https://ml-explore.github.io/mlx/build/html/index.html) |
[**Examples**](#examples)
[](https://circleci.com/gh/ml-explore/mlx)
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](https://github.com/ml-explore/mlx-c), and
[Swift](https://github.com/ml-explore/mlx-swift/) APIs, which closely mirror
the Python API. MLX has higher-level packages like `mlx.nn` and
`mlx.optimizers` with 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](https://numpy.org/doc/stable/index.html),
[PyTorch](https://pytorch.org/), [Jax](https://github.com/google/jax), and
[ArrayFire](https://arrayfire.org/).
## Examples
The [MLX examples repo](https://github.com/ml-explore/mlx-examples) has a
variety of examples, including:
- [Transformer language model](https://github.com/ml-explore/mlx-examples/tree/main/transformer_lm) training.
- Large-scale text generation with
[LLaMA](https://github.com/ml-explore/mlx-examples/tree/main/llms/llama) and
finetuning with [LoRA](https://github.com/ml-explore/mlx-examples/tree/main/lora).
- Generating images with [Stable Diffusion](https://github.com/ml-explore/mlx-examples/tree/main/stable_diffusion).
- Speech recognition with [OpenAI's Whisper](https://github.com/ml-explore/mlx-examples/tree/main/whisper).
## Quickstart
See the [quick start
guide](https://ml-explore.github.io/mlx/build/html/usage/quick_start.html)
in the documentation.
## Installation
MLX is available on [PyPI](https://pypi.org/project/mlx/). To install MLX on
macOS, run:
```bash
pip install mlx
```
To install the CUDA backend on Linux, run:
```bash
pip install mlx[cuda]
```
To install a CPU-only Linux package, run:
```bash
pip install mlx[cpu]
```
Checkout the
[documentation](https://ml-explore.github.io/mlx/build/html/install.html#)
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に近い
#### 実装方法
**基本的な使い方**:
```bash
# 仮想環境を有効化
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
**学習済みアダプターでの推論**:
```bash
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`](examples/prt_llm/README.md) と [`knowledge/SLM_選定とファインチューニング手法と性能変化.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版)の使い方**:
```bash
# 仮想環境を有効化
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版)の使い方**:
```bash
# 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の損失関数は以下の通りです:
```python
# 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`](examples/prt_llm/README.md) と [`knowledge/PRT_ネットワーク構造解説.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`
```mermaid
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`
```mermaid
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`
```mermaid
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`
```mermaid
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):**
1. **PyTorch環境**: GPU環境の準備と依存関係の複雑さ。
2. **メモリ制約**: フルファインチューニングは不可能。LoRAであってもVLM(Vision Model + LLM)はメモリ的に厳しい。
3. **タスクの変化**: 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のポータビリティを検証)」** を容易に。
- **成果物**: 純粋なLoRAアダプタのみ(モデルコード不要)。
- **実装**: `examples/prt13_qwen25vl`
---
### PRT Architecture Details (Mechanism of Portability)
PRTの最大の利点である「ポータビリティ(学習時と推論時で異なるモデルサイズを扱える)」を実現するアーキテクチャの詳細です。
#### 1. Core Concept: Logits Composition
PRTはモデル内部の隠れ層ではなく、最終出力である **「語彙空間(Logits)」** のレベルで結合を行います。これにより、モデルサイズ(7B vs 2B)が異なっていても、使用している「辞書(Tokenizer)」さえ同じであれば計算が可能になります。
$$ v_\theta(y|x) = \log P_{\text{Base}}(y|x) + \frac{R_\phi(y|x)}{\lambda} $$
#### 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)
```mermaid
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 (出力の単純合成)**
```mermaid
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関数は変更不要です)。
```python
# 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](https://github.com/ml-explore/mlx/tree/main/CONTRIBUTING.md) for more information
on contributing to MLX. See the
[docs](https://ml-explore.github.io/mlx/build/html/install.html) for more
information on building from source, and running tests.
We are grateful for all of [our
contributors](https://github.com/ml-explore/mlx/tree/main/ACKNOWLEDGMENTS.md#Individual-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:
```text
@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},
}
```
|