the loss is decrasing very fast and you try and find what might be wrong in this llm…
- User
the loss is decrasing very fast and you try and find what might be wrong in this llm training code ? import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader from transformers import GPT2Tokenizer from datasets import load_dataset from tqdm import tqdm import time import os import math
Constants
BATCH_SIZE = 12 SEQUENCE_LENGTH = 256 LEARNING_RATE = 2e-5 NUM_EPOCHS = 3 SAVE_STEPS = 500 EMBEDDING_DIM = 4096 NUM_LAYERS = 12 HEADS = 16 MODEL_PATH = "reversible_transformer_lm.pth"
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print(f"Using device: {device}")
Load GPT-2 tokenizer
tokenizer = GPT2Tokenizer.from_pretrained("gpt2") tokenizer.pad_token = tokenizer.eos_token
def count_parameters(model): return sum(p.numel() for p in model.parameters() if p.requires_grad)
class ReversibleBlock(nn.Module): def init(self, f_block, g_block): super().init() self.f = f_block self.g = g_block
def forward(self, x1, x2): y1 = x1 + self.f(x2) y2 = x2 + self.g(y1) return y1, y2class CausalLinearAttention(nn.Module): def init(self, embed_dim, heads): super().init() self.embed_dim = embed_dim self.heads = heads self.head_dim = embed_dim // heads assert self.head_dim * heads == embed_dim, f"embed_dim {embed_dim} must be divisible by heads {heads}"
self.to_qk = nn.Linear(embed_dim, embed_dim * 2) self.to_v = nn.Linear(embed_dim, embed_dim) self.to_out = nn.Linear(embed_dim, embed_dim) self.norm = nn.LayerNorm(embed_dim) self.init_weights() def init_weights(self): nn.init.xavier_uniform_(self.to_qk.weight, gain=1/math.sqrt(2)) nn.init.xavier_uniform_(self.to_v.weight, gain=1/math.sqrt(2)) nn.init.xavier_uniform_(self.to_out.weight, gain=1/math.sqrt(2)) nn.init.zeros_(self.to_qk.bias) nn.init.zeros_(self.to_v.bias) nn.init.zeros_(self.to_out.bias) def forward(self, x): x = self.norm(x) B, T, E = x.size() qk = self.to_qk(x).view(B, T, self.heads, 2 * self.head_dim) q, k = qk.chunk(2, dim=-1) v = self.to_v(x).view(B, T, self.heads, self.head_dim) q = F.softmax(q, dim=-2) k = F.softmax(k, dim=-2) # Create causal mask mask = torch.tril(torch.ones(T, T)).unsqueeze(0).unsqueeze(0).to(x.device) context = torch.einsum('bthd,bshd->bhts', k, v) context = context * mask out = torch.einsum('bhts,bthd->bshd', context, q) out = out.contiguous().view(B, T, E) return self.to_out(out)class FeedForward(nn.Module): def init(self, embed_dim, expansion_factor=4): super().init() self.net = nn.Sequential( nn.Linear(embed_dim, embed_dim * expansion_factor), nn.GELU(), nn.Linear(embed_dim * expansion_factor, embed_dim) ) self.norm = nn.LayerNorm(embed_dim) self.init_weights()
- Assistant