Tam betik

The Full Script (main.py)

Tokenizer, model, eğitim döngüsü ve üretimi tek dosyada toplayan main.py; hangi parçanın hangi bölümden geldiğiyle birlikte.

15 dk · Orta

Çalıştırılabilir eğitim betiğinin tamamı, deponun kök dizininde main.py olarak durur: main.py.

tokenizer (belirteçleyici), model, eğitim döngüsü ve çıkarım (inference) aynı dosyanın içinde. main.py ve kilitli bağımlılıkları aynı dizine indirip çalıştırabilirsin:

uv run --python 3.12 --with-requirements requirements.lock main.py

Varsayılan olarak minik bir model kullanır (d_model=256, 4 katman, 4 kafa). Bu model Wikipedia metinlerinden oluşan WikiText-103 veri kümesinin boş olmayan ilk 5.000 satırıyla (paragraflar ve başlıklar) 500 adım eğitilir. Süre donanım, veri indirmesi ve seçilen hassasiyete bağlıdır; kendi cihazında ölç. Betikte bir de yorum satırına alınmış GPT-2 small yapılandırması var (768 boyut, 12 katman, 12 kafa); GPU'n varsa onu açabilirsin.

Eğitimden sonra betik bir kayıp eğrisi çizer (loss_curve.png), birkaç istemden örnek metin üretir ve checkpoint (kontrol noktası) dosyasını checkpoints/model.pt yoluna kaydeder.

Tarayıcıda denemek istersen aynı eğitimin Türkçe Colab defteri var; özgün İngilizce hali Colab'da tek tıkla açılır.

Betiğin haritası

main.py, önceki bölümlerde tek tek yazdığımız sınıfların yorumları ayıklanmış, sıkıştırılmış halleri. Yukarıdan aşağı okuduğunda şu sırayla ilerlersin:

Parça Geldiği bölüm
SimpleTokenizer Tokenizasyon
RotaryPositionalEmbedding, MultiHeadAttention RoPE, Dikkat
RMSNorm, SwiGLU, TransformerBlock, GPT Transformer, GPT
TextDataset, CosineWarmupScheduler, train Eğitim
GPT.generate, main Çıkarım, bu bölüm

main() fonksiyonu işleri şu sırayla yapar: yapılandırmayı kurar, cihazı seçer, tokenizer'ı ve veriyi yükler, modeli oluşturup parametre sayısını yazar, eğitir, kayıp eğrisini çizer, üç istemle metin üretir ve modeli kaydeder.

Uyarlamadaki düzeltmeler

Bu sürüm bu deponun main.py dosyasından üretilir. Gradyan biriktirme sayacı epoch sınırında sıfırlanmaz; her güncelleme tam grad_accum_steps mikro batch görür. Bir tam batch bile üretmeyen veri, beklemek yerine ValueError verir. drop_last=True eksik veri batch'ini atar; biriktirme grubu sonraki epoch'ta tamamlanır.

Warmup ilk optimizer güncellemesinden önce hazırlanır. Dört warmup adımı ilk dört güncellemede en yüksek öğrenme oranının 1/4, 2/4, 3/4 ve tamamını kullanır. CUDA BF16 desteği varsa BF16, yoksa ölçeklemeli FP16 seçilir; CPU ve MPS yolu FP32 kullanır. FP16 taşmasında atlanan güncelleme takvimi ilerletmez. Kayıp, grubun mikro batch ortalamasıdır.

generate modele yalnız context_ids penceresini verir ve tam istem ile üretilen bütün token'ları döndürür. Checkpoint yapılandırması özel sınıf yerine basit sözlük olarak saklanır ve weights_only=True ile yüklenir. Küçük model 17.062.400 parametrelidir.

main.py'nin tamamı

Aşağıdaki kod bu uyarlamanın main.py dosyasıyla aynıdır; scripts/sync-training.py --check eşleşmeyi denetler.

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


# ===== CİHAZ SEÇİMİ =====
def find_device():
    if torch.cuda.is_available():
        print(f"GPU: {torch.cuda.get_device_name(0)}")
        return torch.device("cuda")
    if torch.mps.is_available():
        print("Using Apple MPS")
        return torch.device("mps")
    print("Using CPU")
    return torch.device("cpu")


# ===== DÖNER KONUM GÖMMELERİ (RoPE) =====
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
    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)


