Last chance! 50% off DataCamp Premium
Sale ends in
DeepSeek-R1-0528, DeepSeek R1 modelinin en son sürümüdür ve geliştirilmiş akıl yürütme ile çıkarım yetenekleri sunar. o3 ve Gemini 2.5 Pro gibi önde gelen modellerle aynı seviyededir ve onu dünyadaki en iyi açık kaynak akıl yürütme modeli yapar.
Bu eğitimde, DeepSeek-R1-0528-Qwen3-8B modelini bir Tıbbi Akıl Yürütme Çoktan Seçmeli Soru (MCQ) veri seti üzerinde ince ayar yapacağız. İnce ayar süreci, A, B, C, D seçenekleri biçiminde yeni bir akıl yürütme stili ve yanıt üretimi getirir.
En iyi yanı? Bunu RTX 4090 gibi tüketici sınıfı bir GPU üzerinde yapabilirsiniz; böylece modeli yerelde sorunsuzca ince ayar yapabilirsiniz. Daha fazlası için DeepSeek-R1 hakkındaki kapsamlı rehberimize ve ince ayar rehberimize göz atabilirsiniz.
Görsel: Yazar
RTX 4090 GPU ve PyTorch 2.4.0 imajı ile bir RunPod örneği kuracağız.

Kaynak: My Pods
RunPod konsolunda "My Pods" bölümüne gidin. Pod yapılandırmasını düzenleyin:

Kaynak: My Pods
Pod çalışır duruma geldikten sonra gerekli Python paketlerini kurun.
Not: Transformers kitaplığının en son sürümünde bilinen bazı sorunlar var; bu nedenle daha eski, kararlı bir sürümü kuracağız.
%%capture
%pip install -U transformers==4.52.1
%pip install -U datasets
%pip install -U accelerate
%pip install -U peft
%pip install -U trl
%pip install -U bitsandbytes
Modelleri yüklemek veya Hugging Face Hub'a güncellemeler göndermek için, API anahtarınızı kullanarak Hugging Face CLI'da oturum açın
from huggingface_hub import login
import os
hf_token = os.environ.get("HF_TOKEN")
login(hf_token)
Her ne kadar 24 GB VRAM'imiz olsa da ve bu, tam modeli yüklemek için yeterli olsa da, ince ayar için daha fazla bellek bırakmak ve kararlılığı sağlamak adına 4 bit kuantizasyon kullanacağız. Bu yaklaşım, performansı korurken VRAM kullanımını optimize etmemizi sağlar.
Hugging Face Hub'dan DeepSeek-R1-0528-Qwen3-8B modelini ve tokenizer'ını indirip yükleyeceğiz. Hugging Face ile çalışma ve Hub rehberi hakkında kursumuzdan daha fazlasını öğrenebilirsiniz.
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
import torch
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_use_double_quant=False,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
)
# Load tokenizer & model
model_dir = "deepseek-ai/DeepSeek-R1-0528-Qwen3-8B"
tokenizer = AutoTokenizer.from_pretrained(model_dir, use_fast=True)
model = AutoModelForCausalLM.from_pretrained(
model_dir,
quantization_config=bnb_config,
device_map="auto",
torch_dtype=torch.bfloat16,
trust_remote_code=True
)
model.config.use_cache = False
model.config.pretraining_tp = 1
Modeli yükledikten sonra VRAM kullanımını doğrulamak için aşağıdaki komutu çalıştırın:
!nvidia-smi
VRAM kullanımı yaklaşık 8,3 GB'tır ve belleğin üçte ikisi ince ayar için kullanılabilir durumda kalır.

