Upload 7 files
Browse files- README.md +47 -0
- banner.png +0 -0
- model.py +94 -0
- prepare_data.py +152 -0
- sample.py +141 -0
- train_chatgclm.py +272 -0
- vocab_map.pt +3 -0
README.md
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## ChatGCLM-270M
|
| 2 |
+
<<img src="./banner.png" alt="ChatGCLM Hero" width="600">>
|
| 3 |
+
<strong>A high-performance language model architecture.</strong>
|
| 4 |
+
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
## Overview
|
| 8 |
+
|
| 9 |
+
**ChatGCLM** is a generative language model that deviates from the traditional Transformer architecture by utilizing a hybrid approach of **Local** and **Global Convolutions**. By leveraging Fast Fourier Transforms (FFT) for global context, ChatGCLM achieves a massive receptive field with a fraction of the computational overhead associated with standard attention mechanisms.
|
| 10 |
+
|
| 11 |
+
The architecture is designed for efficiency, speed, and high-quality generation, featuring a custom vocabulary reduction system that optimizes the embedding space for specific datasets.
|
| 12 |
+
|
| 13 |
+
This repository provides the implementation for training and sampling from the ChatGCLM-270M model, which consists of 270 million parameters.
|
| 14 |
+
|
| 15 |
+
The model has the full vocabulary of GPT-2, so it can be fine-tuned on any dataset that GPT-2 can be fine-tuned on.
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
## 📦 Installation
|
| 19 |
+
|
| 20 |
+
Download this repository and extract it.
|
| 21 |
+
|
| 22 |
+
---
|
| 23 |
+
|
| 24 |
+
## Usage
|
| 25 |
+
|
| 26 |
+
### 1. Training the Model
|
| 27 |
+
Place your `.txt` data files in the `data/` directory and run:
|
| 28 |
+
```bash
|
| 29 |
+
python train_chatgclm.py
|
| 30 |
+
```
|
| 31 |
+
This script will build the vocabulary and train the foundation model
|
| 32 |
+
|
| 33 |
+
### 2. Sample from the model
|
| 34 |
+
Run sample.py to generate text with the model
|
| 35 |
+
```bash
|
| 36 |
+
python sample.py
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
---
|
| 40 |
+
|
| 41 |
+
## Fine-tuning
|
| 42 |
+
|
| 43 |
+
You may fine-tune the model by resuming training from a checkpoint, you may use a different dataset, you may also change parameters such as the learning rate, batch size, etc.
|
| 44 |
+
|
| 45 |
+
<p align="center">
|
| 46 |
+
Built with ❤️ by AG
|
| 47 |
+
</p>
|
banner.png
ADDED
|
model.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
|
| 5 |
+
D_MODEL = 1024
|
| 6 |
+
N_LAYERS = 22 # Increased to 22 to ensure >270M params
|
| 7 |
+
MAX_SEQ_LEN = 1024 # Reduced from 4096 for 10x speedup
|
| 8 |
+
LOCAL_KERNEL_SIZE = 3 # Reduced from 5
|
| 9 |
+
GLOBAL_KERNEL_SIZE = 512
|
| 10 |
+
USE_GLOBAL_EVERY_N_LAYERS = 2
|
| 11 |
+
FFT_SIZE = 1024 # Match MAX_SEQ_LEN for peak FFT efficiency
|
| 12 |
+
|
| 13 |
+
class GlobalConv1D(nn.Module):
|
| 14 |
+
def __init__(self, d_model, kernel_size, fft_size):
|
| 15 |
+
super().__init__()
|
| 16 |
+
self.kernel = nn.Parameter(torch.randn(d_model, kernel_size) * 0.01)
|
| 17 |
+
self.kernel_size = kernel_size
|
| 18 |
+
self.fft_size = fft_size
|
| 19 |
+
|
| 20 |
+
def forward(self, x):
|
| 21 |
+
B, C, T = x.shape
|
| 22 |
+
K = min(self.kernel_size, T)
|
| 23 |
+
overlap = K - 1
|
| 24 |
+
block = self.fft_size - overlap
|
| 25 |
+
x = F.pad(x, (overlap, 0))
|
| 26 |
+
k = self.kernel[:, :K]
|
| 27 |
+
k = F.pad(k, (0, self.fft_size - K))
|
| 28 |
+
k_f = torch.fft.rfft(k, n=self.fft_size)
|
| 29 |
+
outs = []
|
| 30 |
+
pos = 0
|
| 31 |
+
while pos < T:
|
| 32 |
+
seg = x[..., pos:pos+self.fft_size]
|
| 33 |
+
if seg.shape[-1] < self.fft_size:
|
| 34 |
+
seg = F.pad(seg, (0, self.fft_size - seg.shape[-1]))
|
| 35 |
+
y = torch.fft.irfft(torch.fft.rfft(seg, n=self.fft_size) * k_f.unsqueeze(0), n=self.fft_size)
|
| 36 |
+
outs.append(y[..., overlap:overlap+block])
|
| 37 |
+
pos += block
|
| 38 |
+
return torch.cat(outs, dim=-1)[..., :T]
|
| 39 |
+
|
| 40 |
+
class LocalConv1D(nn.Module):
|
| 41 |
+
def __init__(self, d_model, k):
|
| 42 |
+
super().__init__()
|
| 43 |
+
self.k = k
|
| 44 |
+
self.dw = nn.Conv1d(d_model, d_model, k, groups=d_model)
|
| 45 |
+
self.pw = nn.Conv1d(d_model, d_model, 1)
|
| 46 |
+
|
| 47 |
+
def forward(self, x):
|
| 48 |
+
x = F.pad(x, (self.k - 1, 0))
|
| 49 |
+
return self.pw(F.relu(self.dw(x)))
|
| 50 |
+
|
| 51 |
+
class Block(nn.Module):
|
| 52 |
+
def __init__(self, d_model, use_global):
|
| 53 |
+
super().__init__()
|
| 54 |
+
self.use_global = use_global
|
| 55 |
+
self.ln1 = nn.LayerNorm(d_model)
|
| 56 |
+
self.local = LocalConv1D(d_model, LOCAL_KERNEL_SIZE)
|
| 57 |
+
if use_global:
|
| 58 |
+
self.ln2 = nn.LayerNorm(d_model)
|
| 59 |
+
self.global_conv = GlobalConv1D(d_model, GLOBAL_KERNEL_SIZE, FFT_SIZE)
|
| 60 |
+
self.ln3 = nn.LayerNorm(d_model)
|
| 61 |
+
self.ff = nn.Sequential(
|
| 62 |
+
nn.Linear(d_model, d_model*4),
|
| 63 |
+
nn.GELU(),
|
| 64 |
+
nn.Linear(d_model*4, d_model)
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
def forward(self, x):
|
| 68 |
+
x = x + self.local(self.ln1(x).transpose(1,2)).transpose(1,2)
|
| 69 |
+
if self.use_global:
|
| 70 |
+
x = x + self.global_conv(self.ln2(x).transpose(1,2)).transpose(1,2)
|
| 71 |
+
return x + self.ff(self.ln3(x))
|
| 72 |
+
|
| 73 |
+
class ChatGCLM(nn.Module):
|
| 74 |
+
def __init__(self, vocab):
|
| 75 |
+
super().__init__()
|
| 76 |
+
self.emb = nn.Embedding(vocab, D_MODEL)
|
| 77 |
+
self.pos = nn.Embedding(MAX_SEQ_LEN, D_MODEL)
|
| 78 |
+
self.layers = nn.ModuleList([
|
| 79 |
+
Block(D_MODEL, i % USE_GLOBAL_EVERY_N_LAYERS == 0)
|
| 80 |
+
for i in range(N_LAYERS)
|
| 81 |
+
])
|
| 82 |
+
self.ln = nn.LayerNorm(D_MODEL)
|
| 83 |
+
self.head = nn.Linear(D_MODEL, vocab)
|
| 84 |
+
self.head.weight = self.emb.weight
|
| 85 |
+
|
| 86 |
+
def forward(self, x):
|
| 87 |
+
T = x.size(1)
|
| 88 |
+
if T > MAX_SEQ_LEN:
|
| 89 |
+
x = x[:, -MAX_SEQ_LEN:]
|
| 90 |
+
T = MAX_SEQ_LEN
|
| 91 |
+
h = self.emb(x) + self.pos(torch.arange(T, device=x.device))
|
| 92 |
+
for layer in self.layers:
|
| 93 |
+
h = layer(h)
|
| 94 |
+
return self.head(self.ln(h))
|
prepare_data.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import csv
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
# Increase field size limit for large CSV fields
|
| 7 |
+
csv.field_size_limit(sys.maxsize)
|
| 8 |
+
|
| 9 |
+
def clean_text(text):
|
| 10 |
+
if not text:
|
| 11 |
+
return ""
|
| 12 |
+
return text.strip()
|
| 13 |
+
|
| 14 |
+
def process_item(system, conversation, output_file):
|
| 15 |
+
# conversion to text format:
|
| 16 |
+
# <system>...
|
| 17 |
+
# <user>...
|
| 18 |
+
# <ai>...
|
| 19 |
+
|
| 20 |
+
# Check if we have valid content
|
| 21 |
+
if not conversation:
|
| 22 |
+
return
|
| 23 |
+
|
| 24 |
+
text_parts = []
|
| 25 |
+
|
| 26 |
+
# Add system if present
|
| 27 |
+
if system:
|
| 28 |
+
text_parts.append(f"<system>{clean_text(system)}")
|
| 29 |
+
|
| 30 |
+
# Process conversation turns
|
| 31 |
+
# conversation is a list of (role, content)
|
| 32 |
+
# roles: 'user', 'ai' (we map 'assistant'->'ai')
|
| 33 |
+
|
| 34 |
+
for role, content in conversation:
|
| 35 |
+
content = clean_text(content)
|
| 36 |
+
if not content:
|
| 37 |
+
continue
|
| 38 |
+
|
| 39 |
+
if role == 'system':
|
| 40 |
+
# Handle system in message list if somehow present/overriding
|
| 41 |
+
text_parts.append(f"<system>{content}")
|
| 42 |
+
elif role == 'user':
|
| 43 |
+
text_parts.append(f"<user>{content}")
|
| 44 |
+
elif role == 'assistant' or role == 'ai':
|
| 45 |
+
text_parts.append(f"<ai>{content}")
|
| 46 |
+
else:
|
| 47 |
+
# Fallback for unknown roles
|
| 48 |
+
text_parts.append(f"<{role}>{content}")
|
| 49 |
+
|
| 50 |
+
if text_parts:
|
| 51 |
+
final_str = "\n".join(text_parts)
|
| 52 |
+
output_file.write(final_str + "\n\n")
|
| 53 |
+
|
| 54 |
+
def process_csv(filepath, output_path):
|
| 55 |
+
print(f"Processing CSV: {filepath}")
|
| 56 |
+
try:
|
| 57 |
+
with open(filepath, 'r', encoding='utf-8', errors='replace') as f:
|
| 58 |
+
reader = csv.DictReader(f)
|
| 59 |
+
with open(output_path, 'a', encoding='utf-8') as out:
|
| 60 |
+
count = 0
|
| 61 |
+
for row in reader:
|
| 62 |
+
# Mapping logic for this specific CSV structure:
|
| 63 |
+
# thread_title -> User context/prompt
|
| 64 |
+
# instruction -> System prompt
|
| 65 |
+
# message -> AI response
|
| 66 |
+
|
| 67 |
+
sys_prompt = row.get('instruction', '')
|
| 68 |
+
title = row.get('thread_title', '')
|
| 69 |
+
msg = row.get('message', '')
|
| 70 |
+
|
| 71 |
+
# If we have mainly 'text' and it looks like it contains everything, we might prefer it?
|
| 72 |
+
# But analysis suggested 'text' was just instruction/duplicate in some rows.
|
| 73 |
+
# We'll stick to constructing from parts which is safer for structured training.
|
| 74 |
+
|
| 75 |
+
conversation = []
|
| 76 |
+
if title:
|
| 77 |
+
conversation.append(('user', title))
|
| 78 |
+
if msg:
|
| 79 |
+
conversation.append(('ai', msg))
|
| 80 |
+
|
| 81 |
+
if conversation:
|
| 82 |
+
process_item(sys_prompt, conversation, out)
|
| 83 |
+
count += 1
|
| 84 |
+
if count % 10000 == 0:
|
| 85 |
+
print(f"CSV Processed {count}...", flush=True)
|
| 86 |
+
print(f"Finished CSV. Processed {count} rows.")
|
| 87 |
+
except Exception as e:
|
| 88 |
+
print(f"Error processing CSV: {e}")
|
| 89 |
+
|
| 90 |
+
def process_jsonl(filepath, output_path):
|
| 91 |
+
print(f"Processing JSONL: {filepath}")
|
| 92 |
+
try:
|
| 93 |
+
with open(filepath, 'r', encoding='utf-8') as f, open(output_path, 'a', encoding='utf-8') as out:
|
| 94 |
+
count = 0
|
| 95 |
+
for line in f:
|
| 96 |
+
if not line.strip(): continue
|
| 97 |
+
try:
|
| 98 |
+
data = json.loads(line)
|
| 99 |
+
messages = data.get('messages', [])
|
| 100 |
+
|
| 101 |
+
# Extract system prompt if it exists as a separate field or role
|
| 102 |
+
system_prompt = data.get('system', '')
|
| 103 |
+
|
| 104 |
+
conversation = []
|
| 105 |
+
|
| 106 |
+
for m in messages:
|
| 107 |
+
role = m.get('role', '')
|
| 108 |
+
content = m.get('content', '')
|
| 109 |
+
|
| 110 |
+
if role == 'system':
|
| 111 |
+
# If we hit a system role, treat it as global system or part of flow
|
| 112 |
+
# User asked to "add system as <system>"
|
| 113 |
+
# I'll just map it directly.
|
| 114 |
+
conversation.append(('system', content))
|
| 115 |
+
else:
|
| 116 |
+
conversation.append((role, content))
|
| 117 |
+
|
| 118 |
+
if conversation:
|
| 119 |
+
# Pass None for separate system arg since we handle it in loop
|
| 120 |
+
process_item(None, conversation, out)
|
| 121 |
+
count += 1
|
| 122 |
+
|
| 123 |
+
if count % 10000 == 0:
|
| 124 |
+
print(f"JSONL Processed {count}...", flush=True)
|
| 125 |
+
|
| 126 |
+
except json.JSONDecodeError:
|
| 127 |
+
continue
|
| 128 |
+
print(f"Finished JSONL. Processed {count} items.")
|
| 129 |
+
except Exception as e:
|
| 130 |
+
print(f"Error processing JSONL: {e}")
|
| 131 |
+
|
| 132 |
+
def main():
|
| 133 |
+
data_dir = "data"
|
| 134 |
+
output_filename = "processed_corpus.txt"
|
| 135 |
+
output_path = os.path.join(data_dir, output_filename)
|
| 136 |
+
|
| 137 |
+
# Overwrite/Create new
|
| 138 |
+
with open(output_path, 'w', encoding='utf-8') as f:
|
| 139 |
+
f.write("")
|
| 140 |
+
|
| 141 |
+
# Process JSONL
|
| 142 |
+
jsonl_path = os.path.join(data_dir, "dataset.jsonl")
|
| 143 |
+
if os.path.exists(jsonl_path):
|
| 144 |
+
process_jsonl(jsonl_path, output_path)
|
| 145 |
+
|
| 146 |
+
# Process CSV
|
| 147 |
+
csv_path = os.path.join(data_dir, "train.csv")
|
| 148 |
+
if os.path.exists(csv_path):
|
| 149 |
+
process_csv(csv_path, output_path)
|
| 150 |
+
|
| 151 |
+
if __name__ == "__main__":
|
| 152 |
+
main()
|
sample.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from collections import OrderedDict
|
| 5 |
+
import tiktoken
|
| 6 |
+
from model import ChatGCLM, MAX_SEQ_LEN
|
| 7 |
+
|
| 8 |
+
MODEL_PATH = None
|
| 9 |
+
for f in os.listdir("."):
|
| 10 |
+
if f.startswith("ChatGCLM_") and f.endswith(".pt"):
|
| 11 |
+
MODEL_PATH = f
|
| 12 |
+
break
|
| 13 |
+
|
| 14 |
+
if MODEL_PATH is None:
|
| 15 |
+
print("Error: No model checkpoint found!")
|
| 16 |
+
print("Please train the model first with: python3 train_chatgclm.py")
|
| 17 |
+
exit(1)
|
| 18 |
+
|
| 19 |
+
TOKENIZER_NAME = "gpt2"
|
| 20 |
+
EOS_ID = 2
|
| 21 |
+
|
| 22 |
+
def load_model(device):
|
| 23 |
+
tok = tiktoken.get_encoding(TOKENIZER_NAME)
|
| 24 |
+
vocab_size = tok.n_vocab
|
| 25 |
+
|
| 26 |
+
model = ChatGCLM(vocab_size).to(device)
|
| 27 |
+
if os.path.exists(MODEL_PATH) and os.path.getsize(MODEL_PATH) > 0:
|
| 28 |
+
print(f"Loading model from: {MODEL_PATH}")
|
| 29 |
+
ckpt = torch.load(MODEL_PATH, map_location=device)
|
| 30 |
+
|
| 31 |
+
# Common checkpoint shapes: either a state_dict, or a dict containing
|
| 32 |
+
# 'model_state_dict' / 'state_dict' keys.
|
| 33 |
+
if isinstance(ckpt, dict):
|
| 34 |
+
if 'model_state_dict' in ckpt:
|
| 35 |
+
state_dict = ckpt['model_state_dict']
|
| 36 |
+
elif 'state_dict' in ckpt:
|
| 37 |
+
state_dict = ckpt['state_dict']
|
| 38 |
+
else:
|
| 39 |
+
state_dict = ckpt
|
| 40 |
+
else:
|
| 41 |
+
state_dict = ckpt
|
| 42 |
+
|
| 43 |
+
# If checkpoint was saved from DataParallel/DistributedDataParallel it may
|
| 44 |
+
# have a 'module.' prefix on every key. Strip it if present.
|
| 45 |
+
def _strip_module_prefix(sd):
|
| 46 |
+
keys = list(sd.keys())
|
| 47 |
+
if any(k.startswith('module.') for k in keys):
|
| 48 |
+
new_sd = OrderedDict()
|
| 49 |
+
for k, v in sd.items():
|
| 50 |
+
new_key = k[len('module.'): ] if k.startswith('module.') else k
|
| 51 |
+
new_sd[new_key] = v
|
| 52 |
+
return new_sd
|
| 53 |
+
return sd
|
| 54 |
+
|
| 55 |
+
state_dict = _strip_module_prefix(state_dict)
|
| 56 |
+
|
| 57 |
+
# Load with strict=False to allow minor mismatches; report missing/unexpected keys.
|
| 58 |
+
res = model.load_state_dict(state_dict, strict=False)
|
| 59 |
+
# res is an _IncompatibleKeys object with missing_keys and unexpected_keys
|
| 60 |
+
missing = getattr(res, 'missing_keys', None)
|
| 61 |
+
unexpected = getattr(res, 'unexpected_keys', None)
|
| 62 |
+
if missing:
|
| 63 |
+
print(f"Warning: missing keys when loading state_dict: {missing}")
|
| 64 |
+
if unexpected:
|
| 65 |
+
print(f"Warning: unexpected keys in state_dict: {unexpected}")
|
| 66 |
+
|
| 67 |
+
model.eval()
|
| 68 |
+
return model, tok
|
| 69 |
+
else:
|
| 70 |
+
print(f"Error: Could not load model from {MODEL_PATH}")
|
| 71 |
+
return None, None
|
| 72 |
+
|
| 73 |
+
@torch.no_grad()
|
| 74 |
+
def generate(model, prompt, tokenizer, device, max_new_tokens=200, temperature=0.8, top_k=50):
|
| 75 |
+
model.eval()
|
| 76 |
+
input_ids = tokenizer.encode(prompt)
|
| 77 |
+
x = torch.tensor([input_ids], dtype=torch.long, device=device)
|
| 78 |
+
|
| 79 |
+
print(f"\n{'='*70}")
|
| 80 |
+
print(f"PROMPT: {prompt}")
|
| 81 |
+
print(f"{'='*70}")
|
| 82 |
+
print("GENERATED TEXT:")
|
| 83 |
+
print(prompt, end="", flush=True)
|
| 84 |
+
|
| 85 |
+
generated_tokens = []
|
| 86 |
+
for _ in range(max_new_tokens):
|
| 87 |
+
ctx = x[:, -MAX_SEQ_LEN:] if x.size(1) > MAX_SEQ_LEN else x
|
| 88 |
+
logits = model(ctx)
|
| 89 |
+
next_token_logits = logits[:, -1, :] / temperature
|
| 90 |
+
|
| 91 |
+
if top_k is not None:
|
| 92 |
+
v, _ = torch.topk(next_token_logits, min(top_k, next_token_logits.size(-1)))
|
| 93 |
+
next_token_logits[next_token_logits < v[:, [-1]]] = -float('Inf')
|
| 94 |
+
|
| 95 |
+
probs = F.softmax(next_token_logits, dim=-1)
|
| 96 |
+
next_token = torch.multinomial(probs, num_samples=1)
|
| 97 |
+
idx = next_token.item()
|
| 98 |
+
|
| 99 |
+
if idx == EOS_ID:
|
| 100 |
+
break
|
| 101 |
+
|
| 102 |
+
x = torch.cat((x, next_token), dim=1)
|
| 103 |
+
generated_tokens.append(idx)
|
| 104 |
+
token_text = tokenizer.decode([idx])
|
| 105 |
+
print(token_text, end="", flush=True)
|
| 106 |
+
|
| 107 |
+
print(f"\n{'='*70}\n")
|
| 108 |
+
return tokenizer.decode(generated_tokens)
|
| 109 |
+
|
| 110 |
+
if __name__ == "__main__":
|
| 111 |
+
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
|
| 112 |
+
print(f"Using device: {device}")
|
| 113 |
+
|
| 114 |
+
model, tokenizer = load_model(device)
|
| 115 |
+
|
| 116 |
+
if model is None:
|
| 117 |
+
exit(1)
|
| 118 |
+
|
| 119 |
+
test_prompts = [
|
| 120 |
+
"Once upon a time",
|
| 121 |
+
"The future of AI is",
|
| 122 |
+
"In a world where",
|
| 123 |
+
]
|
| 124 |
+
|
| 125 |
+
print("\n" + "="*70)
|
| 126 |
+
print("ChatGCLM Text Generation Demo")
|
| 127 |
+
print("="*70)
|
| 128 |
+
|
| 129 |
+
for prompt in test_prompts:
|
| 130 |
+
generate(model, prompt, tokenizer, device, max_new_tokens=150, temperature=0.8, top_k=50)
|
| 131 |
+
|
| 132 |
+
print("\n" + "="*70)
|
| 133 |
+
print("Interactive Mode - Enter your own prompts!")
|
| 134 |
+
print("="*70)
|
| 135 |
+
|
| 136 |
+
while True:
|
| 137 |
+
user_prompt = input("\nEnter prompt (or 'exit' to quit): ")
|
| 138 |
+
if user_prompt.lower() == 'exit':
|
| 139 |
+
break
|
| 140 |
+
if user_prompt.strip():
|
| 141 |
+
generate(model, user_prompt, tokenizer, device, max_new_tokens=200, temperature=0.8, top_k=50)
|
train_chatgclm.py
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import os
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from torch.utils.data import Dataset, DataLoader
|
| 7 |
+
from tqdm import tqdm
|
| 8 |
+
import tiktoken
|
| 9 |
+
import contextlib
|
| 10 |
+
from model import ChatGCLM, MAX_SEQ_LEN
|
| 11 |
+
|
| 12 |
+
if os.name != "nt":
|
| 13 |
+
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
|
| 14 |
+
|
| 15 |
+
if torch.cuda.is_available():
|
| 16 |
+
torch.set_float32_matmul_precision("high")
|
| 17 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 18 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 19 |
+
|
| 20 |
+
DATA_DIR = "data"
|
| 21 |
+
DATA_PCT = 0.002
|
| 22 |
+
MPS_SEQ_LEN = 512
|
| 23 |
+
MPS_STEPS_PER_EPOCH = 18
|
| 24 |
+
CPU_SEQ_LEN = 512
|
| 25 |
+
CPU_STEPS_PER_EPOCH = 48
|
| 26 |
+
TOKENIZER_NAME = "gpt2"
|
| 27 |
+
VOCAB_SAVE_PATH = "vocab_map.pt"
|
| 28 |
+
FINE_TUNE = True
|
| 29 |
+
FINE_TUNE_FILE = "chat_data.txt"
|
| 30 |
+
|
| 31 |
+
EPOCHS = 50
|
| 32 |
+
MICRO_BATCH_SIZE = 8 # Increased for better GPU utilization
|
| 33 |
+
GRAD_ACCUM_STEPS = 4 # Total batch size 32
|
| 34 |
+
STEPS_PER_EPOCH = 500 # Reduced to 500 for ~5-7 min epochs
|
| 35 |
+
LEARNING_RATE = 5e-4
|
| 36 |
+
MIN_LR = 1e-5
|
| 37 |
+
|
| 38 |
+
SAVE_N_EPOCHS = 1
|
| 39 |
+
|
| 40 |
+
PAD_ID = 0
|
| 41 |
+
SEP_ID = 1
|
| 42 |
+
EOS_ID = 2
|
| 43 |
+
OFFSET = 3
|
| 44 |
+
|
| 45 |
+
def build_dataset_vocab(data_dir, tokenizer, save_path):
|
| 46 |
+
vocab_size = tokenizer.n_vocab
|
| 47 |
+
torch.save({
|
| 48 |
+
"vocab_size": vocab_size,
|
| 49 |
+
"PAD_ID": PAD_ID,
|
| 50 |
+
"SEP_ID": SEP_ID,
|
| 51 |
+
"EOS_ID": EOS_ID,
|
| 52 |
+
}, save_path)
|
| 53 |
+
return vocab_size
|
| 54 |
+
|
| 55 |
+
class RemappedTextDataset(Dataset):
|
| 56 |
+
def __init__(self, ids, max_len):
|
| 57 |
+
self.ids = ids
|
| 58 |
+
self.max_len = max_len
|
| 59 |
+
|
| 60 |
+
def __len__(self):
|
| 61 |
+
return max(0, (len(self.ids) - 1) // self.max_len)
|
| 62 |
+
|
| 63 |
+
def __getitem__(self, i):
|
| 64 |
+
start = i * self.max_len
|
| 65 |
+
x = self.ids[start : start + self.max_len]
|
| 66 |
+
y = self.ids[start + 1 : start + self.max_len + 1]
|
| 67 |
+
|
| 68 |
+
if len(x) < self.max_len:
|
| 69 |
+
x = x + [0] * (self.max_len - len(x))
|
| 70 |
+
if len(y) < self.max_len:
|
| 71 |
+
y = y + [0] * (self.max_len - len(y))
|
| 72 |
+
|
| 73 |
+
return torch.tensor(x, dtype=torch.long), torch.tensor(y, dtype=torch.long)
|
| 74 |
+
|
| 75 |
+
def format_params(num):
|
| 76 |
+
if num >= 1_000_000_000:
|
| 77 |
+
return f"{num/1_000_000_000:.1f}B"
|
| 78 |
+
elif num >= 1_000_000:
|
| 79 |
+
return f"{num/1_000_000:.1f}M"
|
| 80 |
+
else:
|
| 81 |
+
return f"{num/1_000:.1f}K"
|
| 82 |
+
|
| 83 |
+
@torch.no_grad()
|
| 84 |
+
def estimate_loss(model, dl, device, ctx):
|
| 85 |
+
model.eval()
|
| 86 |
+
losses = []
|
| 87 |
+
limit = 50
|
| 88 |
+
for i, (x, y) in enumerate(dl):
|
| 89 |
+
if i >= limit: break
|
| 90 |
+
x, y = x.to(device), y.to(device)
|
| 91 |
+
with ctx:
|
| 92 |
+
logits = model(x)
|
| 93 |
+
loss = F.cross_entropy(logits.reshape(-1, logits.size(-1)), y.reshape(-1), ignore_index=PAD_ID)
|
| 94 |
+
losses.append(loss.item())
|
| 95 |
+
model.train()
|
| 96 |
+
return sum(losses) / len(losses) if losses else 0.0
|
| 97 |
+
|
| 98 |
+
def train():
|
| 99 |
+
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
|
| 100 |
+
tok = tiktoken.get_encoding(TOKENIZER_NAME)
|
| 101 |
+
effective_batch_target = MICRO_BATCH_SIZE * GRAD_ACCUM_STEPS
|
| 102 |
+
micro_batch_size = MICRO_BATCH_SIZE
|
| 103 |
+
grad_accum_steps = GRAD_ACCUM_STEPS
|
| 104 |
+
train_seq_len = MAX_SEQ_LEN
|
| 105 |
+
steps_per_epoch = STEPS_PER_EPOCH
|
| 106 |
+
|
| 107 |
+
if device == "mps":
|
| 108 |
+
if hasattr(torch, "mps"):
|
| 109 |
+
torch.mps.empty_cache()
|
| 110 |
+
micro_batch_size = 1
|
| 111 |
+
grad_accum_steps = max(1, math.ceil(effective_batch_target / micro_batch_size))
|
| 112 |
+
train_seq_len = min(MAX_SEQ_LEN, MPS_SEQ_LEN)
|
| 113 |
+
steps_per_epoch = min(STEPS_PER_EPOCH, MPS_STEPS_PER_EPOCH)
|
| 114 |
+
elif device == "cpu":
|
| 115 |
+
micro_batch_size = min(4, MICRO_BATCH_SIZE)
|
| 116 |
+
grad_accum_steps = max(1, math.ceil(effective_batch_target / micro_batch_size))
|
| 117 |
+
train_seq_len = min(MAX_SEQ_LEN, CPU_SEQ_LEN)
|
| 118 |
+
steps_per_epoch = min(STEPS_PER_EPOCH, CPU_STEPS_PER_EPOCH)
|
| 119 |
+
|
| 120 |
+
steps_per_epoch = max(1, steps_per_epoch)
|
| 121 |
+
effective_batch_size = micro_batch_size * grad_accum_steps
|
| 122 |
+
vocab = build_dataset_vocab(DATA_DIR, tok, VOCAB_SAVE_PATH)
|
| 123 |
+
|
| 124 |
+
full_text = ""
|
| 125 |
+
# Read target text files
|
| 126 |
+
if FINE_TUNE:
|
| 127 |
+
candidate = os.path.join(DATA_DIR, FINE_TUNE_FILE)
|
| 128 |
+
target_files = [FINE_TUNE_FILE] if os.path.isfile(candidate) else []
|
| 129 |
+
print(f"Fine-tune mode ON -> using {FINE_TUNE_FILE} only")
|
| 130 |
+
if not target_files:
|
| 131 |
+
raise FileNotFoundError(f"Expected fine-tune file '{FINE_TUNE_FILE}' in {DATA_DIR}")
|
| 132 |
+
else:
|
| 133 |
+
target_files = [f for f in os.listdir(DATA_DIR) if f.endswith(".txt")]
|
| 134 |
+
target_files.sort()
|
| 135 |
+
print(f"Loading {len(target_files)} text file(s) from {DATA_DIR}...")
|
| 136 |
+
for f in target_files:
|
| 137 |
+
fpath = os.path.join(DATA_DIR, f)
|
| 138 |
+
print(f" - Reading {f}...")
|
| 139 |
+
try:
|
| 140 |
+
with open(fpath, "r", encoding="utf-8") as file:
|
| 141 |
+
content = file.read()
|
| 142 |
+
full_text += content + "\n"
|
| 143 |
+
except Exception as e:
|
| 144 |
+
print(f"Error reading {f}: {e}")
|
| 145 |
+
|
| 146 |
+
print(f"Total dataset size: {len(full_text):,} characters")
|
| 147 |
+
ids = tok.encode(full_text) + [EOS_ID]
|
| 148 |
+
if 0 < DATA_PCT < 1.0:
|
| 149 |
+
target_tokens = max(MAX_SEQ_LEN + 1, int(len(ids) * DATA_PCT))
|
| 150 |
+
ids = ids[:target_tokens]
|
| 151 |
+
print(f"Using {DATA_PCT*100:.2f}% of tokens -> {len(ids):,} tokens")
|
| 152 |
+
else:
|
| 153 |
+
print(f"Tokenized dataset -> {len(ids):,} tokens")
|
| 154 |
+
|
| 155 |
+
n = len(ids)
|
| 156 |
+
split_idx = int(n * 0.95) # 95% train, 5% val
|
| 157 |
+
train_ids = ids[:split_idx]
|
| 158 |
+
val_ids = ids[split_idx:]
|
| 159 |
+
|
| 160 |
+
train_ds = RemappedTextDataset(train_ids, train_seq_len)
|
| 161 |
+
val_ds = RemappedTextDataset(val_ids, train_seq_len)
|
| 162 |
+
|
| 163 |
+
# Accelerated DataLoader settings
|
| 164 |
+
kwargs = {'num_workers': 4, 'pin_memory': True} if device == "cuda" else {}
|
| 165 |
+
train_dl = DataLoader(train_ds, batch_size=micro_batch_size, shuffle=True, **kwargs)
|
| 166 |
+
val_dl = DataLoader(val_ds, batch_size=micro_batch_size, shuffle=False, **kwargs)
|
| 167 |
+
|
| 168 |
+
model = ChatGCLM(vocab).to(device)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
# Multi-GPU support
|
| 172 |
+
if torch.cuda.device_count() > 1:
|
| 173 |
+
print(f"Using {torch.cuda.device_count()} GPUs!")
|
| 174 |
+
model = nn.DataParallel(model)
|
| 175 |
+
|
| 176 |
+
num_params = sum(p.numel() for p in model.parameters())
|
| 177 |
+
param_str = format_params(num_params)
|
| 178 |
+
save_path = f"ChatGCLM_{param_str}.pt"
|
| 179 |
+
|
| 180 |
+
print("-" * 30)
|
| 181 |
+
print(f"ChatGCLM TRAINING START")
|
| 182 |
+
print(f"Model ID: {save_path}")
|
| 183 |
+
print(f"Parameters: {num_params:,}")
|
| 184 |
+
print(f"Device: {device}")
|
| 185 |
+
print(f"Vocab Size: {vocab}")
|
| 186 |
+
print(f"Learning Rate: {LEARNING_RATE}")
|
| 187 |
+
print(f"Micro Batch: {micro_batch_size}")
|
| 188 |
+
print(f"Grad Accum: {grad_accum_steps}")
|
| 189 |
+
print(f"Effective Batch: {effective_batch_size}")
|
| 190 |
+
print(f"Train Seq: {train_seq_len}")
|
| 191 |
+
print(f"Epoch Steps: {steps_per_epoch}")
|
| 192 |
+
print(f"Fine-tune: {FINE_TUNE}")
|
| 193 |
+
print(f"Epochs: {EPOCHS}")
|
| 194 |
+
print("-" * 30)
|
| 195 |
+
|
| 196 |
+
if os.path.exists(save_path) and os.path.getsize(save_path) > 0:
|
| 197 |
+
print(f"⏳ Found checkpoint at {save_path}, loading...")
|
| 198 |
+
state_dict = torch.load(save_path, map_location=device)
|
| 199 |
+
# Handle DataParallel/Module prefix mismatch
|
| 200 |
+
if isinstance(model, nn.DataParallel):
|
| 201 |
+
if "module." not in list(state_dict.keys())[0]:
|
| 202 |
+
new_state_dict = {f"module.{k}": v for k, v in state_dict.items()}
|
| 203 |
+
state_dict = new_state_dict
|
| 204 |
+
elif "module." in list(state_dict.keys())[0]:
|
| 205 |
+
# If loading DP checkpoint into non-DP model
|
| 206 |
+
new_state_dict = {k.replace("module.", ""): v for k, v in state_dict.items()}
|
| 207 |
+
state_dict = new_state_dict
|
| 208 |
+
|
| 209 |
+
model.load_state_dict(state_dict)
|
| 210 |
+
print("✓ Model weights loaded successfully! Resuming training.")
|
| 211 |
+
else:
|
| 212 |
+
print("ℹ No checkpoint found. Starting training from scratch.")
|
| 213 |
+
|
| 214 |
+
# Use fused AdamW if available
|
| 215 |
+
opt_kwargs = {"lr": LEARNING_RATE}
|
| 216 |
+
if device == "cuda":
|
| 217 |
+
opt_kwargs["fused"] = True
|
| 218 |
+
opt = torch.optim.AdamW(model.parameters(), **opt_kwargs)
|
| 219 |
+
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=EPOCHS, eta_min=MIN_LR)
|
| 220 |
+
loss_fn = nn.CrossEntropyLoss(ignore_index=PAD_ID)
|
| 221 |
+
if device == "cuda":
|
| 222 |
+
ctx = torch.amp.autocast(device_type="cuda")
|
| 223 |
+
scaler = torch.amp.GradScaler()
|
| 224 |
+
else:
|
| 225 |
+
ctx = contextlib.nullcontext()
|
| 226 |
+
scaler = None
|
| 227 |
+
|
| 228 |
+
for ep in range(EPOCHS):
|
| 229 |
+
model.train()
|
| 230 |
+
opt.zero_grad(set_to_none=True)
|
| 231 |
+
total_steps = min(len(train_dl), steps_per_epoch)
|
| 232 |
+
pbar = tqdm(train_dl, desc=f"Epoch {ep+1}/{EPOCHS}", total=total_steps)
|
| 233 |
+
running_loss = 0.0
|
| 234 |
+
steps_since_update = 0
|
| 235 |
+
for step_idx, (x, y) in enumerate(pbar):
|
| 236 |
+
if step_idx >= total_steps:
|
| 237 |
+
break
|
| 238 |
+
x, y = x.to(device), y.to(device)
|
| 239 |
+
steps_since_update += 1
|
| 240 |
+
is_last_batch = (step_idx + 1) == total_steps
|
| 241 |
+
accum_divisor = grad_accum_steps if not is_last_batch else steps_since_update
|
| 242 |
+
with ctx:
|
| 243 |
+
logits = model(x)
|
| 244 |
+
loss = loss_fn(logits.reshape(-1, logits.size(-1)), y.reshape(-1))
|
| 245 |
+
loss_val = loss.item()
|
| 246 |
+
loss = loss / accum_divisor
|
| 247 |
+
if scaler:
|
| 248 |
+
scaler.scale(loss).backward()
|
| 249 |
+
else:
|
| 250 |
+
loss.backward()
|
| 251 |
+
should_step = steps_since_update == grad_accum_steps or is_last_batch
|
| 252 |
+
if should_step:
|
| 253 |
+
if scaler:
|
| 254 |
+
scaler.step(opt)
|
| 255 |
+
scaler.update()
|
| 256 |
+
else:
|
| 257 |
+
opt.step()
|
| 258 |
+
opt.zero_grad(set_to_none=True)
|
| 259 |
+
if device == "mps" and hasattr(torch, "mps"):
|
| 260 |
+
torch.mps.empty_cache()
|
| 261 |
+
steps_since_update = 0
|
| 262 |
+
running_loss = 0.9 * running_loss + 0.1 * loss_val if running_loss > 0 else loss_val
|
| 263 |
+
pbar.set_postfix(loss=f"{running_loss:.4f}")
|
| 264 |
+
val_loss = estimate_loss(model, val_dl, device, ctx)
|
| 265 |
+
current_lr = scheduler.get_last_lr()[0]
|
| 266 |
+
print(f"Epoch {ep+1} | Train Loss: {running_loss:.4f} | Val Loss: {val_loss:.4f} | LR: {current_lr:.6f}")
|
| 267 |
+
torch.save(model.state_dict(), save_path)
|
| 268 |
+
print(f"✓ Model saved successfully after epoch {ep+1} to {save_path}")
|
| 269 |
+
scheduler.step()
|
| 270 |
+
|
| 271 |
+
if __name__ == "__main__":
|
| 272 |
+
train()
|
vocab_map.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0dfdd3c86cd0d28e178f66c5d80798ebc058e30c5a8432dc9b53dce7cff9b2c8
|
| 3 |
+
size 1337
|