OpenSource-Hub

train-llm-from-scratch

チュートリアル

FareedKhan-dev/train-llm-from-scratch

自分の大規模言語モデルをゼロから訓練する:データからテキスト生成まで。

概要

「Attention is All You Need」論文に基づき、ゼロからTransformerモデルを構築する入門チュートリアル。データ準備、モデルアーキテクチャ、Pileデータセットでのトレーニング、テキスト生成をカバー。大規模言語モデルの内部原理を理解するための実践的なコード。

README プレビュー

\n\n\n\n\n# Train LLM From Scratch\n  \n   [](#step-by-step-code-explanation)\n\n**I am Looking for a PhD position in AI**. [GitHub](https://github.com/FareedKhan-dev)\n\n\n\nI implemented a transformer model from scratch using PyTorch, based on the paper [Attention is All You Need](https://arxiv.org/abs/1706.03762). You can use my scripts to train your own **billion** or **million** parameter LLM using a single GPU.\n\nBelow is the output of the trained 13 million parameter LLM:\n\n```\nIn ***1978, The park was returned to the factory-plate that \nthe public share to the lower of the electronic fence that \nfollow from the Station's cities. The Canal of ancient Western \nnations were confined to the city spot. The villages were directly \nlinked to cities in China that revolt that the US budget and in\nOdambinais is uncertain and fortune established in rural areas.\n```\n\n## Table of Contents\n- [Training Data Info](#training-data-info)\n- [Prerequisites and Training Time](#prerequisites-and-training-time)\n- [Code Structure](#code-structure)\n- [Usage](#usage)\n- [Step by Step Code Explanation](#step-by-step-code-explanation)\n  - [Importing Libraries](#importing-libraries)\n  - [Preparing the Training Data](#preparing-the-training-data)\n  - [Transformer Overview](#transformer-overview)\n  - [Multi Layer Perceptron (MLP)](#multi-layer-perceptron-mlp)\n  - [Single Head Attention](#single-head-attention)\n  - [Multi Head Attention](#multi-head-attention)\n  - [Transformer Block](#transformer-block)\n  - [The Final Model](#the-final-model)\n  - [Batch Processing](#batch-processing)\n  - [Training Parameters](#training-parameters)\n  - [Training the Model](#training-the-model)\n  - [Saving the Trained Model](#saving-the-trained-model)\n  - [Training Loss](#training-loss)\n  - [Generating Text](#generating-text)\n- [What’s Next](#whats-next)\n\n## Training Data Info\n\nTraining data is from the Pile dataset, which is a diverse, open-source, and large-scale dataset fo

FAQ (5)

トラブル対応
torch.compile と DDP で保存した PyTorch チェックポイントを読み込む際に '_orig_mod.' プレフィックスが原因で missing keys が発生する問題の修正方法

すべての state-dict キーから、DDP と torch.compile の両方のラッパープレフィックスを繰り返し取り除きます。これらは任意の順序でネストされている可能性があるためです。単一の module. チェックを次のように置き換えます:

def _strip_ddp_prefix(state_dict: dict) -> dict:
    out = {}
    for k, v in state_dict.items():
        while k.startswith("module.") or k.startswith("_orig_mod."):
            k = k.removeprefix("module.").removeprefix("_orig_mod.")
        out[k] = v
    return out

推論や評価を含む、すべてのチェックポイント読み込みパスでこの同じ関数を使用します:

from src.post_training.utils import _strip_ddp_prefix

state = ck["model_state_dict"] if "model_state_dict" in ck else ck
state = _strip_ddp_prefix(state)
model.load_state_dict(
    {k: v for k, v in state.items() if k in model.state_dict()},
    strict=False,
)

新しいチェックポイントでは、キーが最初からクリーンな状態になるよう、ラップされていないモデルを保存します。また、ローダーは、ランダムに初期化された重みで誤って実行してしまうことを防ぐため、期待されるパラメータが欠落している場合をエラーとして扱う必要があります。この修正後、コンパイル済み/DDP チェックポイントは missing: 0 キーで読み込まれるはずです。

