Rel0aded commited on
Commit
54d3db9
·
verified ·
1 Parent(s): 6d41427

Security clean-up: remove train_tpu.py

Browse files
Files changed (1) hide show
  1. train_tpu.py +0 -418
train_tpu.py DELETED
@@ -1,418 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- # =====================================================================
3
- # 🚀 REL0ADED-1B TPU ENGINE: GOOGLE TPU v5e-8 (128 GB HBM)
4
- # =====================================================================
5
-
6
- import os
7
- os.environ["PJRT_DEVICE"] = "TPU"
8
-
9
- # Otomatik Donanım Tespiti & Metadata Baypası (Kaggle Container Uyumu)
10
- pci_devices = os.listdir('/sys/bus/pci/devices') if os.path.exists('/sys/bus/pci/devices') else []
11
- is_v5e = False
12
- for dev in pci_devices:
13
- dev_path = f'/sys/bus/pci/devices/{dev}/device'
14
- if os.path.exists(dev_path):
15
- try:
16
- with open(dev_path, 'r') as f:
17
- dev_id = f.read().strip()
18
- if any(x in dev_id for x in ['0062', '0063', 'ba16']):
19
- is_v5e = True
20
- break
21
- except Exception:
22
- pass
23
-
24
- if is_v5e:
25
- os.environ['TPU_ACCELERATOR_TYPE'] = 'v5litepod-8'
26
- os.environ['TPU_CHIPS_PER_HOST_BOUNDS'] = '2,4,1'
27
- else:
28
- os.environ['TPU_ACCELERATOR_TYPE'] = 'v3-8'
29
- os.environ['TPU_CHIPS_PER_HOST_BOUNDS'] = '2,2,1'
30
-
31
- os.environ['TPU_HOST_BOUNDS'] = '1,1,1'
32
- os.environ['TPU_SKIP_MDS_QUERY'] = '1'
33
- os.environ['TPU_PROCESS_ADDRESSES'] = 'local'
34
- os.environ['TPU_WORKER_HOSTNAMES'] = 'localhost'
35
- os.environ['TPU_WORKER_ID'] = '0'
36
-
37
- so_path = '/tmp/tpu_env/lib/python3.11/site-packages/libtpu/libtpu.so'
38
- if os.path.exists(so_path):
39
- os.environ['TPU_LIBRARY_PATH'] = so_path
40
-
41
- import sys
42
- import json
43
- import time
44
- import math
45
- import shutil
46
- import base64
47
- import subprocess
48
-
49
- # PyTorch & Hugging Face
50
- import torch
51
- import torch.nn as nn
52
- import torch.nn.functional as F
53
-
54
- for pkg in ["datasets", "tokenizers", "huggingface_hub", "wandb"]:
55
- try:
56
- __import__(pkg)
57
- except ImportError:
58
- subprocess.run([sys.executable, "-m", "pip", "install", "-q", pkg], check=True)
59
-
60
- from datasets import load_dataset
61
- from tokenizers import Tokenizer
62
- from huggingface_hub import HfApi, hf_hub_download
63
- import wandb
64
-
65
- # --- XLA IMPORTS ---
66
- try:
67
- import torch_xla
68
- import torch_xla.core.xla_model as xm
69
- import torch_xla.distributed.xla_multiprocessing as xmp
70
- import torch_xla.distributed.parallel_loader as pl
71
- print("✅ PyTorch/XLA TPU kütüphaneleri başarıyla yüklendi!")
72
- except ImportError:
73
- print("❌ torch_xla bulunamadı! Lütfen TPU hızlandırıcısının aktif olduğundan emin olun.")
74
- sys.exit(1)
75
-
76
- # --- 1. KİMLİK & HESAP YÖNETİMİ ---
77
- _dec = lambda s: base64.b64decode(s).decode("utf-8")
78
- HF_TOKEN = _dec("aGZfWVh1SHJvZkVqUVZLS3JncEd2bFVYbVNCQW1aTGtNQ2hXQw==")
79
- REPO_ID = "Rel0aded/Turkish-1B"
80
- WANDB_API_KEY = _dec("d2FuZGJfdjFfUXZ6eHNPOVdvZk85dElUN3VPWFVBUlo1SnhuX2pPTldOWEhlU2lhNGZteEtpVUE0QktaanMyNzVDelVFVjRTbU54Q0xPRFQzQUFJSVk=")
81
- api = HfApi(token=HF_TOKEN)
82
-
83
- # --- 2. 1.014B MODEL MİMARİSİ (Birebir Uyumlu Llama-3 + GQA) ---
84
- class ModelConfig1B:
85
- vocab_size = 16384
86
- dim = 2048
87
- n_layers = 21 # Tam 1.014 Milyar parametre
88
- n_heads = 16
89
- n_kv_heads = 4 # GQA (Grouped Query Attention 16:4)
90
- head_dim = 128
91
- intermediate_size = 5632 # SwiGLU MLP
92
- max_seq_len = 1024 # 1024 Token Bağlam
93
- rope_theta = 500000.0
94
-
95
- cfg = ModelConfig1B()
96
-
97
- class RMSNorm(nn.Module):
98
- def __init__(self, dim, eps=1e-5):
99
- super().__init__()
100
- self.eps = eps
101
- self.weight = nn.Parameter(torch.ones(dim))
102
- def forward(self, x):
103
- return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight
104
-
105
- def precompute_rope_frequencies(head_dim, max_seq_len, theta=500000.0):
106
- theta_factors = theta ** (-torch.arange(0, head_dim, 2).float() / head_dim)
107
- t = torch.arange(max_seq_len)
108
- freqs = torch.outer(t, theta_factors)
109
- return torch.polar(torch.ones_like(freqs), freqs)
110
-
111
- def apply_rotary_emb(x, freqs_cis):
112
- x_complex = torch.view_as_complex(x.float().reshape(*x.shape[:-1], -1, 2))
113
- freqs_cis = freqs_cis.view(1, x.size(1), 1, x_complex.size(-1))
114
- return torch.view_as_real(x_complex * freqs_cis).flatten(-2).type_as(x)
115
-
116
- class GQAttention(nn.Module):
117
- def __init__(self, cfg):
118
- super().__init__()
119
- self.n_heads = cfg.n_heads
120
- self.n_kv_heads = cfg.n_kv_heads
121
- self.head_dim = cfg.head_dim
122
- self.num_rep = self.n_heads // self.n_kv_heads
123
-
124
- self.q_proj = nn.Linear(cfg.dim, self.n_heads * self.head_dim, bias=False)
125
- self.k_proj = nn.Linear(cfg.dim, self.n_kv_heads * self.head_dim, bias=False)
126
- self.v_proj = nn.Linear(cfg.dim, self.n_kv_heads * self.head_dim, bias=False)
127
- self.out_proj = nn.Linear(self.n_heads * self.head_dim, cfg.dim, bias=False)
128
-
129
- def forward(self, x, freqs_cis):
130
- B, S, _ = x.shape
131
- q = self.q_proj(x).view(B, S, self.n_heads, self.head_dim)
132
- k = self.k_proj(x).view(B, S, self.n_kv_heads, self.head_dim)
133
- v = self.v_proj(x).view(B, S, self.n_kv_heads, self.head_dim)
134
-
135
- q = apply_rotary_emb(q, freqs_cis)
136
- k = apply_rotary_emb(k, freqs_cis)
137
-
138
- k = k.repeat_interleave(self.num_rep, dim=2)
139
- v = v.repeat_interleave(self.num_rep, dim=2)
140
-
141
- q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
142
- out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
143
- out = out.transpose(1, 2).contiguous().view(B, S, -1)
144
- return self.out_proj(out)
145
-
146
- class SwiGLUMLP(nn.Module):
147
- def __init__(self, cfg):
148
- super().__init__()
149
- self.gate_proj = nn.Linear(cfg.dim, cfg.intermediate_size, bias=False)
150
- self.up_proj = nn.Linear(cfg.dim, cfg.intermediate_size, bias=False)
151
- self.down_proj = nn.Linear(cfg.intermediate_size, cfg.dim, bias=False)
152
-
153
- def forward(self, x):
154
- return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
155
-
156
- class TransformerBlock(nn.Module):
157
- def __init__(self, cfg):
158
- super().__init__()
159
- self.attn_norm = RMSNorm(cfg.dim)
160
- self.attn = GQAttention(cfg)
161
- self.mlp_norm = RMSNorm(cfg.dim)
162
- self.mlp = SwiGLUMLP(cfg)
163
-
164
- def forward(self, x, freqs_cis):
165
- x = x + self.attn(self.attn_norm(x), freqs_cis)
166
- x = x + self.mlp(self.mlp_norm(x))
167
- return x
168
-
169
- # TPU Uyumlu 1B Model (Katman İsimleri GPU Checkpoint ile %100 Birebir Aynıdır!)
170
- class Rel0aded1B_TPU(nn.Module):
171
- def __init__(self, cfg):
172
- super().__init__()
173
- self.cfg = cfg
174
-
175
- self.tok_embeddings = nn.Embedding(cfg.vocab_size, cfg.dim)
176
- self.layers_0 = nn.ModuleList([TransformerBlock(cfg) for _ in range(11)])
177
- self.layers_1 = nn.ModuleList([TransformerBlock(cfg) for _ in range(10)])
178
- self.norm = RMSNorm(cfg.dim)
179
- self.output = nn.Linear(cfg.dim, cfg.vocab_size, bias=False)
180
-
181
- freqs = precompute_rope_frequencies(cfg.head_dim, cfg.max_seq_len, cfg.rope_theta)
182
- self.register_buffer("freqs_cis", freqs, persistent=False)
183
-
184
- def forward(self, input_ids):
185
- S = input_ids.size(1)
186
- freqs_cis = self.freqs_cis[:S].to(input_ids.device)
187
-
188
- h = self.tok_embeddings(input_ids)
189
- for layer in self.layers_0:
190
- h = layer(h, freqs_cis)
191
- for layer in self.layers_1:
192
- h = layer(h, freqs_cis)
193
- return self.output(self.norm(h))
194
-
195
- # --- 3. TPU MULTI-CORE WORKER FONKSİYONU ---
196
- def _mp_fn(rank, *args):
197
- device = xm.xla_device()
198
- world_size = xm.xrt_world_size()
199
- is_master = xm.is_master_ordinal(local=False)
200
-
201
- if is_master:
202
- print(f"🔥 GOOGLE TPU v5e (Dünya Büyüklüğü: {world_size} Çekirdek) AKTİF!")
203
- print(f"📊 Rank {rank} ana koordinatör olarak devrede.")
204
-
205
- # 1. Tokenizer
206
- tok_path = hf_hub_download(repo_id=REPO_ID, filename="turkce_tokenizer.json", token=HF_TOKEN)
207
- tokenizer = Tokenizer.from_file(tok_path)
208
-
209
- # 2. Model Kurulumu & bfloat16
210
- model = Rel0aded1B_TPU(cfg).to(device).to(torch.bfloat16)
211
-
212
- # 3. Checkpoint'ten Kaldığı Yerden Devam (Adım 6,610)
213
- start_step = 6610
214
- try:
215
- ckpt_path = hf_hub_download(repo_id=REPO_ID, filename="checkpoint.pt", token=HF_TOKEN)
216
- ckpt = torch.load(ckpt_path, map_location="cpu")
217
- if "model_state_dict" in ckpt:
218
- target_dict = model.state_dict()
219
- filtered_state = {k: v for k, v in ckpt["model_state_dict"].items() if k in target_dict and v.shape == target_dict[k].shape}
220
- model.load_state_dict(filtered_state)
221
- start_step = ckpt.get("step", 6610)
222
- if is_master:
223
- print(f"🎉 Checkpoint başarıyla yüklendi! Adım {start_step:,}'den devam ediliyor.")
224
- except Exception as e:
225
- if is_master:
226
- print(f"⚠️ Checkpoint yükleme uyarısı: {e}")
227
-
228
- # 4. Optimizer
229
- optimizer = torch.optim.AdamW(model.parameters(), lr=1.5e-4, weight_decay=0.1, betas=(0.9, 0.95))
230
-
231
- # 5. WandB Canlı Takip (Sadece Master Rank)
232
- wandb_aktif = False
233
- if is_master:
234
- try:
235
- wandb.login(key=WANDB_API_KEY)
236
- wandb.init(
237
- project="Turkish-1B",
238
- name=f"Turkish-1B-TPU-v5e-8-Roket",
239
- config={
240
- "hardware": f"Google TPU v5e ({world_size} Çekirdek - 128GB HBM)",
241
- "cores": world_size,
242
- "params": "1.014B",
243
- "precision": "bfloat16",
244
- "start_step": start_step
245
- }
246
- )
247
- wandb_aktif = True
248
- print("📊 WandB Canlı Takip Başlatıldı!")
249
- except Exception as e:
250
- print(f"WandB uyarısı: {e}")
251
-
252
- # 6. Çok Alanlı Türkçe Veri Havuzu (Her Çekirdeğe Bağımsız Shard)
253
- veri_kaynaklari = [
254
- ("fineweb", "altaidevorg/fineweb-2-turkish-categorized", None),
255
- ("cosmos", "ytu-ce-cosmos/Cosmos-Turkish-Corpus-v1.0", None),
256
- ("tascib", "tascib/turkish-llm-dataset", None),
257
- ("kitap", "ytu-ce-cosmos/turkce-kitap", None),
258
- ("python_kod", "bysismo/Turkish-Python-instruction", None),
259
- ("temiz_metin", "serda-dev/turkish-raw-text-cleaned", None),
260
- ("wiki", "wikimedia/wikipedia", "20231101.tr"),
261
- ("culturax", "uonlp/CulturaX", "tr")
262
- ]
263
-
264
- veri_listesi = []
265
- for isim, repo, subset in veri_kaynaklari:
266
- try:
267
- if subset:
268
- ds = load_dataset(repo, subset, split="train", streaming=True)
269
- else:
270
- ds = load_dataset(repo, split="train", streaming=True)
271
- sharded_ds = ds.shard(num_shards=max(world_size, 1), index=rank)
272
- veri_listesi.append(sharded_ds)
273
- except Exception:
274
- continue
275
-
276
- def veri_akis():
277
- while True:
278
- for ds in veri_listesi:
279
- try:
280
- for ornek in ds:
281
- metin = ""
282
- if "text" in ornek and ornek["text"]:
283
- metin = ornek["text"]
284
- elif "instruction" in ornek:
285
- parts = [str(ornek.get(k, "")).strip() for k in ["instruction", "input", "output"] if ornek.get(k)]
286
- metin = "\n".join(parts)
287
- elif "book" in ornek and ornek["book"]:
288
- metin = ornek["book"]
289
-
290
- if metin and len(metin.strip()) > 50:
291
- yield metin
292
- except Exception:
293
- continue
294
-
295
- gen = veri_akis()
296
- token_tamponu = []
297
-
298
- # Kalibre Edilmiş Global Batch Boyutu: Tam 32 Batch (32,768 Token/Adım)
299
- seq_len = cfg.max_seq_len # 1024
300
- if world_size >= 8:
301
- batch_size = 2
302
- grad_accum_steps = 2
303
- elif world_size >= 4:
304
- batch_size = 2
305
- grad_accum_steps = 4
306
- else:
307
- batch_size = 2
308
- grad_accum_steps = 16
309
-
310
- gereken = batch_size * (seq_len + 1)
311
-
312
- def sonraki_batch():
313
- nonlocal token_tamponu
314
- while len(token_tamponu) < gereken:
315
- try:
316
- metin = next(gen)
317
- ids = tokenizer.encode(metin).ids + [2]
318
- token_tamponu.extend(ids)
319
- except Exception:
320
- continue
321
- secilen = token_tamponu[:gereken]
322
- token_tamponu = token_tamponu[gereken:]
323
- dizi = torch.tensor(secilen, dtype=torch.long).view(batch_size, seq_len + 1)
324
- return dizi[:, :-1].to(device), dizi[:, 1:].to(device)
325
-
326
- # 7. EĞİTİM DÖNGÜSÜ
327
- SEANS_SURESI_SANIYE = 8.5 * 3600 # 8.5 Saatlik dev TPU seansı
328
- KAYIT_ARALIGI_DAKIKA = 30
329
- seans_baslangic = time.time()
330
- son_kayit_zamani = time.time()
331
- step = start_step
332
-
333
- model.train()
334
- optimizer.zero_grad(set_to_none=True)
335
-
336
- if is_master:
337
- print(f"\n🚀 TPU v5e TAM VERİM ROKETİ ATEŞLENDİ!")
338
- print(f"🎯 Hedef: 10.000+ Adımı Delip Geçmek!")
339
- print(f"📦 Batch Boyutu: {batch_size} (Çekirdek başına) | Grad Accum: {grad_accum_steps} | Global: 32 ({32*seq_len:,} tok/adım)")
340
-
341
- while True:
342
- gecen = time.time() - seans_baslangic
343
- if gecen >= SEANS_SURESI_SANIYE:
344
- if is_master:
345
- print(f"\n⏰ 8.5 Saatlik TPU seansı tamamlandı!")
346
- break
347
-
348
- step_baslangic = time.time()
349
- toplam_loss = 0.0
350
-
351
- for micro in range(grad_accum_steps):
352
- x, y = sonraki_batch()
353
- logits = model(x)
354
- loss = F.cross_entropy(logits.view(-1, cfg.vocab_size).float(), y.view(-1))
355
- loss = loss / grad_accum_steps
356
- loss.backward()
357
- toplam_loss += loss.item() * grad_accum_steps
358
-
359
- # TPU Senkronizasyon & Optimizer Adımı
360
- xm.optimizer_step(optimizer)
361
- optimizer.zero_grad(set_to_none=True)
362
- xm.mark_step()
363
-
364
- step += 1
365
-
366
- step_sure = time.time() - step_baslangic
367
- token_hizi = (batch_size * world_size * grad_accum_steps * seq_len) / max(step_sure, 0.001)
368
-
369
- # 10 adımda bir ekrana ve WandB'ye log
370
- if step % 10 == 0 and is_master:
371
- kalan_dk = (SEANS_SURESI_SANIYE - gecen) / 60
372
- print(f"⚡ TPU Adım {step:,} | Loss: {toplam_loss:.4f} | Hız: {token_hizi:.0f} tok/s | Kalan: {kalan_dk:.1f} dk")
373
- if wandb_aktif:
374
- wandb.log({
375
- "train/loss": toplam_loss,
376
- "train/tokens_per_sec": token_hizi,
377
- "train/step": step,
378
- "train/elapsed_hours": gecen / 3600
379
- })
380
-
381
- # 30 dakikada bir buluta yedekle
382
- if (time.time() - son_kayit_zamani) >= (KAYIT_ARALIGI_DAKIKA * 60) and is_master:
383
- print(f"\n💾 [TPU Bulut Kaydı] Adım {step:,} Hugging Face'e mühürleniyor...")
384
- ckpt_data = {
385
- "step": step,
386
- "model_state_dict": model.state_dict(),
387
- "optimizer_state_dict": optimizer.state_dict(),
388
- "loss": toplam_loss
389
- }
390
- xm.save(ckpt_data, "checkpoint.pt")
391
- try:
392
- api.upload_file(path_or_fileobj="checkpoint.pt", path_in_repo="checkpoint.pt", repo_id=REPO_ID)
393
- print(f"☁️ ✅ Adım {step:,} başarıyla kilitlendi!\n")
394
- except Exception as e:
395
- print(f"⚠️ Yedekleme uyarısı: {e}\n")
396
- son_kayit_zamani = time.time()
397
-
398
- # Seans Sonu Final Kayıt
399
- if is_master:
400
- print(f"\n🏁 TPU Final durumu kaydediliyor...")
401
- ckpt_data = {
402
- "step": step,
403
- "model_state_dict": model.state_dict(),
404
- "optimizer_state_dict": optimizer.state_dict(),
405
- "loss": toplam_loss
406
- }
407
- xm.save(ckpt_data, "checkpoint.pt")
408
- try:
409
- api.upload_file(path_or_fileobj="checkpoint.pt", path_in_repo="checkpoint.pt", repo_id=REPO_ID)
410
- print("✅ Son TPU checkpoint buluta kaydedildi.")
411
- except Exception as e:
412
- print(f"⚠️ Checkpoint yükleme: {e}")
413
- print("🎉 TEBRİKLER! TPU Seansı başarıyla tamamlandı!")
414
-
415
- # --- ANA ÇALIŞTIRICI ---
416
- if __name__ == "__main__":
417
- print("🚀 Google TPU Motoru Başlatılıyor (8 Çekirdek)...")
418
- xmp.spawn(_mp_fn, args=(), nprocs=8, start_method="spawn")