{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Çıkarım defteri\n", "\n", "Bu defter eğitim defterinin kaydettiği minik modeli yükler ve farklı sıcaklıklarla, top-k örneklemesiyle metin üretir.\n", "\n", "Anlatımı: GPT'ni Nasıl Eğitirsin? sitesinde \"Çıkarım: modeli konuşturmak\" (`/bolumler/09-cikarim`). Orijinal İngilizce defter: [notebooks/09_inference.ipynb](https://github.com/raiyanyahya/how-to-train-your-gpt/blob/master/notebooks/09_inference.ipynb)" ], "id": "1c51c4682a62" }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Çıkarım\n", "\n", "Eğitilmiş bir modelimiz var. Şimdi ondan bir şeyler yazmasını istiyoruz. Buna çıkarım (inference) ya da metin üretimi denir. Modele bir başlangıç prompt'u (istem) veririz, model bir sonraki kelimeyi tahmin eder. Sonra o kelimeyi girdiye ekler ve ondan sonrakini tahmin eder. Her adımda bir token (belirteç) üretir ve bütün bir paragraf çıkana kadar böyle devam eder.\n", "\n", "Sonraki token'ı nasıl seçtiğimiz sonucu çok etkiler. Hep en olası token'ı seçersek çıktı kendini tekrar etmeye başlar. Bütün token'lar arasından rastgele seçersek anlamsızlaşır. Modelin ne kadar cesur davranacağını sıcaklıkla (temperature) ayarlarız. Seçenekleri en mantıklı token'larla sınırlamak için top-k (top-k örnekleme), seçenek sayısını modelin ne kadar emin olduğuna göre ayarlamak için top-p (çekirdek örnekleme) kullanırız. Bu defterdeki `generate` yalnızca sıcaklık ve top-k kullanır; top-p'li üretim kodu Bölüm 9'da.\n", "\n", "Bu defterde eğitim sırasında kaydettiğimiz minik checkpoint'i (kontrol noktası) yükleyip modele metin ürettireceğiz. Model küçük ve çok az eğitildiği için çıktı anlamlı olmayacak, ama üretim döngüsünün token token çalıştığını göreceksin." ], "id": "82cb4936815f" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## İçe aktarmalar ve yapı taşları\n", "\n", "Checkpoint'i yükleyebilmek için model mimarisine ihtiyacımız var.\n", "\n", "Çeviri notu: Orijinal defterdeki `GPT` sınıfı iki yerde eğitim defterinden ayrılıyordu, ikisi de burada eğitim defteriyle aynı yapıldı. Birincisi, `forward` içinde `targets` bir kez daha kaydırılıyordu (`logits[:, :-1]` ile `targets[:, 1:]`); oysa eğitim defterindeki `TextDataset` hedefleri zaten bir kaydırarak verir, ikinci kaydırma bir sonraki yerine iki sonraki token'ı hedeflerdi. Bu defter kayıp hesaplamadığı için hata görünmüyordu. İkincisi, `generate` dizi `max_seq_len`'i aşınca `input_ids`'in kendisini kırpıyordu ve 128 token'dan uzun üretimlerde istem ile ilk üretilen token'lar dönen sonuçtan kayboluyordu; şimdi yalnızca modele verilen pencere `context_ids` olarak kırpılır, dönen dizi istem artı `max_new_tokens` uzunluğundadır.\n" ], "id": "b16f35354f0e" }, { "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\n", "\n", "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\n", "\n", "\n", "@dataclass\n", "class GPTConfig:\n", " vocab_size: int = 50257\n", " d_model: int = 256\n", " num_heads: int = 4\n", " num_layers: int = 4\n", " max_seq_len: int = 128\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 = 50\n", " max_steps: int = 500\n", " batch_size: int = 4\n", " grad_accum_steps: int = 2\n", " betas: tuple = (0.9, 0.95)\n", " eps: float = 1e-8\n", "\n", "\n", "class GPT(nn.Module):\n", " def __init__(self, config):\n", " super().__init__()\n", " self.config = config\n", " self.token_embedding = nn.Embedding(config.vocab_size, config.d_model)\n", " self.embd_dropout = nn.Dropout(config.embd_dropout)\n", " self.layers = nn.ModuleList([\n", " TransformerBlock(config.d_model, config.num_heads, config.dropout)\n", " for _ in range(config.num_layers)\n", " ])\n", " self.final_norm = RMSNorm(config.d_model)\n", " self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)\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", " x = self.token_embedding(input_ids)\n", " x = self.embd_dropout(x)\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", " logits = self.lm_head(x)\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", " return logits, loss\n", "\n", " @torch.no_grad()\n", " def generate(self, input_ids, max_new_tokens, temperature=1.0, top_k=None):\n", " self.eval()\n", " for _ in range(max_new_tokens):\n", " # Modele yalnızca son max_seq_len token verilir; tam dizi input_ids'de kalır\n", " context_ids = input_ids[:, -self.config.max_seq_len:]\n", " logits, _ = self.forward(context_ids)\n", " logits = logits[:, -1, :] / temperature\n", " if top_k is not None:\n", " v, _ = torch.topk(logits, min(top_k, logits.size(-1)))\n", " logits[logits < v[:, -1:]] = float('-inf')\n", " probs = F.softmax(logits, dim=-1)\n", " next_token = torch.multinomial(probs, num_samples=1)\n", " input_ids = torch.cat([input_ids, next_token], dim=1)\n", " return input_ids\n", "\n", " def get_num_params(self):\n", " return sum(p.numel() for p in self.parameters())" ], "id": "f8a1cecdeb55" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Eğitimde kaydedilen checkpoint'i yükle" ], "id": "ea2fdea478fc" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "\n", "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", "\n", "if os.path.exists(\"checkpoints/tiny_model.pt\"):\n", " checkpoint = torch.load(\"checkpoints/tiny_model.pt\", map_location=device, weights_only=True)\n", " model = GPT(GPTConfig(**checkpoint[\"config\"]))\n", " model.load_state_dict(checkpoint[\"model_state_dict\"])\n", " model = model.to(device)\n", " model.eval()\n", " print(f\"Loaded model with {model.get_num_params():,} parameters\")\n", "else:\n", " print(\"No checkpoint found. Run the training notebook first.\")\n", " print(\"Creating an untrained model for demonstration.\")\n", " config = GPTConfig()\n", " model = GPT(config).to(device)\n", " model.eval()" ], "id": "359881cd0c1d" }, { "cell_type": "markdown", "metadata": {}, "source": [ "2026 notu: Bu uyarlamada yapılandırma basit sözlük olarak kaydedilir; weights_only=True ile yüklenir ve GPTConfig(**checkpoint[\"config\"]) olarak yeniden kurulur. Eski özel sınıflar için yalnız güvenilen sınıfı safe_globals ile izinli listeye al. weights_only=False keyfi kod çalıştırabilir; güvenilmeyen dosyalarda kullanma. https://docs.pytorch.org/docs/2.14/notes/serialization.html" ], "id": "f5b4e3e87ba8" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Metin üret\n", "\n", "Farklı prompt'lar ve sıcaklıklar dene. Düşük sıcaklık odaklı, yüksek sıcaklık yaratıcı çıktı verir; top-k de seçenekleri en olası token'larla sınırlar." ], "id": "af572e91fcdd" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import tiktoken\n", "\n", "@dataclass\n", "class TokenizerConfig:\n", " name: str = \"gpt2\"\n", " vocab_size: int = 50257\n", "\n", "class SimpleTokenizer:\n", " def __init__(self, config=None):\n", " self.config = config or TokenizerConfig()\n", " self.enc = tiktoken.get_encoding(self.config.name)\n", " self.eos_token = \"<|endoftext|>\"\n", " self.eos_token_id = self.enc.encode(\n", " self.eos_token, allowed_special={self.eos_token})[0]\n", " def encode(self, text):\n", " return self.enc.encode(text, allowed_special={self.eos_token})\n", " def decode(self, ids):\n", " return self.enc.decode(ids)\n", " @property\n", " def vocab_size(self):\n", " return self.config.vocab_size\n", "\n", "tokenizer = SimpleTokenizer()\n", "\n", "prompts = [\n", " \"The cat sat on the\",\n", " \"Machine learning is\",\n", " \"The most important thing is\",\n", "]\n", "\n", "for prompt in prompts:\n", " print(f\"Prompt: {prompt}\")\n", " for temp in [0.5, 0.8, 1.2]:\n", " label = \"focused\" if temp < 0.7 else (\"balanced\" if temp < 1.0 else \"creative\")\n", " input_ids = torch.tensor([tokenizer.encode(prompt)], dtype=torch.long, device=device)\n", " output_ids = model.generate(input_ids, max_new_tokens=20, temperature=temp, top_k=50)\n", " text = tokenizer.decode(output_ids[0].tolist())\n", " print(f\" T={temp:.1f} ({label}): {text[:120]}\")\n", " print()" ], "id": "ce07c57e18a0" } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.10.0" } }, "nbformat": 4, "nbformat_minor": 5 }