Eğitim defteri

AdamW, ısınmalı kosinüs takvimi ve karma hassasiyetle küçük modeli eğit, kaybı izle.

Anlatımı: Eğitim hattı · Defteri indir

Bu defter küçük bir GPT'yi AdamW, ısınmalı kosinüs takvimi ve karma hassasiyetle kısa bir süre eğitir, kayıp eğrisini çizer ve modeli checkpoints/tiny_model.pt dosyasına kaydeder.

Anlatımı: GPT'ni Nasıl Eğitirsin? sitesinde "Eğitim hattı" (/bolumler/08-egitim). Orijinal İngilizce defter: notebooks/08_training.ipynb

Eğitim

Eksiksiz bir GPT modelimiz var. Şimdi ona bir şey öğretmemiz gerekiyor. Eğitim (training), modele milyonlarca cümle gösterip her seferinde bir sonraki kelimeyi tahmin etmesini istemek demek. Yanlış bildiğinde ağırlıklarını (weights) doğru yöne çok az kaydırırız; Bölüm 7'deki tam boy modelde bu, yaklaşık 150 milyon ağırlık demek. Bunu yeterince tekrarlarsan model kalıpları öğrenir.

Eğitim döngüsünün beş adımı var. Bir batch (yığın) metin alırsın. Onu modelden geçirip tahminleri elde edersin. Tahminlerin ne kadar yanlış olduğunu çapraz entropi (cross-entropy) kaybıyla (loss) ölçersin. Kaybı azaltmak için her ağırlığın nasıl değişmesi gerektiğini geri yayılımla (backpropagation) hesaplarsın. Son olarak ağırlıkları AdamW adlı optimizer (eniyileyici) ile güncellersin.

Eğitimi hızlı ve kararlı tutmak için birkaç yöntem daha kullanıyoruz. Karma hassasiyet (mixed precision) işlemlerin çoğunu daha küçük sayı biçimleriyle yapar. Gradyan kırpma (gradient clipping) modelin ani ve büyük sıçramalar yapmasını engeller. Öğrenme oranı takvimi (learning rate schedule) önce yavaşça ısınır (warmup), sonra kosinüs eğrisini izleyerek düşer.

Bu defterde küçük bir metin kümesi üzerinde kısa bir eğitim çalıştıracağız: her şeyin çalıştığını göstermeye yetecek kadar adım. Model bu sürede pek bir şey öğrenmez, ama kaybın düştüğünü görür ve düzeneğin doğru çalıştığından emin olursun.

İçe aktarmalar

import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import time
import os
from dataclasses import dataclass, asdict
from torch.utils.data import Dataset, DataLoader
import tiktoken
import matplotlib.pyplot as plt

Bütün yapı taşları

Önceki bölümlerdeki bütün bileşenler tek bir hücrede.

class RotaryPositionalEmbedding(nn.Module):
    def __init__(self, d_model, max_seq_len=2048, theta=10000.0):
        super().__init__()
        assert d_model % 2 == 0
        dim_indices = torch.arange(0, d_model, 2).float()
        inv_freq = 1.0 / (theta ** (dim_indices / d_model))
        positions = torch.arange(max_seq_len).float()
        freqs = torch.outer(positions, inv_freq)
        emb = freqs.repeat_interleave(2, dim=-1)
        self.register_buffer("cos_cached", emb.cos())
        self.register_buffer("sin_cached", emb.sin())

    @staticmethod
    @staticmethod
    def rotate_half(x):
        x_even = x[..., 0::2]
        x_odd  = x[..., 1::2]
        return torch.stack([-x_odd, x_even], dim=-1).flatten(-2)
    def forward(self, x, seq_len):
        cos = self.cos_cached[:seq_len].unsqueeze(0).unsqueeze(0)
        sin = self.sin_cached[:seq_len].unsqueeze(0).unsqueeze(0)
        return (x * cos) + (self.rotate_half(x) * sin)


def create_causal_mask(seq_len, device):
    mask = torch.tril(torch.ones(seq_len, seq_len, device=device))
    return mask.view(1, 1, seq_len, seq_len)


class RMSNorm(nn.Module):
    def __init__(self, d_model, eps=1e-6):
        super().__init__()
        self.weight = nn.Parameter(torch.ones(d_model))
        self.eps = eps

    def forward(self, x):
        rms = torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
        return x * rms * self.weight


class SwiGLU(nn.Module):
    def __init__(self, d_model, expansion_factor=4):
        super().__init__()
        hidden_dim = expansion_factor * d_model
        self.w1 = nn.Linear(d_model, hidden_dim, bias=False)
        self.w2 = nn.Linear(d_model, hidden_dim, bias=False)
        self.w3 = nn.Linear(hidden_dim, d_model, bias=False)

    def forward(self, x):
        return self.w3(F.silu(self.w1(x)) * self.w2(x))