参照 Issue #36
トラブル対応
CPUのみのノートパソコンで、小規模なLLMをゼロから学習させるにはどうすればよいですか?

リポジトリの CPU フレンドリーな laptop/tiny プリセットを使用します。まず TinyStories データセットを準備して BPE トークナイザーを学習し、次に 369K パラメータのモデルを学習し、最後にテキストを生成します:

python scripts/prepare_tiny_data.py
python scripts/train_transformer.py --preset tiny --arch modern
python scripts/generate_text.py --model_path models/tiny.pt

tiny プリセットは CPU のみのマシン向けに設計されており、一般的なラップトップ CPU で約 5 分かかります。より大きな student および small プリセットも利用可能です。python scripts/benchmark.py を実行してお使いのハードウェアでの学習時間を確認し、ガイド付き学習パスについては docs/student を参照してください。

参照 Issue #38
トラブル対応
A100 40GBでデフォルトの3Bパラメータのトランスフォーマーを学習する際にCUDA out of memoryを修正するにはどうすればよいですか?

OOM は想定どおりの動作です。デフォルトの設定では約 3B のパラメータ(N_EMBED=2048、N_BLOCKS=64)が使用され、オプティマイザの状態とアクティベーションを合わせると 40GB を超えるためです。PR #29 を含むバージョンに更新し、オプトインのメモリ最適化を有効にして学習を実行してください:

python scripts/train_transformer.py --amp --amp-dtype bf16 --grad-checkpointing --grad-accum 8

学習を開始する前に VRAM 使用量を見積もるには:

python scripts/train_transformer.py --report-memory

--amp は混合精度を有効にし、--grad-checkpointing は Transformer ブロックを再計算することでアクティベーションメモリを削減し、--grad-accum 8 はより小さなマイクロバッチを使って大きなバッチをシミュレートします。これらの変更により、3B の設定が A100 40GB に収まるようになり、RTX 3090/4090/5090 クラスの GPU でも VRAM 使用量を削減できます。断片化が報告された場合は、以下も試してください:

PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True python scripts/train_transformer.py --amp --amp-dtype bf16 --grad-checkpointing --grad-accum 8

参照 Issue #5
トラブル対応
中断したLLMのトレーニングを最新のチェックポイントから再開するにはどうすればよいですか?

チェックポイントからの再開サポートは、main の scripts/train_transformer.py で利用可能です。トレーニング中は、--checkpoint-every N で定期的なチェックポイントを有効にし、--keep-last K を使って最新のチェックポイントのみを保持します。中断後は、--resume latest で最新のチェックポイントを読み込んで再開するか、--resume /path/to/checkpoint.pt で特定のチェックポイントを指定して再開します。復元されるチェックポイントには、モデルの重み、オプティマイザの状態、LRスケジューラの状態、損失履歴、および最後に完了したステップが含まれているため、トレーニングは次のステップから継続されます。例: python scripts/train_transformer.py --checkpoint-every 1000 --keep-last 3 --resume latest。チェックポイントは、一時ファイルと os.replace を使ってアトミックに書き込まれるため、保存中にプロセスがクラッシュした場合の破損リスクが低減されます。

参照 Issue #16
トラブル対応
README.md 内で 404 を返す壊れた Google Drive リンクは、どう修正すればよいですか?

404 は、Google Drive のファイルが削除されたか、共有権限がプライベートになっていることを意味します。README.md から壊れたリンクを削除するか、Google Drive でリンク共有を有効にしてから有効な共有リンクに置き換えてください。報告されたケースでは、https://drive.google.com/file/d/1Q_iklJ1RVGSb-Pdey8BHy3k8IF3UJv0z/view を削除し、代わりに GitHub への参照を残すことが修正方法でした。変更をコミットしてください。例: git add README.md && git commit -m "fix: remove broken resume Google Drive link"

参照 Issue #11