메뉴
HN
Hacker News 26일 전

밑바닥부터 LLM 직접 만들어보기

IMP
8/10
핵심 요약

이 워크숍은 허깅페이스 등의 블랙박스 라이브러리 없이, 순수 파이토치만으로 GPT 모델을 밑바닥부터 직접 코딩하고 학습시키는 실습 중심 가이드입니다. 약 1,000만 개(10M) 파라미터 규모의 경량 모델을 노트북에서 한 시간 만에 학습시킬 수 있도록 안내합니다. AI 입문자부터 실무자까지 트랜스포머(Transformer)의 근본적인 작동 원리를 완벽히 이해하고 싶은 개발자에게 매우 유용한 자료입니다.

번역된 본문

밑바닥부터 나만의 LLM 학습시키기

이 워크숍은 GPT 학습 파이프라인의 모든 코드를 직접 작성해 보는 실습 프로그램입니다. 각 구성 요소가 무엇을 하고 왜 필요한지 직관적으로 이해할 수 있습니다.

Andrej Karpathy의 nanoGPT는 내가 LLM과 트랜스포머를 처음으로 제대로 접하게 된 계기였습니다. 단 수백 줄의 PyTorch 코드로 작동하는 언어 모델을 만들 수 있다는 것을 보고, AI에 대한 내 생각이 완전히 바뀌었고 이 분야를 더 깊이 파고들게 되었습니다. 이 워크숍은 다른 사람들에게도 똑같은 경험을 선사하기 위해 기획했습니다.

nanoGPT는 GPT-2(1억 2,400만 파라미터)를 재현하는 것을 목표로 하며 매우 광범위한 내용을 다룹니다. 본 프로젝트는 이를 핵심적인 요소만 남기고 축소하여, 노트북에서 1시간 이내로 학습 가능한 약 1,000만(10M) 파라미터 모델로 확장했습니다. 단일 워크숍 세션 내에 끝낼 수 있도록 설계되었습니다. 블랙박스 라이브러리는 사용하지 않습니다. model = AutoModel.from_pretrained() 같은 추상화된 코드도 없습니다. 모든 것을 직접 만들게 됩니다.

만들게 될 것 MacBook에서 밑바닥부터 학습시킨, 셰익스피어 풍의 텍스트를 생성할 수 있는 작동하는 GPT 모델입니다. 여러분이 직접 작성할 내용은 다음과 같습니다:

  • Tokenizer(토크나이저) — 텍스트를 모델이 처리할 수 있는 숫자로 변환
  • Model architecture(모델 아키텍처) — 트랜스포머: 임베딩, 어텐션, 피드포워드 레이어
  • Training loop(학습 루프) — 순전파, 손실 함수, 역전파, 옵티마이저, 학습률 스케줄링
  • Text generation(텍스트 생성) — 학습된 모델에서 샘플링

사전 준비 사항

  • 아무 노트북이나 데스크톱 (Mac, Linux, 또는 Windows)
  • Python 3.12 이상
  • Python 코드를 읽을 수 있는 수준 (머신러닝 경험이 없어도 됩니다)

학습은 Apple Silicon GPU(MPS), NVIDIA GPU(CUDA) 또는 CPU를 자동으로 인식해 사용합니다. Google Colab에서도 작동합니다. 파일들을 업로드하고 !python train.py로 실행하면 됩니다.

시작하기

Local (권장) uv가 설치되어 있지 않다면 설치합니다:

# macOS / Linux
curl -LsSf https://astral.sh/uv/install.sh | sh

# Windows
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

그런 다음 프로젝트를 설정합니다:

uv sync
mkdir scratchpad && cd scratchpad

Google Colab 로컬 환경이 준비되지 않았다면, 리포지토리를 Colab에 업로드하고 종속성을 설치합니다:

!pip install torch numpy tqdm tiktoken

data/shakespeare.txt를 Colab 파일에 업로드한 다음, 노트북 셀에서 코드를 작성하거나 .py 파일을 업로드하고 !python train.py로 실행합니다.