Bu adımda, soru ve yanıt için yer tutucular içeren bir şablon oluşturarak eğitim istemlerini hazırlayacağız. Ayrıca veri setini istem stiline göre biçimlendirmek için bir Python fonksiyonu tanımlayacak ve yeni bir “text” sütunu oluşturacağız.
train_prompt_style = """
Please answer with one of the options in the bracket. Write reasoning in between <analysis></analysis>. Write the answer in between <answer></answer>.
### Question:
{}
### Response:
{}"""
EOS_TOKEN = tokenizer.eos_token # Must add EOS_TOKEN
def formatting_prompts_func(examples):
inputs = examples["input"]
outputs = examples["output"]
texts = []
for question, response in zip(inputs, outputs):
# Remove the "Q:" prefix from the question
question = question.replace("Q:", "")
# Append the EOS token to the response if it's not already there
if not response.endswith(tokenizer.eos_token):
response += tokenizer.eos_token
text = train_prompt_style.format(question, response)
texts.append(text)
return {"text": texts}
Ardından mamachang/medical-reasoning veri setini yükleyip formatting_prompts_func fonksiyonunu uygulayacağız ve 11. örneğin “text” sütununu görüntüleyeceğiz.
from datasets import load_dataset
dataset = load_dataset(
"mamachang/medical-reasoning",
split="train",
trust_remote_code=True,
)
dataset = dataset.map(
formatting_prompts_func,
batched=True,
)
print(dataset["text"][10])
Metin sütunu, sistem istemini, soruyu, akıl yürütmeyi ve yanıtı aşağıdaki biçimde içerir:
Please answer with one of the options in the bracket. Write reasoning in between <analysis></analysis>. Write the answer in between <answer></answer>.
### Question:
A research group wants to assess the relationship between childhood diet and cardiovascular disease in adulthood. A prospective cohort study of 500 children between 10 to 15 years of age is conducted in which the participants' diets are recorded for 1 year and then the patients are assessed 20 years later for the presence of cardiovascular disease. A statistically significant association is found between childhood consumption of vegetables and decreased risk of hyperlipidemia and exercise tolerance. When these findings are submitted to a scientific journal, a peer reviewer comments that the researchers did not discuss the study's validity. Which of the following additional analyses would most likely address the concerns about this study's design??
{'A': 'Blinding', 'B': 'Crossover', 'C': 'Matching', 'D': 'Stratification', 'E': 'Randomization'},
### Response:
<analysis>
This is a question about assessing the validity of a prospective cohort study. The study found an association between childhood diet and cardiovascular disease in adulthood. The peer reviewer is concerned that the researchers did not discuss the validity of the study design.
To address concerns about validity in a prospective cohort study, we need to consider potential confounding factors that could influence the results. The additional analysis suggested should help control for confounding.
Modeli ince ayar yapmadan önce, karşılaştırma için bir temel belirlemek amacıyla temel performansını test edeceğiz. Bu, bir çıkarım istemi oluşturmayı, veri setinden örnek bir soru seçmeyi ve temel modeli kullanarak bir yanıt üretmeyi içerir.
Çıkarım için soruya yer tutucu içeren bir istem şablonu oluşturacağız.
inference_prompt_style = """
Please answer with one of the options in the bracket. Write reasoning in between <analysis></analysis>. Write the answer in between <answer></answer>.
### Question:
{}
### Response:
<analysis>
"""
Ardından, 11. örnekteki soruyu seçecek ve biçimlendirdikten sonra token'lara dönüştürerek modele vereceğiz.
question = dataset[10]['input']
question = question.replace("Q:", "")
inputs = tokenizer(
[inference_prompt_style.format(question) + tokenizer.eos_token],
return_tensors="pt"
).to("cuda")
outputs = model.generate(
input_ids=inputs.input_ids,
attention_mask=inputs.attention_mask,
max_new_tokens=1200,
eos_token_id=tokenizer.eos_token_id,
use_cache=True,
)
response = tokenizer.batch_decode(outputs, skip_special_tokens=True)
print(response[0].split("### Response:")[1])
Modelin yanıtı tatmin edici değildi. Analiz bölümü aşırı uzundu, token sınırını tüketti ve uzun akıl yürütme nedeniyle yanıt bölümü hiç üretilmedi.

