{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# LoRA ile ince ayar defteri\n", "\n", "Bu defter küçük bir GPT'yi dondurur, dikkat katmanlarına LoRA adaptörleri ekler ve oyuncak bir talimat veri kümesinde yalnızca bu adaptörleri eğitir.\n", "\n", "Anlatımı: GPT'ni Nasıl Eğitirsin? sitesinde \"LoRA: düşük rank'li uyarlama\" (`/ince-ayar/02-lora`). Orijinal İngilizce defter: [fine-tuning/notebooks/lora_finetune.ipynb](https://github.com/raiyanyahya/how-to-train-your-gpt/blob/master/fine-tuning/notebooks/lora_finetune.ipynb)" ], "id": "f6e60b89699f" }, { "cell_type": "markdown", "metadata": {}, "source": [ "# LoRA ile ince ayar\n", "\n", "Bu defter küçük bir dil modelini (language model) LoRA (Low-Rank Adaptation) ile ince ayardan (fine-tuning) geçirir. Minik bir GPT'ye LoRA adaptörleri (adapter) ekliyor ve küçük bir talimat veri kümesinde (dataset) eğitiyoruz. Amaç, orijinal ağırlıklar hiç değişmeden yalnızca adaptörler eğitilerek modelin davranışının nasıl değiştiğini görmek.\n", "\n", "Taban modelin (base model) 17 milyon parametresi (parameter) var. LoRA adaptörleri yalnızca 32.768 eğitilebilir parametre ekler, bu da taban modelin yaklaşık %0,19'u. Orijinal ağırlıklar donmuş kalır.\n", "\n", "Bu defterdeki taban model önceden eğitilmiş değil, ağırlıkları rastgele başlatılır. Gerçek bir ince ayarda aynı yerde ön eğitimli ağırlıkları yüklersin; LoRA adımları değişmez." ], "id": "88827bec167d" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## İçe aktarmalar" ], "id": "94c307bf603f" }, { "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", "import time\n", "from dataclasses import dataclass\n", "from torch.utils.data import Dataset, DataLoader\n", "import tiktoken" ], "id": "c42a579d0493" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Taban model\n", "\n", "Rehberde kurduğumuz mimarinin aynısıyla minik bir GPT. LoRA eğitimi kısa sürsün diye küçük tutuyoruz.\n", "\n", "Çeviri notu: Orijinal defterdeki `generate`, dizi `max_seq_len`'i aşınca `input_ids`'in kendisini kırpıyordu; 128 token'dan uzun üretimlerde istem ve ilk üretilen token'lar dönen sonuçtan kayboluyordu. Burada yalnızca modele verilen pencere `context_ids` olarak kırpılır, dönen dizi istem artı `max_new_tokens` uzunluğundadır. Çıkarım defterindeki `generate` de aynı biçimde düzeltildi.\n" ], "id": "9c16737dc687" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "class RotaryPositionalEmbedding(nn.Module):\n", " def __init__(self, d_model, max_seq_len=128, 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", "\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=0.8, top_k=50):\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", "\n", "config = GPTConfig()\n", "model = GPT(config)\n", "model.eval()\n", "\n", "print(f\"Base model parameters: {sum(p.numel() for p in model.parameters()):,}\")" ], "id": "76d96d4fa300" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## İnce ayardan önce üretim\n", "\n", "Taban model talimatlara uymak için hiç ince ayardan geçmedi. Ağırlıkları rastgele olduğu için dil de bilmiyor, bu yüzden prompt'lara (istem) anlamsız çıktı vermesini bekle. Ön eğitimli bir modelde burada akıcı ama talimata uymayan metin görürdün." ], "id": "6f3aa9d86b24" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tokenizer = tiktoken.get_encoding(\"gpt2\")\n", "\n", "def chat(model, prompt, max_tokens=30):\n", " full_prompt = f\"User: {prompt}\\nAssistant:\"\n", " ids = torch.tensor([tokenizer.encode(full_prompt)], dtype=torch.long)\n", " output = model.generate(ids, max_new_tokens=max_tokens)\n", " return tokenizer.decode(output[0].tolist())\n", "\n", "prompts = [\n", " \"What is the capital of France?\",\n", " \"Write a short poem about a cat.\",\n", " \"Explain gravity in simple terms.\",\n", "]\n", "\n", "print(\"=== BEFORE FINE-TUNING ===\")\n", "for p in prompts:\n", " print(f\"\\nPrompt: {p}\")\n", " print(f\"Output: {chat(model, p)[:200]}\")" ], "id": "38b3714c48a6" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## LoRA adaptörlerini ekle\n", "\n", "Taban modeli donduruyor ve her dikkat (attention) katmanındaki birleşik `qkv_proj` izdüşümüne LoRA ekliyoruz. Bu tek matris sorgu (query), anahtar (key) ve değer (value) izdüşümlerini birlikte taşıdığı için adaptör üçünü birden etkiler. Yalnızca LoRA ağırlıkları eğitilecek." ], "id": "29c38f6119d0" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "class LoRALinear(nn.Module):\n", " def __init__(self, original_linear, rank=8, alpha=16):\n", " super().__init__()\n", " self.original = original_linear\n", " self.rank = rank\n", " self.alpha = alpha\n", "\n", " in_features = original_linear.in_features\n", " out_features = original_linear.out_features\n", "\n", " self.lora_a = nn.Linear(in_features, rank, bias=False)\n", " self.lora_b = nn.Linear(rank, out_features, bias=False)\n", "\n", " nn.init.normal_(self.lora_a.weight, std=0.02)\n", " nn.init.zeros_(self.lora_b.weight)\n", "\n", " for param in original_linear.parameters():\n", " param.requires_grad = False\n", "\n", " def forward(self, x):\n", " return self.original(x) + self.lora_b(self.lora_a(x)) * (self.alpha / self.rank)\n", "\n", "\n", "def add_lora_to_model(model, rank=8, alpha=16):\n", " for param in model.parameters():\n", " param.requires_grad = False\n", "\n", " lora_params = []\n", " for layer in model.layers:\n", " attn = layer.attention\n", " original_qkv = attn.qkv_proj\n", "\n", " in_dim = original_qkv.in_features\n", " out_dim = original_qkv.out_features\n", "\n", " lora_qkv = LoRALinear(original_qkv, rank=rank, alpha=alpha)\n", " attn.qkv_proj = lora_qkv\n", "\n", " for param in lora_qkv.lora_a.parameters():\n", " lora_params.append(param)\n", " for param in lora_qkv.lora_b.parameters():\n", " lora_params.append(param)\n", "\n", " return lora_params\n", "\n", "\n", "lora_params = add_lora_to_model(model, rank=8, alpha=16)\n", "\n", "base_params = sum(p.numel() for p in model.parameters() if not p.requires_grad)\n", "lora_count = sum(p.numel() for p in lora_params)\n", "\n", "print(f\"Base model (frozen): {base_params:,} parameters\")\n", "print(f\"LoRA adapters (trainable): {lora_count:,} parameters\")\n", "print(f\"LoRA adds only {100 * lora_count / base_params:.2f}% more parameters\")" ], "id": "7de8ddb89f80" }, { "cell_type": "markdown", "metadata": {}, "source": [ "2026 notu: Bu defter LoRA'yı yalnızca dikkat izdüşümüne (`qkv_proj`) ekliyor. QLoRA makalesi, LoRA'yı yalnızca sorgu ve değer izdüşümlerine uygulamanın tam ince ayarın başarımını yakalayamadığını, bunun için bloktaki bütün doğrusal katmanlara uygulamak gerektiğini bildirir. Thinking Machines'in 2025 incelemesi de LoRA'yı başta MLP katmanları (buradaki SwiGLU'nun `w1`, `w2`, `w3` katmanları) olmak üzere bütün katmanlara uygulamayı önerir; en iyi LoRA öğrenme oranı tam ince ayarınkinin yaklaşık 10 katıdır. ([QLoRA](https://arxiv.org/abs/2305.14314), [LoRA Without Regret](https://thinkingmachines.ai/blog/lora/))" ], "id": "61016a00ee57" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Küçük bir talimat veri kümesi oluştur\n", "\n", "Modele asistan gibi cevap vermeyi öğretecek birkaç örnek. Model şu kalıbı öğrenecek: kullanıcı (`User`) bir şey sorar, asistan (`Assistant`) yardımcı bir cevap verir." ], "id": "af770f67db24" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "training_data = [\n", " (\"What is the capital of France?\", \"The capital of France is Paris.\"),\n", " (\"What is 2 + 2?\", \"2 + 2 equals 4.\"),\n", " (\"Who wrote Romeo and Juliet?\", \"William Shakespeare wrote Romeo and Juliet.\"),\n", " (\"What color is the sky?\", \"The sky is blue on a clear day.\"),\n", " (\"How many legs does a cat have?\", \"A cat has four legs.\"),\n", " (\"What is the largest planet?\", \"Jupiter is the largest planet in our solar system.\"),\n", " (\"Name a primary color.\", \"Red is a primary color.\"),\n", " (\"What sound does a dog make?\", \"A dog barks.\"),\n", " (\"What is water made of?\", \"Water is made of hydrogen and oxygen.\"),\n", " (\"How many days in a week?\", \"There are seven days in a week.\"),\n", "] * 5\n", "\n", "print(f\"Training examples: {len(training_data)}\")\n", "\n", "# Birkaçını göster\n", "for q, a in training_data[:3]:\n", " print(f\" Q: {q}\")\n", " print(f\" A: {a}\")\n", " print()" ], "id": "4b7871c326a3" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## LoRA adaptörlerini eğit\n", "\n", "Yalnızca LoRA ağırlıkları güncellenir, taban model donmuş kalır. Eğitim CPU'da bile kısa sürer." ], "id": "5780897e4bce" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "optimizer = torch.optim.AdamW(lora_params, lr=3e-4)\n", "\n", "tokenizer = tiktoken.get_encoding(\"gpt2\")\n", "\n", "print(f\"Training for 200 steps...\")\n", "start = time.time()\n", "\n", "for step in range(200):\n", " total_loss = 0\n", " for question, answer in training_data:\n", " text = f\"User: {question}\\nAssistant: {answer}\"\n", " ids = tokenizer.encode(text)\n", " ids = torch.tensor([ids], dtype=torch.long)\n", "\n", " input_ids = ids[:, :-1]\n", " target_ids = ids[:, 1:]\n", "\n", " if input_ids.shape[1] > config.max_seq_len:\n", " continue\n", "\n", " _, loss = model(input_ids, target_ids)\n", " total_loss += loss.item()\n", " loss.backward()\n", "\n", " optimizer.step()\n", " optimizer.zero_grad()\n", "\n", " if step % 50 == 0 or step == 199:\n", " elapsed = time.time() - start\n", " print(f\" Step {step:>3d}: loss={total_loss / len(training_data):.4f} ({elapsed:.0f}s)\")\n", "\n", "print(f\"\\nDone in {time.time() - start:.1f}s\")" ], "id": "0c2b17591b66" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## İnce ayardan sonra üretim\n", "\n", "Aynı prompt'lar, aynı model. Bu kez asistan gibi cevap vermek üzere eğitilmiş LoRA adaptörleriyle." ], "id": "30b6844c25d1" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "model.eval()\n", "\n", "print(\"=== AFTER FINE-TUNING ===\")\n", "for p in prompts:\n", " print(f\"\\nPrompt: {p}\")\n", " print(f\"Output: {chat(model, p)[:200]}\")" ], "id": "ec85955ccade" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Ne değişti\n", "\n", "Taban modelin ağırlıkları eğitimden öncekiyle birebir aynı; yalnızca LoRA adaptörleri güncellendi. Bunu adaptörleri kaldırıp yeniden üretim yaparak kanıtlayabilirsin: model eski davranışına döner.\n", "\n", "Adaptör dosyası çok küçük. Özetleme, çeviri ve kod üretimi için ayrı adaptörler eğitip taban modeli yeniden yüklemeden bunları takıp çıkarabilirsin; tek bir taban model böylece birçok işe uyarlanır." ], "id": "a964fb26e424" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Kendi prompt'larını dene" ], "id": "8848e09bc6c9" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "your_prompts = [\n", " \"What is the tallest mountain?\",\n", " \"Explain what a computer does.\",\n", "]\n", "\n", "for p in your_prompts:\n", " print(f\"Prompt: {p}\")\n", " print(f\"Output: {chat(model, p)[:200]}\")\n", " print()" ], "id": "dc65266002db" } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.10.0" } }, "nbformat": 4, "nbformat_minor": 5 }