문서를 순서대로 따라 하세요. 각 파트는 파이프라인의 한 조각을 작성하도록 안내하며, 각 구성 요소가 수행하는 작업과 그 이유를 설명합니다. 모두 마치면 여러분이 직접 작성한 model.py, train.py, generate.py가 완성될 것입니다.

  • 1부: 토큰화(Tokenization) — 문자 수준 토크나이저. 문자 인코딩, 어휘 크기(Vocabulary size), 작은 데이터에서 BPE가 실패하는 이유
  • 2부: 트랜스포머(The Transformer) — 완전한 GPT 모델 아키텍처. 임베딩, 셀프 어텐션, 레이어 정규화(Layer Norm), MLP 블록
  • 3부: 학습 루프(The Training Loop) — 완전한 학습 파이프라인. 손실 함수(Loss functions), AdamW, 그래디언트 클리핑, 학습률 스케줄링
  • 4부: 텍스트 생성(Text Generation) — 추론 및 샘플링. 온도(Temperature), top-k, 자기회귀 디코딩(Autoregressive decoding)
  • 5부: 전체 결합(Putting It All Together) — 실제 데이터로 학습 및 실험. 손실 곡선(Loss curves), 스케일링 실험, 다음 단계
  • 6부: 경진대회(Competition) — 최고의 AI 시인 만들기. 데이터셋 찾기, 규모 확장, 최고의 시 제출

아키텍처: GPT 한눈에 보기

Input Text
│
▼
┌─────────────────┐
│     Tokenizer   │ "hello" → [20, 43, 50, 50, 53] (문자 수준)
└────────┬────────┘
         ▼
┌─────────────────┐
│ Token Embed +   │ 토큰 ID → 벡터(n_embd 차원)
│ Position Embed  │ + 위치 정보(Positional information)
└────────┬────────┘
         ▼
┌─────────────────┐
│   Transformer   │ × n_layer
│       Block:    │
│ ┌────────────┐  │
│ │  LayerNorm │  │
│ │ Self-Attn  │  │ n_head개의 병렬 어텐션 헤드
│ │ + Residual │  │
│ ├────────────┤  │
│ │  LayerNorm │  │
│ │  MLP (FFN) │  │ 4배로 확장, GELU, 다시 투영
│ │ + Residual │  │
│ └────────────┘  │
└────────┬────────┘
         ▼
┌─────────────────┐
│    LayerNorm    │
│ Linear → logits│ vocab_size 출력 (다음 토큰에 대한 확률)
└─────────────────┘

워크숍을 위한 모델 설정

  • Tiny: 약 0.5M 파라미터 (n_layer 2, n_head 2, n_embd 128) – 학습 시간 약 5분 (M3 Pro 기준)
  • Small: 약 4M 파라미터 (n_layer 4, n_head 4, n_embd 256) – 학습 시간 약 20분
  • Medium (기본값): 약 10M 파라미터 (n_layer 6, n_head 6, n_embd 384) – 학습 시간 약 45분

모든 설정은 문자 수준 토큰화(vocab_size=65)와 block_size=256을 사용합니다.

토큰화(Tokenization): 문자(Character) vs BPE 이 워크숍에서는...