Bu adımda, modeli ve tokenizer'ı ince ayar için hazırlayacağız.
1. SFTTrainer doğrudan bir tokenizer kabul etmez. Bunun yerine, tokenizer'ı transformers kitaplığındaki DataCollatorForLanguageModeling sınıfını kullanarak bir veri birleştiriciye (data collator) dönüştüreceğiz.
from transformers import DataCollatorForLanguageModeling
data_collator = DataCollatorForLanguageModeling(
tokenizer=tokenizer,
mlm=False
)
Modeli ince ayar yapmak için LoRA (Low-Rank Adaptation) kullanacağız. LoRA, modelin yalnızca küçük bir alt kümesindeki parametreleri değiştirir; bu da onu tam ince ayara kıyasla oldukça bellek verimli ve hızlı kılar.
from peft import LoraConfig, get_peft_model
# LoRA config
peft_config = LoraConfig(
lora_alpha=16, # Scaling factor for LoRA
lora_dropout=0.05, # Add slight dropout for regularization
r=64, # Rank of the LoRA update matrices
bias="none", # No bias reparameterization
task_type="CAUSAL_LM", # Task type: Causal Language Modeling
target_modules=[
"q_proj",
"k_proj",
"v_proj",
"o_proj",
"gate_proj",
"up_proj",
"down_proj",
], # Target modules for LoRA
)
model = get_peft_model(model, peft_config)
TrainingArguments ince ayar sürecini yapılandırmamıza olanak tanır ve SFTTrainer model, veri seti, veri birleştirici, eğitim argümanları ve LoRA yapılandırmasını tek bir iş akışında birleştirerek ince ayarı basitleştirir.
from trl import SFTTrainer
from transformers import TrainingArguments
# Training Arguments
training_arguments = TrainingArguments(
output_dir="DeepSeek-R1-0528-Qwen3-8B-Medical-Reasoning",
per_device_train_batch_size=1,
per_device_eval_batch_size=1,
gradient_accumulation_steps=2,
optim="paged_adamw_32bit",
num_train_epochs=1,
logging_steps=0.2,
warmup_steps=10,
logging_strategy="steps",
learning_rate=2e-4,
fp16=False,
bf16=False,
group_by_length=True,
report_to="none"
)
# Initialize the Trainer
trainer = SFTTrainer(
model=model,
args=training_arguments,
train_dataset=dataset,
peft_config=peft_config,
data_collator=data_collator,
)
Eğitim sürecine başlamadan önce, Bellek Yetersiz (OOM) hatalarından kaçınmak için önbelleği temizlemek ve istenmeyen bellek ve VRAM izlerini kaldırmak önemlidir.
Bellek temizlendikten sonra, SFTTrainer kullanarak eğitim sürecini başlatabiliriz.
import gc, torch
gc.collect()
torch.cuda.empty_cache()
model.config.use_cache = False
trainer.train()
Eğitim sırasında, RunPod kontrol panelinize giderek GPU'yu izleyebilirsiniz. GPU kullanımının %100'e yakın olduğunu görmelisiniz; bu, modelin GPU'da (CPU'da değil) eğitildiğini gösterir.

Eğitim ilerledikçe, eğitim kaybının (loss) kademeli olarak azaldığını fark etmelisiniz. Bu, modelin öğrendiğini ve başarıyla ince ayar yapıldığını gösterir.