# ===== NEDENSEL MASKE =====
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)


# ===== RMS NORMALİZASYONU =====
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


# ===== SwiGLU İLERİ BESLEMELİ AĞ =====
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))


# ===== ÇOK KAFALI DİKKAT =====
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


# ===== TRANSFORMER BLOĞU =====
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


# ===== GPT YAPILANDIRMASI =====
@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


# ===== GPT MODELİ =====
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())

    @torch.no_grad()
    def generate(self, input_ids, max_new_tokens, temperature=1.0, top_k=None, top_p=None):
        self.eval()
        for _ in range(max_new_tokens):
            # Modele yalnızca son max_seq_len token verilir; tam dizi input_ids'de kalır
            context_ids = input_ids[:, -self.config.max_seq_len:]
            logits, _ = self.forward(context_ids)
            logits = logits[:, -1, :] / temperature
            if top_k is not None:
                v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
                logits[logits < v[:, -1:]] = float('-inf')
            if top_p is not None:
                sorted_logits, sorted_indices = torch.sort(logits, descending=True)
                cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
                sorted_mask = cumulative_probs > top_p
                sorted_mask[:, 1:] = sorted_mask[:, :-1].clone()
                sorted_mask[:, 0] = False
                mask = sorted_mask.scatter(1, sorted_indices, sorted_mask)
                logits[mask] = float('-inf')
            probs = F.softmax(logits, dim=-1)
            next_token = torch.multinomial(probs, num_samples=1)
            input_ids = torch.cat([input_ids, next_token], dim=1)
        return input_ids


# ===== TOKENIZER =====
@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


# ===== VERİ KÜMESİ =====
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 max(0, (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]


def load_training_data(max_samples=None):
    from datasets import load_dataset
    print("Loading dataset: wikitext-103-raw-v1...")
    dataset = load_dataset("Salesforce/wikitext", "wikitext-103-raw-v1", split="train")
    texts = [item["text"] for item in dataset if item["text"].strip()]
    if max_samples:
        texts = texts[:max_samples]
    print(f"Loaded {len(texts):,} documents")
    return texts


# ===== ÖĞRENME ORANI TAKVİMİ =====
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()


# ===== OPTIMIZER =====
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ĞİTİM =====
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}")


# ===== ANA FONKSİYON =====
def main():
    print("How to Train Your GPT\n")

    # MİNİK MODEL (CPU'da çalışır, ~2-5 dakika)
    config = GPTConfig(
        d_model=256, num_heads=4, num_layers=4, max_seq_len=128,
        batch_size=4, grad_accum_steps=2, max_steps=500,
        warmup_steps=50, learning_rate=3e-4,
    )

    # KÜÇÜK MODEL (GPT-2 ölçeği, GPU gerekir)
    # config = GPTConfig(
    #     d_model=768, num_heads=12, num_layers=12, max_seq_len=1024,
    #     batch_size=4, grad_accum_steps=8, max_steps=50000,
    #     warmup_steps=2000, learning_rate=3e-4,
    # )

    device = find_device()

    tokenizer = SimpleTokenizer()
    print("Loading training data...")
    texts = load_training_data(max_samples=5000)
    train_dataset = TextDataset(texts, tokenizer, max_seq_len=config.max_seq_len)

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

    print("\n" + "=" * 50)
    print("TRAINING")
    print("=" * 50)
    loss_history = train(model, train_dataset, config, device, steps=config.max_steps)
    plot_loss(loss_history)

    print("\n" + "=" * 50)
    print("GENERATING")
    print("=" * 50 + "\n")

    prompts = [
        "The history of artificial intelligence",
        "In the beginning the universe",
        "The most important scientific discovery",
    ]

    for prompt in prompts:
        input_ids = torch.tensor([tokenizer.encode(prompt)], dtype=torch.long, device=device)
        output_ids = model.generate(input_ids, max_new_tokens=50, temperature=0.8, top_k=50)
        text = tokenizer.decode(output_ids[0].tolist())
        print(f"Prompt: {prompt}")
        print(f"Output: {text}")
        print("-" * 50)
        print()

    os.makedirs("checkpoints", exist_ok=True)
    torch.save({
        "model_state_dict": model.state_dict(),
        "config": asdict(config),
    }, "checkpoints/model.pt")
    print("Model saved to checkpoints/model.pt")


if __name__ == "__main__":
    main()