Veirded commited on
Commit
8afcd65
·
verified ·
1 Parent(s): e0114a1

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +284 -1
README.md CHANGED
@@ -1,3 +1,7 @@
 
 
 
 
1
  ---
2
  license: mit
3
  language:
@@ -67,4 +71,283 @@ SLLM-0.6 runs natively on **macOS**, **Linux**, and **Windows**.
67
  ### 1. Requirements
68
 
69
  ```bash
70
- pip install torch safetensors
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Here is a complete README.md for Veirded/SLLM-0.6, updated with your exact
2
+ V0.21_2 specs, training numbers, and working generate.py code (using SLLM
3
+ instead of Nova):
4
+
5
  ---
6
  license: mit
7
  language:
 
71
  ### 1. Requirements
72
 
73
  ```bash
74
+ pip install torch safetensors
75
+
76
+ 2. Multi-Platform Inference Script (generate.py)
77
+
78
+ Save this script as generate.py alongside sllm_nova_post_best.safetensors,
79
+ config_sllm_nova.json, and tokenizer_sllm_t.json:
80
+
81
+ import re
82
+ import json
83
+ import math
84
+ import torch
85
+ import torch.nn as nn
86
+ import torch.nn.functional as F
87
+ from safetensors.torch import load_model
88
+
89
+ # 1. Hardware Accelerator Detection
90
+ if torch.backends.mps.is_available():
91
+ device = torch.device("mps")
92
+ print("Using Apple Silicon Metal (MPS) acceleration.")
93
+ elif torch.cuda.is_available():
94
+ device = torch.device("cuda")
95
+ print(f"Using NVIDIA CUDA acceleration: {torch.cuda.get_device_name(0)}")
96
+ else:
97
+ device = torch.device("cpu")
98
+ print("Using CPU inference.")
99
+
100
+ # 2. Byte-Level BPE Tokenizer
101
+ SPECIAL_TOKENS = ["<pad>", "<end_of_text>", "<|user|>", "<|ai|>"]
102
+ PRETOK_RE = re.compile(
103
+ r"(?i:'(?:s|t|re|ve|m|ll|d))| ?[A-Za-z]+| ?[0-9]+| ?[^\sA-Za-z0-9]+|\s+(?!\S)|\s+"
104
+ )
105
+ SPECIAL_RE = re.compile("(" + "|".join(re.escape(tok) for tok in SPECIAL_TOKENS) + ")")
106
+
107
+ class ByteBPETokenizer:
108
+ def __init__(self, special_tokens, merges):
109
+ self.special_tokens = list(special_tokens)
110
+ self.merges = [tuple(m) for m in merges]
111
+ self.tok2id = {tok: i for i, tok in enumerate(self.special_tokens)}
112
+ self.pad_id = self.tok2id["<pad>"]
113
+ self.end_id = self.tok2id["<end_of_text>"]
114
+ self.user_id = self.tok2id["<|user|>"]
115
+ self.ai_id = self.tok2id["<|ai|>"]
116
+ self.byte_offset = len(self.special_tokens)
117
+ self.id_to_bytes = {i: b"" for i in range(len(self.special_tokens))}
118
+ for b in range(256):
119
+ self.id_to_bytes[self.byte_offset + b] = bytes([b])
120
+ self.merge_ranks = {}
121
+ for rank, (a, b, new_id) in enumerate(self.merges):
122
+ self.id_to_bytes[new_id] = self.id_to_bytes[a] + self.id_to_bytes[b]
123
+ self.merge_ranks[(a, b)] = (rank, new_id)
124
+
125
+ @classmethod
126
+ def load(cls, path):
127
+ with open(path, "r", encoding="utf-8") as f:
128
+ data = json.load(f)
129
+ return cls(data["special_tokens"], data["merges"])
130
+
131
+ def _encode_word(self, word_bytes):
132
+ ids = [self.byte_offset + b for b in word_bytes]
133
+ while len(ids) >= 2:
134
+ best_rank, best_pair, best_new_id = None, None, None
135
+ for i in range(len(ids) - 1):
136
+ info = self.merge_ranks.get((ids[i], ids[i + 1]))
137
+ if info is not None and (best_rank is None or info[0] < best_rank):
138
+ best_rank, best_new_id = info
139
+ best_pair = (ids[i], ids[i + 1])
140
+ if best_pair is None:
141
+ break
142
+ a, b = best_pair
143
+ merged, i, n = [], 0, len(ids)
144
+ while i < n:
145
+ if i + 1 < n and ids[i] == a and ids[i + 1] == b:
146
+ merged.append(best_new_id)
147
+ i += 2
148
+ else:
149
+ merged.append(ids[i])
150
+ i += 1
151
+ ids = merged
152
+ return ids
153
+
154
+ def encode(self, text):
155
+ ids = []
156
+ for part in SPECIAL_RE.split(text):
157
+ if not part:
158
+ continue
159
+ sid = self.tok2id.get(part)
160
+ if sid is not None:
161
+ ids.append(sid)
162
+ else:
163
+ for chunk in PRETOK_RE.findall(part):
164
+ ids.extend(self._encode_word(chunk.encode("utf-8")))
165
+ return ids
166
+
167
+ def decode(self, ids):
168
+ special_set = set(range(len(self.special_tokens)))
169
+ chunks = [self.id_to_bytes[int(i)] for i in ids if int(i) not in special_set and int(i) in self.id_to_bytes]
170
+ return b"".join(chunks).decode("utf-8", errors="replace")
171
+
172
+ # 3. SLLM-0.6 Architecture
173
+ class RMSNorm(nn.Module):
174
+ def __init__(self, dim, eps=1e-6):
175
+ super().__init__()
176
+ self.eps = eps
177
+ self.weight = nn.Parameter(torch.ones(dim))
178
+ def forward(self, x):
179
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight
180
+
181
+ class SwiGLU(nn.Module):
182
+ def __init__(self, dim, hidden_dim):
183
+ super().__init__()
184
+ self.w1 = nn.Linear(dim, hidden_dim, bias=False)
185
+ self.w2 = nn.Linear(hidden_dim, dim, bias=False)
186
+ self.w3 = nn.Linear(dim, hidden_dim, bias=False)
187
+ def forward(self, x):
188
+ return self.w2(F.silu(self.w1(x)) * self.w3(x))
189
+
190
+ def precompute_rope_tables(dim, max_seq_len, theta=10000.0):
191
+ inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2).float() / dim))
192
+ freqs = torch.outer(torch.arange(max_seq_len, dtype=torch.float32), inv_freq)
193
+ emb = torch.cat((freqs, freqs), dim=-1)
194
+ return emb.cos(), emb.sin()
195
+
196
+ def rotate_half(x):
197
+ half = x.shape[-1] // 2
198
+ return torch.cat((-x[..., half:], x[..., :half]), dim=-1)
199
+
200
+ class RoPEAttention(nn.Module):
201
+ def __init__(self, d_model, n_head):
202
+ super().__init__()
203
+ self.n_head = n_head
204
+ self.head_dim = d_model // n_head
205
+ self.wq = nn.Linear(d_model, d_model, bias=False)
206
+ self.wk = nn.Linear(d_model, d_model, bias=False)
207
+ self.wv = nn.Linear(d_model, d_model, bias=False)
208
+ self.wo = nn.Linear(d_model, d_model, bias=False)
209
+ self.q_norm = RMSNorm(self.head_dim)
210
+ self.k_norm = RMSNorm(self.head_dim)
211
+
212
+ def forward(self, x, cos, sin, attn_mask):
213
+ B, T, C = x.shape
214
+ q = self.q_norm(self.wq(x).view(B, T, self.n_head, self.head_dim).transpose(1, 2))
215
+ k = self.k_norm(self.wk(x).view(B, T, self.n_head, self.head_dim).transpose(1, 2))
216
+ v = self.wv(x).view(B, T, self.n_head, self.head_dim).transpose(1, 2)
217
+ q = (q * cos) + (rotate_half(q) * sin)
218
+ k = (k * cos) + (rotate_half(k) * sin)
219
+ att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(self.head_dim))
220
+ att = F.softmax(att.masked_fill(~attn_mask, float("-inf")).float(), dim=-1).type_as(v)
221
+ return self.wo((att @ v).transpose(1, 2).contiguous().view(B, T, C))
222
+
223
+ class SLLMBlock(nn.Module):
224
+ def __init__(self, d_model, n_head, hidden_dim):
225
+ super().__init__()
226
+ self.attn_norm = RMSNorm(d_model)
227
+ self.attn = RoPEAttention(d_model, n_head)
228
+ self.ffn_norm = RMSNorm(d_model)
229
+ self.ffn = SwiGLU(d_model, hidden_dim)
230
+ def forward(self, x, cos, sin, attn_mask):
231
+ x = x + self.attn(self.attn_norm(x), cos, sin, attn_mask)
232
+ return x + self.ffn(self.ffn_norm(x))
233
+
234
+ class SLLM(nn.Module):
235
+ def __init__(self, vocab_size, d_model, n_head, n_layer, hidden_dim, block_size, pad_id=0):
236
+ super().__init__()
237
+ self.block_size = block_size
238
+ self.pad_id = pad_id
239
+ self.tok_emb = nn.Embedding(vocab_size, d_model)
240
+ self.layers = nn.ModuleList([SLLMBlock(d_model, n_head, hidden_dim) for _ in range(n_layer)])
241
+ self.norm = RMSNorm(d_model)
242
+ self.lm_head = nn.Linear(d_model, vocab_size, bias=False)
243
+ self.lm_head.weight = self.tok_emb.weight
244
+ cos, sin = precompute_rope_tables(d_model // n_head, block_size)
245
+ self.register_buffer("cos", cos, persistent=False)
246
+ self.register_buffer("sin", sin, persistent=False)
247
+ self.register_buffer("causal_mask", torch.tril(torch.ones(block_size, block_size, dtype=torch.bool)).view(1, 1, block_size, block_size), persistent=False)
248
+ self.register_buffer("eye_mask", torch.eye(block_size, dtype=torch.bool).view(1, 1, block_size, block_size), persistent=False)
249
+
250
+ def forward(self, idx):
251
+ B, T = idx.shape
252
+ non_pad_k = (idx != self.pad_id).unsqueeze(1).unsqueeze(2)
253
+ pad_q_diag = (idx == self.pad_id).unsqueeze(1).unsqueeze(3) & self.eye_mask[:, :, :T, :T]
254
+ attn_mask = self.causal_mask[:, :, :T, :T] & (non_pad_k | pad_q_diag)
255
+ x = self.tok_emb(idx)
256
+ cos, sin = self.cos[:T].unsqueeze(0).unsqueeze(0), self.sin[:T].unsqueeze(0).unsqueeze(0)
257
+ for layer in self.layers:
258
+ x = layer(x, cos, sin, attn_mask)
259
+ return self.lm_head(self.norm(x))
260
+
261
+ # 4. Load Model & Run Chat
262
+ with open("config_sllm_nova.json", "r") as f:
263
+ cfg = json.load(f)
264
+
265
+ tokenizer = ByteBPETokenizer.load("tokenizer_sllm_t.json")
266
+ model = SLLM(
267
+ vocab_size=cfg["vocab_size"],
268
+ d_model=cfg["d_model"],
269
+ n_head=cfg["n_head"],
270
+ n_layer=cfg["n_layer"],
271
+ hidden_dim=cfg["hidden_dim"],
272
+ block_size=cfg["block_size"],
273
+ pad_id=tokenizer.pad_id,
274
+ ).to(device)
275
+ load_model(model, "sllm_nova_post_best.safetensors")
276
+ model.eval()
277
+
278
+ print("\n" + "=" * 50)
279
+ print("Connected to Veirded/SLLM-0.6 (1.0M Parameters)")
280
+ print("Single-turn mode. Type 'quit' to exit.")
281
+ print("=" * 50)
282
+
283
+ while True:
284
+ uin = input("\nYou: ").strip()
285
+ if not uin or uin.lower() in ("quit", "exit"):
286
+ break
287
+ ids = tokenizer.encode(f"<|user|> {uin}\n<|ai|>")[-cfg["block_size"]:]
288
+ idx = torch.tensor([ids], dtype=torch.long, device=device)
289
+ gen = []
290
+ with torch.no_grad():
291
+ for _ in range(64):
292
+ logits = model(idx[:, -cfg["block_size"]:])[0, -1].float()
293
+ logits[tokenizer.pad_id] = -float("inf")
294
+ for t in set(idx[0, -64:].tolist()):
295
+ logits[t] = logits[t] * 1.15 if logits[t] < 0 else logits[t] / 1.15
296
+ logits = logits / 0.5
297
+ v, _ = torch.topk(logits, 15)
298
+ logits[logits < v[-1]] = -float("inf")
299
+ nid = int(torch.multinomial(F.softmax(logits, dim=-1), 1).item())
300
+ if nid in (tokenizer.end_id, tokenizer.user_id):
301
+ break
302
+ gen.append(nid)
303
+ idx = torch.cat((idx, torch.tensor([[nid]], dtype=torch.long, device=device)), dim=1)
304
+ print(f"SLLM: {tokenizer.decode(gen).strip()}")
305
+
306
+ Training Details
307
+
308
+ Training Data
309
+
310
+ - Dataset: 238,716 curated, deduplicated, single-turn casual chat pairs (~10M+
311
+ tokens, ~10:1 tokens-to-parameter ratio).
312
+ - Token Coverage: Lossless Byte-Level BPE (1,152 tokens, zero <unk>).
313
+
314
+ Two-Stage Training Hyperparameters
315
+
316
+ - Stage 1 (Pre-Training): 12 epochs, 50,000 random examples/epoch,
317
+ BATCH_SIZE=16, AdamW (lr=1.5e-3 -> 1e-4, weight_decay=0.05, dropout=0.15),
318
+ bfloat16 autocast on MPS. Best Val Loss: 2.1335.
319
+ - Stage 2 (AI-Masked SFT): 4 epochs, 50,000 random examples/epoch,
320
+ BATCH_SIZE=32, AdamW (lr=2.0e-4 -> 1e-5, loss on AI tokens only). Best Val
321
+ Loss: 2.2938.
322
+
323
+ Technical Specifications
324
+
325
+ | Parameter | Value |
326
+ | :------------------------------------ | :-------------------------------- |
327
+ | **Model ID** | **Veirded/SLLM-0.6** |
328
+ | **Model Size** | **1,000,832 Parameters (\~1.0M)** |
329
+ | **Embedding Dimension ($d_{model}$)** | 128 |
330
+ | **Attention Heads** | 4 (Head Dimension = 32 + QK-Norm) |
331
+ | **Layers** | 4 |
332
+ | **SwiGLU Hidden Dimension** | 384 |
333
+ | **Vocabulary Size** | 1,152 (Byte-Level BPE) |
334
+ | **Context Window** | 128 tokens |
335
+
336
+ Hardware Trained On
337
+
338
+ - Machine: Apple MacBook Air (MPS)
339
+ - Precision: bfloat16 mixed precision autocast
340
+
341
+ Citation & Authors
342
+
343
+ Created by: Veirded
344
+ Repository: Veirded/SLLM-0.6
345
+
346
+ @misc{veirded2026sllm06,
347
+ author = {Veirded},
348
+ title = {SLLM-0.6: A 1M-Parameter Single-Turn Casual Chat Language Model},
349
+ year = {2026},
350
+ publisher = {Hugging Face},
351
+ howpublished = {\url{https://huggingface.co/Veirded/SLLM-0.6}}
352
+ }
353
+