원문 보기
원문 보기 (영어)
Train Your Own LLM From Scratch A hands-on workshop where you write every piece of a GPT training pipeline yourself, understanding what each component does and why. Andrej Karpathy's nanoGPT was my first real exposure to LLMs and transformers. Seeing how a working language model could be built in a few hundred lines of PyTorch completely changed how I thought about AI and inspired me to go deeper into the space. This workshop is my attempt to give others that same experience. nanoGPT targets reproducing GPT-2 (124M params) and covers a lot of ground. This project strips it down to the essentials and scales it to a ~10M param model that trains on a laptop in under an hour — designed to be completed in a single workshop session. No black-box libraries. No model = AutoModel.from_pretrained() . You build it all. What You'll Build A working GPT model trained from scratch on your MacBook, capable of generating Shakespeare-like text. You'll write: Tokenizer — turning text into numbers the model can process Model architecture — the transformer: embeddings, attention, feed-forward layers Training loop — forward pass, loss, backprop, optimizer, learning rate scheduling Text generation — sampling from your trained model Prerequisites Any laptop or desktop (Mac, Linux, or Windows) Python 3.12+ Comfort reading Python code (you don't need ML experience) Training uses Apple Silicon GPU (MPS), NVIDIA GPU (CUDA), or CPU automatically. Also works on Google Colab — upload the files and run with !python train.py . Getting Started Local (recommended) Install uv if you don't have it: # macOS / Linux curl -LsSf https://astral.sh/uv/install.sh | sh # Windows powershell -ExecutionPolicy ByPass -c " irm https://astral.sh/uv/install.ps1 | iex " Then set up the project: uv sync mkdir scratchpad && cd scratchpad Google Colab If you don't have a local setup, upload the repo to Colab and install dependencies: !p ip install torch numpy tqdm tiktoken Upload data/shakespeare.txt to your Colab files, then write your code in notebook cells or upload .py files and run them with !python train.py . Work through the docs in order. Each part walks you through writing a piece of the pipeline, explaining what each component does and why. By the end, you'll have a working model.py , train.py , and generate.py that you wrote yourself. Part What You'll Write Concepts Part 1: Tokenization Character-level tokenizer Character encoding, vocabulary size, why BPE fails on small data Part 2: The Transformer Full GPT model architecture Embeddings, self-attention, layer norm, MLP blocks Part 3: The Training Loop Complete training pipeline Loss functions, AdamW, gradient clipping, LR scheduling Part 4: Text Generation Inference and sampling Temperature, top-k, autoregressive decoding Part 5: Putting It All Together Train on real data, experiment Loss curves, scaling experiments, next steps Part 6: Competition Train the best AI poet Find datasets, scale up, submit your best poem Architecture: GPT at a Glance Input Text │ ▼ ┌─────────────────┐ │ Tokenizer │ "hello" → [20, 43, 50, 50, 53] (character-level) └────────┬────────┘ ▼ ┌─────────────────┐ │ Token Embed + │ token IDs → vectors (n_embd dimensions) │ Position Embed │ + positional information └────────┬────────┘ ▼ ┌─────────────────┐ │ Transformer │ × n_layer │ Block: │ │ ┌────────────┐ │ │ │ LayerNorm │ │ │ │ Self-Attn │ │ n_head parallel attention heads │ │ + Residual │ │ │ ├────────────┤ │ │ │ LayerNorm │ │ │ │ MLP (FFN) │ │ expand 4x, GELU, project back │ │ + Residual │ │ │ └────────────┘ │ └────────┬────────┘ ▼ ┌─────────────────┐ │ LayerNorm │ │ Linear → logits│ vocab_size outputs (probability over next token) └─────────────────┘ Model Configs for This Workshop Config Params n_layer n_head n_embd Train Time (M3 Pro) Tiny ~0.5M 2 2 128 ~5 min Small ~4M 4 4 256 ~20 min Medium (default) ~10M 6 6 384 ~45 min All configs use character-level tokenization (vocab_size=65) and block_size=256. Tokenization: Characters vs BPE This workshop uses character-level tokenization on Shakespeare. BPE tokenization (GPT-2's 50k vocab) doesn't work on small datasets — most token bigrams are too rare for the model to learn patterns from. Tokenizer Vocab Size Dataset Size Needed Character-level ~65 Small (Shakespeare, ~1MB) BPE (tiktoken) 50,257 Large (TinyStories+, 100MB+) Part 5 covers switching to BPE for larger datasets. Key References nanoGPT — The project this workshop is based on. Minimal GPT training in ~300 lines of PyTorch build-nanogpt video lecture — 4-hour video building GPT-2 from an empty file Karpathy's microgpt — A full GPT in 200 lines of pure Python, no dependencies nanochat — Full ChatGPT clone training pipeline Attention Is All You Need (2017) — The original transformer paper GPT-2 paper (2019) — Language models as unsupervised learners TinyStories paper — Why small models trained on curated data punch above their weight