-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjsonl-tokenizer.py
More file actions
307 lines (247 loc) · 12.7 KB
/
jsonl-tokenizer.py
File metadata and controls
307 lines (247 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import os
import glob
import json
import random
from tokenizers import ByteLevelBPETokenizer
from transformers import GPT2Tokenizer, GPT2LMHeadModel, AutoModelForCausalLM
import torch
from pathlib import Path
# Konfigürasyon
class Config:
# Veri kaynak türü: "txt" veya "jsonl"
DATA_SOURCE_TYPE = "jsonl"
# JSONL dosya yolu veya metin klasörü yolu
# JSONL_PATH = "./turkce_ilk_5000.jsonl" # JSONL dosyası - DEĞİŞTİRİN!
JSONL_PATH = "./turkce_veriseti.jsonl" # JSONL dosyası - DEĞİŞTİRİN!
TEXT_DIR = "./turkce_veriseti" # Metin klasörü (eğer DATA_SOURCE_TYPE "txt" ise)
# JSONL parametreleri
JSONL_TEXT_FIELD = "text" # JSONL içindeki metin alanı
# İngilizce veri oranı parametreleri
INGILIZCE_VERI_ORANI = 0.3 # İngilizce verinin toplam veri içindeki oranı (0.0-1.0)
INGILIZCE_JSONL_PATH = "./ingilizce_veriseti.jsonl" # İngilizce JSONL dosyası (opsiyonel)
# Sadece Türkçe için
# INGILIZCE_VERI_ORANI = 0 # İngilizce verinin toplam veri içindeki oranı (0.0-1.0)
# INGILIZCE_JSONL_PATH = "" # İngilizce JSONL dosyası (opsiyonel)
# Tokenizer parametreleri
BASE_MODEL = "gpt2" # Temel model
VOCAB_SIZE = 50000 # Kelime dağarcığı boyutu
MIN_FREQUENCY = 2 # Minimum token frekansı
OUTPUT_DIR = "./turkce_ingilizce_tokenizer" # Çıktı dizini
# Veri örnekleme ve işleme parametreleri
SAMPLE_SIZE = None # Veri örnekleme boyutu (None=tümü)
MAX_SAMPLE_LENGTH = 100000 # Her bir metin örneğinin maksimum uzunluğu
def create_temp_text_files(jsonl_path, output_dir, text_field="text", sample_size=None, max_length=100000):
"""JSONL dosyasından metin verilerini okuyup geçici metin dosyaları oluşturur"""
os.makedirs(output_dir, exist_ok=True)
# JSONL dosyasını satır satır oku
print(f"JSONL dosyası okunuyor: {jsonl_path}")
texts = []
try:
with open(jsonl_path, 'r', encoding='utf-8') as f:
for i, line in enumerate(f):
if sample_size and i >= sample_size:
break
try:
# JSON satırını parse et
data = json.loads(line.strip())
# Belirtilen alandan metni al
if text_field in data:
text = data[text_field]
# Boş veya çok kısa metinleri atla
if text and len(text) > 10:
# Metni maksimum uzunluğa kısıtla
text = text[:max_length]
texts.append(text)
except json.JSONDecodeError:
print(f"Hatalı JSON satırı (satır {i+1}): {line[:50]}...")
except Exception as e:
print(f"Satır işleme hatası (satır {i+1}): {str(e)}")
except FileNotFoundError:
print(f"HATA: {jsonl_path} dosyası bulunamadı.")
return []
print(f"Toplam {len(texts)} metin parçası okundu.")
# Metinleri dosyalara yaz
text_files = []
chunk_size = 1000 # Her dosyada maksimum metin sayısı
for i in range(0, len(texts), chunk_size):
chunk = texts[i:i+chunk_size]
file_path = os.path.join(output_dir, f"chunk_{i//chunk_size + 1}.txt")
with open(file_path, 'w', encoding='utf-8') as f:
f.write('\n\n'.join(chunk))
text_files.append(file_path)
print(f"Dosya oluşturuldu: {file_path} ({len(chunk)} metin)")
return text_files
def main():
"""Ana fonksiyon - tokenizer eğitimi sürecini yönetir"""
config = Config()
# Çıktı dizini oluşturma
os.makedirs(config.OUTPUT_DIR, exist_ok=True)
# Geçici dizin oluşturma
temp_dir = os.path.join(config.OUTPUT_DIR, "temp_files")
os.makedirs(temp_dir, exist_ok=True)
# Türkçe metinleri hazırla
if config.DATA_SOURCE_TYPE == "jsonl":
print(f"Türkçe JSONL verisinden metin dosyaları oluşturuluyor...")
turkish_files = create_temp_text_files(
config.JSONL_PATH,
os.path.join(temp_dir, "turkish"),
text_field=config.JSONL_TEXT_FIELD,
sample_size=config.SAMPLE_SIZE,
max_length=config.MAX_SAMPLE_LENGTH
)
else:
# Metin dosyalarını doğrudan kullan
print(f"Türkçe metin dosyaları aranıyor...")
turkish_files = []
for ext in ["*.txt", "*.text"]:
turkish_files.extend(glob.glob(os.path.join(config.TEXT_DIR, "**", ext), recursive=True))
print(f"Toplam {len(turkish_files)} Türkçe metin dosyası hazırlandı.")
# İngilizce metinleri hazırla
english_files = []
if config.INGILIZCE_VERI_ORANI > 0:
if os.path.exists(config.INGILIZCE_JSONL_PATH):
print(f"İngilizce JSONL verisinden metin dosyaları oluşturuluyor...")
english_files = create_temp_text_files(
config.INGILIZCE_JSONL_PATH,
os.path.join(temp_dir, "english"),
text_field=config.JSONL_TEXT_FIELD,
sample_size=config.SAMPLE_SIZE,
max_length=config.MAX_SAMPLE_LENGTH
)
else:
print(f"UYARI: İngilizce JSONL dosyası {config.INGILIZCE_JSONL_PATH} bulunamadı.")
# Varsayılan bir İngilizce örnek oluştur
print("Basit bir İngilizce örnek dosyası oluşturuluyor...")
eng_sample_dir = os.path.join(temp_dir, "english")
os.makedirs(eng_sample_dir, exist_ok=True)
eng_sample_file = os.path.join(eng_sample_dir, "english_sample.txt")
# Basit bir İngilizce metin oluştur
with open(eng_sample_file, 'w', encoding='utf-8') as f:
f.write("This is a sample English text. It's used to ensure the tokenizer has some English tokens.")
f.write("The tokenizer will be trained on both Turkish and English to support bilingual capabilities.")
english_files = [eng_sample_file]
# Dil oranını dengele
all_files = turkish_files + english_files
if english_files and turkish_files and config.INGILIZCE_VERI_ORANI > 0:
# Dosya boyutlarını hesapla
total_turkish_size = sum(os.path.getsize(f) for f in turkish_files)
total_english_size = sum(os.path.getsize(f) for f in english_files)
# Mevcut oran
if total_turkish_size + total_english_size > 0:
current_english_ratio = total_english_size / (total_english_size + total_turkish_size)
print(f"Mevcut İngilizce veri oranı: {current_english_ratio:.2f}")
print(f"Hedef İngilizce veri oranı: {config.INGILIZCE_VERI_ORANI:.2f}")
# Eğer İngilizce oranı hedeften düşükse, İngilizce veriyi çoğalt
if current_english_ratio < config.INGILIZCE_VERI_ORANI and english_files:
repeat_count = int((config.INGILIZCE_VERI_ORANI * total_turkish_size) /
((1 - config.INGILIZCE_VERI_ORANI) * total_english_size))
print(f"İngilizce veri {repeat_count}x çoğaltılıyor...")
english_files = english_files * repeat_count
# Dosya listesini güncelle
all_files = turkish_files + english_files
# Veri karıştırma
random.shuffle(all_files)
print(f"Tokenizer eğitimi için toplam {len(all_files)} dosya hazırlandı.")
# Tokenizer eğitimi
print("Tokenizer eğitiliyor...")
tokenizer = ByteLevelBPETokenizer()
tokenizer.train(
files=all_files,
vocab_size=config.VOCAB_SIZE,
min_frequency=config.MIN_FREQUENCY,
special_tokens=["<s>", "<pad>", "</s>", "<unk>", "<mask>"]
)
# Tokenizer'ı kaydet
print(f"Tokenizer kaydediliyor: {config.OUTPUT_DIR}")
tokenizer.save_model(config.OUTPUT_DIR)
# Transformers uyumlu tokenizer oluştur
print("Transformers uyumlu tokenizer oluşturuluyor...")
tokenizer = GPT2Tokenizer.from_pretrained(config.OUTPUT_DIR)
# GPT-2 tokenizer ile uyumlu olması için gereken ayarlar
tokenizer.add_special_tokens({
"eos_token": "</s>",
"bos_token": "<s>",
"unk_token": "<unk>",
"pad_token": "<pad>",
"mask_token": "<mask>"
})
# Tokenizer'ı test et
test_texts = [
# Türkçe test cümleleri
"Türkçe dil modellemesi için özel bir tokenizer eğitiyoruz.",
"İstanbul Boğazı'nın muhteşem manzarası eşliğinde çay içmek paha biçilemez.",
# İngilizce test cümleleri
"We are training a special tokenizer for Turkish language modeling.",
"Drinking tea with the magnificent view of the Bosphorus in Istanbul is priceless."
]
print("Tokenizer test ediliyor...")
for i, test_text in enumerate(test_texts):
encoded = tokenizer.encode(test_text)
decoded = tokenizer.decode(encoded)
print(f"\nTest {i+1}: {'Türkçe' if i < 2 else 'İngilizce'}")
print(f"Metin: {test_text}")
print(f"Token sayısı: {len(encoded)}")
print(f"Çözülmüş: {decoded}")
# Tokenizer'ı kaydet
tokenizer.save_pretrained(config.OUTPUT_DIR)
print(f"Transformers uyumlu tokenizer kaydedildi: {config.OUTPUT_DIR}")
# Model ile uyumlu hale getir
print(f"Temel model yükleniyor: {config.BASE_MODEL}")
try:
# Modeli yükle
model = AutoModelForCausalLM.from_pretrained(config.BASE_MODEL)
# Modelin kelime dağarcığı boyutunu kontrol et
old_vocab_size = model.get_input_embeddings().weight.shape[0]
new_vocab_size = len(tokenizer)
print(f"Eski kelime dağarcığı boyutu: {old_vocab_size}")
print(f"Yeni kelime dağarcığı boyutu: {new_vocab_size}")
# Embedding katmanını genişlet
print("Embedding katmanı genişletiliyor...")
model.resize_token_embeddings(new_vocab_size)
# Modeli kaydet
output_model_dir = os.path.join(config.OUTPUT_DIR, "model")
os.makedirs(output_model_dir, exist_ok=True)
model.save_pretrained(output_model_dir)
print(f"Uyumlu model kaydedildi: {output_model_dir}")
except Exception as e:
print(f"Model uyumluluk işlemi sırasında hata: {e}")
import traceback
print(traceback.format_exc())
# Orijinal tokenizer ile karşılaştırma
print("\nTokenizer karşılaştırması:")
original_tokenizer = GPT2Tokenizer.from_pretrained(config.BASE_MODEL)
if original_tokenizer.pad_token is None:
original_tokenizer.pad_token = original_tokenizer.eos_token
languages = ["Türkçe", "Türkçe", "İngilizce", "İngilizce"]
for i, text in enumerate(test_texts):
original_tokens = original_tokenizer.encode(text)
new_tokens = tokenizer.encode(text)
print(f"\n{languages[i]} metin: {text}")
print(f"Orijinal tokenizer: {len(original_tokens)} token")
print(f"Yeni tokenizer: {len(new_tokens)} token")
if languages[i] == "Türkçe":
performance_metric = len(new_tokens) < len(original_tokens)
if performance_metric:
efficiency = (1 - len(new_tokens) / len(original_tokens)) * 100
print(f"Türkçe verimlilik artışı: %{efficiency:.2f}")
else:
inefficiency = (len(new_tokens) / len(original_tokens) - 1) * 100
print(f"Türkçe verimlilik kaybı: %{inefficiency:.2f}")
else:
performance_metric = len(new_tokens) <= len(original_tokens) * 1.2 # %20 tolerans
if performance_metric:
print("İngilizce yeteneği korunmuş (kabul edilebilir token sayısı)")
else:
inefficiency = (len(new_tokens) / len(original_tokens) - 1) * 100
print(f"İngilizce verimlilik kaybı: %{inefficiency:.2f}")
# Geçici dosyaları temizle (opsiyonel)
# print("Geçici dosyalar temizleniyor...")
# import shutil
# shutil.rmtree(temp_dir)
print("\nÖNEMLİ KULLANIM TALİMATLARI:")
print("-----------------------------")
print(f"1. Eğitim kodunuzda, model ve tokenizer yüklemek için şu yolu kullanın: {config.OUTPUT_DIR}")
print("2. Fine-tuning veri setinizde hem Türkçe hem İngilizce içerik bulundurun.")
print("3. Eğitim sırasında ilk epoch'larda düşük öğrenme hızı kullanarak embedding katmanının adapte olmasını sağlayın.")
if __name__ == "__main__":
main()