VoidOSS commited on
Commit
23253ec
·
verified ·
1 Parent(s): bd3225e

Upload modeling_gstack.py for GStack v4.1 PythonCode comeback release

Browse files
Files changed (1) hide show
  1. modeling_gstack.py +390 -0
modeling_gstack.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Standalone PyTorch + Hugging Face implementation of GStack v4.1
3
+ (VoidOSS Second Comeback Model — 9.41M params, 67% O(n) Linear, 1/3 KV Cache)
4
+
5
+ Architecture:
6
+ - Shift-Invariant Token Embedding + Multi-Scale Causal Char-Glue (k=3 + k=7)
7
+ - Layers [0, 1, 3, 4] (67% O(n) Linear):
8
+ * Neural Context: 5 power-of-2 linear memory horizons (128, 256, 512, 1024, 2048)
9
+ * Associative Neural Attention: 4 self-cleaning working-memory concept slots with soft eviction
10
+ * Per-Layer Gweight (Galaxyweights): Dedicated SwiGLU Core + 4 Neural-Attention-dialed Orbits
11
+ - Layers [2, 5] (33% Sniper Recall):
12
+ * Compressed UltraFlashAttention (QK-RMSNorm + RoPE) + Per-Layer Gweight
13
+
14
+ Usage:
15
+ from modeling_gstack import GStackModel
16
+ model = GStackModel.from_pretrained("VoidOSS/GStack-v4.1-PythonCode")
17
+ print(model.generate("def parse_config(filepath, default_timeout=30):\n "))
18
+ """
19
+
20
+ import json
21
+ import math
22
+ from pathlib import Path
23
+
24
+ import torch
25
+ import torch.nn as nn
26
+ import torch.nn.functional as F
27
+ from safetensors.torch import load_file
28
+
29
+
30
+ class RMSNorm(nn.Module):
31
+ def __init__(self, dim: int, eps: float = 1e-6):
32
+ super().__init__()
33
+ self.eps = eps
34
+ self.weight = nn.Parameter(torch.ones(dim))
35
+
36
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
37
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight
38
+
39
+
40
+ def precompute_rope(max_len: int, head_dim: int, device: torch.device):
41
+ inv_freq = 1.0 / (10000.0 ** (torch.arange(0, head_dim, 2, device=device, dtype=torch.float32) / head_dim))
42
+ t = torch.arange(max_len, device=device, dtype=torch.float32)
43
+ freqs = torch.outer(t, inv_freq)
44
+ cos = freqs.cos()[None, None, :, :]
45
+ sin = freqs.sin()[None, None, :, :]
46
+ return cos, sin
47
+
48
+
49
+ def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
50
+ T = x.shape[2]
51
+ c = cos[:, :, :T, :].to(x.dtype)
52
+ s = sin[:, :, :T, :].to(x.dtype)
53
+ x1, x2 = x[..., 0::2], x[..., 1::2]
54
+ out1 = x1 * c - x2 * s
55
+ out2 = x1 * s + x2 * c
56
+ return torch.stack([out1, out2], dim=-1).flatten(-2)
57
+
58
+
59
+ class UltraFlashAttentionF(nn.Module):
60
+ def __init__(self, d_model: int, n_heads: int = 6, compress: int = 2):
61
+ super().__init__()
62
+ self.n_heads = n_heads
63
+ self.attn_dim = (d_model // compress // n_heads) * n_heads
64
+ self.head_dim = self.attn_dim // n_heads
65
+ self.qkv_proj = nn.Linear(d_model, 3 * self.attn_dim, bias=False)
66
+ self.q_norm = RMSNorm(self.head_dim)
67
+ self.k_norm = RMSNorm(self.head_dim)
68
+ self.out_proj = nn.Linear(self.attn_dim, d_model, bias=False)
69
+ self.local_conv = nn.Conv1d(d_model, d_model, kernel_size=3, padding=0, groups=d_model, bias=False)
70
+ self.local_gate = nn.Parameter(torch.tensor(0.25))
71
+
72
+ def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
73
+ B, M, D = x.shape
74
+ q, k, v = self.qkv_proj(x).chunk(3, dim=-1)
75
+ q = self.q_norm(q.view(B, M, self.n_heads, self.head_dim)).transpose(1, 2)
76
+ k = self.k_norm(k.view(B, M, self.n_heads, self.head_dim)).transpose(1, 2)
77
+ q = apply_rope(q, cos, sin)
78
+ k = apply_rope(k, cos, sin)
79
+ v = v.view(B, M, self.n_heads, self.head_dim).transpose(1, 2)
80
+ out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
81
+ out = self.out_proj(out.transpose(1, 2).contiguous().view(B, M, self.attn_dim))
82
+ x_local = self.local_conv(F.pad(x.transpose(1, 2), (2, 0))).transpose(1, 2)
83
+ return out + self.local_gate * x_local
84
+
85
+
86
+ class FastNeuralContext(nn.Module):
87
+ """5 power-of-2 linear memory horizons (128, 256, 512, 1024, 2048)."""
88
+ def __init__(self, d_model: int, stride: int = 1, raw_horizons=(128, 256, 512, 1024, 2048), chunk_size: int = 64):
89
+ super().__init__()
90
+ self.n_horizons = len(raw_horizons)
91
+ self.chunk_size = chunk_size
92
+ self.d_h = max(32, (d_model // self.n_horizons // 16) * 16)
93
+ self.total_h = self.n_horizons * self.d_h
94
+
95
+ self.in_proj = nn.Linear(d_model, self.total_h, bias=False)
96
+ self.read_gate = nn.Linear(d_model, self.n_horizons, bias=True)
97
+ self.norm_out = RMSNorm(self.d_h)
98
+ self.out_proj = nn.Linear(self.d_h, d_model, bias=False)
99
+
100
+ base_logits = []
101
+ for rh in raw_horizons:
102
+ void_h = max(2.0, rh / float(stride))
103
+ alpha = math.exp(-math.log(2.0) / void_h)
104
+ base_logits.append(math.log(alpha / (1.0 - alpha)))
105
+ self.register_buffer("base_decay_logits", torch.tensor(base_logits, dtype=torch.float32))
106
+ self.decay_delta = nn.Parameter(torch.zeros(self.n_horizons))
107
+
108
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
109
+ B, M, D = x.shape
110
+ H = self.n_horizons
111
+ u = self.in_proj(x).view(B, M, H, self.d_h)
112
+
113
+ C = min(self.chunk_size, M)
114
+ pad = (C - (M % C)) % C
115
+ if pad > 0:
116
+ u = F.pad(u, (0, 0, 0, 0, 0, pad))
117
+ Mp = u.shape[1]
118
+ Nc = Mp // C
119
+
120
+ alpha = torch.sigmoid(self.base_decay_logits + 0.5 * torch.tanh(self.decay_delta))
121
+ idx = torch.arange(C, device=x.device, dtype=torch.float32)
122
+ diff = idx.unsqueeze(1) - idx.unsqueeze(0)
123
+ mask = (diff >= 0).float()
124
+ a_h = alpha.view(H, 1, 1)
125
+ L = ((1.0 - a_h) * torch.pow(a_h, diff.clamp(min=0.0).unsqueeze(0)) * mask.unsqueeze(0)).to(u.dtype)
126
+
127
+ u_c = u.view(B, Nc, C, H, self.d_h)
128
+ intra = torch.einsum("hij,bnjhd->bnihd", L, u_c)
129
+
130
+ if Nc > 1:
131
+ a_chunk = torch.pow(alpha, float(C))
132
+ c_idx = torch.arange(Nc, device=x.device, dtype=torch.float32)
133
+ c_diff = c_idx.unsqueeze(1) - c_idx.unsqueeze(0) - 1.0
134
+ c_mask = (c_diff >= 0).float()
135
+ M_c = (torch.pow(a_chunk.view(H, 1, 1), c_diff.clamp(min=0.0).unsqueeze(0)) * c_mask.unsqueeze(0)).to(u.dtype)
136
+ prev = torch.einsum("hcj,bjhd->bchd", M_c, intra[:, :, -1])
137
+ pow_in = torch.pow(alpha.view(1, 1, 1, H, 1), (idx + 1.0).view(1, 1, C, 1, 1)).to(u.dtype)
138
+ mem = intra + pow_in * prev.unsqueeze(2)
139
+ else:
140
+ mem = intra
141
+
142
+ mem = mem.reshape(B, Mp, H, self.d_h)[:, :M]
143
+ w = F.softmax(self.read_gate(x), dim=-1).unsqueeze(-1)
144
+ mixed = self.norm_out((mem * w).sum(dim=2))
145
+ return self.out_proj(mixed)
146
+
147
+
148
+ class FastAssociativeNeuralAttention(nn.Module):
149
+ """4 self-cleaning active working-memory concept slots with soft eviction."""
150
+ def __init__(self, d_model: int, n_slots: int = 4, d_k: int = 24, d_v: int = 48, chunk_size: int = 64):
151
+ super().__init__()
152
+ self.n_slots = n_slots
153
+ self.d_k = d_k
154
+ self.d_v = d_v
155
+ self.chunk_size = chunk_size
156
+
157
+ self.q_proj = nn.Linear(d_model, n_slots * d_k, bias=False)
158
+ self.k_proj = nn.Linear(d_model, n_slots * d_k, bias=False)
159
+ self.v_proj = nn.Linear(d_model, n_slots * d_v, bias=False)
160
+ self.q_norm = RMSNorm(d_k)
161
+ self.k_norm = RMSNorm(d_k)
162
+
163
+ self.pull_route = nn.Linear(d_model, n_slots, bias=True)
164
+ self.pull_strength = nn.Linear(d_model, n_slots, bias=True)
165
+ self.focus_gate = nn.Linear(d_model, n_slots, bias=True)
166
+ self.slot_base_decay = nn.Parameter(torch.tensor([2.0, 3.0, 4.0, 5.0], dtype=torch.float32)[:n_slots])
167
+
168
+ self.norm_out = RMSNorm(n_slots * d_v)
169
+ self.out_proj = nn.Linear(n_slots * d_v, d_model, bias=False)
170
+ self.local_conv = nn.Conv1d(d_model, d_model, kernel_size=3, padding=0, groups=d_model, bias=False)
171
+ self.local_gate = nn.Parameter(torch.tensor(0.25))
172
+
173
+ def forward(self, x: torch.Tensor):
174
+ B, M, D = x.shape
175
+ H, dk, dv = self.n_slots, self.d_k, self.d_v
176
+ C = min(self.chunk_size, M)
177
+ pad = (C - (M % C)) % C
178
+
179
+ scale = 1.0 / math.sqrt(float(dk))
180
+ q = self.q_norm(self.q_proj(x).view(B, M, H, dk)) * scale
181
+ k = self.k_norm(self.k_proj(x).view(B, M, H, dk))
182
+ v = self.v_proj(x).view(B, M, H, dv)
183
+
184
+ route = F.softmax(self.pull_route(x), dim=-1)
185
+ strength = torch.sigmoid(self.pull_strength(x))
186
+ pull_in = (route * strength).float()
187
+ base_decay = torch.sigmoid(self.slot_base_decay).view(1, 1, H)
188
+ fade = ((1.0 - 0.5 * pull_in) * base_decay).clamp(min=1e-4, max=0.9999)
189
+ log_fade = torch.log(fade)
190
+
191
+ if pad > 0:
192
+ q = F.pad(q, (0, 0, 0, 0, 0, pad))
193
+ k = F.pad(k, (0, 0, 0, 0, 0, pad))
194
+ v = F.pad(v, (0, 0, 0, 0, 0, pad))
195
+ pull_in = F.pad(pull_in, (0, 0, 0, pad))
196
+ log_fade = F.pad(log_fade, (0, 0, 0, pad))
197
+
198
+ Mp = q.shape[1]
199
+ Nc = Mp // C
200
+
201
+ q_c = q.view(B, Nc, C, H, dk).transpose(2, 3)
202
+ k_c = k.view(B, Nc, C, H, dk).transpose(2, 3)
203
+ v_c = v.view(B, Nc, C, H, dv).transpose(2, 3)
204
+ p_c = pull_in.view(B, Nc, C, H).transpose(2, 3)
205
+ lf_c = log_fade.view(B, Nc, C, H).transpose(2, 3)
206
+
207
+ G = torch.cumsum(lf_c, dim=-1)
208
+ tril = torch.tril(torch.ones(C, C, device=x.device, dtype=torch.bool))
209
+ G_diff = (G.unsqueeze(-1) - G.unsqueeze(-2)).masked_fill(~tril, -1e9)
210
+ D_intra = torch.exp(G_diff) * tril.float()
211
+
212
+ k_weighted = k_c * p_c.to(k_c.dtype).unsqueeze(-1)
213
+ attn_intra = torch.matmul(q_c, k_weighted.transpose(-1, -2)) * D_intra.to(q_c.dtype)
214
+ out_intra = torch.matmul(attn_intra, v_c)
215
+
216
+ if Nc > 1:
217
+ decay_to_end = torch.exp((G[..., -1:] - G).clamp(max=0.0)) * p_c
218
+ k_end = k_c * decay_to_end.to(k_c.dtype).unsqueeze(-1)
219
+ S_chunk = torch.matmul(k_end.transpose(-1, -2), v_c)
220
+ A_chunk = torch.exp(G[..., -1]).to(q_c.dtype).unsqueeze(-1).unsqueeze(-1)
221
+
222
+ prev_S = []
223
+ S = torch.zeros(B, H, dk, dv, device=x.device, dtype=q_c.dtype)
224
+ for c in range(Nc):
225
+ prev_S.append(S)
226
+ S = A_chunk[:, c] * S + S_chunk[:, c]
227
+ S_prev = torch.stack(prev_S, dim=1)
228
+
229
+ decay_from_start = torch.exp(G.clamp(max=0.0)).to(q_c.dtype).unsqueeze(-1)
230
+ out_cross = decay_from_start * torch.matmul(q_c, S_prev)
231
+ out = out_intra + out_cross
232
+ else:
233
+ out = out_intra
234
+
235
+ out = out.transpose(2, 3).reshape(B, Mp, H, dv)[:, :M]
236
+ focus = F.softmax(self.focus_gate(x), dim=-1)
237
+ focused = self.norm_out((out * (1.0 + focus.unsqueeze(-1))).reshape(B, M, H * dv))
238
+ x_local = self.local_conv(F.pad(x.transpose(1, 2), (2, 0))).transpose(1, 2)
239
+ return self.out_proj(focused) + self.local_gate * x_local, focus
240
+
241
+
242
+ class PerLayerGweight(nn.Module):
243
+ """Per-Layer Galaxyweight (Gweight): Dedicated SwiGLU Core + 4 Neural-Attention-dialed Orbits."""
244
+ def __init__(self, d_model: int, hidden: int, n_orbits: int = 4, orbit_rank: int = 32):
245
+ super().__init__()
246
+ self.n_orbits = n_orbits
247
+ self.orbit_rank = orbit_rank
248
+ self.w_gu = nn.Linear(d_model, 2 * hidden, bias=False)
249
+ self.w_down = nn.Linear(hidden, d_model, bias=False)
250
+ self.orbit_down = nn.Linear(d_model, n_orbits * orbit_rank, bias=False)
251
+ self.orbit_up = nn.Linear(n_orbits * orbit_rank, d_model, bias=False)
252
+
253
+ def forward(self, x: torch.Tensor, orbit_dial: torch.Tensor) -> torch.Tensor:
254
+ B, M, D = x.shape
255
+ g, u = self.w_gu(x).chunk(2, dim=-1)
256
+ core_out = self.w_down(F.silu(g) * u)
257
+ o = F.silu(self.orbit_down(x)).view(B, M, self.n_orbits, self.orbit_rank)
258
+ o = (o * orbit_dial.unsqueeze(-1)).reshape(B, M, self.n_orbits * self.orbit_rank)
259
+ return core_out + self.orbit_up(o)
260
+
261
+
262
+ class GStackLinearBlock(nn.Module):
263
+ def __init__(self, d_model: int, hidden: int, orbit_rank: int = 32):
264
+ super().__init__()
265
+ self.ln_mem = RMSNorm(d_model)
266
+ self.neural_ctx = FastNeuralContext(d_model, stride=1, chunk_size=64)
267
+ self.neural_attn = FastAssociativeNeuralAttention(d_model, n_slots=4, d_k=24, d_v=48, chunk_size=64)
268
+ self.ln_gw = RMSNorm(d_model)
269
+ self.gweight = PerLayerGweight(d_model, hidden, n_orbits=4, orbit_rank=orbit_rank)
270
+
271
+ def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
272
+ h = self.ln_mem(x)
273
+ ctx_out = self.neural_ctx(h)
274
+ attn_out, orbit_dial = self.neural_attn(h)
275
+ x = x + ctx_out + attn_out
276
+ x = x + self.gweight(self.ln_gw(x), orbit_dial)
277
+ return x
278
+
279
+
280
+ class GStackRecallBlock(nn.Module):
281
+ def __init__(self, d_model: int, hidden: int, n_heads: int = 6, orbit_rank: int = 32):
282
+ super().__init__()
283
+ self.ln_mem = RMSNorm(d_model)
284
+ self.attn = UltraFlashAttentionF(d_model, n_heads=n_heads, compress=2)
285
+ self.orbit_router = nn.Linear(d_model, 4, bias=True)
286
+ self.ln_gw = RMSNorm(d_model)
287
+ self.gweight = PerLayerGweight(d_model, hidden, n_orbits=4, orbit_rank=orbit_rank)
288
+
289
+ def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
290
+ h = self.ln_mem(x)
291
+ x = x + self.attn(h, cos, sin)
292
+ dial = F.softmax(self.orbit_router(h), dim=-1)
293
+ x = x + self.gweight(self.ln_gw(x), dial)
294
+ return x
295
+
296
+
297
+ class GStackModel(nn.Module):
298
+ def __init__(self, config: dict):
299
+ super().__init__()
300
+ self.config = config
301
+ vocab_size = config["vocab_size"]
302
+ d_model = config.get("d_model", 384)
303
+ n_layers = config.get("n_layers", 6)
304
+ n_heads = config.get("n_heads", 6)
305
+ hidden = config.get("hidden", 960)
306
+ orbit_rank = config.get("orbit_rank", 32)
307
+ self.max_len = config.get("max_len", 2048)
308
+
309
+ self.itos = config.get("itos", [])
310
+ self.stoi = {c: i for i, c in enumerate(self.itos)}
311
+
312
+ self.tok_emb = nn.Embedding(vocab_size, d_model)
313
+ self.emb_conv3 = nn.Conv1d(d_model, d_model, kernel_size=3, padding=0, groups=d_model, bias=False)
314
+ self.emb_conv7 = nn.Conv1d(d_model, d_model, kernel_size=7, padding=0, groups=d_model, bias=False)
315
+
316
+ recall_indices = set(config.get("recall_layers", [2, 5]))
317
+ blocks = []
318
+ for i in range(n_layers):
319
+ if i in recall_indices:
320
+ blocks.append(GStackRecallBlock(d_model, hidden, n_heads=n_heads, orbit_rank=orbit_rank))
321
+ else:
322
+ blocks.append(GStackLinearBlock(d_model, hidden, orbit_rank=orbit_rank))
323
+ self.blocks = nn.ModuleList(blocks)
324
+ self.ln_f = RMSNorm(d_model)
325
+ self.lm_head = nn.Linear(d_model, vocab_size, bias=False)
326
+ self.head_dim = self.blocks[min(recall_indices)].attn.head_dim
327
+ self._rope_cache = None
328
+
329
+ resid_std = 0.02 / math.sqrt(2.0 * n_layers)
330
+ for name, mod in self.named_modules():
331
+ if isinstance(mod, nn.Linear):
332
+ std = resid_std if (
333
+ name.endswith("out_proj")
334
+ or name.endswith("w_down")
335
+ or name.endswith("orbit_up")
336
+ ) else 0.02
337
+ nn.init.normal_(mod.weight, mean=0.0, std=std)
338
+ if mod.bias is not None:
339
+ nn.init.zeros_(mod.bias)
340
+ elif isinstance(mod, nn.Embedding):
341
+ nn.init.normal_(mod.weight, mean=0.0, std=0.02)
342
+
343
+ def _get_rope(self, T: int, device: torch.device):
344
+ if self._rope_cache is None or self._rope_cache[0].shape[2] < T or self._rope_cache[0].device != device:
345
+ self._rope_cache = precompute_rope(max(T, self.max_len), self.head_dim, device)
346
+ return self._rope_cache
347
+
348
+ def forward(self, idx: torch.Tensor) -> torch.Tensor:
349
+ B, T = idx.shape
350
+ x = self.tok_emb(idx)
351
+ xt = x.transpose(1, 2)
352
+ c3 = self.emb_conv3(F.pad(xt, (2, 0))).transpose(1, 2)
353
+ c7 = self.emb_conv7(F.pad(xt, (6, 0))).transpose(1, 2)
354
+ x = x + 0.3 * c3 + 0.2 * c7
355
+ cos, sin = self._get_rope(T, idx.device)
356
+ for blk in self.blocks:
357
+ x = blk(x, cos, sin)
358
+ return self.lm_head(self.ln_f(x))
359
+
360
+ @classmethod
361
+ def from_pretrained(cls, repo_or_dir: str, device: str | None = None):
362
+ p = Path(repo_or_dir)
363
+ if p.is_dir():
364
+ cfg_path = p / "config.json"
365
+ w_path = p / "model.safetensors"
366
+ else:
367
+ from huggingface_hub import hf_hub_download
368
+ cfg_path = Path(hf_hub_download(repo_id=repo_or_dir, filename="config.json"))
369
+ w_path = Path(hf_hub_download(repo_id=repo_or_dir, filename="model.safetensors"))
370
+ config = json.loads(cfg_path.read_text(encoding="utf-8"))
371
+ model = cls(config)
372
+ model.load_state_dict(load_file(str(w_path)), strict=True)
373
+ dev = device or ("cuda" if torch.cuda.is_available() else "cpu")
374
+ return model.to(dev).eval()
375
+
376
+ @torch.no_grad()
377
+ def generate(self, prompt: str, max_chars: int = 280, temperature: float = 0.65, seed: int = 42) -> str:
378
+ device = next(self.parameters()).device
379
+ ids = [self.stoi[c] for c in prompt if c in self.stoi]
380
+ if not ids:
381
+ ids = [0]
382
+ gen = torch.Generator(device=device).manual_seed(seed)
383
+ for _ in range(max_chars):
384
+ ctx = ids[-self.max_len:]
385
+ x = torch.tensor([ctx], dtype=torch.long, device=device)
386
+ with torch.amp.autocast(device.type, dtype=torch.bfloat16, enabled=(device.type == "cuda")):
387
+ logits = self(x)[0, -1].float() / max(temperature, 1e-4)
388
+ probs = F.softmax(logits, dim=-1)
389
+ ids.append(torch.multinomial(probs, 1, generator=gen).item())
390
+ return "".join(self.itos[i] for i in ids)