kgrabko commited on
Commit
c88fe21
·
verified ·
1 Parent(s): 1fe3445

Upload 16 files

Browse files
source_jit/JiRack_H12_L12_V50257_D768_MSL8192_FF768x4.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 CMS Manhattan
2
+ # All rights reserved.
3
+ # Author: Konstantin Vladimirovich Grabko
4
+ # Email: grabko@cmsmanhattan.com
5
+ # Phone: +1(516)777-0945
6
+ #
7
+ # This program is free software: you can redistribute it and/or modify
8
+ # it under the terms of the GNU General Public License as published by
9
+ # the Free Software Foundation, version 3 of the License.
10
+ #
11
+ # This program is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ # GNU General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with this program. If not, see <https://www.gnu.org/licenses/>.
18
+ #
19
+ # Additional terms:
20
+ # Any commercial use or distribution of this software or derivative works
21
+ # requires explicit written permission from the copyright holder.
22
+
23
+
24
+ import os
25
+ import torch
26
+ import torch.nn as nn
27
+ import torch.nn.functional as F
28
+ from typing import Optional, Tuple, List
29
+ import math
30
+
31
+ # ========================================
32
+ # Model Configuration (GPT-2 Base Style)
33
+ # ========================================
34
+ VOCAB_SIZE = 50257
35
+ MODEL_DIM = 768
36
+ NUM_HEADS = 12
37
+ NUM_LAYERS = 12
38
+ MAX_SEQ_LEN = 8192
39
+ FFN_HIDDEN_DIM = 4 * MODEL_DIM
40
+ HEAD_DIM = MODEL_DIM // NUM_HEADS
41
+
42
+ if torch.cuda.is_available():
43
+ device = torch.device("cuda")
44
+ elif hasattr(torch, 'hip') and torch.hip.is_available():
45
+ device = torch.device("cuda")
46
+ else:
47
+ device = torch.device("cpu")
48
+
49
+ # -------------------------------
50
+ # Learned Positional Embedding
51
+ # -------------------------------
52
+ class LearnedPositionalEmbedding(nn.Module):
53
+ def __init__(self, max_seq_len: int, embed_dim: int):
54
+ super().__init__()
55
+ self.pos_emb = nn.Parameter(torch.zeros(max_seq_len, embed_dim))
56
+
57
+ def forward(self, x: torch.Tensor, pos_offset: int = 0) -> torch.Tensor:
58
+ seq_len = x.size(1)
59
+ # Проверка на длину убрана для JIT-совместимости (TracerWarning)
60
+
61
+ pos = self.pos_emb[pos_offset : pos_offset + seq_len]
62
+ return x + pos.unsqueeze(0)
63
+
64
+ # -------------------------------
65
+ # MultiHeadAttention
66
+ # -------------------------------
67
+ class MultiHeadAttention(nn.Module):
68
+ def __init__(self):
69
+ super().__init__()
70
+ self.q_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
71
+ self.k_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
72
+ self.v_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
73
+ self.out_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
74
+ self.scale = HEAD_DIM ** -0.5
75
+
76
+ def forward(self, x: torch.Tensor, past_kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
77
+ B, T, D = x.shape
78
+
79
+ q = self.q_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
80
+ k = self.k_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
81
+ v = self.v_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
82
+
83
+ # Обработка KV-кэша
84
+ pos_offset = 0
85
+ if past_kv is not None and past_kv[0] is not None:
86
+ past_k, past_v = past_kv
87
+ k = torch.cat([past_k, k], dim=2)
88
+ v = torch.cat([past_v, v], dim=2)
89
+ pos_offset = past_k.size(2)
90
+ new_kv = (k, v)
91
+ else:
92
+ new_kv = None
93
+
94
+ seqlen_k = k.size(2)
95
+
96
+ attn = torch.matmul(q, k.transpose(-2, -1)) * self.scale
97
+
98
+ # === ОКОНЧАТЕЛЬНОЕ ИСПРАВЛЕНИЕ: Безусловное маскирование для устранения TracerWarning ===
99
+ # Проверяем T > 0, но не в условном Python 'if'
100
+ mask = torch.full((T, seqlen_k), float("-inf"), device=x.device, dtype=attn.dtype)
101
+
102
+ # Маска для текущего блока (T x T)
103
+ current_causal_mask = torch.tril(torch.ones(T, T, device=x.device, dtype=torch.bool))
104
+
105
+ # Маска для past_kv (T x pos_offset)
106
+ mask[:, :pos_offset] = 0.0
107
+
108
+ # Применение текущей причинной маски к части K, соответствующей текущему входу
109
+ mask[:, pos_offset : pos_offset + T].masked_fill_(~current_causal_mask, float('-inf'))
110
+ attn = attn + mask[None, None, :, :]
111
+
112
+ attn = F.softmax(attn, dim=-1)
113
+ out = torch.matmul(attn, v)
114
+ out = out.transpose(1, 2).contiguous().view(B, T, D)
115
+ out = self.out_proj(out)
116
+
117
+ return out, new_kv
118
+ # -------------------------------
119
+ # FeedForward
120
+ # -------------------------------
121
+ class FeedForward(nn.Module):
122
+ def __init__(self):
123
+ super().__init__()
124
+ self.c_fc = nn.Linear(MODEL_DIM, FFN_HIDDEN_DIM, bias=False)
125
+ self.c_proj = nn.Linear(FFN_HIDDEN_DIM, MODEL_DIM, bias=False)
126
+
127
+ def forward(self, x):
128
+ return self.c_proj(F.gelu(self.c_fc(x), approximate='tanh'))
129
+
130
+ # -------------------------------
131
+ # Transformer Block
132
+ # -------------------------------
133
+ class TransformerBlock(nn.Module):
134
+ def __init__(self):
135
+ super().__init__()
136
+ self.attn = MultiHeadAttention()
137
+ self.ffn = FeedForward()
138
+ self.norm1 = nn.LayerNorm(MODEL_DIM, eps=1e-5)
139
+ self.norm2 = nn.LayerNorm(MODEL_DIM, eps=1e-5)
140
+
141
+ def forward(self, x, past_kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
142
+ attn_out, new_kv = self.attn(self.norm1(x), past_kv)
143
+ x = x + attn_out
144
+ x = x + self.ffn(self.norm2(x))
145
+
146
+ return x, new_kv
147
+ # -------------------------------
148
+ # Главная модель GPTPyTorch
149
+ # -------------------------------
150
+ class GPTPyTorch(nn.Module):
151
+ def __init__(self):
152
+ super().__init__()
153
+ self.token_emb = nn.Embedding(VOCAB_SIZE, MODEL_DIM)
154
+ self.pos_emb = LearnedPositionalEmbedding(MAX_SEQ_LEN, MODEL_DIM)
155
+ self.blocks = nn.ModuleList([TransformerBlock() for _ in range(NUM_LAYERS)])
156
+ self.ln_f = nn.LayerNorm(MODEL_DIM, eps=1e-5)
157
+ self.lm_head = nn.Linear(MODEL_DIM, VOCAB_SIZE, bias=False)
158
+
159
+ signature = "Konstantin V Gbabko . original author © 2025"
160
+ bytes_tensor = torch.tensor([ord(c) for c in signature], dtype=torch.uint8)
161
+ self.register_buffer("konstantin_gbabko_proof_of_authorship", bytes_tensor)
162
+ self.register_buffer("konstantin_gbabko_birth_date", torch.tensor([20251126], dtype=torch.int64))
163
+
164
+ self.lm_head.weight = self.token_emb.weight
165
+ self.apply(self._init_weights)
166
+
167
+ def _init_weights(self, module):
168
+ if isinstance(module, nn.Linear):
169
+ std = 0.02 / (2 * NUM_LAYERS)**0.5 if isinstance(module, nn.Linear) and module.out_features == MODEL_DIM else 0.02
170
+ torch.nn.init.normal_(module.weight, mean=0.0, std=std)
171
+ elif isinstance(module, nn.Embedding):
172
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
173
+ elif isinstance(module, nn.LayerNorm):
174
+ nn.init.zeros_(module.bias)
175
+ nn.init.ones_(module.weight)
176
+
177
+ def forward(self, input_ids, past_kv: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None):
178
+ B, T = input_ids.shape
179
+ x = self.token_emb(input_ids)
180
+
181
+ pos_offset = 0
182
+ if past_kv is not None and past_kv[0] is not None and isinstance(past_kv[0], tuple):
183
+ pos_offset = past_kv[0][0].size(2)
184
+
185
+ x = self.pos_emb(x, pos_offset=pos_offset)
186
+
187
+ new_kv_cache = [] if past_kv is not None else None
188
+ current_past = past_kv
189
+
190
+ for i, block in enumerate(self.blocks):
191
+ layer_past = current_past[i] if (current_past and i < len(current_past)) else None
192
+
193
+ x, layer_kv = block(x, layer_past)
194
+
195
+ if past_kv is not None:
196
+ new_kv_cache.append(layer_kv)
197
+
198
+ x = self.ln_f(x)
199
+ logits = self.lm_head(x)
200
+
201
+ if past_kv is None:
202
+ return logits
203
+ else:
204
+ return logits, new_kv_cache
205
+
206
+ # -------------------------------
207
+ # Обертка для JIT-трассировки (гарантирует только Tensor)
208
+ # -------------------------------
209
+ class GPTPyTorchNoCache(nn.Module):
210
+ def __init__(self, model):
211
+ super().__init__()
212
+ self.model = model
213
+
214
+ def forward(self, input_ids):
215
+ return self.model(input_ids, None)
216
+
217
+
218
+ # -------------------------------
219
+ # ОСНОВНОЙ БЛОК: JIT-КОНВЕРТАЦИЯ
220
+ # -------------------------------
221
+ if __name__ == "__main__":
222
+ os.makedirs("models", exist_ok=True)
223
+
224
+ # =========================================================================
225
+ # 1. ПОДГОТОВКА МОДЕЛИ И ПРОВЕРКА
226
+ # =========================================================================
227
+ model = GPTPyTorch().to(device)
228
+ model.eval()
229
+
230
+ total_params = sum(p.numel() for p in model.parameters())
231
+ print(f"Device: {device}")
232
+ print(f"Total parameters: {total_params / 1e6:.2f}M")
233
+
234
+ TRAIN_SEQ_LEN = 256
235
+
236
+ # Создаем фиктивный входной тензор
237
+ dummy_input = torch.randint(0, VOCAB_SIZE, (1, TRAIN_SEQ_LEN), device=device)
238
+
239
+ # Проверяем обычный проход
240
+ with torch.no_grad():
241
+ logits_test = model(dummy_input, None)
242
+ print(f"Test logits shape: {logits_test.shape}")
243
+
244
+ # =========================================================================
245
+ # 2. JIT-ТРАССИРОВКА И СОХРАНЕНИЕ
246
+ # =========================================================================
247
+ print(f"\nTracing model for JIT export (input sequence length: {TRAIN_SEQ_LEN})...")
248
+
249
+ # Используем обертку для тр��ссировки
250
+ model_no_cache = GPTPyTorchNoCache(model).to(device)
251
+
252
+ try:
253
+ # Трассируем обертку, которая принимает только input_ids
254
+ traced_script_module = torch.jit.trace(model_no_cache, dummy_input, strict=False)
255
+ JIT_SAVE_PATH = "models/JiRack_H12_L12_V50257_D768_MSL8192_FF768x4.script.pt"
256
+ traced_script_module.save(JIT_SAVE_PATH)
257
+ print(f"✅ Success! Model saved as TorchScript (JIT) to: {JIT_SAVE_PATH}")
258
+ print("Now you can run your training script.")
259
+ except Exception as e:
260
+ print(f"🚨 ERROR during JIT tracing: {e}")
261
+ print("Model may contain operations incompatible with torch.jit.trace.")
262
+
263
+ # Сохраняем оригинальную модель (на всякий случай)
264
+ ORIGINAL_SAVE_PATH = "models/JiRack_H12_L12_V50257_D768_MSL8192_FF768x4.pt"
265
+ torch.save(model.state_dict(), ORIGINAL_SAVE_PATH)
266
+ print(f"\nOriginal state_dict saved to {ORIGINAL_SAVE_PATH}")
source_jit/JiRack_H12_L18_V50257_D768_MSL8192_FF768x4.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 CMS Manhattan
2
+ # All rights reserved.
3
+ # Author: Konstantin Vladimirovich Grabko
4
+ # Email: grabko@cmsmanhattan.com
5
+ # Phone: +1(516)777-0945
6
+ #
7
+ # This program is free software: you can redistribute it and/or modify
8
+ # it under the terms of the GNU General Public License as published by
9
+ # the Free Software Foundation, version 3 of the License.
10
+ #
11
+ # This program is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ # GNU General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with this program. If not, see <https://www.gnu.org/licenses/>.
18
+ #
19
+ # Additional terms:
20
+ # Any commercial use or distribution of this software or derivative works
21
+ # requires explicit written permission from the copyright holder.
22
+
23
+ import os
24
+ import torch
25
+ import torch.nn as nn
26
+ import torch.nn.functional as F
27
+ from typing import Optional, Tuple, List
28
+ import math
29
+ from pathlib import Path
30
+
31
+ # ========================================
32
+ # Model Configuration (L=18, D=768)
33
+ # ========================================
34
+ VOCAB_SIZE = 50257
35
+ MODEL_DIM = 768
36
+ NUM_HEADS = 12
37
+ NUM_LAYERS = 18 # Increased depth
38
+ MAX_SEQ_LEN = 8192
39
+ FFN_HIDDEN_DIM = 4 * MODEL_DIM
40
+ HEAD_DIM = MODEL_DIM // NUM_HEADS
41
+
42
+ if torch.cuda.is_available():
43
+ device = torch.device("cuda")
44
+ elif hasattr(torch, 'hip') and torch.hip.is_available():
45
+ device = torch.device("cuda")
46
+ else:
47
+ device = torch.device("cpu")
48
+
49
+ # --- Learned Positional Embedding ---
50
+ class LearnedPositionalEmbedding(nn.Module):
51
+ def __init__(self, max_seq_len: int, embed_dim: int):
52
+ super().__init__()
53
+ self.pos_emb = nn.Parameter(torch.zeros(max_seq_len, embed_dim))
54
+
55
+ def forward(self, x: torch.Tensor, pos_offset: int = 0) -> torch.Tensor:
56
+ seq_len = x.size(1)
57
+ pos = self.pos_emb[pos_offset : pos_offset + seq_len]
58
+ return x + pos.unsqueeze(0)
59
+
60
+
61
+ # --- MultiHeadAttention ---
62
+ class MultiHeadAttention(nn.Module):
63
+ def __init__(self):
64
+ super().__init__()
65
+ self.q_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
66
+ self.k_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
67
+ self.v_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
68
+ self.out_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
69
+ self.scale = HEAD_DIM ** -0.5
70
+
71
+ def forward(self, x: torch.Tensor, past_kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
72
+ B, T, D = x.shape
73
+
74
+ q = self.q_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
75
+ k = self.k_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
76
+ v = self.v_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
77
+
78
+ pos_offset = 0
79
+ new_kv = None
80
+ if past_kv is not None and past_kv[0] is not None:
81
+ past_k, past_v = past_kv
82
+ k = torch.cat([past_k, k], dim=2)
83
+ v = torch.cat([past_v, v], dim=2)
84
+ pos_offset = past_k.size(2)
85
+ new_kv = (k, v)
86
+
87
+ seqlen_k = k.size(2)
88
+
89
+ attn = torch.matmul(q, k.transpose(-2, -1)) * self.scale
90
+
91
+ # === ФИНАЛЬНОЕ ИСПРАВЛЕНИЕ (УДАЛЕНИЕ T > 0) ===
92
+ # Удалено 'if T > 0:', чтобы избежать TracerWarning при трассировке.
93
+ # Код маскирования теперь всегда выполняется (для T >= 1).
94
+ mask = torch.full((T, seqlen_k), float("-inf"), device=x.device, dtype=attn.dtype)
95
+ current_causal_mask = torch.tril(torch.ones(T, T, device=x.device, dtype=torch.bool))
96
+
97
+ mask[:, :pos_offset] = 0.0
98
+ mask[:, pos_offset : pos_offset + T].masked_fill_(~current_causal_mask, float('-inf'))
99
+
100
+ attn = attn + mask[None, None, :, :]
101
+ # ===============================================
102
+
103
+ attn = F.softmax(attn, dim=-1)
104
+ out = torch.matmul(attn, v)
105
+ out = out.transpose(1, 2).contiguous().view(B, T, D)
106
+ out = self.out_proj(out)
107
+
108
+ return out, new_kv
109
+
110
+
111
+ # --- FeedForward (Без изменений) ---
112
+ class FeedForward(nn.Module):
113
+ def __init__(self):
114
+ super().__init__()
115
+ self.c_fc = nn.Linear(MODEL_DIM, FFN_HIDDEN_DIM, bias=False)
116
+ self.c_proj = nn.Linear(FFN_HIDDEN_DIM, MODEL_DIM, bias=False)
117
+
118
+ def forward(self, x):
119
+ return self.c_proj(F.gelu(self.c_fc(x), approximate='tanh'))
120
+
121
+
122
+ # --- Transformer Block (Без изменений) ---
123
+ class TransformerBlock(nn.Module):
124
+ def __init__(self):
125
+ super().__init__()
126
+ self.attn = MultiHeadAttention()
127
+ self.ffn = FeedForward()
128
+ self.norm1 = nn.LayerNorm(MODEL_DIM, eps=1e-5)
129
+ self.norm2 = nn.LayerNorm(MODEL_DIM, eps=1e-5)
130
+
131
+ def forward(self, x, past_kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
132
+ attn_out, new_kv = self.attn(self.norm1(x), past_kv)
133
+ x = x + attn_out
134
+ x = x + self.ffn(self.norm2(x))
135
+ return x, new_kv
136
+
137
+
138
+ # -------------------------------
139
+ # Главная модель GPTPyTorch
140
+ # -------------------------------
141
+ class GPTPyTorch(nn.Module):
142
+ def __init__(self):
143
+ super().__init__()
144
+ self.token_emb = nn.Embedding(VOCAB_SIZE, MODEL_DIM)
145
+ self.pos_emb = LearnedPositionalEmbedding(MAX_SEQ_LEN, MODEL_DIM)
146
+ self.blocks = nn.ModuleList([TransformerBlock() for _ in range(NUM_LAYERS)])
147
+ self.ln_f = nn.LayerNorm(MODEL_DIM, eps=1e-5)
148
+ self.lm_head = nn.Linear(MODEL_DIM, VOCAB_SIZE, bias=False)
149
+
150
+ signature = "Konstantin V Gbabko . original author © 2025"
151
+ bytes_tensor = torch.tensor([ord(c) for c in signature], dtype=torch.uint8)
152
+ self.register_buffer("konstantin_gbabko_proof_of_authorship", bytes_tensor)
153
+ self.register_buffer("konstantin_gbabko_birth_date", torch.tensor([20251126], dtype=torch.int64))
154
+
155
+ self.lm_head.weight = self.token_emb.weight
156
+ self.apply(self._init_weights)
157
+
158
+ def _init_weights(self, module):
159
+ if isinstance(module, nn.Linear):
160
+ std = 0.02 / math.sqrt(2 * NUM_LAYERS) if isinstance(module, nn.Linear) and module.out_features == MODEL_DIM else 0.02
161
+ torch.nn.init.normal_(module.weight, mean=0.0, std=std)
162
+ elif isinstance(module, nn.Embedding):
163
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
164
+ elif isinstance(module, nn.LayerNorm):
165
+ nn.init.zeros_(module.bias)
166
+ nn.init.ones_(module.weight)
167
+
168
+ def forward(self, input_ids, past_kv: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None):
169
+ B, T = input_ids.shape
170
+ x = self.token_emb(input_ids)
171
+
172
+ pos_offset = 0
173
+ if past_kv is not None and past_kv[0] is not None:
174
+ pos_offset = past_kv[0][0].size(2)
175
+
176
+ x = self.pos_emb(x, pos_offset=pos_offset)
177
+
178
+ new_kv_cache = [] if past_kv is not None else None
179
+ current_past = past_kv
180
+
181
+ for i, block in enumerate(self.blocks):
182
+ layer_past = current_past[i] if (current_past and i < len(current_past)) else None
183
+ x, layer_kv = block(x, layer_past)
184
+
185
+ if new_kv_cache is not None:
186
+ new_kv_cache.append(layer_kv)
187
+
188
+ x = self.ln_f(x)
189
+ logits = self.lm_head(x)
190
+
191
+ if past_kv is None:
192
+ return logits
193
+ else:
194
+ return logits, new_kv_cache
195
+
196
+ # -------------------------------
197
+ # Обертка для JIT-трассировки (гарантирует только Tensor)
198
+ # -------------------------------
199
+ class GPTPyTorchNoCache(nn.Module):
200
+ def __init__(self, model):
201
+ super().__init__()
202
+ self.model = model
203
+
204
+ def forward(self, input_ids):
205
+ return self.model(input_ids, None)
206
+
207
+ # =========================================================================
208
+ # ОСНОВНОЙ БЛОК: JIT-КОНВЕРТАЦИЯ
209
+ # =========================================================================
210
+ if __name__ == "__main__":
211
+ os.makedirs("models", exist_ok=True)
212
+
213
+ TRAIN_SEQ_LEN = 256
214
+ JIT_SAVE_PATH = Path("models/JiRack_H12_L18_V50257_D768_MSL8192_FF768x4.script.pt")
215
+
216
+ model = GPTPyTorch().to(device)
217
+ model.eval()
218
+
219
+ total_params = sum(p.numel() for p in model.parameters())
220
+ print(f"Device: {device}")
221
+ print(f"Total parameters: {total_params / 1e6:.2f}M")
222
+
223
+ # 1. Проверка первого прохода
224
+ dummy_input = torch.randint(0, VOCAB_SIZE, (1, TRAIN_SEQ_LEN), device=device)
225
+ with torch.no_grad():
226
+ logits_test = model(dummy_input, None)
227
+ print(f"Test logits shape: {logits_test.shape}")
228
+
229
+ # 2. JIT-ТРАССИРОВКА И СОХРАНЕНИЕ
230
+ print(f"\nTracing model for JIT export (input sequence length: {TRAIN_SEQ_LEN})...")
231
+
232
+ model_no_cache = GPTPyTorchNoCache(model).to(device)
233
+
234
+ try:
235
+ traced_script_module = torch.jit.trace(model_no_cache, dummy_input, strict=False)
236
+
237
+ traced_script_module.save(JIT_SAVE_PATH)
238
+ print(f"✅ Success! Model saved as TorchScript (JIT) to: {JIT_SAVE_PATH}")
239
+ print("Now you can run your training script.")
240
+
241
+ except Exception as e:
242
+ print(f"🚨 ERROR during JIT tracing: {e}")
243
+ print("Model may contain operations incompatible with torch.jit.trace.")
244
+
245
+ # Сохраняем оригинальную модель (на всякий случай)
246
+ ORIGINAL_SAVE_PATH = "models/JiRack_H12_L18_V50257_D768_MSL8192_FF768x4.pt"
247
+ torch.save(model.state_dict(), ORIGINAL_SAVE_PATH)
248
+ print(f"\nOriginal state_dict saved to {ORIGINAL_SAVE_PATH}")
source_jit/JiRack_H12_L24_V50257_D768_MSL8192_FF768x4.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 CMS Manhattan
2
+ # All rights reserved.
3
+ # Author: Konstantin Vladimirovich Grabko
4
+ # Email: grabko@cmsmanhattan.com
5
+ # Phone: +1(516)777-0945
6
+ #
7
+ # This program is free software: you can redistribute it and/or modify
8
+ # it under the terms of the GNU General Public License as published by
9
+ # the Free Software Foundation, version 3 of the License.
10
+ #
11
+ # This program is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ # GNU General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with this program. If not, see <https://www.gnu.org/licenses/>.
18
+ #
19
+ # Additional terms:
20
+ # Any commercial use or distribution of this software or derivative works
21
+ # requires explicit written permission from the copyright holder.
22
+
23
+ import os
24
+ import torch
25
+ import torch.nn as nn
26
+ import torch.nn.functional as F
27
+ from typing import Optional, Tuple, List
28
+ import math
29
+ from pathlib import Path
30
+
31
+ # ========================================
32
+ # Model Configuration (GPT-2 Large Style)
33
+ # ========================================
34
+ VOCAB_SIZE = 50257
35
+ MODEL_DIM = 768
36
+ NUM_HEADS = 12
37
+ NUM_LAYERS = 24 # Increased depth (GPT-2 Large equivalent)
38
+ MAX_SEQ_LEN = 8192
39
+ FFN_HIDDEN_DIM = 4 * MODEL_DIM
40
+ HEAD_DIM = MODEL_DIM // NUM_HEADS
41
+
42
+ # ROCm/HIP-совместимая проверка устройства
43
+ if torch.cuda.is_available():
44
+ device = torch.device("cuda")
45
+ elif hasattr(torch, 'hip') and torch.hip.is_available():
46
+ device = torch.device("cuda")
47
+ else:
48
+ device = torch.device("cpu")
49
+
50
+ # --- Learned Positional Embedding (Без изменений) ---
51
+ class LearnedPositionalEmbedding(nn.Module):
52
+ def __init__(self, max_seq_len: int, embed_dim: int):
53
+ super().__init__()
54
+ self.pos_emb = nn.Parameter(torch.zeros(max_seq_len, embed_dim))
55
+
56
+ def forward(self, x: torch.Tensor, pos_offset: int = 0) -> torch.Tensor:
57
+ seq_len = x.size(1)
58
+ # Убрана Python-проверка для JIT-совместимости (если T > MAX_SEQ_LEN)
59
+ pos = self.pos_emb[pos_offset : pos_offset + seq_len]
60
+ return x + pos.unsqueeze(0)
61
+
62
+
63
+ # --- MultiHeadAttention (MHA) (Исправлено для JIT) ---
64
+ class MultiHeadAttention(nn.Module):
65
+ def __init__(self):
66
+ super().__init__()
67
+ self.q_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
68
+ self.k_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
69
+ self.v_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
70
+ self.out_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
71
+ self.scale = HEAD_DIM ** -0.5
72
+
73
+ def forward(self, x: torch.Tensor, past_kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
74
+ B, T, D = x.shape
75
+
76
+ q = self.q_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
77
+ k = self.k_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
78
+ v = self.v_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
79
+
80
+ pos_offset = 0
81
+ new_kv = None
82
+
83
+ # --- KV-кэш логика ---
84
+ if past_kv is not None and past_kv[0] is not None:
85
+ past_k, past_v = past_kv
86
+ k = torch.cat([past_k, k], dim=2)
87
+ v = torch.cat([past_v, v], dim=2)
88
+ pos_offset = past_k.size(2)
89
+ new_kv = (k, v)
90
+ elif past_kv is not None:
91
+ # Случай, когда past_kv передан, но пуст (например, [None]*24)
92
+ new_kv = (k, v)
93
+
94
+ seqlen_k = k.size(2)
95
+
96
+ attn = torch.matmul(q, k.transpose(-2, -1)) * self.scale
97
+
98
+ # === ИСПРАВЛЕНИЕ TRACERWARNING: Убрано if/and, выполняется безусловно для T >= 1 ===
99
+ # Поскольку T=256 при трассировке, этот путь всегда записывается.
100
+ mask = torch.full((T, seqlen_k), float("-inf"), device=x.device, dtype=attn.dtype)
101
+ current_causal_mask = torch.tril(torch.ones(T, T, device=x.device, dtype=torch.bool))
102
+
103
+ mask[:, :pos_offset] = 0.0
104
+ mask[:, pos_offset : pos_offset + T].masked_fill_(~current_causal_mask, float('-inf'))
105
+
106
+ attn = attn + mask[None, None, :, :]
107
+ # ===================================================================================
108
+
109
+ attn = F.softmax(attn, dim=-1)
110
+ out = torch.matmul(attn, v)
111
+ out = out.transpose(1, 2).contiguous().view(B, T, D)
112
+ out = self.out_proj(out)
113
+
114
+ return out, new_kv
115
+
116
+
117
+ # --- FeedForward (Без изменений) ---
118
+ class FeedForward(nn.Module):
119
+ def __init__(self):
120
+ super().__init__()
121
+ self.c_fc = nn.Linear(MODEL_DIM, FFN_HIDDEN_DIM, bias=False)
122
+ self.c_proj = nn.Linear(FFN_HIDDEN_DIM, MODEL_DIM, bias=False)
123
+
124
+ def forward(self, x):
125
+ return self.c_proj(F.gelu(self.c_fc(x), approximate='tanh'))
126
+
127
+
128
+ # --- Transformer Block (Без изменений) ---
129
+ class TransformerBlock(nn.Module):
130
+ def __init__(self):
131
+ super().__init__()
132
+ self.attn = MultiHeadAttention()
133
+ self.ffn = FeedForward()
134
+ self.norm1 = nn.LayerNorm(MODEL_DIM, eps=1e-5)
135
+ self.norm2 = nn.LayerNorm(MODEL_DIM, eps=1e-5)
136
+
137
+ def forward(self, x, past_kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
138
+ attn_out, new_kv = self.attn(self.norm1(x), past_kv)
139
+ x = x + attn_out
140
+ x = x + self.ffn(self.norm2(x))
141
+ return x, new_kv
142
+
143
+
144
+ # -------------------------------
145
+ # Главная модель GPTPyTorch (24 слоя)
146
+ # -------------------------------
147
+ class GPTPyTorch(nn.Module):
148
+ def __init__(self):
149
+ super().__init__()
150
+ self.token_emb = nn.Embedding(VOCAB_SIZE, MODEL_DIM)
151
+ self.pos_emb = LearnedPositionalEmbedding(MAX_SEQ_LEN, MODEL_DIM)
152
+ self.blocks = nn.ModuleList([TransformerBlock() for _ in range(NUM_LAYERS)])
153
+ self.ln_f = nn.LayerNorm(MODEL_DIM, eps=1e-5)
154
+ self.lm_head = nn.Linear(MODEL_DIM, VOCAB_SIZE, bias=False)
155
+
156
+ signature = "Konstantin V Gbabko . original author © 2025"
157
+ bytes_tensor = torch.tensor([ord(c) for c in signature], dtype=torch.uint8)
158
+ self.register_buffer("konstantin_gbabko_proof_of_authorship", bytes_tensor)
159
+ self.register_buffer("konstantin_gbabko_birth_date", torch.tensor([20251126], dtype=torch.int64))
160
+
161
+ self.lm_head.weight = self.token_emb.weight
162
+ self.apply(self._init_weights)
163
+
164
+ def _init_weights(self, module):
165
+ if isinstance(module, nn.Linear):
166
+ # Инициализация, масштабированная по глубине сети (L=24)
167
+ std = 0.02 / math.sqrt(2 * NUM_LAYERS) if isinstance(module, nn.Linear) and module.out_features == MODEL_DIM else 0.02
168
+ torch.nn.init.normal_(module.weight, mean=0.0, std=std)
169
+ elif isinstance(module, nn.Embedding):
170
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
171
+ elif isinstance(module, nn.LayerNorm):
172
+ nn.init.zeros_(module.bias)
173
+ nn.init.ones_(module.weight)
174
+
175
+ # Метод forward для обучения и инференса с кешем
176
+ def forward(self, input_ids, past_kv: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None):
177
+ B, T = input_ids.shape
178
+ x = self.token_emb(input_ids)
179
+
180
+ pos_offset = 0
181
+ if past_kv is not None and past_kv[0] is not None:
182
+ pos_offset = past_kv[0][0].size(2)
183
+
184
+ x = self.pos_emb(x, pos_offset=pos_offset)
185
+
186
+ new_kv_cache = [] if past_kv is not None else None
187
+ current_past = past_kv
188
+
189
+ for i, block in enumerate(self.blocks):
190
+ layer_past = current_past[i] if (current_past and i < len(current_past)) else None
191
+ x, layer_kv = block(x, layer_past)
192
+
193
+ if new_kv_cache is not None:
194
+ new_kv_cache.append(layer_kv)
195
+
196
+ x = self.ln_f(x)
197
+ logits = self.lm_head(x)
198
+
199
+ # === КРИТИЧЕСКОЕ ИСПРАВЛЕНИЕ: Статический вывод для JIT-трассировки ===
200
+ if past_kv is None:
201
+ # Путь обучения: JIT может трассировать только Tensor
202
+ return logits
203
+ else:
204
+ # Путь инференса с кэшем: возвращаем Tensor и кеш
205
+ return logits, new_kv_cache
206
+
207
+ # -------------------------------
208
+ # Обертка для JIT-трассировки (гарантирует только Tensor)
209
+ # -------------------------------
210
+ class GPTPyTorchNoCache(nn.Module):
211
+ def __init__(self, model):
212
+ super().__init__()
213
+ self.model = model
214
+
215
+ def forward(self, input_ids):
216
+ # Вызов с None гарантирует, что основной forward вернет только logits (Tensor).
217
+ return self.model(input_ids, None)
218
+
219
+ # =========================================================================
220
+ # ОСНОВНОЙ БЛОК: JIT-КОНВЕРТАЦИЯ
221
+ # =========================================================================
222
+ if __name__ == "__main__":
223
+ os.makedirs("models", exist_ok=True)
224
+
225
+ TRAIN_SEQ_LEN = 256
226
+ # Обновленное имя файла для отражения L=24
227
+ JIT_SAVE_PATH = Path("models/JiRack_H12_L24_V50257_D768_MSL8192_FF768x4.script.pt")
228
+
229
+ model = GPTPyTorch().to(device)
230
+ model.eval()
231
+
232
+ total_params = sum(p.numel() for p in model.parameters())
233
+ print(f"Device: {device}")
234
+ print(f"Total parameters: {total_params / 1e6:.2f}M")
235
+
236
+ # 1. Проверка первого прохода
237
+ dummy_input = torch.randint(0, VOCAB_SIZE, (1, TRAIN_SEQ_LEN), device=device)
238
+ with torch.no_grad():
239
+ # Тестируем путь обучения (past_kv=None)
240
+ logits_test = model(dummy_input, None)
241
+ print(f"Test logits shape: {logits_test.shape}")
242
+
243
+ # 2. JIT-ТРАССИРОВКА И СОХРАНЕНИЕ
244
+ print(f"\nTracing model for JIT export (input sequence length: {TRAIN_SEQ_LEN})...")
245
+
246
+ model_no_cache = GPTPyTorchNoCache(model).to(device)
247
+
248
+ try:
249
+ # Трассируем обертку, которая принимает только input_ids,
250
+ # что гарантирует один Tensor на выходе.
251
+ traced_script_module = torch.jit.trace(model_no_cache, dummy_input, strict=False)
252
+
253
+ traced_script_module.save(JIT_SAVE_PATH)
254
+ print(f"✅ Success! Model saved as TorchScript (JIT) to: {JIT_SAVE_PATH}")
255
+ print("Now you can run your training script to fine-tune this model.")
256
+
257
+ except Exception as e:
258
+ print(f"🚨 ERROR during JIT tracing: {e}")
259
+ print("Model may contain operations incompatible with torch.jit.trace.")
260
+
261
+ # Сохраняем оригинальную модель (на всякий случай)
262
+ ORIGINAL_SAVE_PATH = "models/JiRack_H12_L24_V50257_D768_MSL8192_FF768x4.pt"
263
+ torch.save(model.state_dict(), ORIGINAL_SAVE_PATH)
264
+ print(f"\nOriginal state_dict saved to {ORIGINAL_SAVE_PATH}")
source_jit/JiRack_H12_L32_V50257_D768_MSL8192_FF768x4.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 CMS Manhattan
2
+ # All rights reserved.
3
+ # Author: Konstantin Vladimirovich Grabko
4
+ # Email: grabko@cmsmanhattan.com
5
+ # Phone: +1(516)777-0945
6
+ #
7
+ # This program is free software: you can redistribute it and/or modify
8
+ # it under the terms of the GNU General Public License as published by
9
+ # the Free Software Foundation, version 3 of the License.
10
+ #
11
+ # This program is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ # GNU General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with this program. If not, see <https://www.gnu.org/licenses/>.
18
+ #
19
+ # Additional terms:
20
+ # Any commercial use or distribution of this software or derivative works
21
+ # requires explicit written permission from the copyright holder.
22
+
23
+ import os
24
+ import torch
25
+ import torch.nn as nn
26
+ import torch.nn.functional as F
27
+ from typing import Optional, Tuple, List
28
+ import math
29
+ from pathlib import Path
30
+
31
+ # ========================================
32
+ # Model Configuration (GPT-2 XL Style)
33
+ # ========================================
34
+ VOCAB_SIZE = 50257
35
+ MODEL_DIM = 768
36
+ NUM_HEADS = 12
37
+ NUM_LAYERS = 32 # Increased depth (GPT-2 XL equivalent)
38
+ MAX_SEQ_LEN = 8192
39
+ FFN_HIDDEN_DIM = 4 * MODEL_DIM
40
+ HEAD_DIM = MODEL_DIM // NUM_HEADS
41
+
42
+ # ROCm/HIP-совместимая проверка устройства
43
+ if torch.cuda.is_available():
44
+ device = torch.device("cuda")
45
+ elif hasattr(torch, 'hip') and torch.hip.is_available():
46
+ device = torch.device("cuda")
47
+ else:
48
+ device = torch.device("cpu")
49
+
50
+ # --- Learned Positional Embedding (Исправлено для JIT) ---
51
+ class LearnedPositionalEmbedding(nn.Module):
52
+ def __init__(self, max_seq_len: int, embed_dim: int):
53
+ super().__init__()
54
+ self.pos_emb = nn.Parameter(torch.zeros(max_seq_len, embed_dim))
55
+
56
+ def forward(self, x: torch.Tensor, pos_offset: int = 0) -> torch.Tensor:
57
+ seq_len = x.size(1)
58
+ # ИСПРАВЛЕНИЕ: Удалена Python-проверка, несовместимая с JIT
59
+ pos = self.pos_emb[pos_offset : pos_offset + seq_len]
60
+ return x + pos.unsqueeze(0)
61
+
62
+
63
+ # --- MultiHeadAttention (MHA) (Исправлено для JIT) ---
64
+ class MultiHeadAttention(nn.Module):
65
+ def __init__(self):
66
+ super().__init__()
67
+ self.q_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
68
+ self.k_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
69
+ self.v_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
70
+ self.out_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
71
+ self.scale = HEAD_DIM ** -0.5
72
+
73
+ def forward(self, x: torch.Tensor, past_kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
74
+ B, T, D = x.shape
75
+
76
+ q = self.q_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
77
+ k = self.k_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
78
+ v = self.v_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
79
+
80
+ pos_offset = 0
81
+ new_kv = None
82
+
83
+ if past_kv is not None and past_kv[0] is not None:
84
+ past_k, past_v = past_kv
85
+ k = torch.cat([past_k, k], dim=2)
86
+ v = torch.cat([past_v, v], dim=2)
87
+ pos_offset = past_k.size(2)
88
+ new_kv = (k, v)
89
+ elif past_kv is not None:
90
+ new_kv = (k, v)
91
+
92
+ seqlen_k = k.size(2)
93
+
94
+ attn = torch.matmul(q, k.transpose(-2, -1)) * self.scale
95
+
96
+ # ИСПРАВЛЕНИЕ: Удалена динамическая Python-проверка 'if T == seqlen_k_new and seqlen_k > 0:'
97
+ # Маскирование выполняется безусловно для JIT-совместимости.
98
+ mask = torch.full((T, seqlen_k), float("-inf"), device=x.device, dtype=attn.dtype)
99
+ current_causal_mask = torch.tril(torch.ones(T, T, device=x.device, dtype=torch.bool))
100
+
101
+ mask[:, :pos_offset] = 0.0
102
+ mask[:, pos_offset : pos_offset + T].masked_fill_(~current_causal_mask, float('-inf'))
103
+
104
+ attn = attn + mask[None, None, :, :]
105
+
106
+ attn = F.softmax(attn, dim=-1)
107
+ out = torch.matmul(attn, v)
108
+ out = out.transpose(1, 2).contiguous().view(B, T, D)
109
+ out = self.out_proj(out)
110
+
111
+ return out, new_kv
112
+
113
+
114
+ # --- FeedForward (Без изменений) ---
115
+ class FeedForward(nn.Module):
116
+ def __init__(self):
117
+ super().__init__()
118
+ self.c_fc = nn.Linear(MODEL_DIM, FFN_HIDDEN_DIM, bias=False)
119
+ self.c_proj = nn.Linear(FFN_HIDDEN_DIM, MODEL_DIM, bias=False)
120
+
121
+ def forward(self, x):
122
+ return self.c_proj(F.gelu(self.c_fc(x), approximate='tanh'))
123
+
124
+
125
+ # --- Transformer Block (Без изменений) ---
126
+ class TransformerBlock(nn.Module):
127
+ def __init__(self):
128
+ super().__init__()
129
+ self.attn = MultiHeadAttention()
130
+ self.ffn = FeedForward()
131
+ self.norm1 = nn.LayerNorm(MODEL_DIM, eps=1e-5)
132
+ self.norm2 = nn.LayerNorm(MODEL_DIM, eps=1e-5)
133
+
134
+ def forward(self, x, past_kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
135
+ attn_out, new_kv = self.attn(self.norm1(x), past_kv)
136
+ x = x + attn_out
137
+ x = x + self.ffn(self.norm2(x))
138
+ return x, new_kv
139
+
140
+
141
+ # -------------------------------
142
+ # Главная модель GPTPyTorch (32 слоя)
143
+ # -------------------------------
144
+ class GPTPyTorch(nn.Module):
145
+ def __init__(self):
146
+ super().__init__()
147
+ self.token_emb = nn.Embedding(VOCAB_SIZE, MODEL_DIM)
148
+ self.pos_emb = LearnedPositionalEmbedding(MAX_SEQ_LEN, MODEL_DIM)
149
+ self.blocks = nn.ModuleList([TransformerBlock() for _ in range(NUM_LAYERS)])
150
+ self.ln_f = nn.LayerNorm(MODEL_DIM, eps=1e-5)
151
+ self.lm_head = nn.Linear(MODEL_DIM, VOCAB_SIZE, bias=False)
152
+
153
+ signature = "Konstantin V Gbabko . original author © 2025"
154
+ bytes_tensor = torch.tensor([ord(c) for c in signature], dtype=torch.uint8)
155
+ self.register_buffer("konstantin_gbabko_proof_of_authorship", bytes_tensor)
156
+ self.register_buffer("konstantin_gbabko_birth_date", torch.tensor([20251126], dtype=torch.int64))
157
+
158
+ self.lm_head.weight = self.token_emb.weight
159
+ self.apply(self._init_weights)
160
+
161
+ def _init_weights(self, module):
162
+ if isinstance(module, nn.Linear):
163
+ # Инициализация, масштабированная по глубине сети (L=32)
164
+ std = 0.02 / math.sqrt(2 * NUM_LAYERS) if isinstance(module, nn.Linear) and module.out_features == MODEL_DIM else 0.02
165
+ torch.nn.init.normal_(module.weight, mean=0.0, std=std)
166
+ elif isinstance(module, nn.Embedding):
167
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
168
+ elif isinstance(module, nn.LayerNorm):
169
+ nn.init.zeros_(module.bias)
170
+ nn.init.ones_(module.weight)
171
+
172
+ # Метод forward для обучения и инференса с кешем
173
+ def forward(self, input_ids, past_kv: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None):
174
+ B, T = input_ids.shape
175
+ x = self.token_emb(input_ids)
176
+
177
+ pos_offset = 0
178
+ if past_kv is not None and past_kv[0] is not None:
179
+ pos_offset = past_kv[0][0].size(2)
180
+
181
+ x = self.pos_emb(x, pos_offset=pos_offset)
182
+
183
+ # Инициализация нового кеша
184
+ new_kv_cache = [] if past_kv is not None else None
185
+ current_past = past_kv
186
+
187
+ for i, block in enumerate(self.blocks):
188
+ layer_past = current_past[i] if (current_past and i < len(current_past)) else None
189
+ x, layer_kv = block(x, layer_past)
190
+
191
+ if new_kv_cache is not None:
192
+ new_kv_cache.append(layer_kv)
193
+
194
+ x = self.ln_f(x)
195
+ logits = self.lm_head(x)
196
+
197
+ # === КРИТИЧЕСКОЕ ИСПРАВЛЕНИЕ: Статический вывод для JIT-трассировки ===
198
+ if past_kv is None:
199
+ return logits # Путь обучения (возвращает только Tensor)
200
+ else:
201
+ return logits, new_kv_cache # Путь инференса с кэшем (возвращает Tensor и List)
202
+
203
+ # -------------------------------
204
+ # Обертка для JIT-трассировки (гарантирует только Tensor)
205
+ # -------------------------------
206
+ class GPTPyTorchNoCache(nn.Module):
207
+ def __init__(self, model):
208
+ super().__init__()
209
+ self.model = model
210
+
211
+ def forward(self, input_ids):
212
+ # Вызов с None гарантирует, что основной forward вернет только logits (Tensor).
213
+ return self.model(input_ids, None)
214
+
215
+ # =========================================================================
216
+ # ОСНОВНОЙ БЛОК: JIT-КОНВЕРТАЦИЯ
217
+ # =========================================================================
218
+ if __name__ == "__main__":
219
+ os.makedirs("models", exist_ok=True)
220
+
221
+ TRAIN_SEQ_LEN = 256
222
+ # Обновленное имя файла для отражения L=32
223
+ JIT_SAVE_PATH = Path("models/JiRack_H12_L32_V50257_D768_MSL8192_FF768x4.script.pt")
224
+
225
+ model = GPTPyTorch().to(device)
226
+ model.eval()
227
+
228
+ total_params = sum(p.numel() for p in model.parameters())
229
+ print(f"Device: {device}")
230
+ print(f"Total parameters: {total_params / 1e6:.2f}M")
231
+
232
+ # 1. Проверка первого прохода
233
+ dummy_input = torch.randint(0, VOCAB_SIZE, (1, TRAIN_SEQ_LEN), device=device)
234
+ with torch.no_grad():
235
+ # Тестируем путь обучения (past_kv=None)
236
+ # ИСПРАВЛЕНИЕ: Теперь вызываем model(dummy_input, None)
237
+ logits_test = model(dummy_input, None)
238
+ print(f"Test logits shape: {logits_test.shape}")
239
+
240
+ # 2. JIT-ТРАССИРОВКА И СОХРАНЕНИЕ
241
+ print(f"\nTracing model for JIT export (input sequence length: {TRAIN_SEQ_LEN})...")
242
+
243
+ # ИСПРАВЛЕНИЕ: Используем обертку для чистой трассировки
244
+ model_no_cache = GPTPyTorchNoCache(model).to(device)
245
+
246
+ try:
247
+ traced_script_module = torch.jit.trace(model_no_cache, dummy_input, strict=False)
248
+
249
+ traced_script_module.save(JIT_SAVE_PATH)
250
+ print(f"✅ Success! Model saved as TorchScript (JIT) to: {JIT_SAVE_PATH}")
251
+ print("Now you can run your training script to fine-tune this model.")
252
+
253
+ except Exception as e:
254
+ print(f"🚨 ERROR during JIT tracing: {e}")
255
+ print("Model may contain operations incompatible with torch.jit.trace.")
256
+
257
+ # Сохраняем оригинальную модель (на всякий случай)
258
+ ORIGINAL_SAVE_PATH = "models/JiRack_H12_L32_V50257_D768_MSL8192_FF768x4.pt"
259
+ torch.save(model.state_dict(), ORIGINAL_SAVE_PATH)
260
+ print(f"\nOriginal state_dict saved to {ORIGINAL_SAVE_PATH}")
source_jit/JiRack_H12_L6_V50257_D768_MSL8192_FF768x4.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 CMS Manhattan
2
+ # All rights reserved.
3
+ # Author: Konstantin Vladimirovich Grabko
4
+ # Email: grabko@cmsmanhattan.com
5
+ # Phone: +1(516)777-0945
6
+ #
7
+ # This program is free software: you can redistribute it and/or modify
8
+ # it under the terms of the GNU General Public License as published by
9
+ # the Free Software Foundation, version 3 of the License.
10
+ #
11
+ # This program is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ # GNU General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with this program. If not, see <https://www.gnu.org/licenses/>.
18
+ #
19
+ # Additional terms:
20
+ # Any commercial use or distribution of this software or derivative works
21
+ # requires explicit written permission from the copyright holder.
22
+
23
+ import os
24
+ import torch
25
+ import torch.nn as nn
26
+ import torch.nn.functional as F
27
+ from typing import Optional, Tuple, List
28
+ import math
29
+ from pathlib import Path
30
+
31
+ # ========================================
32
+ # Model Configuration (GPT-2 Small Style)
33
+ # ========================================
34
+ VOCAB_SIZE = 50257
35
+ MODEL_DIM = 768
36
+ NUM_HEADS = 12
37
+ NUM_LAYERS = 6 # Back to 6 layers (GPT-2 Small equivalent)
38
+ MAX_SEQ_LEN = 8192
39
+ FFN_HIDDEN_DIM = 4 * MODEL_DIM
40
+ HEAD_DIM = MODEL_DIM // NUM_HEADS
41
+
42
+ # ROCm/HIP-совместимая проверка устройства
43
+ if torch.cuda.is_available():
44
+ device = torch.device("cuda")
45
+ elif hasattr(torch, 'hip') and torch.hip.is_available():
46
+ device = torch.device("cuda")
47
+ else:
48
+ device = torch.device("cpu")
49
+
50
+ # --- Learned Positional Embedding (Исправлено для JIT) ---
51
+ class LearnedPositionalEmbedding(nn.Module):
52
+ def __init__(self, max_seq_len: int, embed_dim: int):
53
+ super().__init__()
54
+ self.pos_emb = nn.Parameter(torch.zeros(max_seq_len, embed_dim))
55
+
56
+ def forward(self, x: torch.Tensor, pos_offset: int = 0) -> torch.Tensor:
57
+ seq_len = x.size(1)
58
+ # ИСПРАВЛЕНИЕ: Удалена Python-проверка, несовместимая с JIT
59
+ pos = self.pos_emb[pos_offset : pos_offset + seq_len]
60
+ return x + pos.unsqueeze(0)
61
+
62
+
63
+ # --- MultiHeadAttention (MHA) (Исправлено для JIT) ---
64
+ class MultiHeadAttention(nn.Module):
65
+ def __init__(self):
66
+ super().__init__()
67
+ self.q_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
68
+ self.k_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
69
+ self.v_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
70
+ self.out_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
71
+ self.scale = HEAD_DIM ** -0.5
72
+
73
+ def forward(self, x: torch.Tensor, past_kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
74
+ B, T, D = x.shape
75
+
76
+ q = self.q_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
77
+ k = self.k_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
78
+ v = self.v_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
79
+
80
+ pos_offset = 0
81
+ new_kv = None
82
+
83
+ if past_kv is not None and past_kv[0] is not None:
84
+ past_k, past_v = past_kv
85
+ k = torch.cat([past_k, k], dim=2)
86
+ v = torch.cat([past_v, v], dim=2)
87
+ pos_offset = past_k.size(2)
88
+ new_kv = (k, v)
89
+ elif past_kv is not None:
90
+ new_kv = (k, v)
91
+
92
+ seqlen_k = k.size(2)
93
+
94
+ attn = torch.matmul(q, k.transpose(-2, -1)) * self.scale
95
+
96
+ # ИСПРАВЛЕНИЕ: Удалена динамическая Python-проверка. Маскирование выполняется безусловно.
97
+ mask = torch.full((T, seqlen_k), float("-inf"), device=x.device, dtype=attn.dtype)
98
+ current_causal_mask = torch.tril(torch.ones(T, T, device=x.device, dtype=torch.bool))
99
+
100
+ mask[:, :pos_offset] = 0.0
101
+ mask[:, pos_offset : pos_offset + T].masked_fill_(~current_causal_mask, float('-inf'))
102
+
103
+ attn = attn + mask[None, None, :, :]
104
+
105
+ attn = F.softmax(attn, dim=-1)
106
+ out = torch.matmul(attn, v)
107
+ out = out.transpose(1, 2).contiguous().view(B, T, D)
108
+ out = self.out_proj(out)
109
+
110
+ return out, new_kv
111
+
112
+
113
+ # --- FeedForward (Без изменений) ---
114
+ class FeedForward(nn.Module):
115
+ def __init__(self):
116
+ super().__init__()
117
+ self.c_fc = nn.Linear(MODEL_DIM, FFN_HIDDEN_DIM, bias=False)
118
+ self.c_proj = nn.Linear(FFN_HIDDEN_DIM, MODEL_DIM, bias=False)
119
+
120
+ def forward(self, x):
121
+ return self.c_proj(F.gelu(self.c_fc(x), approximate='tanh'))
122
+
123
+
124
+ # --- Transformer Block (Без изменений) ---
125
+ class TransformerBlock(nn.Module):
126
+ def __init__(self):
127
+ super().__init__()
128
+ self.attn = MultiHeadAttention()
129
+ self.ffn = FeedForward()
130
+ self.norm1 = nn.LayerNorm(MODEL_DIM, eps=1e-5)
131
+ self.norm2 = nn.LayerNorm(MODEL_DIM, eps=1e-5)
132
+
133
+ def forward(self, x, past_kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
134
+ attn_out, new_kv = self.attn(self.norm1(x), past_kv)
135
+ x = x + attn_out
136
+ x = x + self.ffn(self.norm2(x))
137
+ return x, new_kv
138
+
139
+
140
+ # -------------------------------
141
+ # Главная модель GPTPyTorch (6 слоев)
142
+ # -------------------------------
143
+ class GPTPyTorch(nn.Module):
144
+ def __init__(self):
145
+ super().__init__()
146
+ self.token_emb = nn.Embedding(VOCAB_SIZE, MODEL_DIM)
147
+ self.pos_emb = LearnedPositionalEmbedding(MAX_SEQ_LEN, MODEL_DIM)
148
+ self.blocks = nn.ModuleList([TransformerBlock() for _ in range(NUM_LAYERS)])
149
+ self.ln_f = nn.LayerNorm(MODEL_DIM, eps=1e-5)
150
+ self.lm_head = nn.Linear(MODEL_DIM, VOCAB_SIZE, bias=False)
151
+
152
+ signature = "Konstantin V Gbabko . original author © 2025"
153
+ bytes_tensor = torch.tensor([ord(c) for c in signature], dtype=torch.uint8)
154
+ self.register_buffer("konstantin_gbabko_proof_of_authorship", bytes_tensor)
155
+ self.register_buffer("konstantin_gbabko_birth_date", torch.tensor([20251126], dtype=torch.int64))
156
+
157
+ self.lm_head.weight = self.token_emb.weight
158
+ self.apply(self._init_weights)
159
+
160
+ def _init_weights(self, module):
161
+ if isinstance(module, nn.Linear):
162
+ # Инициализация, масштабированная по глубине сети (L=6)
163
+ std = 0.02 / math.sqrt(2 * NUM_LAYERS) if isinstance(module, nn.Linear) and module.out_features == MODEL_DIM else 0.02
164
+ torch.nn.init.normal_(module.weight, mean=0.0, std=std)
165
+ elif isinstance(module, nn.Embedding):
166
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
167
+ elif isinstance(module, nn.LayerNorm):
168
+ nn.init.zeros_(module.bias)
169
+ nn.init.ones_(module.weight)
170
+
171
+ # Метод forward для обучения и инференса с кешем
172
+ def forward(self, input_ids, past_kv: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None):
173
+ B, T = input_ids.shape
174
+ x = self.token_emb(input_ids)
175
+
176
+ pos_offset = 0
177
+ if past_kv is not None and past_kv[0] is not None:
178
+ pos_offset = past_kv[0][0].size(2)
179
+
180
+ x = self.pos_emb(x, pos_offset=pos_offset)
181
+
182
+ # Инициализация нового кеша
183
+ new_kv_cache = [] if past_kv is not None else None
184
+ current_past = past_kv
185
+
186
+ for i, block in enumerate(self.blocks):
187
+ layer_past = current_past[i] if (current_past and i < len(current_past)) else None
188
+ x, layer_kv = block(x, layer_past)
189
+
190
+ if new_kv_cache is not None:
191
+ new_kv_cache.append(layer_kv)
192
+
193
+ x = self.ln_f(x)
194
+ logits = self.lm_head(x)
195
+
196
+ # === КРИТИЧЕСКОЕ ИСПРАВЛЕНИЕ: Статический вывод для JIT-трассировки ===
197
+ if past_kv is None:
198
+ return logits # Путь обучения (возвращает только Tensor)
199
+ else:
200
+ return logits, new_kv_cache # Путь инференса с кэшем (возвращает Tensor и List)
201
+
202
+ # -------------------------------
203
+ # Обертка для JIT-трассировки (гарантирует только Tensor)
204
+ # -------------------------------
205
+ class GPTPyTorchNoCache(nn.Module):
206
+ def __init__(self, model):
207
+ super().__init__()
208
+ self.model = model
209
+
210
+ def forward(self, input_ids):
211
+ # Вызов с None гарантирует, что основной forward вернет только logits (Tensor).
212
+ return self.model(input_ids, None)
213
+
214
+ # =========================================================================
215
+ # ОСНОВНОЙ БЛОК: JIT-КОНВЕРТАЦИЯ
216
+ # =========================================================================
217
+ if __name__ == "__main__":
218
+ os.makedirs("models", exist_ok=True)
219
+
220
+ TRAIN_SEQ_LEN = 256
221
+ # Обновленное имя файла для отражения L=6
222
+ JIT_SAVE_PATH = Path("models/JiRack_H12_L6_V50257_D768_MSL8192_FF768x4.script.pt")
223
+
224
+ model = GPTPyTorch().to(device)
225
+ model.eval()
226
+
227
+ total_params = sum(p.numel() for p in model.parameters())
228
+ print(f"Device: {device}")
229
+ print(f"Total parameters: {total_params / 1e6:.2f}M")
230
+
231
+ # 1. Проверка первого прохода
232
+ dummy_input = torch.randint(0, VOCAB_SIZE, (1, TRAIN_SEQ_LEN), device=device)
233
+ with torch.no_grad():
234
+ # Тестируем путь обучения (past_kv=None)
235
+ logits_test = model(dummy_input, None)
236
+ print(f"Test logits shape: {logits_test.shape}")
237
+
238
+ # 2. JIT-ТРАССИРОВКА И СОХРАНЕНИЕ
239
+ print(f"\nTracing model for JIT export (input sequence length: {TRAIN_SEQ_LEN})...")
240
+
241
+ # Используем обертку для чистой трассировки
242
+ model_no_cache = GPTPyTorchNoCache(model).to(device)
243
+
244
+ try:
245
+ traced_script_module = torch.jit.trace(model_no_cache, dummy_input, strict=False)
246
+
247
+ traced_script_module.save(JIT_SAVE_PATH)
248
+ print(f"✅ Success! Model saved as TorchScript (JIT) to: {JIT_SAVE_PATH}")
249
+ print("Now you can run your training script to fine-tune this model.")
250
+
251
+ except Exception as e:
252
+ print(f"🚨 ERROR during JIT tracing: {e}")
253
+ print("Model may contain operations incompatible with torch.jit.trace.")
254
+
255
+ # Сохраняем оригинальную модель (на всякий случай)
256
+ ORIGINAL_SAVE_PATH = "models/JiRack_H12_L6_V50257_D768_MSL8192_FF768x4.pt"
257
+ torch.save(model.state_dict(), ORIGINAL_SAVE_PATH)
258
+ print(f"\nOriginal state_dict saved to {ORIGINAL_SAVE_PATH}")
source_jit/JiRack_H16_L24_V50257_D768_MSL8192_FF768x4.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 CMS Manhattan
2
+ # All rights reserved.
3
+ # Author: Konstantin Vladimirovich Grabko
4
+ # Email: grabko@cmsmanhattan.com
5
+ # Phone: +1(516)777-0945
6
+ #
7
+ # This program is free software: you can redistribute it and/or modify
8
+ # it under the terms of the GNU General Public License as published by
9
+ # the Free Software Foundation, version 3 of the License.
10
+ #
11
+ # This program is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ # GNU General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with this program. If not, see <https://www.gnu.org/licenses/>.
18
+ #
19
+ # Additional terms:
20
+ # Any commercial use or distribution of this software or derivative works
21
+ # requires explicit written permission from the copyright holder.
22
+
23
+ import os
24
+ import torch
25
+ import torch.nn as nn
26
+ import torch.nn.functional as F
27
+ from typing import Optional, Tuple, List
28
+ import math
29
+ from pathlib import Path
30
+
31
+ # ========================================
32
+ # Model Configuration (L=24, H=16)
33
+ # ========================================
34
+ VOCAB_SIZE = 50257
35
+ MODEL_DIM = 768
36
+ NUM_HEADS = 16 # Changed to 16
37
+ NUM_LAYERS = 24 # Layer count
38
+ MAX_SEQ_LEN = 8192
39
+ FFN_HIDDEN_DIM = 4 * MODEL_DIM
40
+ HEAD_DIM = MODEL_DIM // NUM_HEADS # Recalculated: 768 / 16 = 48
41
+
42
+ # ROCm/HIP-совместимая проверка устройства
43
+ if torch.cuda.is_available():
44
+ device = torch.device("cuda")
45
+ elif hasattr(torch, 'hip') and torch.hip.is_available():
46
+ device = torch.device("cuda")
47
+ else:
48
+ device = torch.device("cpu")
49
+
50
+ # --- Learned Positional Embedding (Исправлено для JIT) ---
51
+ class LearnedPositionalEmbedding(nn.Module):
52
+ def __init__(self, max_seq_len: int, embed_dim: int):
53
+ super().__init__()
54
+ self.pos_emb = nn.Parameter(torch.zeros(max_seq_len, embed_dim))
55
+
56
+ def forward(self, x: torch.Tensor, pos_offset: int = 0) -> torch.Tensor:
57
+ seq_len = x.size(1)
58
+ # ИСПРАВЛЕНИЕ: Удалена Python-проверка, несовместимая с JIT
59
+ pos = self.pos_emb[pos_offset : pos_offset + seq_len]
60
+ return x + pos.unsqueeze(0)
61
+
62
+
63
+ # --- MultiHeadAttention (MHA) (Исправлено для JIT) ---
64
+ class MultiHeadAttention(nn.Module):
65
+ def __init__(self):
66
+ super().__init__()
67
+ self.q_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
68
+ self.k_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
69
+ self.v_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
70
+ self.out_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
71
+ self.scale = HEAD_DIM ** -0.5
72
+
73
+ def forward(self, x: torch.Tensor, past_kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
74
+ B, T, D = x.shape
75
+
76
+ q = self.q_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
77
+ k = self.k_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
78
+ v = self.v_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
79
+
80
+ pos_offset = 0
81
+ new_kv = None
82
+
83
+ if past_kv is not None and past_kv[0] is not None:
84
+ past_k, past_v = past_kv
85
+ k = torch.cat([past_k, k], dim=2)
86
+ v = torch.cat([past_v, v], dim=2)
87
+ pos_offset = past_k.size(2)
88
+ new_kv = (k, v)
89
+ elif past_kv is not None:
90
+ new_kv = (k, v)
91
+
92
+ seqlen_k = k.size(2)
93
+
94
+ attn = torch.matmul(q, k.transpose(-2, -1)) * self.scale
95
+
96
+ # ИСПРАВЛЕНИЕ: Удалена динамическая Python-проверка. Маскирование выполняется безусловно.
97
+ mask = torch.full((T, seqlen_k), float("-inf"), device=x.device, dtype=attn.dtype)
98
+ current_causal_mask = torch.tril(torch.ones(T, T, device=x.device, dtype=torch.bool))
99
+
100
+ mask[:, :pos_offset] = 0.0
101
+ mask[:, pos_offset : pos_offset + T].masked_fill_(~current_causal_mask, float('-inf'))
102
+
103
+ attn = attn + mask[None, None, :, :]
104
+
105
+ attn = F.softmax(attn, dim=-1)
106
+ out = torch.matmul(attn, v)
107
+ out = out.transpose(1, 2).contiguous().view(B, T, D)
108
+ out = self.out_proj(out)
109
+
110
+ return out, new_kv
111
+
112
+
113
+ # --- FeedForward (Без изменений) ---
114
+ class FeedForward(nn.Module):
115
+ def __init__(self):
116
+ super().__init__()
117
+ self.c_fc = nn.Linear(MODEL_DIM, FFN_HIDDEN_DIM, bias=False)
118
+ self.c_proj = nn.Linear(FFN_HIDDEN_DIM, MODEL_DIM, bias=False)
119
+
120
+ def forward(self, x):
121
+ return self.c_proj(F.gelu(self.c_fc(x), approximate='tanh'))
122
+
123
+
124
+ # --- Transformer Block (Без изменений) ---
125
+ class TransformerBlock(nn.Module):
126
+ def __init__(self):
127
+ super().__init__()
128
+ self.attn = MultiHeadAttention()
129
+ self.ffn = FeedForward()
130
+ self.norm1 = nn.LayerNorm(MODEL_DIM, eps=1e-5)
131
+ self.norm2 = nn.LayerNorm(MODEL_DIM, eps=1e-5)
132
+
133
+ def forward(self, x, past_kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
134
+ attn_out, new_kv = self.attn(self.norm1(x), past_kv)
135
+ x = x + attn_out
136
+ x = x + self.ffn(self.norm2(x))
137
+ return x, new_kv
138
+
139
+
140
+ # -------------------------------
141
+ # Главная модель GPTPyTorch (L=24, H=16)
142
+ # -------------------------------
143
+ class GPTPyTorch(nn.Module):
144
+ def __init__(self):
145
+ super().__init__()
146
+ self.token_emb = nn.Embedding(VOCAB_SIZE, MODEL_DIM)
147
+ self.pos_emb = LearnedPositionalEmbedding(MAX_SEQ_LEN, MODEL_DIM)
148
+ self.blocks = nn.ModuleList([TransformerBlock() for _ in range(NUM_LAYERS)])
149
+ self.ln_f = nn.LayerNorm(MODEL_DIM, eps=1e-5)
150
+ self.lm_head = nn.Linear(MODEL_DIM, VOCAB_SIZE, bias=False)
151
+
152
+ signature = "Konstantin V Gbabko . original author © 2025"
153
+ bytes_tensor = torch.tensor([ord(c) for c in signature], dtype=torch.uint8)
154
+ self.register_buffer("konstantin_gbabko_proof_of_authorship", bytes_tensor)
155
+ self.register_buffer("konstantin_gbabko_birth_date", torch.tensor([20251126], dtype=torch.int64))
156
+
157
+ self.lm_head.weight = self.token_emb.weight
158
+ self.apply(self._init_weights)
159
+
160
+ def _init_weights(self, module):
161
+ if isinstance(module, nn.Linear):
162
+ # Инициализация, масштабированная по глубине сети (L=24)
163
+ std = 0.02 / math.sqrt(2 * NUM_LAYERS) if isinstance(module, nn.Linear) and module.out_features == MODEL_DIM else 0.02
164
+ torch.nn.init.normal_(module.weight, mean=0.0, std=std)
165
+ elif isinstance(module, nn.Embedding):
166
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
167
+ elif isinstance(module, nn.LayerNorm):
168
+ nn.init.zeros_(module.bias)
169
+ nn.init.ones_(module.weight)
170
+
171
+ # Метод forward для обучения и инференса с кешем
172
+ def forward(self, input_ids, past_kv: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None):
173
+ B, T = input_ids.shape
174
+ x = self.token_emb(input_ids)
175
+
176
+ pos_offset = 0
177
+ if past_kv is not None and past_kv[0] is not None:
178
+ pos_offset = past_kv[0][0].size(2)
179
+
180
+ x = self.pos_emb(x, pos_offset=pos_offset)
181
+
182
+ # Инициализация нового кеша
183
+ new_kv_cache = [] if past_kv is not None else None
184
+ current_past = past_kv
185
+
186
+ for i, block in enumerate(self.blocks):
187
+ layer_past = current_past[i] if (current_past and i < len(current_past)) else None
188
+ x, layer_kv = block(x, layer_past)
189
+
190
+ if new_kv_cache is not None:
191
+ new_kv_cache.append(layer_kv)
192
+
193
+ x = self.ln_f(x)
194
+ logits = self.lm_head(x)
195
+
196
+ # === КРИТИЧЕСКОЕ ИСПРАВЛЕНИЕ: Статический вывод для JIT-трассировки ===
197
+ if past_kv is None:
198
+ return logits # Путь обучения (возвращает только Tensor)
199
+ else:
200
+ return logits, new_kv_cache # Путь инференса с кэшем (возвращает Tensor и List)
201
+
202
+
203
+ # -------------------------------
204
+ # Обертка для JIT-трассировки (гарантирует только Tensor)
205
+ # -------------------------------
206
+ class GPTPyTorchNoCache(nn.Module):
207
+ def __init__(self, model):
208
+ super().__init__()
209
+ self.model = model
210
+
211
+ def forward(self, input_ids):
212
+ # Вызов с None гарантирует, что основной forward вернет только logits (Tensor).
213
+ return self.model(input_ids, None)
214
+
215
+
216
+ # =========================================================================
217
+ # ОСНОВНОЙ БЛОК: JIT-КОНВЕРТАЦИЯ
218
+ # =========================================================================
219
+ if __name__ == "__main__":
220
+ os.makedirs("models", exist_ok=True)
221
+
222
+ TRAIN_SEQ_LEN = 256
223
+ # Обновленное имя файла для отражения L=24, H=16
224
+ JIT_SAVE_PATH = Path("models/JiRack_H16_L24_V50257_D768_MSL8192_FF768x4.script.pt")
225
+
226
+ model = GPTPyTorch().to(device)
227
+ model.eval()
228
+
229
+ total_params = sum(p.numel() for p in model.parameters())
230
+ print(f"Device: {device}")
231
+ print(f"Total parameters: {total_params / 1e6:.2f}M")
232
+
233
+ # 1. Проверка первого прохода
234
+ dummy_input = torch.randint(0, VOCAB_SIZE, (1, TRAIN_SEQ_LEN), device=device)
235
+ with torch.no_grad():
236
+ # Тестируем путь обучения (past_kv=None), который возвращает только logits
237
+ logits_test = model(dummy_input, None)
238
+ print(f"Test logits shape: {logits_test.shape}")
239
+
240
+ # 2. JIT-ТРАССИРОВКА И СОХРАНЕНИЕ
241
+ print(f"\nTracing model for JIT export (input sequence length: {TRAIN_SEQ_LEN})...")
242
+
243
+ # Используем обертку для чистой трассировки
244
+ model_no_cache = GPTPyTorchNoCache(model).to(device)
245
+
246
+ try:
247
+ traced_script_module = torch.jit.trace(model_no_cache, dummy_input, strict=False)
248
+
249
+ traced_script_module.save(JIT_SAVE_PATH)
250
+ print(f"✅ Success! Model saved as TorchScript (JIT) to: {JIT_SAVE_PATH}")
251
+ print("Now you can run your training script to fine-tune this model.")
252
+
253
+ except Exception as e:
254
+ print(f"🚨 ERROR during JIT tracing: {e}")
255
+ print("Model may contain operations incompatible with torch.jit.trace.")
256
+
257
+ # Сохраняем оригинальную модель (на всякий случай)
258
+ ORIGINAL_SAVE_PATH = "models/JiRack_H16_L24_V50257_D768_MSL8192_FF768x4.pt"
259
+ torch.save(model.state_dict(), ORIGINAL_SAVE_PATH)
260
+ print(f"\nOriginal state_dict saved to {ORIGINAL_SAVE_PATH}")
source_jit/JiRack_H16_L32_V50257_D768_MSL8192_FF768x4.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 CMS Manhattan
2
+ # All rights reserved.
3
+ # Author: Konstantin Vladimirovich Grabko
4
+ # Email: grabko@cmsmanhattan.com
5
+ # Phone: +1(516)777-0945
6
+ #
7
+ # This program is free software: you can redistribute it and/or modify
8
+ # it under the terms of the GNU General Public License as published by
9
+ # the Free Software Foundation, version 3 of the License.
10
+ #
11
+ # This program is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ # GNU General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with this program. If not, see <https://www.gnu.org/licenses/>.
18
+ #
19
+ # Additional terms:
20
+ # Any commercial use or distribution of this software or derivative works
21
+ # requires explicit written permission from the copyright holder.
22
+
23
+ import os
24
+ import torch
25
+ import torch.nn as nn
26
+ import torch.nn.functional as F
27
+ from typing import Optional, Tuple, List
28
+ import math
29
+ from pathlib import Path
30
+
31
+ # ========================================
32
+ # Model Configuration (L=32, H=16, D=768)
33
+ # ========================================
34
+ VOCAB_SIZE = 50257
35
+ MODEL_DIM = 768
36
+ NUM_HEADS = 16
37
+ NUM_LAYERS = 32 # Deepest version yet
38
+ MAX_SEQ_LEN = 8192
39
+ FFN_HIDDEN_DIM = 4 * MODEL_DIM
40
+ HEAD_DIM = MODEL_DIM // NUM_HEADS # 768 / 16 = 48
41
+
42
+ # ROCm/HIP-совместимая проверка устройства
43
+ if torch.cuda.is_available():
44
+ device = torch.device("cuda")
45
+ elif hasattr(torch, 'hip') and torch.hip.is_available():
46
+ device = torch.device("cuda")
47
+ else:
48
+ device = torch.device("cpu")
49
+
50
+ # --- Learned Positional Embedding (Исправлено для JIT) ---
51
+ class LearnedPositionalEmbedding(nn.Module):
52
+ def __init__(self, max_seq_len: int, embed_dim: int):
53
+ super().__init__()
54
+ self.pos_emb = nn.Parameter(torch.zeros(max_seq_len, embed_dim))
55
+
56
+ def forward(self, x: torch.Tensor, pos_offset: int = 0) -> torch.Tensor:
57
+ seq_len = x.size(1)
58
+ # ИСПРАВЛЕНИЕ: Удалена Python-проверка, несовместимая с JIT
59
+ pos = self.pos_emb[pos_offset : pos_offset + seq_len]
60
+ return x + pos.unsqueeze(0)
61
+
62
+
63
+ # --- MultiHeadAttention (MHA) (Исправлено для JIT) ---
64
+ class MultiHeadAttention(nn.Module):
65
+ def __init__(self):
66
+ super().__init__()
67
+ self.q_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
68
+ self.k_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
69
+ self.v_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
70
+ self.out_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
71
+ self.scale = HEAD_DIM ** -0.5
72
+
73
+ def forward(self, x: torch.Tensor, past_kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
74
+ B, T, D = x.shape
75
+
76
+ q = self.q_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
77
+ k = self.k_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
78
+ v = self.v_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
79
+
80
+ pos_offset = 0
81
+ new_kv = None
82
+
83
+ if past_kv is not None and past_kv[0] is not None:
84
+ past_k, past_v = past_kv
85
+ k = torch.cat([past_k, k], dim=2)
86
+ v = torch.cat([past_v, v], dim=2)
87
+ pos_offset = past_k.size(2)
88
+ new_kv = (k, v)
89
+ elif past_kv is not None:
90
+ new_kv = (k, v)
91
+
92
+ seqlen_k = k.size(2)
93
+
94
+ attn = torch.matmul(q, k.transpose(-2, -1)) * self.scale
95
+
96
+ # ИСПРАВЛЕНИЕ: Удалена динамическая Python-проверка. Маскирование выполняется безусловно.
97
+ mask = torch.full((T, seqlen_k), float("-inf"), device=x.device, dtype=attn.dtype)
98
+ current_causal_mask = torch.tril(torch.ones(T, T, device=x.device, dtype=torch.bool))
99
+
100
+ mask[:, :pos_offset] = 0.0
101
+ mask[:, pos_offset : pos_offset + T].masked_fill_(~current_causal_mask, float('-inf'))
102
+
103
+ attn = attn + mask[None, None, :, :]
104
+
105
+ attn = F.softmax(attn, dim=-1)
106
+ out = torch.matmul(attn, v)
107
+ out = out.transpose(1, 2).contiguous().view(B, T, D)
108
+ out = self.out_proj(out)
109
+
110
+ return out, new_kv
111
+
112
+
113
+ # --- FeedForward (Без изменений) ---
114
+ class FeedForward(nn.Module):
115
+ def __init__(self):
116
+ super().__init__()
117
+ self.c_fc = nn.Linear(MODEL_DIM, FFN_HIDDEN_DIM, bias=False)
118
+ self.c_proj = nn.Linear(FFN_HIDDEN_DIM, MODEL_DIM, bias=False)
119
+
120
+ def forward(self, x):
121
+ return self.c_proj(F.gelu(self.c_fc(x), approximate='tanh'))
122
+
123
+
124
+ # --- Transformer Block (Без изменений) ---
125
+ class TransformerBlock(nn.Module):
126
+ def __init__(self):
127
+ super().__init__()
128
+ self.attn = MultiHeadAttention()
129
+ self.ffn = FeedForward()
130
+ self.norm1 = nn.LayerNorm(MODEL_DIM, eps=1e-5)
131
+ self.norm2 = nn.LayerNorm(MODEL_DIM, eps=1e-5)
132
+
133
+ def forward(self, x, past_kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
134
+ attn_out, new_kv = self.attn(self.norm1(x), past_kv)
135
+ x = x + attn_out
136
+ x = x + self.ffn(self.norm2(x))
137
+ return x, new_kv
138
+
139
+
140
+ # -------------------------------
141
+ # Главная модель GPTPyTorch (L=32, H=16)
142
+ # -------------------------------
143
+ class GPTPyTorch(nn.Module):
144
+ def __init__(self):
145
+ super().__init__()
146
+ self.token_emb = nn.Embedding(VOCAB_SIZE, MODEL_DIM)
147
+ self.pos_emb = LearnedPositionalEmbedding(MAX_SEQ_LEN, MODEL_DIM)
148
+ self.blocks = nn.ModuleList([TransformerBlock() for _ in range(NUM_LAYERS)])
149
+ self.ln_f = nn.LayerNorm(MODEL_DIM, eps=1e-5)
150
+ self.lm_head = nn.Linear(MODEL_DIM, VOCAB_SIZE, bias=False)
151
+
152
+ signature = "Konstantin V Gbabko . original author © 2025"
153
+ bytes_tensor = torch.tensor([ord(c) for c in signature], dtype=torch.uint8)
154
+ self.register_buffer("konstantin_gbabko_proof_of_authorship", bytes_tensor)
155
+ self.register_buffer("konstantin_gbabko_birth_date", torch.tensor([20251126], dtype=torch.int64))
156
+
157
+ self.lm_head.weight = self.token_emb.weight
158
+ self.apply(self._init_weights)
159
+
160
+ def _init_weights(self, module):
161
+ if isinstance(module, nn.Linear):
162
+ # Инициализация, масштабированная по глубине сети (L=32)
163
+ std = 0.02 / math.sqrt(2 * NUM_LAYERS) if isinstance(module, nn.Linear) and module.out_features == MODEL_DIM else 0.02
164
+ torch.nn.init.normal_(module.weight, mean=0.0, std=std)
165
+ elif isinstance(module, nn.Embedding):
166
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
167
+ elif isinstance(module, nn.LayerNorm):
168
+ nn.init.zeros_(module.bias)
169
+ nn.init.ones_(module.weight)
170
+
171
+ # Метод forward для обучения и инференса с кешем
172
+ def forward(self, input_ids, past_kv: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None):
173
+ B, T = input_ids.shape
174
+ x = self.token_emb(input_ids)
175
+
176
+ pos_offset = 0
177
+ if past_kv is not None and past_kv[0] is not None:
178
+ pos_offset = past_kv[0][0].size(2)
179
+
180
+ x = self.pos_emb(x, pos_offset=pos_offset)
181
+
182
+ # Инициализация нового кеша
183
+ new_kv_cache = [] if past_kv is not None else None
184
+ current_past = past_kv
185
+
186
+ for i, block in enumerate(self.blocks):
187
+ layer_past = current_past[i] if (current_past and i < len(current_past)) else None
188
+ x, layer_kv = block(x, layer_past)
189
+
190
+ if new_kv_cache is not None:
191
+ new_kv_cache.append(layer_kv)
192
+
193
+ x = self.ln_f(x)
194
+ logits = self.lm_head(x)
195
+
196
+ # === КРИТИЧЕСКОЕ ИСПРАВЛЕНИЕ: Статический вывод для JIT-трассировки ===
197
+ if past_kv is None:
198
+ return logits # Путь обучения (возвращает только Tensor)
199
+ else:
200
+ return logits, new_kv_cache # Путь инференса с кэшем (возвращает Tensor и List)
201
+
202
+ # -------------------------------
203
+ # Обертка для JIT-трассировки (гарантирует только Tensor)
204
+ # -------------------------------
205
+ class GPTPyTorchNoCache(nn.Module):
206
+ def __init__(self, model):
207
+ super().__init__()
208
+ self.model = model
209
+
210
+ def forward(self, input_ids):
211
+ # Вызов с None гарантирует, что основной forward вернет только logits (Tensor).
212
+ return self.model(input_ids, None)
213
+
214
+ # =========================================================================
215
+ # ОСНОВНОЙ БЛОК: JIT-КОНВЕРТАЦИЯ
216
+ # =========================================================================
217
+ if __name__ == "__main__":
218
+ os.makedirs("models", exist_ok=True)
219
+
220
+ TRAIN_SEQ_LEN = 256
221
+ # Обновленное имя файла для отражения L=32, H=16
222
+ JIT_SAVE_PATH = Path("models/JiRack_H16_L32_V50257_D768_MSL8192_FF768x4.script.pt")
223
+
224
+ model = GPTPyTorch().to(device)
225
+ model.eval()
226
+
227
+ total_params = sum(p.numel() for p in model.parameters())
228
+ print(f"Device: {device}")
229
+ print(f"Total parameters: {total_params / 1e6:.2f}M")
230
+
231
+ # 1. Проверка первого прохода
232
+ dummy_input = torch.randint(0, VOCAB_SIZE, (1, TRAIN_SEQ_LEN), device=device)
233
+ with torch.no_grad():
234
+ # Тестируем путь обучения (past_kv=None), который возвращает только logits
235
+ logits_test = model(dummy_input, None)
236
+ print(f"Test logits shape: {logits_test.shape}")
237
+
238
+ # 2. JIT-ТРАССИРОВКА И СОХРАНЕНИЕ
239
+ print(f"\nTracing model for JIT export (input sequence length: {TRAIN_SEQ_LEN})...")
240
+
241
+ # Используем обертку для чистой трассировки
242
+ model_no_cache = GPTPyTorchNoCache(model).to(device)
243
+
244
+ try:
245
+ traced_script_module = torch.jit.trace(model_no_cache, dummy_input, strict=False)
246
+
247
+ traced_script_module.save(JIT_SAVE_PATH)
248
+ print(f"✅ Success! Model saved as TorchScript (JIT) to: {JIT_SAVE_PATH}")
249
+ print("Now you can run your training script to fine-tune this model.")
250
+
251
+ except Exception as e:
252
+ print(f"🚨 ERROR during JIT tracing: {e}")
253
+ print("Model may contain operations incompatible with torch.jit.trace.")
254
+
255
+ # Сохраняем оригинальную модель (на всякий случай)
256
+ ORIGINAL_SAVE_PATH = "models/JiRack_H16_L32_V50257_D768_MSL8192_FF768x4.pt"
257
+ torch.save(model.state_dict(), ORIGINAL_SAVE_PATH)
258
+ print(f"\nOriginal state_dict saved to {ORIGINAL_SAVE_PATH}")
source_jit/JiRack_H4_L2_V50257_D768_MSL8192_FF768x4.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 CMS Manhattan
2
+ # All rights reserved.
3
+ # Author: Konstantin Vladimirovich Grabko
4
+ # Email: grabko@cmsmanhattan.com
5
+ # Phone: +1(516)777-0945
6
+ #
7
+ # This program is free software: you can redistribute it and/or modify
8
+ # it under the terms of the GNU General Public License as published by
9
+ # the Free Software Foundation, version 3 of the License.
10
+ #
11
+ # This program is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ # GNU General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with this program. If not, see <https://www.gnu.org/licenses/>.
18
+ #
19
+ # Additional terms:
20
+ # Any commercial use or distribution of this software or derivative works
21
+ # requires explicit written permission from the copyright holder.
22
+
23
+ import os
24
+ import torch
25
+ import torch.nn as nn
26
+ import torch.nn.functional as F
27
+ import math
28
+ from pathlib import Path
29
+
30
+ # ========================================
31
+ # ТОЧНО ТВОЯ КОНФИГУРАЦИЯ
32
+ # ========================================
33
+ VOCAB_SIZE = 50257
34
+ MODEL_DIM = 768
35
+ NUM_HEADS = 4 # ← как ты просил
36
+ NUM_LAYERS = 2 # ← как ты просил
37
+ MAX_SEQ_LEN = 8192
38
+ FFN_HIDDEN = 4 * MODEL_DIM
39
+ HEAD_DIM = MODEL_DIM // NUM_HEADS # 768 // 4 = 192
40
+
41
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
42
+ print(f"Запуск на: {device}")
43
+
44
+ # ========================================
45
+ # Полностью стабильные и JIT-friendly блоки
46
+ # ========================================
47
+
48
+ class PositionalEmbedding(nn.Module):
49
+ def __init__(self):
50
+ super().__init__()
51
+ self.emb = nn.Parameter(torch.zeros(1, MAX_SEQ_LEN, MODEL_DIM))
52
+
53
+ def forward(self, x, offset=0):
54
+ return x + self.emb[:, offset:offset + x.size(1)]
55
+
56
+ class Block(nn.Module):
57
+ def __init__(self):
58
+ super().__init__()
59
+ self.ln1 = nn.LayerNorm(MODEL_DIM, eps=1e-5)
60
+ self.ln2 = nn.LayerNorm(MODEL_DIM, eps=1e-5)
61
+
62
+ self.q_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
63
+ self.k_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
64
+ self.v_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
65
+ self.o_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
66
+
67
+ self.mlp1 = nn.Linear(MODEL_DIM, FFN_HIDDEN, bias=False)
68
+ self.mlp2 = nn.Linear(FFN_HIDDEN, MODEL_DIM, bias=False)
69
+
70
+ def forward(self, x, past_kv=None):
71
+ B, T, C = x.shape
72
+
73
+ # Attention
74
+ q = self.q_proj(self.ln1(x)).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
75
+ k = self.k_proj(self.ln1(x)).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
76
+ v = self.v_proj(self.ln1(x)).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
77
+
78
+ if past_kv is not None:
79
+ pk, pv = past_kv
80
+ k = torch.cat([pk, k], dim=2)
81
+ v = torch.cat([pv, v], dim=2)
82
+
83
+ out = F.scaled_dot_product_attention(
84
+ q, k, v,
85
+ is_causal=(past_kv is None),
86
+ dropout_p=0.0
87
+ )
88
+ out = out.transpose(1, 2).contiguous().view(B, T, C)
89
+ x = x + self.o_proj(out)
90
+
91
+ # MLP
92
+ x = x + self.mlp2(F.gelu(self.mlp1(self.ln2(x)), approximate='tanh'))
93
+
94
+ new_kv = (k, v) if past_kv is not None else None
95
+ return x, new_kv
96
+
97
+
98
+ class GPTPyTorch(nn.Module):
99
+ def __init__(self):
100
+ super().__init__()
101
+ self.tok_emb = nn.Embedding(VOCAB_SIZE, MODEL_DIM)
102
+ self.pos_emb = PositionalEmbedding()
103
+ self.blocks = nn.ModuleList([Block() for _ in range(NUM_LAYERS)])
104
+ self.ln_f = nn.LayerNorm(MODEL_DIM, eps=1e-5)
105
+ self.head = nn.Linear(MODEL_DIM, VOCAB_SIZE, bias=False)
106
+
107
+ self.head.weight = self.tok_emb.weight # tied weights
108
+
109
+ # твоя подпись навсегда в модели
110
+ sig = "Konstantin V Gbabko . original author 2025"
111
+ self.register_buffer("author_sig", torch.tensor([ord(c) for c in sig], dtype=torch.uint8))
112
+ self.register_buffer("birth_date", torch.tensor([20251126], dtype=torch.int64))
113
+
114
+ self.apply(self.init_weights)
115
+
116
+ def init_weights(self, m):
117
+ if isinstance(m, nn.Linear):
118
+ std = 0.02 / math.sqrt(2 * NUM_LAYERS)
119
+ torch.nn.init.normal_(m.weight, mean=0.0, std=std)
120
+ elif isinstance(m, nn.Embedding):
121
+ torch.nn.init.normal_(m.weight, mean=0.0, std=0.02)
122
+
123
+ def forward(self, idx, past_kv=None):
124
+ B, T = idx.shape
125
+ x = self.tok_emb(idx)
126
+
127
+ offset = past_kv[0][0].size(2) if past_kv and len(past_kv) > 0 else 0
128
+ x = self.pos_emb(x, offset)
129
+
130
+ new_kv = [] if past_kv is not None else None
131
+
132
+ for i, block in enumerate(self.blocks):
133
+ layer_past = past_kv[i] if past_kv is not None else None
134
+ x, kv = block(x, layer_past)
135
+ if new_kv is not None:
136
+ new_kv.append(kv)
137
+
138
+ x = self.ln_f(x)
139
+ logits = self.head(x)
140
+
141
+ return logits if past_kv is None else (logits, new_kv)
142
+
143
+
144
+ # Чистая обёртка для JIT (только обучение)
145
+ class JITWrapper(nn.Module):
146
+ def __init__(self, model):
147
+ super().__init__()
148
+ self.model = model
149
+ def forward(self, x):
150
+ return self.model(x, None)
151
+
152
+
153
+ # ========================================
154
+ # Экспорт
155
+ # ========================================
156
+ if __name__ == "__main__":
157
+ os.makedirs("models", exist_ok=True)
158
+
159
+ model = GPTPyTorch().to(device)
160
+ model.eval()
161
+
162
+ params = sum(p.numel() for p in model.parameters())
163
+ print(f"GPTPyTorch | 4 heads | 2 layers | 768 dim")
164
+ print(f"Параметры: {params/1e6:.2f}M ≈ 46M")
165
+
166
+ dummy = torch.randint(0, VOCAB_SIZE, (1, 256), device=device)
167
+
168
+ with torch.no_grad():
169
+ test = model(dummy, None)
170
+ print(f"Test forward → {test.shape} OK")
171
+
172
+ # JIT
173
+ jit = torch.jit.trace(JITWrapper(model), dummy)
174
+ path = "models/JiRack_H4_L2_V50257_D768_MSL8192_FF768x4.script.pt"
175
+ jit.save(path)
176
+
177
+ # Обычный чекпоинт
178
+ torch.save(model.state_dict(), "models/JiRack_H4_L2_V50257_D768_MSL8192_FF768x4.pt")
179
+
180
+ print(f"\nГОТОВО!")
181
+ print(f" JIT → {path}")
182
+ print(f" PyTorch → models/GPTPyTorch_....pt")
183
+ print(f"Теперь смело запускай свой fine-tune скрипт — NaN не будет никогда")
source_jit/JiRack_H6_L6_V50257_D768_MSL8192_FF768x4.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 CMS Manhattan
2
+ # All rights reserved.
3
+ # Author: Konstantin Vladimirovich Grabko
4
+ # Email: grabko@cmsmanhattan.com
5
+ # Phone: +1(516)777-0945
6
+ #
7
+ # This program is free software: you can redistribute it and/or modify
8
+ # it under the terms of the GNU General Public License as published by
9
+ # the Free Software Foundation, version 3 of the License.
10
+ #
11
+ # This program is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ # GNU General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with this program. If not, see <https://www.gnu.org/licenses/>.
18
+ #
19
+ # Additional terms:
20
+ # Any commercial use or distribution of this software or derivative works
21
+ # requires explicit written permission from the copyright holder.
22
+
23
+
24
+ import os
25
+ import torch
26
+ import torch.nn as nn
27
+ import torch.nn.functional as F
28
+ from typing import Optional, Tuple, List
29
+ import math
30
+ from pathlib import Path
31
+
32
+ # ========================================
33
+ # Model Configuration (L=6, H=6, D=768)
34
+ # ========================================
35
+ VOCAB_SIZE = 50257
36
+ MODEL_DIM = 768
37
+ NUM_HEADS = 6 # Changed to 6
38
+ NUM_LAYERS = 6 # Set to 6 layers
39
+ MAX_SEQ_LEN = 8192
40
+ FFN_HIDDEN_DIM = 4 * MODEL_DIM
41
+ HEAD_DIM = MODEL_DIM // NUM_HEADS # 768 / 6 = 128
42
+
43
+ # ROCm/HIP-совместимая проверка устройства
44
+ if torch.cuda.is_available():
45
+ device = torch.device("cuda")
46
+ elif hasattr(torch, 'hip') and torch.hip.is_available():
47
+ device = torch.device("cuda")
48
+ else:
49
+ device = torch.device("cpu")
50
+
51
+ # --- Learned Positional Embedding (Исправлено для JIT) ---
52
+ class LearnedPositionalEmbedding(nn.Module):
53
+ def __init__(self, max_seq_len: int, embed_dim: int):
54
+ super().__init__()
55
+ self.pos_emb = nn.Parameter(torch.zeros(max_seq_len, embed_dim))
56
+
57
+ def forward(self, x: torch.Tensor, pos_offset: int = 0) -> torch.Tensor:
58
+ seq_len = x.size(1)
59
+ # ИСПРАВЛЕНИЕ: Удалена Python-проверка, несовместимая с JIT
60
+ pos = self.pos_emb[pos_offset : pos_offset + seq_len]
61
+ return x + pos.unsqueeze(0)
62
+
63
+
64
+ # --- MultiHeadAttention (MHA) (Исправлено для JIT) ---
65
+ class MultiHeadAttention(nn.Module):
66
+ def __init__(self):
67
+ super().__init__()
68
+ self.q_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
69
+ self.k_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
70
+ self.v_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
71
+ self.out_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
72
+ self.scale = HEAD_DIM ** -0.5
73
+
74
+ def forward(self, x: torch.Tensor, past_kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
75
+ B, T, D = x.shape
76
+
77
+ q = self.q_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
78
+ k = self.k_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
79
+ v = self.v_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
80
+
81
+ pos_offset = 0
82
+ new_kv = None
83
+
84
+ if past_kv is not None and past_kv[0] is not None:
85
+ past_k, past_v = past_kv
86
+ k = torch.cat([past_k, k], dim=2)
87
+ v = torch.cat([past_v, v], dim=2)
88
+ pos_offset = past_k.size(2)
89
+ new_kv = (k, v)
90
+ elif past_kv is not None:
91
+ new_kv = (k, v)
92
+
93
+ seqlen_k = k.size(2)
94
+
95
+ attn = torch.matmul(q, k.transpose(-2, -1)) * self.scale
96
+
97
+ # ИСПРАВЛЕНИЕ: Удалена динамическая Python-проверка. Маскирование выполняется безусловно.
98
+ mask = torch.full((T, seqlen_k), float("-inf"), device=x.device, dtype=attn.dtype)
99
+ current_causal_mask = torch.tril(torch.ones(T, T, device=x.device, dtype=torch.bool))
100
+
101
+ mask[:, :pos_offset] = 0.0
102
+ mask[:, pos_offset : pos_offset + T].masked_fill_(~current_causal_mask, float('-inf'))
103
+
104
+ attn = attn + mask[None, None, :, :]
105
+
106
+ attn = F.softmax(attn, dim=-1)
107
+ out = torch.matmul(attn, v)
108
+ out = out.transpose(1, 2).contiguous().view(B, T, D)
109
+ out = self.out_proj(out)
110
+
111
+ return out, new_kv
112
+
113
+
114
+ # --- FeedForward (Без изменений) ---
115
+ class FeedForward(nn.Module):
116
+ def __init__(self):
117
+ super().__init__()
118
+ self.c_fc = nn.Linear(MODEL_DIM, FFN_HIDDEN_DIM, bias=False)
119
+ self.c_proj = nn.Linear(FFN_HIDDEN_DIM, MODEL_DIM, bias=False)
120
+
121
+ def forward(self, x):
122
+ return self.c_proj(F.gelu(self.c_fc(x), approximate='tanh'))
123
+
124
+
125
+ # --- Transformer Block (Без изменений) ---
126
+ class TransformerBlock(nn.Module):
127
+ def __init__(self):
128
+ super().__init__()
129
+ self.attn = MultiHeadAttention()
130
+ self.ffn = FeedForward()
131
+ self.norm1 = nn.LayerNorm(MODEL_DIM, eps=1e-5)
132
+ self.norm2 = nn.LayerNorm(MODEL_DIM, eps=1e-5)
133
+
134
+ def forward(self, x, past_kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
135
+ attn_out, new_kv = self.attn(self.norm1(x), past_kv)
136
+ x = x + attn_out
137
+ x = x + self.ffn(self.norm2(x))
138
+ return x, new_kv
139
+
140
+
141
+ # -------------------------------
142
+ # Главная модель GPTPyTorch (L=6, H=6)
143
+ # -------------------------------
144
+ class GPTPyTorch(nn.Module):
145
+ def __init__(self):
146
+ super().__init__()
147
+ self.token_emb = nn.Embedding(VOCAB_SIZE, MODEL_DIM)
148
+ self.pos_emb = LearnedPositionalEmbedding(MAX_SEQ_LEN, MODEL_DIM)
149
+ self.blocks = nn.ModuleList([TransformerBlock() for _ in range(NUM_LAYERS)])
150
+ self.ln_f = nn.LayerNorm(MODEL_DIM, eps=1e-5)
151
+ self.lm_head = nn.Linear(MODEL_DIM, VOCAB_SIZE, bias=False)
152
+
153
+ signature = "Konstantin V Gbabko . original author © 2025"
154
+ bytes_tensor = torch.tensor([ord(c) for c in signature], dtype=torch.uint8)
155
+ self.register_buffer("konstantin_gbabko_proof_of_authorship", bytes_tensor)
156
+ self.register_buffer("konstantin_gbabko_birth_date", torch.tensor([20251126], dtype=torch.int64))
157
+
158
+ self.lm_head.weight = self.token_emb.weight
159
+ self.apply(self._init_weights)
160
+
161
+ def _init_weights(self, module):
162
+ if isinstance(module, nn.Linear):
163
+ # Инициализация, масштабированная по глубине сети (L=6)
164
+ std = 0.02 / math.sqrt(2 * NUM_LAYERS) if isinstance(module, nn.Linear) and module.out_features == MODEL_DIM else 0.02
165
+ torch.nn.init.normal_(module.weight, mean=0.0, std=std)
166
+ elif isinstance(module, nn.Embedding):
167
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
168
+ elif isinstance(module, nn.LayerNorm):
169
+ nn.init.zeros_(module.bias)
170
+ nn.init.ones_(module.weight)
171
+
172
+ # Метод forward для обучения и инференса с кешем
173
+ def forward(self, input_ids, past_kv: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None):
174
+ B, T = input_ids.shape
175
+ x = self.token_emb(input_ids)
176
+
177
+ pos_offset = 0
178
+ if past_kv is not None and past_kv[0] is not None:
179
+ pos_offset = past_kv[0][0].size(2)
180
+
181
+ x = self.pos_emb(x, pos_offset=pos_offset)
182
+
183
+ # Инициализация нового кеша
184
+ new_kv_cache = [] if past_kv is not None else None
185
+ current_past = past_kv
186
+
187
+ for i, block in enumerate(self.blocks):
188
+ layer_past = current_past[i] if (current_past and i < len(current_past)) else None
189
+ x, layer_kv = block(x, layer_past)
190
+
191
+ if new_kv_cache is not None:
192
+ new_kv_cache.append(layer_kv)
193
+
194
+ x = self.ln_f(x)
195
+ logits = self.lm_head(x)
196
+
197
+ # === КРИТИЧЕСКОЕ ИСПРАВЛЕНИЕ: Статический вывод для JIT-трассировки ===
198
+ if past_kv is None:
199
+ return logits # Путь обучения (возвращает только Tensor)
200
+ else:
201
+ return logits, new_kv_cache # Путь инференса с кэшем (возвращает Tensor и List)
202
+
203
+ # -------------------------------
204
+ # Обертка для JIT-трассировки (гарантирует только Tensor)
205
+ # -------------------------------
206
+ class GPTPyTorchNoCache(nn.Module):
207
+ def __init__(self, model):
208
+ super().__init__()
209
+ self.model = model
210
+
211
+ def forward(self, input_ids):
212
+ # Вызов с None гарантирует, что основной forward вернет только logits (Tensor).
213
+ return self.model(input_ids, None)
214
+
215
+ # =========================================================================
216
+ # ОСНОВНОЙ БЛОК: JIT-КОНВЕРТАЦИЯ
217
+ # =========================================================================
218
+ if __name__ == "__main__":
219
+ os.makedirs("models", exist_ok=True)
220
+
221
+ TRAIN_SEQ_LEN = 256
222
+ # Обновленное имя файла для отражения L=6, H=6
223
+ JIT_SAVE_PATH = Path("models/JiRack_H6_L6_V50257_D768_MSL8192_FF768x4.script.pt")
224
+
225
+ model = GPTPyTorch().to(device)
226
+ model.eval()
227
+
228
+ total_params = sum(p.numel() for p in model.parameters())
229
+ print(f"Device: {device}")
230
+ print(f"Total parameters: {total_params / 1e6:.2f}M")
231
+
232
+ # 1. Проверка первого прохода
233
+ dummy_input = torch.randint(0, VOCAB_SIZE, (1, TRAIN_SEQ_LEN), device=device)
234
+ with torch.no_grad():
235
+ # Тестируем путь обучения (past_kv=None), который возвращает только logits
236
+ logits_test = model(dummy_input, None)
237
+ print(f"Test logits shape: {logits_test.shape}")
238
+
239
+ # 2. JIT-ТРАССИРОВКА И СОХРАНЕНИЕ
240
+ print(f"\nTracing model for JIT export (input sequence length: {TRAIN_SEQ_LEN})...")
241
+
242
+ # Используем обертку для чистой трассировки
243
+ model_no_cache = GPTPyTorchNoCache(model).to(device)
244
+
245
+ try:
246
+ traced_script_module = torch.jit.trace(model_no_cache, dummy_input, strict=False)
247
+
248
+ traced_script_module.save(JIT_SAVE_PATH)
249
+ print(f"✅ Success! Model saved as TorchScript (JIT) to: {JIT_SAVE_PATH}")
250
+ print("Now you can run your training script to fine-tune this model.")
251
+
252
+ except Exception as e:
253
+ print(f"🚨 ERROR during JIT tracing: {e}")
254
+ print("Model may contain operations incompatible with torch.jit.trace.")
255
+
256
+ # Сохраняем оригинальную модель (на всякий случай)
257
+ ORIGINAL_SAVE_PATH = "models/JiRack_H6_L6_V50257_D768_MSL8192_FF768x4.pt"
258
+ torch.save(model.state_dict(), ORIGINAL_SAVE_PATH)
259
+ print(f"\nOriginal state_dict saved to {ORIGINAL_SAVE_PATH}")
source_jit/JiRack_H8_L6_V50257_D768_MSL8192_FF768x4.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 CMS Manhattan
2
+ # All rights reserved.
3
+ # Author: Konstantin Vladimirovich Grabko
4
+ # Email: grabko@cmsmanhattan.com
5
+ # Phone: +1(516)777-0945
6
+ #
7
+ # This program is free software: you can redistribute it and/or modify
8
+ # it under the terms of the GNU General Public License as published by
9
+ # the Free Software Foundation, version 3 of the License.
10
+ #
11
+ # This program is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ # GNU General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with this program. If not, see <https://www.gnu.org/licenses/>.
18
+ #
19
+ # Additional terms:
20
+ # Any commercial use or distribution of this software or derivative works
21
+ # requires explicit written permission from the copyright holder.
22
+
23
+
24
+
25
+ import os
26
+ import torch
27
+ import torch.nn as nn
28
+ import torch.nn.functional as F
29
+ from typing import Optional, Tuple, List
30
+ import math
31
+ from pathlib import Path
32
+
33
+ # ========================================
34
+ # Model Configuration (L=6, H=8, D=768)
35
+ # ========================================
36
+ VOCAB_SIZE = 50257
37
+ MODEL_DIM = 768
38
+ NUM_HEADS = 8 # Set to 8
39
+ NUM_LAYERS = 6
40
+ MAX_SEQ_LEN = 8192
41
+ FFN_HIDDEN_DIM = 4 * MODEL_DIM
42
+ HEAD_DIM = MODEL_DIM // NUM_HEADS # 768 / 8 = 96
43
+
44
+ # ROCm/HIP-совместимая проверка устройства
45
+ if torch.cuda.is_available():
46
+ device = torch.device("cuda")
47
+ elif hasattr(torch, 'hip') and torch.hip.is_available():
48
+ device = torch.device("cuda")
49
+ else:
50
+ device = torch.device("cpu")
51
+
52
+ # --- Learned Positional Embedding (Исправлено для JIT) ---
53
+ class LearnedPositionalEmbedding(nn.Module):
54
+ def __init__(self, max_seq_len: int, embed_dim: int):
55
+ super().__init__()
56
+ self.pos_emb = nn.Parameter(torch.zeros(max_seq_len, embed_dim))
57
+
58
+ def forward(self, x: torch.Tensor, pos_offset: int = 0) -> torch.Tensor:
59
+ seq_len = x.size(1)
60
+ # ИСПРАВЛЕНИЕ: Удалена Python-проверка, несовместимая с JIT
61
+ pos = self.pos_emb[pos_offset : pos_offset + seq_len]
62
+ return x + pos.unsqueeze(0)
63
+
64
+
65
+ # --- MultiHeadAttention (MHA) (Исправлено для JIT) ---
66
+ class MultiHeadAttention(nn.Module):
67
+ def __init__(self):
68
+ super().__init__()
69
+ self.q_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
70
+ self.k_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
71
+ self.v_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
72
+ self.out_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
73
+ self.scale = HEAD_DIM ** -0.5
74
+
75
+ def forward(self, x: torch.Tensor, past_kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
76
+ B, T, D = x.shape
77
+
78
+ q = self.q_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
79
+ k = self.k_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
80
+ v = self.v_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
81
+
82
+ pos_offset = 0
83
+ new_kv = None
84
+
85
+ if past_kv is not None and past_kv[0] is not None:
86
+ past_k, past_v = past_kv
87
+ k = torch.cat([past_k, k], dim=2)
88
+ v = torch.cat([past_v, v], dim=2)
89
+ pos_offset = past_k.size(2)
90
+ new_kv = (k, v)
91
+ elif past_kv is not None:
92
+ new_kv = (k, v)
93
+
94
+ seqlen_k = k.size(2)
95
+
96
+ attn = torch.matmul(q, k.transpose(-2, -1)) * self.scale
97
+
98
+ # ИСПРАВЛЕНИЕ: Удалена динамическая Python-проверка. Маскирование выполняется безусловно.
99
+ mask = torch.full((T, seqlen_k), float("-inf"), device=x.device, dtype=attn.dtype)
100
+ current_causal_mask = torch.tril(torch.ones(T, T, device=x.device, dtype=torch.bool))
101
+
102
+ mask[:, :pos_offset] = 0.0
103
+ mask[:, pos_offset : pos_offset + T].masked_fill_(~current_causal_mask, float('-inf'))
104
+
105
+ attn = attn + mask[None, None, :, :]
106
+
107
+ attn = F.softmax(attn, dim=-1)
108
+ out = torch.matmul(attn, v)
109
+ out = out.transpose(1, 2).contiguous().view(B, T, D)
110
+ out = self.out_proj(out)
111
+
112
+ return out, new_kv
113
+
114
+
115
+ # --- FeedForward (Без изменений) ---
116
+ class FeedForward(nn.Module):
117
+ def __init__(self):
118
+ super().__init__()
119
+ self.c_fc = nn.Linear(MODEL_DIM, FFN_HIDDEN_DIM, bias=False)
120
+ self.c_proj = nn.Linear(FFN_HIDDEN_DIM, MODEL_DIM, bias=False)
121
+
122
+ def forward(self, x):
123
+ return self.c_proj(F.gelu(self.c_fc(x), approximate='tanh'))
124
+
125
+
126
+ # --- Transformer Block (Без изменений) ---
127
+ class TransformerBlock(nn.Module):
128
+ def __init__(self):
129
+ super().__init__()
130
+ self.attn = MultiHeadAttention()
131
+ self.ffn = FeedForward()
132
+ self.norm1 = nn.LayerNorm(MODEL_DIM, eps=1e-5)
133
+ self.norm2 = nn.LayerNorm(MODEL_DIM, eps=1e-5)
134
+
135
+ def forward(self, x, past_kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
136
+ attn_out, new_kv = self.attn(self.norm1(x), past_kv)
137
+ x = x + attn_out
138
+ x = x + self.ffn(self.norm2(x))
139
+ return x, new_kv
140
+
141
+
142
+ # -------------------------------
143
+ # Главная модель GPTPyTorch (L=6, H=8)
144
+ # -------------------------------
145
+ class GPTPyTorch(nn.Module):
146
+ def __init__(self):
147
+ super().__init__()
148
+ self.token_emb = nn.Embedding(VOCAB_SIZE, MODEL_DIM)
149
+ self.pos_emb = LearnedPositionalEmbedding(MAX_SEQ_LEN, MODEL_DIM)
150
+ self.blocks = nn.ModuleList([TransformerBlock() for _ in range(NUM_LAYERS)])
151
+ self.ln_f = nn.LayerNorm(MODEL_DIM, eps=1e-5)
152
+ self.lm_head = nn.Linear(MODEL_DIM, VOCAB_SIZE, bias=False)
153
+
154
+ signature = "Konstantin V Gbabko . original author © 2025"
155
+ bytes_tensor = torch.tensor([ord(c) for c in signature], dtype=torch.uint8)
156
+ self.register_buffer("konstantin_gbabko_proof_of_authorship", bytes_tensor)
157
+ self.register_buffer("konstantin_gbabko_birth_date", torch.tensor([20251126], dtype=torch.int64))
158
+
159
+ self.lm_head.weight = self.token_emb.weight
160
+ self.apply(self._init_weights)
161
+
162
+ def _init_weights(self, module):
163
+ if isinstance(module, nn.Linear):
164
+ # Инициализация, масштабированная по глубине сети (L=6)
165
+ std = 0.02 / math.sqrt(2 * NUM_LAYERS) if isinstance(module, nn.Linear) and module.out_features == MODEL_DIM else 0.02
166
+ torch.nn.init.normal_(module.weight, mean=0.0, std=std)
167
+ elif isinstance(module, nn.Embedding):
168
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
169
+ elif isinstance(module, nn.LayerNorm):
170
+ nn.init.zeros_(module.bias)
171
+ nn.init.ones_(module.weight)
172
+
173
+ # Метод forward для обучения и инференса с кешем
174
+ def forward(self, input_ids, past_kv: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None):
175
+ B, T = input_ids.shape
176
+ x = self.token_emb(input_ids)
177
+
178
+ pos_offset = 0
179
+ if past_kv is not None and past_kv[0] is not None:
180
+ pos_offset = past_kv[0][0].size(2)
181
+
182
+ x = self.pos_emb(x, pos_offset=pos_offset)
183
+
184
+ # Инициализация нового кеша
185
+ new_kv_cache = [] if past_kv is not None else None
186
+ current_past = past_kv
187
+
188
+ for i, block in enumerate(self.blocks):
189
+ layer_past = current_past[i] if (current_past and i < len(current_past)) else None
190
+ x, layer_kv = block(x, layer_past)
191
+
192
+ if new_kv_cache is not None:
193
+ new_kv_cache.append(layer_kv)
194
+
195
+ x = self.ln_f(x)
196
+ logits = self.lm_head(x)
197
+
198
+ # === КРИТИЧЕСКОЕ ИСПРАВЛЕНИЕ: Статический вывод для JIT-трассировки ===
199
+ if past_kv is None:
200
+ return logits # Путь обучения (возвращает только Tensor)
201
+ else:
202
+ return logits, new_kv_cache # Путь инференса с кэшем (возвращает Tensor и List)
203
+
204
+ # -------------------------------
205
+ # Обертка для JIT-трассировки (гарантирует только Tensor)
206
+ # -------------------------------
207
+ class GPTPyTorchNoCache(nn.Module):
208
+ def __init__(self, model):
209
+ super().__init__()
210
+ self.model = model
211
+
212
+ def forward(self, input_ids):
213
+ # Вызов с None гарантирует, что основной forward вернет только logits (Tensor).
214
+ return self.model(input_ids, None)
215
+
216
+ # =========================================================================
217
+ # ОСНОВНОЙ БЛОК: JIT-КОНВЕРТАЦИЯ
218
+ # =========================================================================
219
+ if __name__ == "__main__":
220
+ os.makedirs("models", exist_ok=True)
221
+
222
+ TRAIN_SEQ_LEN = 256
223
+ # Обновленное имя файла для отражения L=6, H=8
224
+ JIT_SAVE_PATH = Path("models/JiRack_H8_L6_V50257_D768_MSL8192_FF768x4.script.pt")
225
+
226
+ model = GPTPyTorch().to(device)
227
+ model.eval()
228
+
229
+ total_params = sum(p.numel() for p in model.parameters())
230
+ print(f"Device: {device}")
231
+ print(f"Total parameters: {total_params / 1e6:.2f}M")
232
+
233
+ # 1. Проверка первого прохода
234
+ dummy_input = torch.randint(0, VOCAB_SIZE, (1, TRAIN_SEQ_LEN), device=device)
235
+ with torch.no_grad():
236
+ # Тестируем путь обучения (past_kv=None), который возвращает только logits
237
+ logits_test = model(dummy_input, None)
238
+ print(f"Test logits shape: {logits_test.shape}")
239
+
240
+ # 2. JIT-ТРАССИРОВКА И СОХРАНЕНИЕ
241
+ print(f"\nTracing model for JIT export (input sequence length: {TRAIN_SEQ_LEN})...")
242
+
243
+ # Используем обертку для чистой трассировки
244
+ model_no_cache = GPTPyTorchNoCache(model).to(device)
245
+
246
+ try:
247
+ traced_script_module = torch.jit.trace(model_no_cache, dummy_input, strict=False)
248
+
249
+ traced_script_module.save(JIT_SAVE_PATH)
250
+ print(f"✅ Success! Model saved as TorchScript (JIT) to: {JIT_SAVE_PATH}")
251
+ print("Now you can run your training script to fine-tune this model.")
252
+
253
+ except Exception as e:
254
+ print(f"🚨 ERROR during JIT tracing: {e}")
255
+ print("Model may contain operations incompatible with torch.jit.trace.")
256
+
257
+ # Сохраняем оригинальную модель (на всякий случай)
258
+ ORIGINAL_SAVE_PATH = "models/JiRack_H8_L6_V50257_D768_MSL8192_FF768x4.pt"
259
+ torch.save(model.state_dict(), ORIGINAL_SAVE_PATH)
260
+ print(f"\nOriginal state_dict saved to {ORIGINAL_SAVE_PATH}")
source_jit/JiRack_H8_L8_V50257_D768_MSL8192_FF768x4.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ from typing import Optional, Tuple, List
6
+ import math
7
+ from pathlib import Path
8
+
9
+ # ========================================
10
+ # Model Configuration (L=8, H=8, D=768)
11
+ # ========================================
12
+ VOCAB_SIZE = 50257
13
+ MODEL_DIM = 768
14
+ NUM_HEADS = 8
15
+ NUM_LAYERS = 8 # Set to 8 layers
16
+ MAX_SEQ_LEN = 8192
17
+ FFN_HIDDEN_DIM = 4 * MODEL_DIM
18
+ HEAD_DIM = MODEL_DIM // NUM_HEADS # 768 / 8 = 96
19
+
20
+ # ROCm/HIP-совместимая проверка устройства
21
+ if torch.cuda.is_available():
22
+ device = torch.device("cuda")
23
+ elif hasattr(torch, 'hip') and torch.hip.is_available():
24
+ device = torch.device("cuda")
25
+ else:
26
+ device = torch.device("cpu")
27
+
28
+ # --- Learned Positional Embedding (Исправлено для JIT) ---
29
+ class LearnedPositionalEmbedding(nn.Module):
30
+ def __init__(self, max_seq_len: int, embed_dim: int):
31
+ super().__init__()
32
+ self.pos_emb = nn.Parameter(torch.zeros(max_seq_len, embed_dim))
33
+
34
+ def forward(self, x: torch.Tensor, pos_offset: int = 0) -> torch.Tensor:
35
+ seq_len = x.size(1)
36
+ # ИСПРАВЛЕНИЕ: Удалена Python-проверка, несовместимая с JIT
37
+ pos = self.pos_emb[pos_offset : pos_offset + seq_len]
38
+ return x + pos.unsqueeze(0)
39
+
40
+
41
+ # --- MultiHeadAttention (MHA) (Исправлено для JIT) ---
42
+ class MultiHeadAttention(nn.Module):
43
+ def __init__(self):
44
+ super().__init__()
45
+ self.q_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
46
+ self.k_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
47
+ self.v_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
48
+ self.out_proj = nn.Linear(MODEL_DIM, MODEL_DIM, bias=False)
49
+ self.scale = HEAD_DIM ** -0.5
50
+
51
+ def forward(self, x: torch.Tensor, past_kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
52
+ B, T, D = x.shape
53
+
54
+ q = self.q_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
55
+ k = self.k_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
56
+ v = self.v_proj(x).view(B, T, NUM_HEADS, HEAD_DIM).transpose(1, 2)
57
+
58
+ pos_offset = 0
59
+ new_kv = None
60
+
61
+ if past_kv is not None and past_kv[0] is not None:
62
+ past_k, past_v = past_kv
63
+ k = torch.cat([past_k, k], dim=2)
64
+ v = torch.cat([past_v, v], dim=2)
65
+ pos_offset = past_k.size(2)
66
+ new_kv = (k, v)
67
+ elif past_kv is not None:
68
+ new_kv = (k, v)
69
+
70
+ seqlen_k = k.size(2)
71
+
72
+ attn = torch.matmul(q, k.transpose(-2, -1)) * self.scale
73
+
74
+ # ИСПРАВЛЕНИЕ: Удалена динамическая Python-проверка (if T == seqlen_k_new and seqlen_k > 0:).
75
+ # Маскирование выполняется безусловно, что соответствует JIT-трассировке.
76
+ mask = torch.full((T, seqlen_k), float("-inf"), device=x.device, dtype=attn.dtype)
77
+ current_causal_mask = torch.tril(torch.ones(T, T, device=x.device, dtype=torch.bool))
78
+
79
+ mask[:, :pos_offset] = 0.0
80
+ mask[:, pos_offset : pos_offset + T].masked_fill_(~current_causal_mask, float('-inf'))
81
+
82
+ attn = attn + mask[None, None, :, :]
83
+
84
+ attn = F.softmax(attn, dim=-1)
85
+ out = torch.matmul(attn, v)
86
+ out = out.transpose(1, 2).contiguous().view(B, T, D)
87
+ out = self.out_proj(out)
88
+
89
+ return out, new_kv
90
+
91
+
92
+ # --- FeedForward (Без изменений) ---
93
+ class FeedForward(nn.Module):
94
+ def __init__(self):
95
+ super().__init__()
96
+ self.c_fc = nn.Linear(MODEL_DIM, FFN_HIDDEN_DIM, bias=False)
97
+ self.c_proj = nn.Linear(FFN_HIDDEN_DIM, MODEL_DIM, bias=False)
98
+
99
+ def forward(self, x):
100
+ return self.c_proj(F.gelu(self.c_fc(x), approximate='tanh'))
101
+
102
+
103
+ # --- Transformer Block (Без изменений) ---
104
+ class TransformerBlock(nn.Module):
105
+ def __init__(self):
106
+ super().__init__()
107
+ self.attn = MultiHeadAttention()
108
+ self.ffn = FeedForward()
109
+ self.norm1 = nn.LayerNorm(MODEL_DIM, eps=1e-5)
110
+ self.norm2 = nn.LayerNorm(MODEL_DIM, eps=1e-5)
111
+
112
+ def forward(self, x, past_kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
113
+ attn_out, new_kv = self.attn(self.norm1(x), past_kv)
114
+ x = x + attn_out
115
+ x = x + self.ffn(self.norm2(x))
116
+ return x, new_kv
117
+
118
+
119
+ # -------------------------------
120
+ # Главная модель GPTPyTorch (L=8, H=8)
121
+ # -------------------------------
122
+ class GPTPyTorch(nn.Module):
123
+ def __init__(self):
124
+ super().__init__()
125
+ self.token_emb = nn.Embedding(VOCAB_SIZE, MODEL_DIM)
126
+ self.pos_emb = LearnedPositionalEmbedding(MAX_SEQ_LEN, MODEL_DIM)
127
+ self.blocks = nn.ModuleList([TransformerBlock() for _ in range(NUM_LAYERS)])
128
+ self.ln_f = nn.LayerNorm(MODEL_DIM, eps=1e-5)
129
+ self.lm_head = nn.Linear(MODEL_DIM, VOCAB_SIZE, bias=False)
130
+
131
+ signature = "Konstantin V Gbabko . original author © 2025"
132
+ bytes_tensor = torch.tensor([ord(c) for c in signature], dtype=torch.uint8)
133
+ self.register_buffer("konstantin_gbabko_proof_of_authorship", bytes_tensor)
134
+ self.register_buffer("konstantin_gbabko_birth_date", torch.tensor([20251126], dtype=torch.int64))
135
+
136
+ self.lm_head.weight = self.token_emb.weight
137
+ self.apply(self._init_weights)
138
+
139
+ def _init_weights(self, module):
140
+ if isinstance(module, nn.Linear):
141
+ # Инициализация, масштабированная по глубине сети (L=8)
142
+ std = 0.02 / math.sqrt(2 * NUM_LAYERS) if isinstance(module, nn.Linear) and module.out_features == MODEL_DIM else 0.02
143
+ torch.nn.init.normal_(module.weight, mean=0.0, std=std)
144
+ elif isinstance(module, nn.Embedding):
145
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
146
+ elif isinstance(module, nn.LayerNorm):
147
+ nn.init.zeros_(module.bias)
148
+ nn.init.ones_(module.weight)
149
+
150
+ # Метод forward для обучения и инференса с кешем
151
+ def forward(self, input_ids, past_kv: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None):
152
+ B, T = input_ids.shape
153
+ x = self.token_emb(input_ids)
154
+
155
+ pos_offset = 0
156
+ if past_kv is not None and past_kv[0] is not None:
157
+ pos_offset = past_kv[0][0].size(2)
158
+
159
+ x = self.pos_emb(x, pos_offset=pos_offset)
160
+
161
+ # Инициализация нового кеша
162
+ new_kv_cache = [] if past_kv is not None else None
163
+ current_past = past_kv
164
+
165
+ for i, block in enumerate(self.blocks):
166
+ layer_past = current_past[i] if (current_past and i < len(current_past)) else None
167
+ x, layer_kv = block(x, layer_past)
168
+
169
+ if new_kv_cache is not None:
170
+ new_kv_cache.append(layer_kv)
171
+
172
+ x = self.ln_f(x)
173
+ logits = self.lm_head(x)
174
+
175
+ # === КРИТИЧЕСКОЕ ИСПРАВЛЕНИЕ: Статический вывод для JIT-трассировки ===
176
+ if past_kv is None:
177
+ return logits # Путь обучения (возвращает только Tensor)
178
+ else:
179
+ return logits, new_kv_cache # Путь инференса с кэшем (возвращает Tensor и List)
180
+
181
+ # -------------------------------
182
+ # Обертка для JIT-трассировки (гарантирует только Tensor)
183
+ # -------------------------------
184
+ class GPTPyTorchNoCache(nn.Module):
185
+ def __init__(self, model):
186
+ super().__init__()
187
+ self.model = model
188
+
189
+ def forward(self, input_ids):
190
+ # Вызов с None гарантирует, что основной forward вернет только logits (Tensor).
191
+ return self.model(input_ids, None)
192
+
193
+ # =========================================================================
194
+ # ОСНОВНОЙ БЛОК: JIT-КОНВЕРТАЦИЯ
195
+ # =========================================================================
196
+ if __name__ == "__main__":
197
+ os.makedirs("models", exist_ok=True)
198
+
199
+ TRAIN_SEQ_LEN = 256
200
+ # Обновленное имя файла для отражения L=8, H=8
201
+ JIT_SAVE_PATH = Path("models/JiRack_H8_L8_V50257_D768_MSL8192_FF768x4.script.pt")
202
+
203
+ model = GPTPyTorch().to(device)
204
+ model.eval()
205
+
206
+ total_params = sum(p.numel() for p in model.parameters())
207
+ print(f"Device: {device}")
208
+ print(f"Total parameters: {total_params / 1e6:.2f}M")
209
+
210
+ # 1. Проверка первого прохода
211
+ dummy_input = torch.randint(0, VOCAB_SIZE, (1, TRAIN_SEQ_LEN), device=device)
212
+ with torch.no_grad():
213
+ # Тестируем путь обучения (past_kv=None), который возвращает только logits
214
+ logits_test = model(dummy_input, None)
215
+ print(f"Test logits shape: {logits_test.shape}")
216
+
217
+ # 2. JIT-ТРАССИРОВКА И СОХРАНЕНИЕ
218
+ print(f"\nTracing model for JIT export (input sequence length: {TRAIN_SEQ_LEN})...")
219
+
220
+ # Используем обертку для чистой трассировки
221
+ model_no_cache = GPTPyTorchNoCache(model).to(device)
222
+
223
+ try:
224
+ # Трассируем, используя обертку, которая обеспечивает статический вывод (logits)
225
+ traced_script_module = torch.jit.trace(model_no_cache, dummy_input, strict=False)
226
+
227
+ traced_script_module.save(JIT_SAVE_PATH)
228
+ print(f"✅ Success! Model saved as TorchScript (JIT) to: {JIT_SAVE_PATH}")
229
+ print("Now you can run your training script to fine-tune this model.")
230
+
231
+ except Exception as e:
232
+ print(f"🚨 ERROR during JIT tracing: {e}")
233
+ print("Model may contain operations incompatible with torch.jit.trace.")
234
+
235
+ # Сохраняем оригинальную модель (на всякий случай)
236
+ ORIGINAL_SAVE_PATH = "models/JiRack_H8_L8_V50257_D768_MSL8192_FF768x4.pt"
237
+ torch.save(model.state_dict(), ORIGINAL_SAVE_PATH)
238
+ print(f"\nOriginal state_dict saved to {ORIGINAL_SAVE_PATH}")
source_jit/TestLoadModel.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 CMS Manhattan
2
+ # All rights reserved.
3
+ # Author: Konstantin Vladimirovich Grabko
4
+ # Email: grabko@cmsmanhattan.com
5
+ # Phone: +1(516)777-0945
6
+ #
7
+ # This program is free software: you can redistribute it and/or modify
8
+ # it under the terms of the GNU General Public License as published by
9
+ # the Free Software Foundation, version 3 of the License.
10
+ #
11
+ # This program is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ # GNU General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with this program. If not, see <https://www.gnu.org/licenses/>.
18
+ #
19
+ # Additional terms:
20
+ # Any commercial use or distribution of this software or derivative works
21
+ # requires explicit written permission from the copyright holder.
22
+
23
+
24
+ import torch
25
+ from pathlib import Path
26
+
27
+ # ========================================
28
+ # Конфигурация (должна совпадать с моделью)
29
+ # ========================================
30
+ VOCAB_SIZE = 50257
31
+ MODEL_DIM = 768
32
+ NUM_LAYERS = 8
33
+ NUM_HEADS = 8
34
+ TRAIN_SEQ_LEN = 256
35
+ HEAD_DIM = MODEL_DIM // NUM_HEADS
36
+
37
+ # Путь к сохраненному файлу
38
+ JIT_SAVE_PATH = Path("models/gpt_pytorch_L8_H8_base.script.pt")
39
+
40
+ # Проверка устройства (для соответствия JIT-трассировке)
41
+ if torch.cuda.is_available():
42
+ device = torch.device("cuda")
43
+ elif hasattr(torch, 'hip') and torch.hip.is_available():
44
+ device = torch.device("cuda")
45
+ else:
46
+ device = torch.device("cpu")
47
+
48
+ def test_jit_model():
49
+ """Загружает и тестирует модель TorchScript."""
50
+
51
+ if not JIT_SAVE_PATH.exists():
52
+ print(f"🚨 Ошибка: Файл JIT-модели не найден по пути: {JIT_SAVE_PATH}")
53
+ return
54
+
55
+ print(f"--- Тестирование TorchScript (JIT) модели ---")
56
+ print(f"Загрузка модели с {JIT_SAVE_PATH} на {device}...")
57
+
58
+ try:
59
+ # 1. Загрузка трассированной модели
60
+ # torch.jit.load загружает модель и ее веса.
61
+ loaded_jit_model = torch.jit.load(str(JIT_SAVE_PATH), map_location=device)
62
+ loaded_jit_model.eval()
63
+
64
+ # 2. Создание тестового ввода
65
+ # Входные данные должны соответствовать конфигурации, использованной при трассировке (T=256, B=1).
66
+ test_input = torch.randint(0, VOCAB_SIZE, (1, TRAIN_SEQ_LEN), device=device, dtype=torch.long)
67
+
68
+ # 3. Выполнение инференса
69
+ with torch.no_grad():
70
+ # Поскольку мы трассировали обертку NoCache, модель принимает только один вход (input_ids)
71
+ jit_logits = loaded_jit_model(test_input)
72
+
73
+ # 4. Проверки
74
+ expected_shape = torch.Size([1, TRAIN_SEQ_LEN, VOCAB_SIZE])
75
+
76
+ assert jit_logits.shape == expected_shape, (
77
+ f"Неверная форма вывода. Ожидалось: {expected_shape}, "
78
+ f"Получено: {jit_logits.shape}"
79
+ )
80
+
81
+ print("\n✅ Тест успешно пройден!")
82
+ print(f"Модель JIT загружена и работает корректно.")
83
+ print(f"Форма логитов: {jit_logits.shape}")
84
+ print(f"Устройство: {jit_logits.device}")
85
+
86
+ except Exception as e:
87
+ print(f"\n🚨 Критическая ошибка при тестировании JIT-модели: {e}")
88
+ print("Проверьте, что конфигурация (VOCAB_SIZE, MODEL_DIM, T) соответствует трассировке.")
89
+
90
+
91
+ if __name__ == "__main__":
92
+ test_jit_model()
source_jit/fine_tune_jit_with_validation_H4_L2.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 CMS Manhattan
2
+ # All rights reserved.
3
+ # Author: Konstantin Vladimirovich Grabko
4
+ # Email: grabko@cmsmanhattan.com
5
+ # Phone: +1(516)777-0945
6
+ #
7
+ # This program is free software: you can redistribute it and/or modify
8
+ # it under the terms of the GNU General Public License as published by
9
+ # the Free Software Foundation, version 3 of the License.
10
+ #
11
+ # This program is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ # GNU General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with this program. If not, see <https://www.gnu.org/licenses/>.
18
+ #
19
+ # Additional terms:
20
+ # Any commercial use or distribution of this software or derivative works
21
+ # requires explicit written permission from the copyright holder.
22
+
23
+ import os
24
+ from pathlib import Path
25
+ import torch
26
+ import torch.nn as nn
27
+ import torch.optim as optim
28
+ from torch.utils.data import DataLoader
29
+ from tqdm import tqdm
30
+ import math
31
+ from torch.cuda.amp import autocast, GradScaler # 👈 Добавлен импорт AMP
32
+
33
+ # Параметры (пример)
34
+ TRAIN_SEQ_LEN = 256
35
+ BATCH_SIZE = 12
36
+ EPOCHS = 10
37
+ LEARNING_RATE = 1e-6 # 👈 СНИЖЕНО ДЛЯ СТАБИЛЬНОСТИ
38
+ WEIGHT_DECAY = 0.01
39
+ GRAD_CLIP = 0.5
40
+ VAL_SPLIT_RATIO = 0.05
41
+
42
+ BASE_MODEL_PATH = Path("models/JiRack_H4_L2_V50257_D768_MSL8192_FF768x4.script.pt")
43
+ DATASET_PATH = Path("datasets/dialogues_text_clean.txt")
44
+
45
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
46
+ print(f"Устройство: {device}")
47
+
48
+ def print_model_devices(model):
49
+ sd = model.state_dict()
50
+ devs = set()
51
+ for k, v in sd.items():
52
+ try:
53
+ devs.add(v.device)
54
+ except Exception:
55
+ devs.add(torch.device('cpu'))
56
+ print("Devices present in model.state_dict():", devs)
57
+ return devs
58
+
59
+ def safe_load_jit_model(path: Path, map_device: torch.device):
60
+ """
61
+ Загружает JIT модель с map_location и пытается привести её к map_device.
62
+ Возвращает (model, model_device) — модель и устройство, на котором находятся её параметры/буферы.
63
+ """
64
+ if not path.exists():
65
+ raise FileNotFoundError(f"JIT model not found: {path}")
66
+
67
+ # Попытка загрузки с map_location
68
+ print(f"Loading JIT model from {path} with map_location={map_device} ...")
69
+ model = torch.jit.load(str(path), map_location=str(map_device))
70
+ print("Loaded model. Попытка model.to(...) ...")
71
+ try:
72
+ model = model.to(map_device)
73
+ print("model.to(map_device) выполнен.")
74
+ except Exception as e:
75
+ # У некоторых JIT объектов .to() может не сработать — это нормально, продолжим диагностику
76
+ print("Warning: model.to(map_device) вызвал исключение:", e)
77
+
78
+ # Диагностика устройств, где лежат параметры/буферы
79
+ devs = print_model_devices(model)
80
+
81
+ # Выберем устройство "модели" — если их несколько, отдаём предпочтение CUDA если есть
82
+ if len(devs) == 0:
83
+ model_device = map_device
84
+ elif len(devs) == 1:
85
+ model_device = list(devs)[0]
86
+ else:
87
+ # если есть смешанные устройства — попробуем приоритет cuda, иначе первый в множестве
88
+ cuda_devs = [d for d in devs if 'cuda' in str(d)]
89
+ model_device = cuda_devs[0] if cuda_devs else list(devs)[0]
90
+ print("Внимание: обнаружены несколько устройств внутри state_dict(). Выбран model_device =", model_device)
91
+
92
+ # Если model_device не равен map_device — уведомим пользователя и попытаемся ещё раз загрузить с конкретным map_location
93
+ if str(model_device) != str(map_device):
94
+ print(f"Model tensors are on {model_device} but requested map_device is {map_device}.")
95
+ print("Попробую заново загрузить модель с map_location=model_device ...")
96
+ try:
97
+ model = torch.jit.load(str(path), map_location=str(model_device))
98
+ try:
99
+ model = model.to(model_device)
100
+ except Exception:
101
+ pass
102
+ devs2 = print_model_devices(model)
103
+ if len(devs2) == 1 and list(devs2)[0] == model_device:
104
+ print("Успешно перезагружено на целевое устройство.")
105
+ except Exception as e:
106
+ print("Не удалось перезагрузить модель на желаемое устройство:", e)
107
+ # продолжаем, но предупредим пользователя
108
+ return model, model_device
109
+
110
+ def get_logits_from_model(model, inputs):
111
+ """
112
+ Вызов модели, допускающий возможные варианты возврата.
113
+ Мы предполагаем, что inputs уже находится на том же устройстве, что и модель.
114
+ """
115
+ try:
116
+ out = model(inputs)
117
+ # model может вернуть logits или (logits, kv)
118
+ if isinstance(out, tuple) or isinstance(out, list):
119
+ return out[0]
120
+ return out
121
+ except RuntimeError as e:
122
+ # Если ошибка связана с устройствами, добавим детальный лог
123
+ msg = str(e)
124
+ if "Expected all tensors to be on the same device" in msg or "but found at least two devices" in msg:
125
+ print("RuntimeError: вероятно есть mismatch устройств (cpu/cuda) внутри model. Диагностика state_dict():")
126
+ try:
127
+ print_model_devices(model)
128
+ except Exception:
129
+ pass
130
+ # Ребросим исключение с более понятным сообщением
131
+ raise RuntimeError("Device mismatch while running the JIT model. See printed diagnostics above.") from e
132
+ else:
133
+ raise
134
+
135
+ # ----------------- Пример интеграции в train loop -----------------
136
+ def train():
137
+ model, model_device = safe_load_jit_model(BASE_MODEL_PATH, device)
138
+
139
+ # Подготовьте датасеты здесь как вы уже делаете (замените на свой TextDataset)
140
+ from transformers import GPT2TokenizerFast
141
+ # Замените на ваш реальный TextDataset; здесь лишь заглушка
142
+ class DummyDataset(torch.utils.data.Dataset):
143
+ def __init__(self, n=1000, seq_len=TRAIN_SEQ_LEN, vocab_size=50257):
144
+ self.n = n
145
+ self.seq_len = seq_len
146
+ self.vocab_size = vocab_size
147
+ def __len__(self): return self.n
148
+ def __getitem__(self, i):
149
+ x = torch.randint(0, self.vocab_size, (self.seq_len,), dtype=torch.long)
150
+ y = torch.randint(0, self.vocab_size, (self.seq_len,), dtype=torch.long)
151
+ return x, y
152
+
153
+ train_dataset = DummyDataset(n=2000)
154
+ val_dataset = DummyDataset(n=200)
155
+
156
+ train_loader = DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=True, drop_last=True)
157
+ val_loader = DataLoader(val_dataset, batch_size=BATCH_SIZE, shuffle=False, drop_last=True)
158
+
159
+ # Создаём optimizer
160
+ params = list(model.parameters()) if hasattr(model, 'parameters') else []
161
+ if len(params) == 0:
162
+ print("Warning: model.parameters() пуст. Убедитесь, что JIT-модель содержит параметры для оптимизации.")
163
+ optimizer = optim.AdamW(params, lr=LEARNING_RATE, weight_decay=WEIGHT_DECAY) if params else None
164
+ criterion = nn.CrossEntropyLoss()
165
+
166
+ # Инициализация GradScaler для AMP
167
+ scaler = GradScaler()
168
+
169
+ model.train()
170
+
171
+ for epoch in range(1, EPOCHS + 1):
172
+ print(f"Эпоха {epoch}/{EPOCHS}")
173
+ epoch_loss = 0.0
174
+ pbar = tqdm(train_loader, desc=f"Epoch {epoch} [TRAIN]", leave=False)
175
+
176
+ batch_count = 0
177
+ skipped_batches = 0
178
+
179
+ for xb, yb in pbar:
180
+ # === 1. ПРОВЕРКА ДАННЫХ НА NAN/INF ===
181
+ # Проверяем только если тип данных — float (для LongTensor проверка не нужна)
182
+ if torch.is_floating_point(xb) and (torch.isnan(xb).any() or torch.isinf(xb).any()):
183
+ print(f"\n[E{epoch}] WARNING: NaN or Inf found in input data (xb). Skipping batch.")
184
+ skipped_batches += 1
185
+ continue
186
+
187
+ # Приводим батчи к устройству модели (model_device)
188
+ xb = xb.to(model_device)
189
+ yb = yb.to(model_device)
190
+
191
+ if optimizer:
192
+ optimizer.zero_grad()
193
+
194
+ # === 2. AMP: Выполняем forward-pass в half-precision ===
195
+ with autocast():
196
+ logits = get_logits_from_model(model, xb)
197
+
198
+ # У logits размер [B, seq_len, vocab] — приводим к числу классов
199
+ loss = criterion(logits.view(-1, logits.size(-1)), yb.view(-1))
200
+ # ========================================================
201
+
202
+ # === 3. ПРОВЕРКА ЛОССА НА NAN/INF ПЕРЕД BACKWARD ===
203
+ # Проверяем лосс, который теперь может быть float16 или float32
204
+ if torch.isnan(loss) or torch.isinf(loss):
205
+ print(f"\n[E{epoch}] CRITICAL: Loss is NaN or Inf. Skipping backward and update.")
206
+ skipped_batches += 1
207
+ continue
208
+
209
+ # AMP: Вычисляем градиенты, масштабируя их
210
+ scaler.scale(loss).backward()
211
+
212
+ if optimizer:
213
+ # AMP: Сначала снимаем масштаб
214
+ scaler.unscale_(optimizer)
215
+
216
+ # Обрезка градиентов
217
+ torch.nn.utils.clip_grad_norm_(params, GRAD_CLIP)
218
+
219
+ # AMP: Обновляем веса (scaler сам проверяет, не являются ли градиенты Inf/NaN)
220
+ scaler.step(optimizer)
221
+ scaler.update()
222
+
223
+ # Переводим лосс в float32 для записи и отображения
224
+ loss_val = loss.item()
225
+ epoch_loss += loss_val
226
+ batch_count += 1
227
+
228
+ pbar.set_postfix({"loss": f"{loss_val:.4f}", "ppl": f"{math.exp(min(loss_val, 10)):.2f}"})
229
+
230
+ # Средняя потеря считается только по не пропущенным батчам
231
+ avg_loss = epoch_loss / batch_count if batch_count > 0 else float('nan')
232
+ print(f"Средняя потеря за эпоху: {avg_loss:.4f}")
233
+
234
+ if skipped_batches > 0:
235
+ print(f"Внимание: {skipped_batches} батчей было пропущено из-за NaN/Inf в данных или лоссе.")
236
+
237
+
238
+ if __name__ == "__main__":
239
+ train()
source_jit/fine_tune_native_H4_L2.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 CMS Manhattan
2
+ # All rights reserved.
3
+ # Author: Konstantin Vladimirovich Grabko
4
+ # Email: grabko@cmsmanhattan.com
5
+ # Phone: +1(516)777-0945
6
+ #
7
+ # This program is free software: you can redistribute it and/or modify
8
+ # it under the terms of the GNU General Public License as published by
9
+ # the Free Software Foundation, version 3 of the License.
10
+ #
11
+ # This program is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ # GNU General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with this program. If not, see <https://www.gnu.org/licenses/>.
18
+ #
19
+ # Additional terms:
20
+ # Any commercial use or distribution of this software or derivative works
21
+ # requires explicit written permission from the copyright holder.
22
+
23
+ import torch
24
+ import torch.nn as nn
25
+ from torch.optim import AdamW
26
+ from torch.utils.data import DataLoader
27
+ from torch.amp import autocast, GradScaler
28
+ from tqdm import tqdm
29
+ import math
30
+ from pathlib import Path
31
+
32
+ # Подключаем твою модель (ту же самую, что была в JIT)
33
+ from your_model_file import JiRack_H4_L2 # ← сюда имя файла с классом модели (который я тебе дал последним)
34
+
35
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
36
+ print(f"Устройство: {device}")
37
+
38
+ # Загружаем обычную модель (НЕ JIT!)
39
+ model = JiRack_H4_L2().to(device)
40
+
41
+ # Загружаем веса из JIT-конвертированной модели (они совместимы!)
42
+ state_dict = torch.load("models/JiRack_H4_L2_V50257_D768_MSL8192_FF3072.pt", map_location=device)
43
+ model.load_state_dict(state_dict)
44
+ print("Веса загружены из .pt файла")
45
+
46
+ # Параметры обучения — теперь можно чуть агрессивнее
47
+ BATCH_SIZE = 12
48
+ SEQ_LEN = 256
49
+ EPOCHS = 10
50
+ LR = 5e-5
51
+ WARMUP_STEPS = 100
52
+
53
+ # Твой датасет (пример с рандомом — замени на реальный)
54
+ class DummyDataset(torch.utils.data.Dataset):
55
+ def __init__(self, n=10000): self.n = n
56
+ def __len__(self): return self.n
57
+ def __getitem__(self, i):
58
+ x = torch.randint(0, 50257, (SEQ_LEN,))
59
+ return x, x.roll(-1) # next token prediction
60
+
61
+ train_loader = DataLoader(DummyDataset(), batch_size=BATCH_SIZE, shuffle=True, drop_last=True)
62
+
63
+ optimizer = AdamW(model.parameters(), lr=LR, weight_decay=0.01)
64
+ scaler = GradScaler('cuda')
65
+ criterion = nn.CrossEntropyLoss()
66
+
67
+ global_step = 0
68
+ model.train()
69
+
70
+ for epoch in range(1, EPOCHS + 1):
71
+ total_loss = 0
72
+ pbar = tqdm(train_loader, desc=f"Эпоха {epoch}/{EPOCHS}")
73
+
74
+ for xb, yb in pbar:
75
+ global_step += 1
76
+ xb, yb = xb.to(device), yb.to(device)
77
+
78
+ optimizer.zero_grad()
79
+
80
+ with autocast('cuda'):
81
+ logits = model(xb) # ← обычный forward, без past_kv
82
+ loss = criterion(logits.view(-1, logits.size(-1)), yb.view(-1))
83
+
84
+ scaler.scale(loss).backward()
85
+ scaler.unscale_(optimizer)
86
+ torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
87
+ scaler.step(optimizer)
88
+ scaler.update()
89
+
90
+ # LR warmup
91
+ if global_step < WARMUP_STEPS:
92
+ lr_scale = global_step / WARMUP_STEPS
93
+ for pg in optimizer.param_groups:
94
+ pg['lr'] = LR * lr_scale
95
+
96
+ total_loss += loss.item()
97
+ pbar.set_postfix({"loss": f"{loss.item():.4f}", "ppl": f"{math.exp(loss.item()):.1f}"})
98
+
99
+ avg_loss = total_loss / len(train_loader)
100
+ print(f"Эпоха {epoch} завершена | Средний loss: {avg_loss:.4f} | Perplexity: {math.exp(avg_loss):.2f}\n")
101
+
102
+ # После обучения — сохраняем и JIT-версию для инференса
103
+ torch.save(model.state_dict(), "models/JiRack_H4_L2_finetuned.pt")
104
+
105
+ # Экспорт в JIT (теперь уже обученной модели)
106
+ class JITWrapper(nn.Module):
107
+ def __init__(self, m): super().__init__(); self.m = m
108
+ def forward(self, x): return self.m(x)
109
+
110
+ dummy = torch.randint(0, 50257, (1, 256), device=device)
111
+ traced = torch.jit.trace(JITWrapper(model.cpu().eval()), dummy)
112
+ traced.save("models/JiRack_H4_L2_finetuned.script.pt")
113
+ print("Обученная модель сохранена + экспортирована в JIT для инференса")
source_jit/tools_diagnostics_print_jit_constants.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 CMS Manhattan
2
+ # All rights reserved.
3
+ # Author: Konstantin Vladimirovich Grabko
4
+ # Email: grabko@cmsmanhattan.com
5
+ # Phone: +1(516)777-0945
6
+ #
7
+ # This program is free software: you can redistribute it and/or modify
8
+ # it under the terms of the GNU General Public License as published by
9
+ # the Free Software Foundation, version 3 of the License.
10
+ #
11
+ # This program is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ # GNU General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with this program. If not, see <https://www.gnu.org/licenses/>.
18
+ #
19
+ # Additional terms:
20
+ # Any commercial use or distribution of this software or derivative works
21
+ # requires explicit written permission from the copyright holder.
22
+
23
+
24
+ import sys
25
+ import torch
26
+ from pathlib import Path
27
+
28
+ def main():
29
+ if len(sys.argv) < 2:
30
+ print("Usage: python diagnostics_print_jit_constants.py <jit_model_path>")
31
+ return
32
+ path = Path(sys.argv[1])
33
+ if not path.exists():
34
+ print("File not found:", path)
35
+ return
36
+
37
+ print("Loading JIT model (map_location='cpu') for safe inspection...")
38
+ m = torch.jit.load(str(path), map_location='cpu')
39
+ print("Loaded. Collecting info...\n")
40
+
41
+ print("Named parameters (name, device, shape):")
42
+ try:
43
+ for n, p in m.named_parameters():
44
+ print(" PARAM:", n, p.device, tuple(p.shape))
45
+ except Exception as e:
46
+ print(" (named_parameters() not available / raised):", e)
47
+
48
+ print("\nNamed buffers (name, device, shape):")
49
+ try:
50
+ for n, b in m.named_buffers():
51
+ print(" BUFFER:", n, b.device, tuple(b.shape))
52
+ except Exception as e:
53
+ print(" (named_buffers() not available / raised):", e)
54
+
55
+ print("\nstate_dict keys and devices:")
56
+ try:
57
+ sd = m.state_dict()
58
+ devices = set()
59
+ for k, v in sd.items():
60
+ try:
61
+ devices.add(v.device)
62
+ print(" ", k, v.device, tuple(v.shape))
63
+ except Exception:
64
+ print(" ", k, " - (non-tensor?)")
65
+ print("Devices in state_dict():", devices)
66
+ except Exception as e:
67
+ print(" state_dict() failed:", e)
68
+
69
+ print("\nAttempt to show TorchScript graph (short version). Look for prim::Constant Tensor entries:")
70
+ try:
71
+ g = m.graph
72
+ print(g)
73
+ except Exception as e:
74
+ print(" Could not print graph directly:", e)
75
+ try:
76
+ print("m.code():")
77
+ print(m.code)
78
+ except Exception as e2:
79
+ print(" Also could not print m.code():", e2)
80
+
81
+ print("\nIf you find prim::Constant values with Tensor on CPU, those likely cause device mismatch.")
82
+ print("Recommendation: re-create JIT on target device (see retrace_to_cuda.py).")
83
+
84
+ if __name__ == "__main__":
85
+ main()
source_jit/tools_retrace_to_cuda.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 CMS Manhattan
2
+ # All rights reserved.
3
+ # Author: Konstantin Vladimirovich Grabko
4
+ # Email: grabko@cmsmanhattan.com
5
+ # Phone: +1(516)777-0945
6
+ #
7
+ # This program is free software: you can redistribute it and/or modify
8
+ # it under the terms of the GNU General Public License as published by
9
+ # the Free Software Foundation, version 3 of the License.
10
+ #
11
+ # This program is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ # GNU General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with this program. If not, see <https://www.gnu.org/licenses/>.
18
+ #
19
+ # Additional terms:
20
+ # Any commercial use or distribution of this software or derivative works
21
+ # requires explicit written permission from the copyright holder.
22
+
23
+ import argparse
24
+ import torch
25
+ from pathlib import Path
26
+ import importlib
27
+ import sys
28
+
29
+ parser = argparse.ArgumentParser()
30
+ parser.add_argument("--jit", required=True, help="Path to existing JIT model (used to extract state_dict)")
31
+ parser.add_argument("--out", required=True, help="Output path for new JIT model on CUDA")
32
+ parser.add_argument("--py_module", required=False, help="Python import path for model (e.g. jirackkit.src.main.python.gpt2_jit.JiRack_H4_L2_V50257_D768_MSL8192_FF768x4)", default=None)
33
+ parser.add_argument("--class_name", required=False, help="Name of model class in module", default=None)
34
+ parser.add_argument("--seq_len", type=int, default=8, help="Sequence length for example input (short is fine for trace)")
35
+ parser.add_argument("--vocab_size", type=int, default=50257, help="Vocab size for dummy input")
36
+ parser.add_argument("--use_script", action="store_true", help="Use torch.jit.script instead of trace (requires model to be scriptable)")
37
+ args = parser.parse_args()
38
+
39
+ jit_path = Path(args.jit)
40
+ out_path = Path(args.out)
41
+ if not jit_path.exists():
42
+ print("JIT file not found:", jit_path)
43
+ sys.exit(1)
44
+
45
+ # 1) load state_dict from existing JIT (safe: load on cpu)
46
+ print("Loading state_dict from existing JIT (cpu)...")
47
+ jit = torch.jit.load(str(jit_path), map_location='cpu')
48
+ try:
49
+ sd = jit.state_dict()
50
+ print("state_dict keys:", list(sd.keys())[:10], "...")
51
+ except Exception as e:
52
+ print("Failed to obtain state_dict() from JIT:", e)
53
+ sd = None
54
+
55
+ # 2) Import python module & create model instance
56
+ if args.py_module is None or args.class_name is None:
57
+ print("ERROR: You must provide --py_module and --class_name to reconstruct the Python model.")
58
+ print("Example: --py_module jirackkit.src.main.python.gpt2_jit.JiRack_H4_L2_V50257_D768_MSL8192_FF768x4 --class_name GPTPyTorch")
59
+ sys.exit(1)
60
+
61
+ print("Importing Python model:", args.py_module, args.class_name)
62
+ module = importlib.import_module(args.py_module)
63
+ ModelClass = getattr(module, args.class_name)
64
+
65
+ # NOTE: Provide the correct constructor args for your model here if needed.
66
+ MODEL_KWARGS = {} # <-- EDIT if your model constructor requires arguments
67
+
68
+ print("Instantiating Python model...")
69
+ model = ModelClass(**MODEL_KWARGS)
70
+
71
+ # 3) load weights if available
72
+ if sd is not None:
73
+ try:
74
+ model.load_state_dict(sd)
75
+ print("Weights loaded into Python model from JIT.state_dict().")
76
+ except Exception as e:
77
+ print("Failed to load state_dict into Python model:", e)
78
+ print("You may need to adapt keys or load partial weights. Exiting.")
79
+ sys.exit(1)
80
+
81
+ # 4) move to cuda
82
+ if not torch.cuda.is_available():
83
+ print("CUDA not available on this machine. Aborting.")
84
+ sys.exit(1)
85
+ device = torch.device('cuda:0')
86
+ model.to(device)
87
+ model.eval()
88
+
89
+ # 5) prepare example input on CUDA (batch=1)
90
+ seq_len = args.seq_len
91
+ vocab = args.vocab_size
92
+ example_input = torch.randint(0, vocab, (1, seq_len), dtype=torch.long, device=device)
93
+
94
+ # 6) trace or script
95
+ print("Tracing/script-model on CUDA. This will produce a JIT module whose constants are on CUDA.")
96
+ if args.use_script:
97
+ print("Using torch.jit.script...")
98
+ scripted = torch.jit.script(model)
99
+ else:
100
+ print("Using torch.jit.trace with example input of shape", example_input.shape)
101
+ scripted = torch.jit.trace(model, example_input)
102
+
103
+ # 7) save
104
+ out_path.parent.mkdir(parents=True, exist_ok=True)
105
+ scripted.save(str(out_path))
106
+ print("Saved new JIT (CUDA) model to:", out_path)
107
+ print("Done. Replace your old model file with this one (keep backup).")