class MultiHeadAttention(nn.Module):
    def __init__(self, d_model, num_heads, dropout=0.1):
        super().__init__()
        assert d_model % num_heads == 0
        self.d_model = d_model
        self.num_heads = num_heads
        self.head_dim = d_model // num_heads
        self.qkv_proj = nn.Linear(d_model, 3 * d_model, bias=False)
        self.out_proj = nn.Linear(d_model, d_model, bias=False)
        self.rotary = RotaryPositionalEmbedding(self.head_dim)
        self.attn_dropout = nn.Dropout(dropout)
        self.resid_dropout = nn.Dropout(dropout)

    def forward(self, x, mask=None):
        batch_size, seq_len, _ = x.shape
        qkv = self.qkv_proj(x)
        qkv = qkv.reshape(batch_size, seq_len, 3, self.num_heads, self.head_dim)
        qkv = qkv.permute(2, 0, 3, 1, 4)
        q, k, v = qkv[0], qkv[1], qkv[2]
        q = self.rotary(q, seq_len)
        k = self.rotary(k, seq_len)
        attn_scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim)
        if mask is not None:
            attn_scores = attn_scores.masked_fill(mask == 0, float('-inf'))
        attn_weights = F.softmax(attn_scores, dim=-1)
        attn_weights = self.attn_dropout(attn_weights)
        attn_output = attn_weights @ v
        attn_output = attn_output.transpose(1, 2).contiguous()
        attn_output = attn_output.reshape(batch_size, seq_len, self.d_model)
        output = self.out_proj(attn_output)
        output = self.resid_dropout(output)
        return output


class TransformerBlock(nn.Module):
    def __init__(self, d_model, num_heads, dropout=0.1):
        super().__init__()
        self.norm1 = RMSNorm(d_model)
        self.attention = MultiHeadAttention(d_model, num_heads, dropout)
        self.norm2 = RMSNorm(d_model)
        self.ffn = SwiGLU(d_model)

    def forward(self, x, mask=None):
        x = x + self.attention(self.norm1(x), mask)
        x = x + self.ffn(self.norm2(x))
        return x


@dataclass
class GPTConfig:
    vocab_size: int = 50257
    d_model: int = 256
    num_heads: int = 4
    num_layers: int = 4
    max_seq_len: int = 128
    dropout: float = 0.1
    embd_dropout: float = 0.1
    learning_rate: float = 3e-4
    weight_decay: float = 0.1
    warmup_steps: int = 50
    max_steps: int = 500
    batch_size: int = 4
    grad_accum_steps: int = 2
    betas: tuple = (0.9, 0.95)
    eps: float = 1e-8


