File size: 3,941 Bytes
a5a2705 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | import torch
import sentencepiece as spm
from gpt_model import MiniGPT
import math
import time
import os
# ======================
# CONFIG
# ======================
SEQ_LEN = 128
BATCH_SIZE = 32
EPOCHS = 4
LR = 3e-4
MAX_TOKENS_LIMIT = 3000000
CHECKPOINT_FILE = "/content/drive/MyDrive/xr_ai_checkpoint.pt"
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Using device:", device)
# ======================
# TOKENIZER
# ======================
print("π¦ Loading tokenizer...")
sp = spm.SentencePieceProcessor()
sp.load("hindi_tokenizer.model")
vocab_size = sp.get_piece_size()
# ======================
# DATASET
# ======================
print("π Loading dataset...")
text = open("sangraha_hindi_final_dataset.txt", encoding="utf-8").read()
tokens = sp.encode(text)
if MAX_TOKENS_LIMIT:
tokens = tokens[:MAX_TOKENS_LIMIT]
data = torch.tensor(tokens, dtype=torch.long)
split = int(0.9 * len(data))
train_data = data[:split]
val_data = data[split:]
# ======================
# MODEL
# ======================
model = MiniGPT(vocab_size).to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=LR)
loss_fn = torch.nn.CrossEntropyLoss()
resume_step = 0
# ======================
# RESUME CHECKPOINT
# ======================
if os.path.exists(CHECKPOINT_FILE):
print("π Loading checkpoint...")
checkpoint = torch.load(CHECKPOINT_FILE)
model.load_state_dict(checkpoint["model"])
optimizer.load_state_dict(checkpoint["optimizer"])
resume_step = checkpoint["step"]
print("Resuming from step:", resume_step)
# ======================
# TRAINING
# ======================
print("π XR_AI Training Started...")
step = resume_step
for epoch in range(EPOCHS):
model.train()
total_train_loss = 0
train_steps = 0
for i in range(0, len(train_data) - SEQ_LEN - 1, SEQ_LEN * BATCH_SIZE):
batch_inputs = []
batch_targets = []
for j in range(BATCH_SIZE):
start = i + j * SEQ_LEN
if start + SEQ_LEN + 1 >= len(train_data):
continue
x = train_data[start:start+SEQ_LEN]
y = train_data[start+1:start+SEQ_LEN+1]
batch_inputs.append(x)
batch_targets.append(y)
if len(batch_inputs) == 0:
continue
inputs = torch.stack(batch_inputs).to(device)
targets = torch.stack(batch_targets).to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = loss_fn(outputs.view(-1, vocab_size), targets.view(-1))
loss.backward()
optimizer.step()
step += 1
train_steps += 1
total_train_loss += loss.item()
# checkpoint
if step % 200 == 0:
torch.save({
"model": model.state_dict(),
"optimizer": optimizer.state_dict(),
"step": step
}, CHECKPOINT_FILE)
print("πΎ checkpoint saved at step", step)
avg_train_loss = total_train_loss / train_steps
# ======================
# VALIDATION
# ======================
model.eval()
total_val_loss = 0
val_steps = 0
with torch.no_grad():
for i in range(0, len(val_data) - SEQ_LEN - 1, SEQ_LEN):
inputs = val_data[i:i+SEQ_LEN].unsqueeze(0).to(device)
targets = val_data[i+1:i+SEQ_LEN+1].unsqueeze(0).to(device)
outputs = model(inputs)
loss = loss_fn(outputs.view(-1, vocab_size), targets.view(-1))
total_val_loss += loss.item()
val_steps += 1
avg_val_loss = total_val_loss / val_steps
perplexity = math.exp(avg_val_loss)
print(
f"Epoch {epoch+1}/{EPOCHS} | "
f"Train: {avg_train_loss:.4f} | "
f"Val: {avg_val_loss:.4f} | "
f"PPL: {perplexity:.2f}"
)
torch.save(model.state_dict(), "best_model.pt")
print("π Training complete")
|