MageLord commited on
Commit
554a560
·
verified ·
1 Parent(s): a488035

Upload stage 1 checkpoint (51044 steps)

Browse files
README.md ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # PCoreX Turkish 1B — Stage 1 checkpoint
2
+
3
+ Continued pretraining on MageLord/PCoreX-TR-Alpaca-V2.
4
+ Training steps: 51044. T4 time-limited run.
config.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoConfig": "configuration_tr_en.TrEnConfig"
4
+ },
5
+ "bias": false,
6
+ "block_size": 256,
7
+ "bos_token_id": 2,
8
+ "dropout": 0.0,
9
+ "eos_token_id": 3,
10
+ "ffn_mult": 4,
11
+ "initializer_range": 0.02,
12
+ "max_position_embeddings": 256,
13
+ "model_type": "tr_en_gpt",
14
+ "n_embd": 2048,
15
+ "n_head": 16,
16
+ "n_layer": 18,
17
+ "pad_token_id": 0,
18
+ "rope_theta": 10000.0,
19
+ "tie_weights": false,
20
+ "tie_word_embeddings": false,
21
+ "transformers_version": "5.0.0",
22
+ "vocab_size": 32000
23
+ }
configuration_tr_en.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Hugging Face uyumlu config sınıfı.
3
+ AutoConfig ile kayıt edilir, save_pretrained/from_pretrained otomatik çalışır.
4
+ """
5
+
6
+ from transformers import PretrainedConfig
7
+
8
+
9
+ class TrEnConfig(PretrainedConfig):
10
+ model_type = "tr_en_gpt"
11
+
12
+ def __init__(
13
+ self,
14
+ vocab_size: int = 36864,
15
+ block_size: int = 2048,
16
+ n_layer: int = 18,
17
+ n_head: int = 16,
18
+ n_embd: int = 2048,
19
+ ffn_mult: int = 4,
20
+ dropout: float = 0.0,
21
+ bias: bool = False,
22
+ tie_weights: bool = True,
23
+ rope_theta: float = 10000.0,
24
+ initializer_range: float = 0.02,
25
+ pad_token_id: int = 0,
26
+ bos_token_id: int = 2,
27
+ eos_token_id: int = 3,
28
+ **kwargs,
29
+ ):
30
+ self.vocab_size = vocab_size
31
+ self.block_size = block_size
32
+ self.max_position_embeddings = block_size # HF ekosistemiyle uyumluluk için alias
33
+ self.n_layer = n_layer
34
+ self.n_head = n_head
35
+ self.n_embd = n_embd
36
+ self.ffn_mult = ffn_mult
37
+ self.dropout = dropout
38
+ self.bias = bias
39
+ self.tie_weights = tie_weights
40
+ self.rope_theta = rope_theta
41
+ self.initializer_range = initializer_range
42
+
43
+ super().__init__(
44
+ pad_token_id=pad_token_id,
45
+ bos_token_id=bos_token_id,
46
+ eos_token_id=eos_token_id,
47
+ tie_word_embeddings=tie_weights,
48
+ **kwargs,
49
+ )
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c92f44236a50e22804f0a035933be20c2101be5bc27942efdca23884a82ff515
3
+ size 4223981208
modeling_tr_en.py ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Hugging Face `transformers` ekosistemine tam uyumlu, TPU (torch_xla / accelerate)
3
+ üzerinde eğitilebilir causal dil modeli.
4
+
5
+ - `TrEnForCausalLM`, `PreTrainedModel` ve `GenerationMixin`'den türer:
6
+ save_pretrained / from_pretrained / push_to_hub / Trainer / accelerate / PEFT
7
+ hepsiyle doğrudan uyumludur.
8
+ - `AutoConfig` ve `AutoModelForCausalLM` ile kayıt edilir, böylece
9
+ `AutoModelForCausalLM.from_pretrained("./tr_en_llm")` çalışır.
10
+ - KV-cache (past_key_values) destekler -> `model.generate()` kullanılabilir.
11
+ - Gradient checkpointing destekler (`model.gradient_checkpointing_enable()`).
12
+ - Eager attention kullanır (TPU/XLA ile en sorunsuz çalışan yol); istenirse
13
+ `attn_implementation="sdpa"` GPU'da otomatik hızlanma sağlar.
14
+
15
+ Eğitim (TPU örneği, siz çalıştıracaksınız):
16
+
17
+ # accelerate ile (önerilen, HF Trainer da içeride bunu kullanır)
18
+ accelerate config # TPU seçin
19
+ accelerate launch train.py
20
+
21
+ # ya da doğrudan HF Trainer:
22
+ from transformers import Trainer, TrainingArguments
23
+ args = TrainingArguments(output_dir="out", tpu_num_cores=8, ...)
24
+ trainer = Trainer(model=model, args=args, train_dataset=...)
25
+ trainer.train()
26
+ """
27
+
28
+ import math
29
+ from typing import Optional, Tuple, List
30
+
31
+ import torch
32
+ import torch.nn as nn
33
+ import torch.nn.functional as F
34
+
35
+ from transformers import PreTrainedModel, GenerationMixin
36
+ from transformers.modeling_outputs import CausalLMOutputWithPast
37
+ from transformers.activations import ACT2FN
38
+
39
+ from configuration_tr_en import TrEnConfig
40
+
41
+
42
+ class RMSNorm(nn.Module):
43
+ def __init__(self, dim: int, eps: float = 1e-5):
44
+ super().__init__()
45
+ self.eps = eps
46
+ self.weight = nn.Parameter(torch.ones(dim))
47
+
48
+ def forward(self, x):
49
+ norm = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
50
+ return norm * self.weight
51
+
52
+
53
+ class RotaryEmbedding(nn.Module):
54
+ """RoPE - pozisyon bilgisini attention içine döndürerek gömer."""
55
+
56
+ def __init__(self, dim: int, base: float = 10000.0):
57
+ super().__init__()
58
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
59
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
60
+
61
+ def forward(self, position_ids: torch.Tensor, dtype: torch.dtype):
62
+ # position_ids: (B, T)
63
+ inv_freq = self.inv_freq.to(position_ids.device)
64
+ freqs = torch.einsum("bt,d->btd", position_ids.float(), inv_freq)
65
+ emb = torch.cat((freqs, freqs), dim=-1)
66
+ return emb.cos().to(dtype), emb.sin().to(dtype)
67
+
68
+
69
+ def rotate_half(x):
70
+ x1, x2 = x.chunk(2, dim=-1)
71
+ return torch.cat((-x2, x1), dim=-1)
72
+
73
+
74
+ def apply_rope(q, k, cos, sin):
75
+ # cos/sin: (B, T, head_dim) -> (B, 1, T, head_dim)
76
+ cos = cos.unsqueeze(1)
77
+ sin = sin.unsqueeze(1)
78
+ q_rot = (q * cos) + (rotate_half(q) * sin)
79
+ k_rot = (k * cos) + (rotate_half(k) * sin)
80
+ return q_rot, k_rot
81
+
82
+
83
+ class TrEnAttention(nn.Module):
84
+ def __init__(self, config: TrEnConfig):
85
+ super().__init__()
86
+ self.n_head = config.n_head
87
+ self.head_dim = config.n_embd // config.n_head
88
+ self.qkv_proj = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias)
89
+ self.out_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
90
+ self.attn_dropout = config.dropout
91
+ self.rotary = RotaryEmbedding(self.head_dim, base=config.rope_theta)
92
+
93
+ def forward(self, x, attention_mask=None, position_ids=None, past_key_value=None, use_cache=False):
94
+ B, T, C = x.shape
95
+ qkv = self.qkv_proj(x)
96
+ q, k, v = qkv.split(C, dim=2)
97
+ q = q.view(B, T, self.n_head, self.head_dim).transpose(1, 2)
98
+ k = k.view(B, T, self.n_head, self.head_dim).transpose(1, 2)
99
+ v = v.view(B, T, self.n_head, self.head_dim).transpose(1, 2)
100
+
101
+ cos, sin = self.rotary(position_ids, x.dtype)
102
+ q, k = apply_rope(q, k, cos, sin)
103
+
104
+ if past_key_value is not None:
105
+ past_k, past_v = past_key_value
106
+ k = torch.cat([past_k, k], dim=2)
107
+ v = torch.cat([past_v, v], dim=2)
108
+ present = (k, v) if use_cache else None
109
+
110
+ attn_mask = None
111
+ is_causal = past_key_value is None
112
+ if attention_mask is not None:
113
+ # attention_mask: (B, 1, T_q, T_kv) additive mask (0 / -inf), zaten causal içerir
114
+ attn_mask = attention_mask
115
+ is_causal = False
116
+
117
+ y = F.scaled_dot_product_attention(
118
+ q, k, v,
119
+ attn_mask=attn_mask,
120
+ is_causal=is_causal and attn_mask is None,
121
+ dropout_p=self.attn_dropout if self.training else 0.0,
122
+ )
123
+ y = y.transpose(1, 2).contiguous().view(B, T, C)
124
+ return self.out_proj(y), present
125
+
126
+
127
+ class TrEnMLP(nn.Module):
128
+ def __init__(self, config: TrEnConfig):
129
+ super().__init__()
130
+ hidden = int(config.ffn_mult * config.n_embd * 2 / 3)
131
+ hidden = 256 * ((hidden + 255) // 256)
132
+ self.gate_proj = nn.Linear(config.n_embd, hidden, bias=config.bias)
133
+ self.up_proj = nn.Linear(config.n_embd, hidden, bias=config.bias)
134
+ self.down_proj = nn.Linear(hidden, config.n_embd, bias=config.bias)
135
+ self.act_fn = ACT2FN["silu"]
136
+
137
+ def forward(self, x):
138
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
139
+
140
+
141
+ class TrEnBlock(nn.Module):
142
+ def __init__(self, config: TrEnConfig):
143
+ super().__init__()
144
+ self.ln1 = RMSNorm(config.n_embd)
145
+ self.attn = TrEnAttention(config)
146
+ self.ln2 = RMSNorm(config.n_embd)
147
+ self.mlp = TrEnMLP(config)
148
+
149
+ def forward(self, x, attention_mask=None, position_ids=None, past_key_value=None, use_cache=False):
150
+ attn_out, present = self.attn(
151
+ self.ln1(x), attention_mask=attention_mask, position_ids=position_ids,
152
+ past_key_value=past_key_value, use_cache=use_cache,
153
+ )
154
+ x = x + attn_out
155
+ x = x + self.mlp(self.ln2(x))
156
+ return x, present
157
+
158
+
159
+ class TrEnPreTrainedModel(PreTrainedModel):
160
+ config_class = TrEnConfig
161
+ base_model_prefix = "model"
162
+ supports_gradient_checkpointing = True
163
+ _no_split_modules = ["TrEnBlock"]
164
+ _supports_sdpa = True
165
+
166
+ def _init_weights(self, module):
167
+ std = self.config.initializer_range
168
+ if isinstance(module, nn.Linear):
169
+ nn.init.normal_(module.weight, mean=0.0, std=std)
170
+ if module.bias is not None:
171
+ nn.init.zeros_(module.bias)
172
+ elif isinstance(module, nn.Embedding):
173
+ nn.init.normal_(module.weight, mean=0.0, std=std)
174
+ elif isinstance(module, RMSNorm):
175
+ nn.init.ones_(module.weight)
176
+
177
+
178
+ class TrEnModel(TrEnPreTrainedModel):
179
+ """Gövde: embedding + transformer blokları (lm_head yok)."""
180
+
181
+ def __init__(self, config: TrEnConfig):
182
+ super().__init__(config)
183
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.n_embd, padding_idx=config.pad_token_id)
184
+ self.drop = nn.Dropout(config.dropout)
185
+ self.layers = nn.ModuleList([TrEnBlock(config) for _ in range(config.n_layer)])
186
+ self.norm = RMSNorm(config.n_embd)
187
+ self.gradient_checkpointing = False
188
+ self.post_init()
189
+
190
+ def get_input_embeddings(self):
191
+ return self.embed_tokens
192
+
193
+ def set_input_embeddings(self, value):
194
+ self.embed_tokens = value
195
+
196
+ @staticmethod
197
+ def _build_causal_mask(attention_mask, seq_len, past_len, dtype, device):
198
+ # (B, T) padding mask -> (B, 1, T, T+past) additive causal+padding mask
199
+ total_len = seq_len + past_len
200
+ causal = torch.full((seq_len, total_len), torch.finfo(dtype).min, device=device, dtype=dtype)
201
+ causal = torch.triu(causal, diagonal=1 + past_len)
202
+ causal = causal[None, None, :, :]
203
+ if attention_mask is not None:
204
+ pad = (1.0 - attention_mask[:, None, None, :].to(dtype)) * torch.finfo(dtype).min
205
+ causal = causal + pad
206
+ return causal
207
+
208
+ def forward(
209
+ self,
210
+ input_ids=None,
211
+ attention_mask=None,
212
+ position_ids=None,
213
+ past_key_values=None,
214
+ inputs_embeds=None,
215
+ use_cache=False,
216
+ output_hidden_states=False,
217
+ **kwargs,
218
+ ):
219
+ if inputs_embeds is None:
220
+ inputs_embeds = self.embed_tokens(input_ids)
221
+ B, T, _ = inputs_embeds.shape
222
+ past_len = past_key_values[0][0].shape[2] if past_key_values is not None else 0
223
+
224
+ if position_ids is None:
225
+ position_ids = torch.arange(past_len, past_len + T, device=inputs_embeds.device).unsqueeze(0).expand(B, -1)
226
+
227
+ causal_mask = self._build_causal_mask(attention_mask, T, past_len, inputs_embeds.dtype, inputs_embeds.device)
228
+
229
+ x = self.drop(inputs_embeds)
230
+ all_hidden = () if output_hidden_states else None
231
+ new_past = [] if use_cache else None
232
+
233
+ for i, layer in enumerate(self.layers):
234
+ if output_hidden_states:
235
+ all_hidden = all_hidden + (x,)
236
+ layer_past = past_key_values[i] if past_key_values is not None else None
237
+
238
+ if self.gradient_checkpointing and self.training:
239
+ x, present = torch.utils.checkpoint.checkpoint(
240
+ layer, x, causal_mask, position_ids, layer_past, use_cache, use_reentrant=False,
241
+ )
242
+ else:
243
+ x, present = layer(x, attention_mask=causal_mask, position_ids=position_ids,
244
+ past_key_value=layer_past, use_cache=use_cache)
245
+ if use_cache:
246
+ new_past.append(present)
247
+
248
+ x = self.norm(x)
249
+ if output_hidden_states:
250
+ all_hidden = all_hidden + (x,)
251
+
252
+ return x, new_past, all_hidden
253
+
254
+
255
+ class TrEnForCausalLM(TrEnPreTrainedModel, GenerationMixin):
256
+ """AutoModelForCausalLM ile kayıt edilecek üst sınıf (lm_head dahil)."""
257
+
258
+ _tied_weights_keys = ["lm_head.weight"]
259
+
260
+ def __init__(self, config: TrEnConfig):
261
+ super().__init__(config)
262
+ self.model = TrEnModel(config)
263
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
264
+ self.post_init()
265
+ if config.tie_weights:
266
+ self.tie_weights()
267
+
268
+ def get_input_embeddings(self):
269
+ return self.model.embed_tokens
270
+
271
+ def set_input_embeddings(self, value):
272
+ self.model.embed_tokens = value
273
+
274
+ def get_output_embeddings(self):
275
+ return self.lm_head
276
+
277
+ def set_output_embeddings(self, new_embeddings):
278
+ self.lm_head = new_embeddings
279
+
280
+ def forward(
281
+ self,
282
+ input_ids=None,
283
+ attention_mask=None,
284
+ position_ids=None,
285
+ past_key_values=None,
286
+ inputs_embeds=None,
287
+ labels=None,
288
+ use_cache=None,
289
+ output_hidden_states=False,
290
+ return_dict=True,
291
+ **kwargs,
292
+ ):
293
+ use_cache = use_cache if use_cache is not None else False
294
+
295
+ hidden_states, new_past, all_hidden = self.model(
296
+ input_ids=input_ids,
297
+ attention_mask=attention_mask,
298
+ position_ids=position_ids,
299
+ past_key_values=past_key_values,
300
+ inputs_embeds=inputs_embeds,
301
+ use_cache=use_cache,
302
+ output_hidden_states=output_hidden_states,
303
+ )
304
+ logits = self.lm_head(hidden_states)
305
+
306
+ loss = None
307
+ if labels is not None:
308
+ shift_logits = logits[..., :-1, :].contiguous()
309
+ shift_labels = labels[..., 1:].contiguous()
310
+ loss = F.cross_entropy(
311
+ shift_logits.view(-1, shift_logits.size(-1)),
312
+ shift_labels.view(-1),
313
+ ignore_index=-100,
314
+ )
315
+
316
+ return CausalLMOutputWithPast(
317
+ loss=loss,
318
+ logits=logits,
319
+ past_key_values=new_past,
320
+ hidden_states=all_hidden,
321
+ )
322
+
323
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **kwargs):
324
+ if past_key_values is not None:
325
+ input_ids = input_ids[:, -1:]
326
+ return {
327
+ "input_ids": input_ids,
328
+ "attention_mask": attention_mask,
329
+ "past_key_values": past_key_values,
330
+ "use_cache": True,
331
+ }
332
+
333
+ def num_params(self, non_embedding=False):
334
+ n = sum(p.numel() for p in self.parameters())
335
+ if non_embedding:
336
+ n -= self.model.embed_tokens.weight.numel()
337
+ return n
338
+
339
+
340
+ # --- Auto sınıflarına kayıt: AutoConfig / AutoModelForCausalLM ile çalışsın ---
341
+ TrEnConfig.register_for_auto_class()
342
+ TrEnForCausalLM.register_for_auto_class("AutoModelForCausalLM")
343
+
344
+
345
+ if __name__ == "__main__":
346
+ config = TrEnConfig()
347
+ model = TrEnForCausalLM(config)
348
+ total = model.num_params()
349
+ print(f"Config: n_layer={config.n_layer}, n_head={config.n_head}, n_embd={config.n_embd}, vocab={config.vocab_size}")
350
+ print(f"Toplam parametre sayısı: {total:,} (~{total/1e6:.1f}M)")
351
+
352
+ x = torch.randint(0, config.vocab_size, (2, 16))
353
+ out = model(input_ids=x, labels=x)
354
+ print(f"logits shape: {tuple(out.logits.shape)}, loss (rastgele init): {out.loss.item():.3f}")
355
+
356
+ # HF standart kaydetme/yükleme testi
357
+ model.save_pretrained("./tr_en_llm_ckpt")
358
+ config.save_pretrained("./tr_en_llm_ckpt")
359
+ print("save_pretrained tamam -> ./tr_en_llm_ckpt")
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "is_local": true,
4
+ "model_max_length": 1000000000000000019884624838656,
5
+ "tokenizer_class": "TokenizersBackend"
6
+ }