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.' 접두사로 인해 키가 누락되는 문제를 해결하는 방법

모든 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,
)

새 체크포인트의 경우 래핑되지 않은 모델을 저장하여 키가 처음부터 깨끗한 상태를 유지하도록 하십시오. 또한 로더는 예상되는 파라미터가 누락된 경우 이를 오류로 처리하여 무작위로 초기화된 가중치로 실수로 실행되는 것을 방지해야 합니다. 수정 후에는 compiled/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은 트랜스포머 블록을 재계산하여 활성화 메모리를 줄이며, --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