Turkish GPT-2 Large - DeepSeek Soru-Cevap İnce Ayarlı Model (kayrab/turkish-gpt2-large-deepseek-qa)
Bu model, ytu-ce-cosmos/turkish-gpt2-large temel alınarak, belirli bir soru-cevap veri kümesi üzerinde LoRA (Low-Rank Adaptation) yöntemiyle ince ayarlanmış (fine-tuned) bir Türkçe dil modelidir.
Model Açıklaması
Model, kendisine <SORU>
ve <CEVAP>
etiketleriyle yapılandırılmış bir biçimde sunulan sorulara yanıt vermek üzere eğitilmiştir. Eğitimde kullanılan cevaplar DeepSeek modeli tarafından üretilmiştir. Amaç, temel modelin belirli bir talimat biçimine uyarak tutarlı ve bağlama uygun cevaplar üretme yeteneğini geliştirmektir.
Eğitim Verisi
Model, aşağıdaki yapıya sahip bir .csv
dosyasındaki verilerle eğitilmiştir:
- Soru: Türkçe sorunun metni.
- DeepSeek cevabı: İlgili soru için DeepSeek tarafından üretilmiş cevap metni.
Eğitim sırasında veri, modelin girdi/çıktı sınırlarını anlaması için özel etiketlerle biçimlendirilmiştir:
<SORU> [Soru metni buraya gelecek] </SORU> <CEVAP> [Cevap metni buraya gelecek] </CEVAP><|endoftext|>
<SORU>
ve</SORU>
: Sorunun başlangıcını ve bitişini işaretler.<CEVAP>
ve</CEVAP>
: Cevabın başlangıcını ve bitişini işaretler.<|endoftext|>
: GPT-2'nin standart metin sonu (EOS) belirteci olup, her örneğin bittiğini gösterir.
Bu özel belirteçler tokenizer'a eklenmiş ve modelin kelime dağarcığı genişletilmiştir.
Eğitim Prosedürü
Model, Hugging Face transformers
ve trl
(Transformer Reinforcement Learning) kütüphaneleri kullanılarak SFTTrainer
(Supervised Fine-tuning Trainer) ile eğitilmiştir. Eğitimde kullanılan temel hiperparametreler şunlardır:
- Öğrenme Oranı (Learning Rate): 1e-4
- Batch Büyüklüğü (Per Device): 2
- Gradyan Biriktirme Adımları (Gradient Accumulation Steps): 8 (Etkin batch büyüklüğü: 2 * 8 * #GPU)
- Epoch Sayısı: 2
- Maksimum Sekans Uzunluğu (Max Sequence Length): 1024 token
- Optimizatör (Optimizer): paged_adamw_8bit (Bellek verimliliği için)
- Ağırlık Azaltma (Weight Decay): 0.01
- Isınma Oranı (Warmup Ratio): 0.03
- LR Zamanlayıcı Tipi (LR Scheduler Type): linear
- Maksimum Gradyan Normu (Max Grad Norm): 0.1
- LoRA Rank (r): 8
- LoRA Alpha (α): 16
- LoRA Hedef Modüller (Target Modules):
c_attn
,c_proj
,c_fc
(GPT-2 mimarisine uygun dikkat ve feed-forward katmanları) - Eğitim Hassasiyeti: fp16
Eğitim sırasında, padding belirteçleri ve özel <SORU>
, </SORU>
, <CEVAP>
belirteçleri kayıp (loss) hesaplamasından maskelenmiştir (ignore_index = -100
). Yalnızca cevap kısmındaki (</CEVAP>
hariç) belirteçler üzerinden öğrenme gerçekleşmiştir.
Eğitim Kayıp Grafiği (Training Loss):
Eğitim süreci boyunca kayıp değerinin (loss) değişimi aşağıdaki grafikte görülebilir.
Nasıl Kullanılır
Modeli transformers
kütüphanesi ile kolayca kullanabilirsiniz. Model, girdiyi eğitimde kullanılan biçimde beklemektedir (<SORU> ... </SORU> <CEVAP>
).
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
# Model ve tokenizer adını belirtin
model_name = "kayrab/turkish-gpt2-large-deepseek-qa"
# Tokenizer'ı yükleyin (use_fast=True önerilir)
tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True)
# Modeli yükleyin (GPU varsa otomatik olarak GPU'ya yükler)
# Düşük bellekli GPU'lar için dtype=torch.float16 veya torch.bfloat16 kullanabilirsiniz
model = AutoModelForCausalLM.from_pretrained(
model_name,
# torch_dtype=torch.float16, # Opsiyonel: fp16 kullanmak için
device_map="auto" # Modeli uygun cihaza (GPU/CPU) dağıtır
)
# Kullanılacak soruyu tanımlayın
soru = "Türkiye'nin en kalabalık şehri hangisidir ve neden önemlidir?"
# Soruyu modelin beklediği biçime getirin
# Dikkat: Prompt'un sonunda <CEVAP> etiketi ve bir boşluk olmalı!
prompt = f"<SORU> {soru} </SORU> <CEVAP> "
# Girdiyi token'lara çevirin ve modelin cihazına gönderin
inputs = tokenizer(prompt, return_tensors="pt", return_attention_mask=False).to(model.device)
# Cevap üretme parametreleri
# </CEVAP> token'ını EOS (End Of Sentence) olarak kullanacağız
eos_token_id = tokenizer.convert_tokens_to_ids("</CEVAP>")
if eos_token_id == tokenizer.unk_token_id: # Eğer token eklenmemişse (nadiren olur)
eos_token_id = tokenizer.eos_token_id
# Metin üretme (generate) fonksiyonunu çağırın
outputs = model.generate(
**inputs,
max_new_tokens=150, # Üretilecek maksimum yeni token sayısı
eos_token_id=eos_token_id, # Bu token üretildiğinde dur
pad_token_id=tokenizer.eos_token_id, # Padding için EOS kullan
do_sample=True, # Olasılıksal örnekleme yap
temperature=0.7, # Daha tutarlı çıktılar için sıcaklığı düşür
top_p=0.9, # Nucleus sampling
no_repeat_ngram_size=3 # 3-gram tekrarını engelle
)
# Üretilen tokenları alın (girdi prompt'u hariç)
output_tokens = outputs[0, inputs["input_ids"].shape[1]:]
# Tokenları metne çevirin
# skip_special_tokens=True, özel token'ları (örn: <|endoftext|>) çıktıdan kaldırır
cevap = tokenizer.decode(output_tokens, skip_special_tokens=True)
# </CEVAP> etiketi kalıntılarını temizle (generate bazen tam EOS'ta durmaz)
cevap_temiz = cevap.split("</CEVAP>")[0].strip()
print("-" * 20)
print(f"Soru: {soru}")
print("-" * 20)
print(f"Üretilen Cevap: {cevap_temiz}")
print("-" * 20)
# Örnek Çıktı (Modele göre değişebilir):
# --------------------
# Soru: Türkiye'nin en kalabalık şehri hangisidir ve neden önemlidir?
# --------------------
# Üretilen Cevap: Türkiye'nin en kalabalık şehri İstanbul'dur. İstanbul, tarihi, kültürel ve ekonomik açıdan büyük bir öneme sahiptir. İki kıtayı birbirine bağlayan stratejik konumu, zengin tarihi mirası ve Türkiye ekonomisinin merkezi olması nedeniyle önemlidir.
# --------------------
Değerlendirme Sonuçları
Modelin performansı, eğitim veri kümesinde bulunmayan, özel olarak hazırlanmış bir soru kümesi üzerinde de sınanmıştır. Bu sınama için kullanılan sorular ve modelin ürettiği cevaplar gpt2_large_deepseek.csv
dosyasında yer almaktadır.
gpt2_large_deepseek.csv dosyasını inceleyerek modelin farklı türdeki sorulara verdiği yanıtların kalitesini görebilirsiniz.
Sınırlılıklar ve Dikkat Edilmesi Gerekenler
- Modelin performansı, girdi sorusunun eğitim verisindeki biçim ve tarza ne kadar benzediğine bağlıdır.
- Model, temel modelden (turkish-gpt2-large) ve eğitim verisinden (DeepSeek cevapları) kaynaklanan yanlılıkları (bias) miras almış olabilir.
- Üretilen cevapların doğruluğu her zaman garanti edilmez ve kritik uygulamalar için kontrol edilmelidir.
- Model,
<SORU> ... </SORU> <CEVAP>
biçimi dışında verilen girdilere beklenmedik veya anlamsız yanıtlar üretebilir.
Turkish GPT-2 Large - DeepSeek Question-Answering Fine-tuned Model (kayrab/turkish-gpt2-large-deepseek-qa)
This model is a Turkish language model fine-tuned using the LoRA (Low-Rank Adaptation) method on a specific question-answering dataset, based on ytu-ce-cosmos/turkish-gpt2-large.
Model Description
The model is trained to respond to questions presented in a structured format with <SORU>
and <CEVAP>
tags. The answers used during training were generated by the DeepSeek model. The goal is to enhance the base model's ability to produce consistent and contextually appropriate answers following a specific instruction format.
Training Data
The model was trained on data from a .csv
file with the following structure:
- Soru: The text of the Turkish question.
- DeepSeek cevabı: The answer text generated by DeepSeek for the corresponding question.
During training, the data was formatted with special tags to help the model understand input/output boundaries:
<SORU> [Question text here] </SORU> <CEVAP> [Answer text here] </CEVAP><|endoftext|>
<SORU>
and</SORU>
: Mark the beginning and end of the question.<CEVAP>
and</CEVAP>
: Mark the beginning and end of the answer.<|endoftext|>
: GPT-2's standard end-of-text (EOS) token, indicating the end of each example. These special tokens were added to the tokenizer, expanding the model's vocabulary.
Training Procedure
The model was trained using the Hugging Face transformers
and trl
(Transformer Reinforcement Learning) libraries with the SFTTrainer
(Supervised Fine-tuning Trainer). The core hyperparameters used during training are:
- Learning Rate: 1e-4
- Batch Size (Per Device): 2
- Gradient Accumulation Steps: 8 (Effective batch size: 2 * 8 * #GPUs)
- Number of Epochs: 2
- Maximum Sequence Length: 1024 tokens
- Optimizer: paged_adamw_8bit (For memory efficiency)
- Weight Decay: 0.01
- Warmup Ratio: 0.03
- LR Scheduler Type: linear
- Max Grad Norm: 0.1
- LoRA Rank (r): 8
- LoRA Alpha (α): 16
- LoRA Target Modules:
c_attn
,c_proj
,c_fc
(Attention and feed-forward layers suitable for GPT-2 architecture) - Training Precision: fp16
During training, padding tokens and the special tokens <SORU>
, </SORU>
, <CEVAP>
were masked from the loss calculation (ignore_index = -100
). Learning occurred only over the tokens in the answer part (excluding </CEVAP>
).
Training Loss Graph:
The change in the loss value during the training process can be seen in the graph below.
How to Use
You can easily use the model with the transformers
library. The model expects the input in the format used during training (<SORU> ... </SORU> <CEVAP>
).
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
# Specify the model and tokenizer name
model_name = "kayrab/turkish-gpt2-large-deepseek-qa"
# Load the tokenizer (use_fast=True is recommended)
tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True)
# Load the model (automatically loads to GPU if available)
# For low-memory GPUs, you can use dtype=torch.float16 or torch.bfloat16
model = AutoModelForCausalLM.from_pretrained(
model_name,
# torch_dtype=torch.float16, # Optional: to use fp16
device_map="auto" # Distributes the model to the appropriate device (GPU/CPU)
)
# Define the question to use
soru = "Türkiye'nin en kalabalık şehri hangisidir ve neden önemlidir?" # "Which is Turkey's most populous city and why is it important?"
# Format the question into the format expected by the model
# Note: The prompt must end with the <CEVAP> tag and a space!
prompt = f"<SORU> {soru} </SORU> <CEVAP> "
# Tokenize the input and send it to the model's device
inputs = tokenizer(prompt, return_tensors="pt", return_attention_mask=False).to(model.device)
# Answer generation parameters
# We will use the </CEVAP> token as EOS (End Of Sentence)
eos_token_id = tokenizer.convert_tokens_to_ids("</CEVAP>")
if eos_token_id == tokenizer.unk_token_id: # If the token wasn't added (rarely happens)
eos_token_id = tokenizer.eos_token_id
# Call the text generation (generate) function
outputs = model.generate(
**inputs,
max_new_tokens=150, # Maximum number of new tokens to generate
eos_token_id=eos_token_id, # Stop when this token is generated
pad_token_id=tokenizer.eos_token_id, # Use EOS for padding
do_sample=True, # Perform probabilistic sampling
temperature=0.7, # Lower temperature for more consistent outputs
top_p=0.9, # Nucleus sampling
no_repeat_ngram_size=3 # Prevent 3-gram repetition
)
# Get the generated tokens (excluding the input prompt)
output_tokens = outputs[0, inputs["input_ids"].shape[1]:]
# Decode the tokens into text
# skip_special_tokens=True removes special tokens (e.g., <|endoftext|>) from the output
cevap = tokenizer.decode(output_tokens, skip_special_tokens=True)
# Clean up any </CEVAP> tag remnants (generate sometimes doesn't stop exactly at EOS)
cevap_temiz = cevap.split("</CEVAP>")[0].strip()
print("-" * 20)
print(f"Soru (Question): {soru}")
print("-" * 20)
print(f"Üretilen Cevap (Generated Answer): {cevap_temiz}")
print("-" * 20)
# Example Output (May vary depending on the model):
# --------------------
# Soru (Question): Türkiye'nin en kalabalık şehri hangisidir ve neden önemlidir?
# --------------------
# Üretilen Cevap (Generated Answer): Türkiye'nin en kalabalık şehri İstanbul'dur. İstanbul, tarihi, kültürel ve ekonomik açıdan büyük bir öneme sahiptir. İki kıtayı birbirine bağlayan stratejik konumu, zengin tarihi mirası ve Türkiye ekonomisinin merkezi olması nedeniyle önemlidir.
# (English: Turkey's most populous city is Istanbul. Istanbul holds great importance historically, culturally, and economically. It is important due to its strategic location connecting two continents, its rich historical heritage, and being the center of Turkey's economy.)
# --------------------
Evaluation Results
The model's performance was also tested on a custom set of questions not present in the training dataset. The questions used for this test and the answers generated by the model are available in the gpt2_large_deepseek.csv
file.
You can examine the quality of the model's responses to different types of questions by reviewing the gpt2_large_deepseek.csv file.
Limitations and Considerations
- The model's performance depends on how closely the input question resembles the format and style of the training data.
- The model may have inherited biases from the base model (
turkish-gpt2-large
) and the training data (DeepSeek answers). - The accuracy of the generated answers is not always guaranteed and should be verified for critical applications.
- The model might produce unexpected or nonsensical responses to inputs given outside the
<SORU> ... </SORU> <CEVAP>
format.
- Downloads last month
- 20
Model tree for kayrab/turkish-gpt2-large-deepseek-qa
Base model
ytu-ce-cosmos/turkish-gpt2-large