{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# GPT modeli defteri\n", "\n", "Bu defter önceki bölümlerdeki parçaları üst üste koyup ağırlık paylaşımlı tam bir GPT modeli kurar, parametrelerini sayar ve rastgele token'larla bir ileri geçiş çalıştırır.\n", "\n", "Anlatımı: GPT'ni Nasıl Eğitirsin? sitesinde \"Eksiksiz GPT modeli\" (`/bolumler/07-gpt-modeli`). Orijinal İngilizce defter: [notebooks/07_gpt_model.ipynb](https://github.com/raiyanyahya/how-to-train-your-gpt/blob/master/notebooks/07_gpt_model.ipynb)" ], "id": "0f5c9af9912f" }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Eksiksiz GPT modeli\n", "\n", "Parçaların hepsini kurduk: tokenizer (belirteçleyici), gömmeler (embedding), konum bilgisi için RoPE (Rotary Position Embedding), bağlam için dikkat (attention) ve bunları tekrarlanabilir bir birimde toplayan Transformer bloğu (Transformer block).\n", "\n", "Şimdi hepsini tek bir modelde birleştiriyoruz. Ortaya girdi olarak token (belirteç) ID'lerini alan, çıktı olarak bir sonraki token'ı tahmin eden tek bir sınıf çıkıyor. GPT-2, GPT-3, LLaMA ve Mistral de bu mimari ailesinden.\n", "\n", "Modelin dört ana parçası var. Token gömmesi ID'leri vektörlere çevirir. Üst üste dizilmiş Transformer blokları bu vektörleri dikkat ve ileri beslemeli ağ (feed-forward network, FFN) katmanlarından geçirir. Ardından son bir normalizasyon (normalization) katmanı gelir. En sonda LM head (dil modeli başlığı), gizli durumu kelime dağarcığındaki (vocabulary) her token için bir skora izdüşürür.\n", "\n", "Bir de ağırlık paylaşımı (weight tying) kullanıyoruz: gömme tablosu (embedding table) ile LM head aynı ağırlıkları paylaşır. Bu defterdeki yapılandırmada paylaşım 38,6 milyon parametre (parameter) kazandırır. Paylaşım olmasaydı model yaklaşık 190 milyon parametre olurdu, yani tasarruf beşte bir civarında. Paylaşılan matris iki yönden de güncellendiği için model ayrıca daha fazla eğitim sinyali alır.\n", "\n", "Defterin sonunda elinde eğitilmeye hazır, eksiksiz bir dil modeli (language model) olacak." ], "id": "90515cc2e55d" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## İçe aktarmalar" ], "id": "a867f9f9992f" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import torch\n", "import torch.nn as nn\n", "import torch.nn.functional as F\n", "import math\n", "from dataclasses import dataclass" ], "id": "07a985580268" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Önceki bölümlerden yapı taşları" ], "id": "8383d2337fb4" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "class RotaryPositionalEmbedding(nn.Module):\n", " def __init__(self, d_model, max_seq_len=2048, theta=10000.0):\n", " super().__init__()\n", " assert d_model % 2 == 0\n", " dim_indices = torch.arange(0, d_model, 2).float()\n", " inv_freq = 1.0 / (theta ** (dim_indices / d_model))\n", " positions = torch.arange(max_seq_len).float()\n", " freqs = torch.outer(positions, inv_freq)\n", " emb = freqs.repeat_interleave(2, dim=-1)\n", " self.register_buffer(\"cos_cached\", emb.cos())\n", " self.register_buffer(\"sin_cached\", emb.sin())\n", "\n", " @staticmethod\n", " @staticmethod\n", " def rotate_half(x):\n", " x_even = x[..., 0::2]\n", " x_odd = x[..., 1::2]\n", " return torch.stack([-x_odd, x_even], dim=-1).flatten(-2)\n", " def forward(self, x, seq_len):\n", " cos = self.cos_cached[:seq_len].unsqueeze(0).unsqueeze(0)\n", " sin = self.sin_cached[:seq_len].unsqueeze(0).unsqueeze(0)\n", " return (x * cos) + (self.rotate_half(x) * sin)\n", "\n", "\n", "def create_causal_mask(seq_len, device):\n", " mask = torch.tril(torch.ones(seq_len, seq_len, device=device))\n", " return mask.view(1, 1, seq_len, seq_len)\n", "\n", "\n", "class RMSNorm(nn.Module):\n", " def __init__(self, d_model, eps=1e-6):\n", " super().__init__()\n", " self.weight = nn.Parameter(torch.ones(d_model))\n", " self.eps = eps\n", "\n", " def forward(self, x):\n", " rms = torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)\n", " return x * rms * self.weight\n", "\n", "\n", "class SwiGLU(nn.Module):\n", " def __init__(self, d_model, expansion_factor=4):\n", " super().__init__()\n", " hidden_dim = expansion_factor * d_model\n", " self.w1 = nn.Linear(d_model, hidden_dim, bias=False)\n", " self.w2 = nn.Linear(d_model, hidden_dim, bias=False)\n", " self.w3 = nn.Linear(hidden_dim, d_model, bias=False)\n", "\n", " def forward(self, x):\n", " return self.w3(F.silu(self.w1(x)) * self.w2(x))\n", "\n", "\n", "class MultiHeadAttention(nn.Module):\n", " def __init__(self, d_model, num_heads, dropout=0.1):\n", " super().__init__()\n", " assert d_model % num_heads == 0\n", " self.d_model = d_model\n", " self.num_heads = num_heads\n", " self.head_dim = d_model // num_heads\n", " self.qkv_proj = nn.Linear(d_model, 3 * d_model, bias=False)\n", " self.out_proj = nn.Linear(d_model, d_model, bias=False)\n", " self.rotary = RotaryPositionalEmbedding(self.head_dim)\n", " self.attn_dropout = nn.Dropout(dropout)\n", " self.resid_dropout = nn.Dropout(dropout)\n", "\n", " def forward(self, x, mask=None):\n", " batch_size, seq_len, _ = x.shape\n", " qkv = self.qkv_proj(x)\n", " qkv = qkv.reshape(batch_size, seq_len, 3, self.num_heads, self.head_dim)\n", " qkv = qkv.permute(2, 0, 3, 1, 4)\n", " q, k, v = qkv[0], qkv[1], qkv[2]\n", " q = self.rotary(q, seq_len)\n", " k = self.rotary(k, seq_len)\n", " attn_scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim)\n", " if mask is not None:\n", " attn_scores = attn_scores.masked_fill(mask == 0, float('-inf'))\n", " attn_weights = F.softmax(attn_scores, dim=-1)\n", " attn_weights = self.attn_dropout(attn_weights)\n", " attn_output = attn_weights @ v\n", " attn_output = attn_output.transpose(1, 2).contiguous()\n", " attn_output = attn_output.reshape(batch_size, seq_len, self.d_model)\n", " output = self.out_proj(attn_output)\n", " output = self.resid_dropout(output)\n", " return output\n", "\n", "\n", "class TransformerBlock(nn.Module):\n", " def __init__(self, d_model, num_heads, dropout=0.1):\n", " super().__init__()\n", " self.norm1 = RMSNorm(d_model)\n", " self.attention = MultiHeadAttention(d_model, num_heads, dropout)\n", " self.norm2 = RMSNorm(d_model)\n", " self.ffn = SwiGLU(d_model)\n", "\n", " def forward(self, x, mask=None):\n", " x = x + self.attention(self.norm1(x), mask)\n", " x = x + self.ffn(self.norm2(x))\n", " return x" ], "id": "009cc46d1c25" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## GPT yapılandırması\n", "\n", "Bütün ayarlar tek bir dataclass'ta durur. Bir sayıyı değiştirdiğinde model ona göre kurulur." ], "id": "ae8a4a85258f" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "@dataclass\n", "class GPTConfig:\n", " vocab_size: int = 50257\n", " d_model: int = 768\n", " num_heads: int = 12\n", " num_layers: int = 12\n", " max_seq_len: int = 1024\n", " dropout: float = 0.1\n", " embd_dropout: float = 0.1\n", " learning_rate: float = 3e-4\n", " weight_decay: float = 0.1\n", " warmup_steps: int = 2000\n", " max_steps: int = 100000\n", " batch_size: int = 8\n", " grad_accum_steps: int = 4\n", " betas: tuple = (0.9, 0.95)\n", " eps: float = 1e-8" ], "id": "69ff97cdf5b6" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## GPT modeli\n", "\n", "Model sırasıyla token gömmesi ve dropout (seyreltme), üst üste dizilmiş Transformer blokları, son bir RMSNorm ve kelime dağarcığı skorlarını üreten çıktı izdüşümünden oluşur. Gömme ağırlıkları LM head ile paylaşılır. Bütün ağırlıklar ortalaması 0, standart sapması 0,02 olan normal dağılımdan başlatılır." ], "id": "45288d25435b" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "class GPT(nn.Module):\n", " def __init__(self, config):\n", " super().__init__()\n", " self.config = config\n", "\n", " self.token_embedding = nn.Embedding(config.vocab_size, config.d_model)\n", " self.embd_dropout = nn.Dropout(config.embd_dropout)\n", "\n", " self.layers = nn.ModuleList([\n", " TransformerBlock(config.d_model, config.num_heads, config.dropout)\n", " for _ in range(config.num_layers)\n", " ])\n", "\n", " self.final_norm = RMSNorm(config.d_model)\n", " self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)\n", "\n", " self.token_embedding.weight = self.lm_head.weight\n", " self.apply(self._init_weights)\n", "\n", " def _init_weights(self, module):\n", " if isinstance(module, (nn.Linear, nn.Embedding)):\n", " torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)\n", " if hasattr(module, 'bias') and module.bias is not None:\n", " torch.nn.init.zeros_(module.bias)\n", "\n", " def forward(self, input_ids, targets=None):\n", " batch_size, seq_len = input_ids.shape\n", "\n", " x = self.token_embedding(input_ids)\n", " x = self.embd_dropout(x)\n", "\n", " mask = create_causal_mask(seq_len, input_ids.device)\n", " for layer in self.layers:\n", " x = layer(x, mask)\n", " x = self.final_norm(x)\n", "\n", " logits = self.lm_head(x)\n", "\n", " loss = None\n", " if targets is not None:\n", " logits_flat = logits.contiguous().view(-1, self.config.vocab_size)\n", " targets_flat = targets.contiguous().view(-1)\n", " loss = F.cross_entropy(logits_flat, targets_flat)\n", "\n", " return logits, loss\n", "\n", " def get_num_params(self):\n", " return sum(p.numel() for p in self.parameters())" ], "id": "16571748b04f" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Modeli oluştur ve incele" ], "id": "058804ed1f5e" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "config = GPTConfig()\n", "model = GPT(config)\n", "print(f\"Total parameters: {model.get_num_params():,}\")\n", "print()\n", "\n", "print(f\"Config:\")\n", "print(f\" d_model: {config.d_model}\")\n", "print(f\" num_heads: {config.num_heads}\")\n", "print(f\" num_layers:{config.num_layers}\")\n", "print(f\" vocab_size:{config.vocab_size}\")\n", "print(f\" max_seq_len: {config.max_seq_len}\")" ], "id": "9ac01268ac81" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Bir ileri geçiş (forward pass) çalıştır\n", "\n", "Modele rastgele token ID'leri ver ve ürettiği logit'lerin (logits) şeklini kontrol et. Kaybı (loss) da hesapla." ], "id": "bad96d9e26a1" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "batch_size = 4\n", "seq_len = 128\n", "\n", "input_ids = torch.randint(0, config.vocab_size, (batch_size, seq_len))\n", "target_ids = torch.randint(0, config.vocab_size, (batch_size, seq_len))\n", "\n", "logits, loss = model(input_ids, target_ids)\n", "\n", "print(f\"Input shape: {input_ids.shape}\")\n", "print(f\"Logits shape: {logits.shape}\")\n", "print(f\"Loss: {loss.item():.4f}\")\n", "print()\n", "\n", "print(f\"Expected logits shape: [{batch_size}, {seq_len}, {config.vocab_size}]\")\n", "print(f\"Actual logits shape: [{logits.shape[0]}, {logits.shape[1]}, {logits.shape[2]}]\")\n", "print()\n", "\n", "print(f\"For each of the {seq_len} positions the model produces\")\n", "print(f\"{config.vocab_size} scores. One score per possible next token.\")" ], "id": "2de23b5df978" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Ağırlık paylaşımını doğrula\n", "\n", "Gömme ile LM head aynı tensörü (tensor) paylaşır. İkisi aynı belleği gösterdiği için birini değiştirdiğinde diğeri de değişir." ], "id": "d131de172e75" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "emb_weight = model.token_embedding.weight\n", "head_weight = model.lm_head.weight\n", "\n", "print(f\"Embedding weight id: {id(emb_weight)}\")\n", "print(f\"LM head weight id: {id(head_weight)}\")\n", "print(f\"Same memory: {emb_weight.data_ptr() == head_weight.data_ptr()}\")\n", "print()\n", "\n", "saved_params = config.vocab_size * config.d_model\n", "print(f\"Parameters saved by weight tying: {saved_params:,}\")" ], "id": "74583de05dff" }, { "cell_type": "markdown", "metadata": {}, "source": [ "2026 notu: Ağırlık paylaşımı küçük modellerde hâlâ yaygın, büyük modeller ise çoğunlukla paylaşmaz. Büyük modelde kelime dağarcığı matrisi toplamın küçük bir kısmıdır: Llama 3 70B'de 128.256 × 8.192 ≈ 1,05 milyar parametre, toplamın yaklaşık %1,5'i. Llama'nın resmi kodunda çıktı katmanı ayrı bir matris, Mistral 7B'de `tie_word_embeddings` false, Qwen2.5'te yalnızca 0,5B, 1,5B ve 3B modeller paylaşıyor. Gemma ailesi gibi küçük modeller paylaşmaya devam ediyor. ([Llama 3 model kodu](https://github.com/meta-llama/llama3/blob/main/llama/model.py), [Mistral 7B config](https://huggingface.co/mistralai/Mistral-7B-v0.1/raw/main/config.json), [Qwen2.5 raporu](https://arxiv.org/abs/2412.15115))" ], "id": "fc110da1a021" } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.10.0" } }, "nbformat": 4, "nbformat_minor": 5 }