Modeli ince ayar yaptıktan sonra, veri setinden aynı 11. örnek soruyu vererek performansını test edeceğiz. Bu, temel model ile sonuçları karşılaştırmamıza ve ince ayarın sağladığı iyileştirmeleri değerlendirmemize olanak tanır.
question = dataset[10]['input']
question = question.replace("Q:", "")
inputs = tokenizer(
[inference_prompt_style.format(question,) + tokenizer.eos_token],
return_tensors="pt"
).to("cuda")
outputs = model.generate(
input_ids=inputs.input_ids,
attention_mask=inputs.attention_mask,
max_new_tokens=1200,
eos_token_id=tokenizer.eos_token_id,
use_cache=True,
)
response = tokenizer.batch_decode(outputs, skip_special_tokens=True)
print(response[0].split("### Response:")[1])
İnce ayarlı modelin yanıtı belirgin iyileşmeler gösteriyor:
<analysis>
This is a question about evaluating the validity of a prospective cohort study design. The study looked at childhood diet and cardiovascular disease in adulthood. The peer reviewer raised concerns about the study's validity, likely because it was an observational study without randomization or control group.
The question asks which additional analysis would most likely address the concerns about the study's design. The choices include blinding, crossover, matching, stratification, and randomization.
Randomization is the key to reducing bias in observational studies. By randomly assigning participants to different groups, you can control for confounding factors. The other choices do not directly address the lack of randomization in the original study design.
</analysis>
<answer>
E: Randomization
</answer>
İnce ayarlı modeli daha kapsamlı değerlendirmek için, veri setinden bir başka örnek üzerinde test edecek ve sonuçları gözlemleyeceğiz.
question = dataset[100]['input']
question = question.replace("Q:", "")
inputs = tokenizer(
[inference_prompt_style.format(question) + tokenizer.eos_token],
return_tensors="pt"
).to("cuda")
outputs = model.generate(
input_ids=inputs.input_ids,
attention_mask=inputs.attention_mask,
max_new_tokens=1200,
eos_token_id=tokenizer.eos_token_id,
use_cache=True,
)
response = tokenizer.batch_decode(outputs, skip_special_tokens=True)
print(response[0].split("### Response:")[1])
Model bu örnekte mükemmel bir performans sergiliyor:
<analysis>
This is a clinical vignette describing a 55-year-old man with burning and shooting pain in his feet and lower legs that worsens at night. He has a history of type 2 diabetes mellitus and hypertension. The description of the pain being burning and shooting in a symmetric distribution in the lower extremities, worsening at night, along with his history of diabetes, is most consistent with distal symmetric sensorimotor polyneuropathy. Autonomic neuropathy would not cause sensory symptoms. Isolated cranial nerve or peripheral nerve neuropathy would not explain the symmetric distribution. Radiculopathy would not explain the sensory symptoms.
</analysis>
<answer>
D: Distal symmetric sensorimotor polyneuropathy
</answer>
Sıradaki adım, ince ayarlı modeli kaydetmek ve Hugging Face Hub'a göndermektir. Bu, başkalarının ince ayarlı modeli çıkarım veya daha fazla ince ayar için kullanmasına olanak tanır.
new_model_name = "DeepSeek-R1-0528-Qwen3-8B-Medical-Reasoning"
trainer.model.push_to_hub(new_model_name)
trainer.processing_class.push_to_hub(new_model_name)
Model başarıyla gönderildiğinde, Hugging Face Hub üzerinde kullanılabilir olacaktır: kingabzpro/DeepSeek-R1-0528-Qwen3-8B-Medical-Reasoning.
İnce ayarlı modeli ve adaptörü Hugging Face Hub'a kaydettikten sonra, şimdi modeli geri yükleyerek beklendiği gibi çalışıp çalışmadığını test edeceğiz. Bu, GPU belleğini temizlemeyi, temel modeli ve LoRA adaptörünü yüklemeyi ve örnek bir istem üzerinde çıkarım yapmayı içerir.
1. Olası Bellek Yetersiz (OOM) sorunlarından kaçınmak için GPU belleğini temizleyin. Bu, modeli yüklemek için temiz bir ortam sağlar.
del model
del trainer
torch.cuda.empty_cache()
2. Temel modeli ve ince ayarlı LoRA adaptörünü Hugging Face Hub'dan yükleyin. Bellek kullanımını optimize etmek için temel model 4 bit kuantizasyonla yüklenecek ve LoRA adaptörü onunla birleştirilecektir.
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
from peft import PeftModel
import torch
# Base model
base_model_id = "deepseek-ai/DeepSeek-R1-0528-Qwen3-8B"
# Your fine-tuned LoRA adapter repository
lora_adapter_id = "kingabzpro/DeepSeek-R1-0528-Qwen3-8B-Medical-Reasoning"
# Load the model in 4-bit
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_use_double_quant=False,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
)
# Load base model
base_model = AutoModelForCausalLM.from_pretrained(
base_model_id,
device_map="auto",
torch_dtype=torch.bfloat16,
quantization_config=bnb_config,
trust_remote_code=True,
)
# Attach the LoRA adapter
model = PeftModel.from_pretrained(
base_model,
lora_adapter_id,
device_map="auto",
trust_remote_code=True,
)
# Load tokenizer
tokenizer = AutoTokenizer.from_pretrained(base_model_id, trust_remote_code=True)
3. Şimdi ince ayarlı modeli örnek bir istem vererek test edeceğiz. İstem, tokenize edilip modelden geçirilecek ve yanıt çözümlenecek.
# Inference example
prompt = """
Please answer with one of the options in the bracket. Write reasoning in between <analysis></analysis>. Write the answer in between <answer></answer>.
### Question:
A research group wants to assess the relationship between childhood diet and cardiovascular disease in adulthood.
A prospective cohort study of 500 children between 10 to 15 years of age is conducted in which the participants' diets are recorded for 1 year and then the patients are assessed 20 years later for the presence of cardiovascular disease.
A statistically significant association is found between childhood consumption of vegetables and decreased risk of hyperlipidemia and exercise tolerance.
When these findings are submitted to a scientific journal, a peer reviewer comments that the researchers did not discuss the study's validity.
Which of the following additional analyses would most likely address the concerns about this study's design?
{'A': 'Blinding', 'B': 'Crossover', 'C': 'Matching', 'D': 'Stratification', 'E': 'Randomization'},
### Response:
<analysis>
"""
inputs = tokenizer(
[prompt + tokenizer.eos_token],
return_tensors="pt"
).to("cuda")
outputs = model.generate(
input_ids=inputs.input_ids,
attention_mask=inputs.attention_mask,
max_new_tokens=1200,
eos_token_id=tokenizer.eos_token_id,
use_cache=True,
)
response = tokenizer.batch_decode(outputs, skip_special_tokens=True)
print(response[0].split("### Response:")[1])
İnce ayarlı model, veri setine benzer bir yanıt üretiyor; bu da modelin ve adaptörün doğru yüklendiğini teyit eder.
<analysis>
This is a question about evaluating the validity of a prospective cohort study design. The study looked at childhood diet and cardiovascular disease in adulthood. The peer reviewer was concerned about the study's validity.
To address concerns about validity in a prospective cohort study, we need to consider potential confounding factors. The choices given are different statistical methods that can help control for confounding.
Blinding and crossover designs are not applicable to a prospective cohort study. Matching and stratification can help control for confounding by balancing the distribution of confounders between groups. Randomization is the best way to minimize confounding by randomly assigning participants to different exposure groups.
</analysis>
<answer>
E: Randomization
</answer>
Yukarıdaki kodu çalıştırırken herhangi bir sorunla karşılaşırsanız, fine-tuning-Deepseek-new-R1.ipynb not defterine başvurun. Bu not defteri birden çok kez test edilmiştir ve RunPod veya benzeri bir ortamda yüklendiğinde doğrudan çalışmalıdır.
DeepSeek-R1-0528 modeli, bugün mevcut en iyi açık kaynak akıl yürütme modellerinden biridir. Karmaşık akıl yürütme görevlerini yerine getirme yeteneği ve açık kaynak doğası, onu geliştiriciler ve araştırmacılar için öne çıkan bir seçenek yapar. İnce ayarlı model zaten etkileyici sonuçlar verse de, ince ayar sonuçlarını daha da iyileştirmenin birkaç yolu vardır:
Ayrıca, bu rehber, DeepSeek R1 modelini OpenAI’nin o3 gibi diğer modeller kullanılarak oluşturulan sentetik veri setleri de dahil olmak üzere herhangi bir akıl yürütme veri seti üzerinde ince ayar yapmak için kullanılabilir. Burada gösterilen bazı tekniklerle uygulamalı çalışmak için Llama 3 ile Fine-Tuning kursumuza da katılabilirsiniz. Tıbbi veri setleriyle diğer modelleri ince ayar yapmakla ilgileniyorsanız, şu eğitimimize göz atın: Beyin MR Veri Seti Üzerinde MedGemma’nın İnce Ayarı.
Sertifikalı bir veri bilimcisi olarak, yenilikçi makine öğrenimi uygulamaları oluşturmak için en son teknolojileri kullanmaya büyük ilgi duyuyorum. Konuşma tanıma, veri analizi ve raporlama, MLOps, konuşma yapay zekası ve NLP alanlarında güçlü bir geçmişe sahip olarak, gerçek bir etki yaratabilecek akıllı sistemler geliştirme becerilerimi geliştirdim. Teknik uzmanlığımın yanı sıra, karmaşık kavramları açık ve özlü bir dille ifade etme yeteneğine sahip, becerikli bir iletişimciyim. Sonuç olarak, veri bilimi konusunda aranan bir blog yazarı oldum ve giderek büyüyen veri profesyonelleri topluluğuyla görüşlerimi ve deneyimlerimi paylaşıyorum. Şu anda, içerik oluşturma ve düzenlemeye odaklanıyorum. Büyük dil modelleriyle çalışarak, hem işletmelerin hem de bireylerin verilerinden en iyi şekilde yararlanmalarına yardımcı olabilecek güçlü ve ilgi çekici içerikler geliştiriyorum.
En İyi DataCamp Kursları
Kurs
Kurs
Kurs

blog
Abid Ali Awan
14 dk.
blog
Dario Radečić
15 dk.
Eğitim
Kurtis Pykes
8 dk.
Eğitim
Adel Nehme