AGofficial commited on
Commit
53264fa
·
verified ·
1 Parent(s): 37b52d9

Upload 8 files

Browse files
Files changed (8) hide show
  1. README.md +35 -0
  2. Turing_22.1M.pt +3 -0
  3. chat.py +179 -0
  4. model.py +94 -0
  5. sample.py +141 -0
  6. train.py +264 -0
  7. turing.jpg +0 -0
  8. vocab_map.pt +3 -0
README.md ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ![Turing](turing.jpg)
2
+
3
+ # Turing
4
+
5
+ Turing is a character-level AI language model based on the GCLM (Global Context Language Model) architecture. It is designed to learn from text using a hybrid approach of Local 1D Convolutions for short-range dependencies and FFT-based Global 1D Convolutions for long-range context.
6
+
7
+ ## Architecture
8
+
9
+ The model (`GCLM`) processes sequences using a stack of blocks that alternate between:
10
+ - **LocalConv1D**: Captures immediate local context.
11
+ - **GlobalConv1D**: Uses FFT to capture global context across the entire sequence length.
12
+
13
+ ## Usage
14
+
15
+ ### Training
16
+
17
+ To train the model on your own text data:
18
+ 1. Place `.txt` files in the `data/` directory.
19
+ 2. Run the training script:
20
+ ```bash
21
+ python train.py
22
+ ```
23
+ This will automatically detect available hardware (CUDA, MPS, or CPU) and start training, saving checkpoints to `Turing_<params>.pt`.
24
+
25
+ ### Inference
26
+
27
+ To generate text, run:
28
+ ```bash
29
+ python sample.py
30
+ ```
31
+
32
+ ## Requirements
33
+ - Python 3
34
+ - PyTorch
35
+ - tqdm
Turing_22.1M.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eff3a6284a95416cd47a74b3d0aacca6fdf62130917fab782c43061441cd495e
3
+ size 88579632
chat.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import torch.nn.functional as F
4
+ from collections import OrderedDict
5
+ import string
6
+ import sys
7
+ from model import ChatGCLM, MAX_SEQ_LEN
8
+
9
+ # --- Configuration ---
10
+ EOS_ID = 2
11
+ OFFSET = 3
12
+ CHARS = string.printable
13
+
14
+ def get_model_path():
15
+ """Finds the first model file starting with Turing_ in the current directory."""
16
+ for f in os.listdir("."):
17
+ if f.startswith("Turing_") and f.endswith(".pt"):
18
+ return f
19
+ return None
20
+
21
+ MODEL_PATH = get_model_path()
22
+
23
+ if MODEL_PATH is None:
24
+ print("Error: No model checkpoint found!")
25
+ print("Please train the model first with: python3 train.py")
26
+ sys.exit(1)
27
+
28
+ # --- Helper Functions ---
29
+
30
+ def encode(text):
31
+ return [CHARS.index(c) + OFFSET for c in text if c in CHARS]
32
+
33
+ def decode(ids):
34
+ return "".join([CHARS[i - OFFSET] for i in ids if i >= OFFSET])
35
+
36
+ def load_model(device):
37
+ vocab_size = len(CHARS) + OFFSET
38
+
39
+ model = ChatGCLM(vocab_size).to(device)
40
+ if os.path.exists(MODEL_PATH) and os.path.getsize(MODEL_PATH) > 0:
41
+ print(f"Loading model from: {MODEL_PATH}")
42
+ ckpt = torch.load(MODEL_PATH, map_location=device)
43
+
44
+ if isinstance(ckpt, dict):
45
+ if 'model_state_dict' in ckpt:
46
+ state_dict = ckpt['model_state_dict']
47
+ elif 'state_dict' in ckpt:
48
+ state_dict = ckpt['state_dict']
49
+ else:
50
+ state_dict = ckpt
51
+ else:
52
+ state_dict = ckpt
53
+
54
+ # Handle compilation prefix if present
55
+ def _strip_module_prefix(sd):
56
+ keys = list(sd.keys())
57
+ if any(k.startswith('module.') for k in keys):
58
+ new_sd = OrderedDict()
59
+ for k, v in sd.items():
60
+ new_key = k[len('module.'): ] if k.startswith('module.') else k
61
+ new_sd[new_key] = v
62
+ return new_sd
63
+ return sd
64
+
65
+ state_dict = _strip_module_prefix(state_dict)
66
+
67
+ res = model.load_state_dict(state_dict, strict=False)
68
+ missing = getattr(res, 'missing_keys', None)
69
+ unexpected = getattr(res, 'unexpected_keys', None)
70
+ if missing:
71
+ print(f"Warning: missing keys when loading state_dict: {missing}")
72
+ if unexpected:
73
+ print(f"Warning: unexpected keys in state_dict: {unexpected}")
74
+
75
+ model.eval()
76
+ return model
77
+ else:
78
+ print(f"Error: Could not load model from {MODEL_PATH}")
79
+ return None
80
+
81
+ @torch.no_grad()
82
+ def generate_stream(model, prompt, device, max_new_tokens=500, temperature=0.7, top_k=50):
83
+ """
84
+ Generates text from the model and streams it to stdout.
85
+ Returns the full generated text.
86
+ """
87
+ model.eval()
88
+ input_ids = encode(prompt)
89
+ x = torch.tensor([input_ids], dtype=torch.long, device=device)
90
+
91
+ # We don't print the prompt again, we just stream the new tokens
92
+ generated_ids = []
93
+
94
+ for _ in range(max_new_tokens):
95
+ # Crop context if needed
96
+ ctx = x[:, -MAX_SEQ_LEN:] if x.size(1) > MAX_SEQ_LEN else x
97
+
98
+ logits = model(ctx)
99
+ next_token_logits = logits[:, -1, :] / temperature
100
+
101
+ if top_k is not None:
102
+ v, _ = torch.topk(next_token_logits, min(top_k, next_token_logits.size(-1)))
103
+ next_token_logits[next_token_logits < v[:, [-1]]] = -float('Inf')
104
+
105
+ probs = F.softmax(next_token_logits, dim=-1)
106
+ next_token = torch.multinomial(probs, num_samples=1)
107
+ idx = next_token.item()
108
+
109
+ if idx == EOS_ID:
110
+ break
111
+
112
+ x = torch.cat((x, next_token), dim=1)
113
+ generated_ids.append(idx)
114
+
115
+ token_text = decode([idx])
116
+ print(token_text, end="", flush=True)
117
+
118
+ if len(generated_ids) >= 3 and decode(generated_ids[-3:]) == "<u>":
119
+ print('\b\b\b \b\b\b', end="", flush=True)
120
+ break
121
+
122
+ return decode(generated_ids)
123
+
124
+ def main():
125
+ device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
126
+ print(f"Using device: {device}")
127
+
128
+ model = load_model(device)
129
+
130
+ if model is None:
131
+ sys.exit(1)
132
+
133
+ print("\n" + "="*50)
134
+ print("Turing | Chat Interface")
135
+ print(f"Model: {MODEL_PATH}")
136
+ print("Type 'quit', 'exit', or 'q' to end the session.")
137
+ print("="*50 + "\n")
138
+
139
+ history = ""
140
+ while True:
141
+ try:
142
+ # Get user input
143
+ user_input = input("\n\033[1;36mYou:\033[0m ") # Cyan color for "You:"
144
+
145
+ if user_input.strip().lower() in ['quit', 'exit', 'q']:
146
+ print("\nGoodbye!")
147
+ break
148
+
149
+ if not user_input.strip():
150
+ continue
151
+
152
+ print("\033[1;32mModel:\033[0m ", end="", flush=True) # Green color for "Model:"
153
+
154
+ # Since this is a raw completion model, we might want to feed it the input directly
155
+ # and let it continue.
156
+ # Prepare the prompt with history
157
+ current_turn = f"<u> {user_input} <a>"
158
+ full_prompt = history + current_turn
159
+
160
+ # Generate response
161
+ response = generate_stream(model, full_prompt, device=device)
162
+
163
+ # Update history
164
+ # We strip <u> from the end if it was generated as a stop token
165
+ cleaned_response = response
166
+ if cleaned_response.endswith("<u>"):
167
+ cleaned_response = cleaned_response[:-3]
168
+
169
+ history += current_turn + cleaned_response
170
+ print() # Newline after generation
171
+
172
+ except KeyboardInterrupt:
173
+ print("\n\nExiting...")
174
+ break
175
+ except Exception as e:
176
+ print(f"\nError: {e}")
177
+
178
+ if __name__ == "__main__":
179
+ main()
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 = 512
6
+ N_LAYERS = 8
7
+ MAX_SEQ_LEN = 4096
8
+ LOCAL_KERNEL_SIZE = 3
9
+ GLOBAL_KERNEL_SIZE = 512
10
+ USE_GLOBAL_EVERY_N_LAYERS = 2
11
+ FFT_SIZE = MAX_SEQ_LEN
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))
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 string
6
+ from model import ChatGCLM, MAX_SEQ_LEN
7
+
8
+ MODEL_PATH = None
9
+ for f in os.listdir("."):
10
+ if f.startswith("Turing_") 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.py")
17
+ exit(1)
18
+
19
+ EOS_ID = 2
20
+ OFFSET = 3
21
+ CHARS = string.printable
22
+
23
+ def encode(text):
24
+ return [CHARS.index(c) + OFFSET for c in text if c in CHARS]
25
+
26
+ def decode(ids):
27
+ return "".join([CHARS[i - OFFSET] for i in ids if i >= OFFSET])
28
+
29
+ def load_model(device):
30
+ vocab_size = len(CHARS) + OFFSET
31
+
32
+ model = ChatGCLM(vocab_size).to(device)
33
+ if os.path.exists(MODEL_PATH) and os.path.getsize(MODEL_PATH) > 0:
34
+ print(f"Loading model from: {MODEL_PATH}")
35
+ ckpt = torch.load(MODEL_PATH, map_location=device)
36
+
37
+ if isinstance(ckpt, dict):
38
+ if 'model_state_dict' in ckpt:
39
+ state_dict = ckpt['model_state_dict']
40
+ elif 'state_dict' in ckpt:
41
+ state_dict = ckpt['state_dict']
42
+ else:
43
+ state_dict = ckpt
44
+ else:
45
+ state_dict = ckpt
46
+
47
+ def _strip_module_prefix(sd):
48
+ keys = list(sd.keys())
49
+ if any(k.startswith('module.') for k in keys):
50
+ new_sd = OrderedDict()
51
+ for k, v in sd.items():
52
+ new_key = k[len('module.'): ] if k.startswith('module.') else k
53
+ new_sd[new_key] = v
54
+ return new_sd
55
+ return sd
56
+
57
+ state_dict = _strip_module_prefix(state_dict)
58
+
59
+ res = model.load_state_dict(state_dict, strict=False)
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
69
+ else:
70
+ print(f"Error: Could not load model from {MODEL_PATH}")
71
+ return None
72
+
73
+ @torch.no_grad()
74
+ def generate(model, prompt, device, max_new_tokens=200, temperature=0.8, top_k=50):
75
+ model.eval()
76
+ input_ids = 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 = decode([idx])
105
+ print(token_text, end="", flush=True)
106
+
107
+ print(f"\n{'='*70}\n")
108
+ return 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 = 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, 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, device, max_new_tokens=200, temperature=0.8, top_k=50)
train.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 string
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
+ FINETUNE = True
21
+ DATA_DIR = "finetune" if FINETUNE else "data"
22
+ DATA_PCT = 0.002
23
+ MPS_SEQ_LEN = 512
24
+ MPS_STEPS_PER_EPOCH = 18
25
+ CPU_SEQ_LEN = 512
26
+ CPU_STEPS_PER_EPOCH = 48
27
+ VOCAB_SAVE_PATH = "vocab_map.pt"
28
+
29
+ EPOCHS = 100
30
+ MICRO_BATCH_SIZE = 8
31
+ GRAD_ACCUM_STEPS = 4
32
+ STEPS_PER_EPOCH = 500
33
+ LEARNING_RATE = 5e-4
34
+ MIN_LR = 1e-5
35
+
36
+ SAVE_N_EPOCHS = 1
37
+
38
+ PAD_ID = 0
39
+ SEP_ID = 1
40
+ EOS_ID = 2
41
+ OFFSET = 3
42
+ CHARS = string.printable
43
+ VOCAB_SIZE = len(CHARS) + OFFSET
44
+
45
+ def encode(text):
46
+ return [CHARS.index(c) + OFFSET for c in text if c in CHARS]
47
+
48
+ def decode(ids):
49
+ return "".join([CHARS[i - OFFSET] for i in ids if i >= OFFSET])
50
+
51
+ def build_dataset_vocab(save_path):
52
+ torch.save({
53
+ "vocab_size": VOCAB_SIZE,
54
+ "PAD_ID": PAD_ID,
55
+ "SEP_ID": SEP_ID,
56
+ "EOS_ID": EOS_ID,
57
+ "CHARS": CHARS
58
+ }, save_path)
59
+ return VOCAB_SIZE
60
+
61
+ class RemappedTextDataset(Dataset):
62
+ def __init__(self, ids, max_len):
63
+ self.ids = ids
64
+ self.max_len = max_len
65
+
66
+ def __len__(self):
67
+ return max(0, (len(self.ids) - 1) // self.max_len)
68
+
69
+ def __getitem__(self, i):
70
+ start = i * self.max_len
71
+ x = self.ids[start : start + self.max_len]
72
+ y = self.ids[start + 1 : start + self.max_len + 1]
73
+
74
+ if len(x) < self.max_len:
75
+ x = x + [PAD_ID] * (self.max_len - len(x))
76
+ if len(y) < self.max_len:
77
+ y = y + [PAD_ID] * (self.max_len - len(y))
78
+
79
+ return torch.tensor(x, dtype=torch.long), torch.tensor(y, dtype=torch.long)
80
+
81
+ def format_params(num):
82
+ if num >= 1_000_000_000:
83
+ return f"{num/1_000_000_000:.1f}B"
84
+ elif num >= 1_000_000:
85
+ return f"{num/1_000_000:.1f}M"
86
+ else:
87
+ return f"{num/1_000:.1f}K"
88
+
89
+ @torch.no_grad()
90
+ def estimate_loss(model, dl, device, ctx):
91
+ model.eval()
92
+ losses = []
93
+ limit = 50
94
+ for i, (x, y) in enumerate(dl):
95
+ if i >= limit: break
96
+ x, y = x.to(device), y.to(device)
97
+ with ctx:
98
+ logits = model(x)
99
+ loss = F.cross_entropy(logits.reshape(-1, logits.size(-1)), y.reshape(-1), ignore_index=PAD_ID)
100
+ losses.append(loss.item())
101
+ model.train()
102
+ return sum(losses) / len(losses) if losses else 0.0
103
+
104
+ def train():
105
+ device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
106
+
107
+ effective_batch_target = MICRO_BATCH_SIZE * GRAD_ACCUM_STEPS
108
+ micro_batch_size = MICRO_BATCH_SIZE
109
+ grad_accum_steps = GRAD_ACCUM_STEPS
110
+ train_seq_len = MAX_SEQ_LEN
111
+ steps_per_epoch = STEPS_PER_EPOCH
112
+
113
+ if device == "mps":
114
+ if hasattr(torch, "mps"):
115
+ torch.mps.empty_cache()
116
+ micro_batch_size = 1
117
+ grad_accum_steps = max(1, math.ceil(effective_batch_target / micro_batch_size))
118
+ train_seq_len = min(MAX_SEQ_LEN, MPS_SEQ_LEN)
119
+ steps_per_epoch = min(STEPS_PER_EPOCH, MPS_STEPS_PER_EPOCH)
120
+ elif device == "cpu":
121
+ micro_batch_size = min(4, MICRO_BATCH_SIZE)
122
+ grad_accum_steps = max(1, math.ceil(effective_batch_target / micro_batch_size))
123
+ train_seq_len = min(MAX_SEQ_LEN, CPU_SEQ_LEN)
124
+ steps_per_epoch = min(STEPS_PER_EPOCH, CPU_STEPS_PER_EPOCH)
125
+
126
+ steps_per_epoch = max(1, steps_per_epoch)
127
+ effective_batch_size = micro_batch_size * grad_accum_steps
128
+ vocab = build_dataset_vocab(VOCAB_SAVE_PATH)
129
+
130
+ full_text = ""
131
+ target_files = [f for f in os.listdir(DATA_DIR) if f.endswith(".txt")]
132
+ target_files.sort()
133
+ print(f"Loading {len(target_files)} text file(s) from {DATA_DIR}...")
134
+ for f in target_files:
135
+ fpath = os.path.join(DATA_DIR, f)
136
+ print(f" - Reading {f}...")
137
+ try:
138
+ with open(fpath, "r", encoding="utf-8") as file:
139
+ content = file.read()
140
+ full_text += content + "\n"
141
+ except Exception as e:
142
+ print(f"Error reading {f}: {e}")
143
+
144
+ print(f"Total dataset size: {len(full_text):,} characters")
145
+ ids = encode(full_text) + [EOS_ID]
146
+ if 0 < DATA_PCT < 1.0:
147
+ target_tokens = max(MAX_SEQ_LEN + 1, int(len(ids) * DATA_PCT))
148
+ ids = ids[:target_tokens]
149
+ print(f"Using {DATA_PCT*100:.2f}% of tokens -> {len(ids):,} tokens")
150
+ else:
151
+ print(f"Tokenized dataset -> {len(ids):,} tokens")
152
+
153
+ n = len(ids)
154
+ split_idx = int(n * 0.95)
155
+ train_ids = ids[:split_idx]
156
+ val_ids = ids[split_idx:]
157
+
158
+ train_ds = RemappedTextDataset(train_ids, train_seq_len)
159
+ val_ds = RemappedTextDataset(val_ids, train_seq_len)
160
+
161
+ kwargs = {'num_workers': 4, 'pin_memory': True} if device == "cuda" else {}
162
+ train_dl = DataLoader(train_ds, batch_size=micro_batch_size, shuffle=True, **kwargs)
163
+ val_dl = DataLoader(val_ds, batch_size=micro_batch_size, shuffle=False, **kwargs)
164
+
165
+ model = ChatGCLM(vocab).to(device)
166
+
167
+
168
+ if torch.cuda.device_count() > 1:
169
+ print(f"Using {torch.cuda.device_count()} GPUs!")
170
+ model = nn.DataParallel(model)
171
+
172
+ num_params = sum(p.numel() for p in model.parameters())
173
+ param_str = format_params(num_params)
174
+ save_path = f"Turing_{param_str}.pt"
175
+
176
+ print("-" * 30)
177
+ print(f"Turing TRAINING START")
178
+ print(f"Model ID: {save_path}")
179
+ print(f"Parameters: {num_params:,}")
180
+ print(f"Device: {device}")
181
+ print(f"Vocab Size: {vocab}")
182
+ print(f"Learning Rate: {LEARNING_RATE}")
183
+ print(f"Micro Batch: {micro_batch_size}")
184
+ print(f"Grad Accum: {grad_accum_steps}")
185
+ print(f"Effective Batch: {effective_batch_size}")
186
+ print(f"Train Seq: {train_seq_len}")
187
+ print(f"Epoch Steps: {steps_per_epoch}")
188
+ print(f"Epochs: {EPOCHS}")
189
+ print("-" * 30)
190
+
191
+ if os.path.exists(save_path) and os.path.getsize(save_path) > 0:
192
+ print(f" Found checkpoint at {save_path}, loading...")
193
+ state_dict = torch.load(save_path, map_location=device)
194
+ if isinstance(model, nn.DataParallel):
195
+ if "module." not in list(state_dict.keys())[0]:
196
+ new_state_dict = {f"module.{k}": v for k, v in state_dict.items()}
197
+ state_dict = new_state_dict
198
+ elif "module." in list(state_dict.keys())[0]:
199
+ new_state_dict = {k.replace("module.", ""): v for k, v in state_dict.items()}
200
+ state_dict = new_state_dict
201
+
202
+ model.load_state_dict(state_dict)
203
+ print(" Model weights loaded successfully! Resuming training.")
204
+ else:
205
+ print(" No checkpoint found. Starting training from scratch.")
206
+
207
+ opt_kwargs = {"lr": LEARNING_RATE}
208
+ if device == "cuda":
209
+ opt_kwargs["fused"] = True
210
+ opt = torch.optim.AdamW(model.parameters(), **opt_kwargs)
211
+ scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=EPOCHS, eta_min=MIN_LR)
212
+ loss_fn = nn.CrossEntropyLoss(ignore_index=PAD_ID)
213
+ if device == "cuda":
214
+ ctx = torch.amp.autocast(device_type="cuda")
215
+ scaler = torch.amp.GradScaler()
216
+ else:
217
+ ctx = contextlib.nullcontext()
218
+ scaler = None
219
+
220
+ for ep in range(EPOCHS):
221
+ model.train()
222
+ opt.zero_grad(set_to_none=True)
223
+ total_steps = min(len(train_dl), steps_per_epoch)
224
+ pbar = tqdm(train_dl, desc=f"Epoch {ep+1}/{EPOCHS}", total=total_steps)
225
+ running_loss = 0.0
226
+ steps_since_update = 0
227
+ for step_idx, (x, y) in enumerate(pbar):
228
+ if step_idx >= total_steps:
229
+ break
230
+ x, y = x.to(device), y.to(device)
231
+ steps_since_update += 1
232
+ is_last_batch = (step_idx + 1) == total_steps
233
+ accum_divisor = grad_accum_steps if not is_last_batch else steps_since_update
234
+ with ctx:
235
+ logits = model(x)
236
+ loss = loss_fn(logits.reshape(-1, logits.size(-1)), y.reshape(-1))
237
+ loss_val = loss.item()
238
+ loss = loss / accum_divisor
239
+ if scaler:
240
+ scaler.scale(loss).backward()
241
+ else:
242
+ loss.backward()
243
+ should_step = steps_since_update == grad_accum_steps or is_last_batch
244
+ if should_step:
245
+ if scaler:
246
+ scaler.step(opt)
247
+ scaler.update()
248
+ else:
249
+ opt.step()
250
+ opt.zero_grad(set_to_none=True)
251
+ if device == "mps" and hasattr(torch, "mps"):
252
+ torch.mps.empty_cache()
253
+ steps_since_update = 0
254
+ running_loss = 0.9 * running_loss + 0.1 * loss_val if running_loss > 0 else loss_val
255
+ pbar.set_postfix(loss=f"{running_loss:.4f}")
256
+ val_loss = estimate_loss(model, val_dl, device, ctx)
257
+ current_lr = scheduler.get_last_lr()[0]
258
+ print(f"Epoch {ep+1} | Train Loss: {running_loss:.4f} | Val Loss: {val_loss:.4f} | LR: {current_lr:.6f}")
259
+ torch.save(model.state_dict(), save_path)
260
+ print(f" Model saved successfully after epoch {ep+1} to {save_path}")
261
+ scheduler.step()
262
+
263
+ if __name__ == "__main__":
264
+ train()
turing.jpg ADDED
vocab_map.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1a7450cd0f8c56fe319658bac35ad0a94e919cac68ccb074e2d6f0d0b21c5066
3
+ size 1465