class GPT(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.config = config
        self.token_embedding = nn.Embedding(config.vocab_size, config.d_model)
        self.embd_dropout = nn.Dropout(config.embd_dropout)
        self.layers = nn.ModuleList([
            TransformerBlock(config.d_model, config.num_heads, config.dropout)
            for _ in range(config.num_layers)
        ])
        self.final_norm = RMSNorm(config.d_model)
        self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
        self.token_embedding.weight = self.lm_head.weight
        self.apply(self._init_weights)

    def _init_weights(self, module):
        if isinstance(module, (nn.Linear, nn.Embedding)):
            torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
            if hasattr(module, 'bias') and module.bias is not None:
                torch.nn.init.zeros_(module.bias)

    def forward(self, input_ids, targets=None):
        batch_size, seq_len = input_ids.shape
        x = self.token_embedding(input_ids)
        x = self.embd_dropout(x)
        mask = create_causal_mask(seq_len, input_ids.device)
        for layer in self.layers:
            x = layer(x, mask)
        x = self.final_norm(x)
        logits = self.lm_head(x)
        loss = None
        if targets is not None:
            logits_flat = logits.contiguous().view(-1, self.config.vocab_size)
            targets_flat = targets.contiguous().view(-1)
            loss = F.cross_entropy(logits_flat, targets_flat)
        return logits, loss

    def get_num_params(self):
        return sum(p.numel() for p in self.parameters())

Tokenizer (belirteçleyici) ve veri kümesi (dataset)

@dataclass
class TokenizerConfig:
    name: str = "gpt2"
    vocab_size: int = 50257


class SimpleTokenizer:
    def __init__(self, config=None):
        self.config = config or TokenizerConfig()
        self.enc = tiktoken.get_encoding(self.config.name)
        self.eos_token = "<|endoftext|>"
        self.eos_token_id = self.enc.encode(
            self.eos_token, allowed_special={self.eos_token}
        )[0]

    def encode(self, text):
        return self.enc.encode(text, allowed_special={self.eos_token})

    def decode(self, ids):
        return self.enc.decode(ids)

    @property
    def vocab_size(self):
        return self.config.vocab_size


class TextDataset(Dataset):
    def __init__(self, texts, tokenizer, max_seq_len=128):
        self.tokenizer = tokenizer
        self.max_seq_len = max_seq_len
        all_tokens = []
        for text in texts:
            tokens = tokenizer.encode(text)
            all_tokens.extend(tokens)
            all_tokens.append(tokenizer.eos_token_id)
        self.tokens = torch.tensor(all_tokens, dtype=torch.long)

    def __len__(self):
        return (len(self.tokens) - 1) // self.max_seq_len

    def __getitem__(self, idx):
        start = idx * self.max_seq_len
        end = start + self.max_seq_len
        return self.tokens[start:end], self.tokens[start+1:end+1]

Öğrenme oranı takvimi ve optimizer

class CosineWarmupScheduler:
    """current_step counts completed updates; LR is prepared for the NEXT update.

    With warmup=4 the first four updates use max_lr * [1/4, 2/4, 3/4, 1].
    The last scheduled update uses min_lr when max_steps > warmup_steps.
    """
    def __init__(self, optimizer, warmup_steps, max_steps, max_lr=3e-4, min_lr=1e-5):
        if max_steps < 1 or warmup_steps < 0 or not 0 <= min_lr <= max_lr:
            raise ValueError("Invalid learning-rate schedule")
        self.optimizer = optimizer
        self.warmup_steps = warmup_steps
        self.max_steps = max_steps
        self.max_lr = max_lr
        self.min_lr = min_lr
        self.current_step = 0
        self._apply()

    def get_lr(self):
        update = self.current_step + 1
        if self.warmup_steps and update <= self.warmup_steps:
            return self.max_lr * update / self.warmup_steps
        if self.warmup_steps == 0:
            progress = (update - 1) / max(1, self.max_steps - 1)
            progress = min(1.0, progress)
            return self.min_lr + (self.max_lr - self.min_lr) * 0.5 * (1 + math.cos(math.pi * progress))
        if update < self.max_steps:
            progress = (update - self.warmup_steps) / (self.max_steps - self.warmup_steps)
            return self.min_lr + (self.max_lr - self.min_lr) * 0.5 * (1 + math.cos(math.pi * progress))
        return self.min_lr

    def _apply(self):
        for group in self.optimizer.param_groups:
            group["lr"] = self.get_lr()

    def step(self):
        self.current_step += 1
        self._apply()

    def state_dict(self):
        return {"current_step": self.current_step}

    def load_state_dict(self, state):
        self.current_step = state["current_step"]
        self._apply()


def create_optimizer(model, config):
    decay_params = []
    no_decay_params = []
    for name, param in model.named_parameters():
        if not param.requires_grad:
            continue
        if param.dim() <= 1 or 'norm' in name.lower() or 'bias' in name:
            no_decay_params.append(param)
        else:
            decay_params.append(param)
    return torch.optim.AdamW([
        {'params': decay_params, 'weight_decay': config.weight_decay},
        {'params': no_decay_params, 'weight_decay': 0.0},
    ], lr=config.learning_rate, betas=config.betas, eps=config.eps)

Eğitim döngüsü

def amp_policy(device):
    """CUDA BF16 when supported; otherwise CUDA FP16 with scaling. CPU/MPS FP32."""
    device = torch.device(device)
    enabled = device.type == "cuda"
    dtype = torch.bfloat16 if enabled and torch.cuda.is_bf16_supported() else torch.float16
    return enabled, dtype, enabled and dtype == torch.float16


def train(model, train_dataset, config, device, steps=500, save_dir=None):
    if steps < 1 or config.grad_accum_steps < 1 or config.batch_size < 1:
        raise ValueError("steps, batch_size and grad_accum_steps must be positive")
    if len(train_dataset) < config.batch_size:
        raise ValueError("Dataset must contain at least one complete batch (drop_last=True)")
    device = torch.device(device)
    model = model.to(device)
    model.train()
    dataloader = DataLoader(train_dataset, batch_size=config.batch_size,
                            shuffle=True, drop_last=True)
    optimizer = create_optimizer(model, config)
    scheduler = CosineWarmupScheduler(optimizer, config.warmup_steps,
                                     steps, max_lr=config.learning_rate)
    use_amp, amp_dtype, use_scaler = amp_policy(device)
    scaler = torch.amp.GradScaler("cuda", enabled=use_scaler)
    optimizer.zero_grad(set_to_none=True)
    step = micro_steps = 0
    group_loss = 0.0
    loss_history = []
    start = time.time()

    # Accumulation carries across epochs; every update sees a FULL fixed-size group.
    # Incomplete data batches are dropped, never incomplete accumulation groups.
    while step < steps:
        for input_ids, target_ids in dataloader:
            input_ids, target_ids = input_ids.to(device), target_ids.to(device)
            with torch.amp.autocast(device.type, dtype=amp_dtype, enabled=use_amp):
                _, raw_loss = model(input_ids, target_ids)
            group_loss += raw_loss.detach().item()
            loss = raw_loss / config.grad_accum_steps
            scaler.scale(loss).backward()
            micro_steps += 1
            if micro_steps % config.grad_accum_steps:
                continue
            scaler.unscale_(optimizer)
            torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
            old_scale = scaler.get_scale()
            scaler.step(optimizer)
            scaler.update()
            optimizer.zero_grad(set_to_none=True)
            avg_loss = group_loss / config.grad_accum_steps
            group_loss = 0.0
            if scaler.get_scale() < old_scale:
                continue  # FP16 overflow: skipped optimizer update must not advance LR.
            step += 1
            loss_history.append((step, avg_loss))
            scheduler.step()
            if step % 50 == 0 or step == 1:
                print(f"Step {step:>4d} | Loss: {avg_loss:.4f} | Time: {time.time()-start:.0f}s")
            if save_dir and step % 5000 == 0:
                os.makedirs(save_dir, exist_ok=True)
                torch.save({"step": step, "model_state_dict": model.state_dict(),
                            "optimizer_state_dict": optimizer.state_dict(),
                            "scheduler_state_dict": scheduler.state_dict(),
                            "loss": avg_loss, "config": asdict(config)},
                           f"{save_dir}/checkpoint_step_{step}.pt")
            if step >= steps:
                break
    print(f"\nDone. {time.time() - start:.0f}s total.")
    return loss_history


def plot_loss(loss_history, save_path="loss_curve.png"):
    steps, losses = zip(*loss_history)
    plt.figure(figsize=(10, 4))
    plt.plot(steps, losses)
    plt.xlabel("Step")
    plt.ylabel("Loss")
    plt.title("Training Loss")
    plt.grid(True, alpha=0.3)
    plt.tight_layout()
    plt.savefig(save_path, dpi=100)
    plt.close()
    print(f"Loss curve saved to {save_path}")

Uyarlama notu: Biriktirme epoch boyunca sürer; boş loader reddedilir. Warmup ilk güncellemeden başlar ve kayıp bütün mikro batch grubunun ortalamasıdır. Bu hücreler main.py ile birlikte eşleştirilir.

Küçük bir eğitim çalıştır

Sekiz kısa cümlenin 15 kez tekrarlanmasıyla 120 metinlik çok küçük bir veri kümesi hazırlıyor ve minik bir modeli eğitiyoruz. Hücre 50 adım çalışır (steps=50); CPU'da birkaç dakika, GPU'da birkaç saniye sürer. Kaybın düşüşünü izle.

sample_texts = [
    "The cat sat on the mat. The dog ran in the park.",
    "Machine learning is the study of algorithms that improve through experience.",
    "Python is a programming language that lets you work quickly.",
    "The transformer architecture was introduced in two thousand seventeen.",
    "Language models predict the next word in a sequence of text.",
    "Training a neural network requires a lot of data and compute.",
    "The sun rises in the east and sets in the west every day.",
    "Mathematics is the language of the universe and all sciences.",
] * 15

tokenizer = SimpleTokenizer()
dataset = TextDataset(sample_texts, tokenizer, max_seq_len=128)
print(f"Dataset size: {len(dataset)} chunks of {128} tokens")

config = GPTConfig()
print(f"Model: {config.d_model} dims, {config.num_layers} layers, {config.num_heads} heads")

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Device: {device}")

model = GPT(config)
print(f"Parameters: {model.get_num_params():,}")
print()

loss_history = train(model, dataset, config, device, steps=50)  # Daha hızlı bir çalıştırma için 50'ye düşürüldü
plot_loss(loss_history, "loss_curve.png")

os.makedirs("checkpoints", exist_ok=True)
torch.save({
    "model_state_dict": model.state_dict(),
    "config": asdict(config),
}, "checkpoints/tiny_model.pt")
print("Model saved to checkpoints/tiny_model.pt")
Dataset size: 12 chunks of 128 tokens
Model: 256 dims, 4 layers, 4 heads
Device: cpu
Parameters: 17,062,400