Last chance! 50% off DataCamp Premium
Sale ends in
DeepSeek-R1-0528, DeepSeek R1 मॉडल का नवीनतम संस्करण है, जिसमें उन्नत तर्क और इन्फरेंस क्षमताएँ शामिल हैं। यह o3 और Gemini 2.5 Pro जैसे अग्रणी मॉडलों के समकक्ष है, जिससे यह दुनिया का सर्वश्रेष्ठ ओपन-सोर्स रीजनिंग मॉडल बनता है।
इस ट्यूटोरियल में, हम DeepSeek-R1-0528-Qwen3-8B मॉडल को Medical Reasoning Multiple Choice Question (MCQ) डेटासेट पर फाइन-ट्यून करेंगे। फाइन-ट्यूनिंग प्रक्रिया A, B, C, D विकल्पों के रूप में नई तर्क शैली और उत्तर जनरेशन प्रस्तुत करती है।
सबसे अच्छी बात? यह काम RTX 4090 जैसे कंज़्यूमर GPU पर किया जा सकता है, जिससे आप मॉडल को लोकली बिना किसी परेशानी के फाइन-ट्यून कर सकते हैं। अधिक जानने के लिए हमारा DeepSeek-R1 पर पूरा गाइड और हमारा फाइन-ट्यूनिंग गाइड देखें।
चित्र: लेखक द्वारा
हम RTX 4090 GPU और PyTorch 2.4.0 इमेज के साथ एक RunPod इंस्टेंस सेटअप करेंगे।

स्रोत: My Pods
RunPod कंसोल में "My Pods" सेक्शन पर जाएँ। Pod कॉन्फ़िगरेशन एडिट करें:

स्रोत: My Pods
Pod के चलने के बाद, आवश्यक Python पैकेज इंस्टॉल करें।
नोट कि Transformers लाइब्रेरी के नवीनतम संस्करण में कुछ ज्ञात समस्याएँ हैं, इसलिए हम इसके बजाय एक पुराने, स्थिर संस्करण को इंस्टॉल करेंगे।
%%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
मॉडलों को लोड करने या Hugging Face Hub पर अपडेट पुश करने के लिए, अपने API key का उपयोग करके Hugging Face CLI में लॉग इन करें
from huggingface_hub import login
import os
hf_token = os.environ.get("HF_TOKEN")
login(hf_token)
भले ही हमारे पास 24GB VRAM है, जो पूरे मॉडल को लोड करने के लिए पर्याप्त है, हम 4-बिट क्वांटाइज़ेशन का उपयोग करेंगे ताकि फाइन-ट्यूनिंग के लिए अधिक मेमोरी उपलब्ध रहे और स्थिरता सुनिश्चित हो। यह तरीका VRAM उपयोग को अनुकूलित करते हुए प्रदर्शन बनाए रखता है।
हम Hugging Face Hub से DeepSeek-R1-0528-Qwen3-8B मॉडल और टोकनाइज़र डाउनलोड और लोड करेंगे। हमारे कोर्स के साथ आप Hugging Face के साथ काम करना और Hub का गाइड भी सीख सकते हैं।
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
मॉडल लोड होने के बाद VRAM उपयोग की जाँच करने के लिए, निम्न कमांड चलाएँ:
!nvidia-smi
VRAM उपयोग लगभग 8.3GB है, जिससे लगभग दो-तिहाई मेमोरी फाइन-ट्यूनिंग के लिए उपलब्ध रहती है।

इस चरण में, हम training prompts तैयार करेंगे—प्रश्न और उत्तर के लिए placeholders के साथ एक टेम्पलेट बनाकर। हम डेटासेट को प्रॉम्प्ट शैली के अनुसार फ़ॉर्मैट करने के लिए एक Python फ़ंक्शन भी परिभाषित करेंगे और एक नया “text” कॉलम बनाएँगे।
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}
फिर हम mamachang/medical-reasoning लोड करेंगे, formatting_prompts_func फ़ंक्शन लागू करेंगे, और 11वें सैंपल के “text” कॉलम को प्रदर्शित करेंगे।
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])
टेक्स्ट कॉलम में सिस्टम प्रॉम्प्ट, प्रश्न, तर्क और उत्तर निम्नलिखित फ़ॉर्मैट में होते हैं:
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.
मॉडल को फाइन-ट्यून करने से पहले, हम तुलना के लिए एक बेसलाइन स्थापित करने हेतु इसकी बेस परफॉर्मेंस का परीक्षण करेंगे। इसमें एक इन्फरेंस प्रॉम्प्ट बनाना, डेटासेट से एक सैंपल प्रश्न चुनना, और बेस मॉडल का उपयोग कर प्रतिक्रिया जनरेट करना शामिल है।
हम इन्फरेंस के लिए एक प्रॉम्प्ट टेम्पलेट बनाएँगे जिसमें प्रश्न के लिए placeholder शामिल होगा।
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>
"""
फिर, हम 11वें सैंपल से प्रश्न चुनेंगे और उसे फ़ॉर्मैट कर टोकन्स में बदलकर मॉडल को देंगे।
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])
मॉडल की प्रतिक्रिया संतोषजनक नहीं थी। विश्लेषण अनुभाग अत्यधिक लंबा था, जिससे टोकन सीमा खर्च हो गई, और लंबे तर्क के कारण उत्तर अनुभाग कभी जनरेट ही नहीं हुआ।

इस चरण में, हम फाइन-ट्यूनिंग के लिए मॉडल और टोकनाइज़र तैयार करेंगे।
1. SFTTrainer सीधे टोकनाइज़र स्वीकार नहीं करता। इसके बजाय, हम DataCollatorForLanguageModeling क्लास (transformers लाइब्रेरी से) का उपयोग करके टोकनाइज़र को डेटा कोलेटेर में बदलेंगे।
from transformers import DataCollatorForLanguageModeling
data_collator = DataCollatorForLanguageModeling(
tokenizer=tokenizer,
mlm=False
)
हम मॉडल को फाइन-ट्यून करने के लिए LoRA (Low-Rank Adaptation) का उपयोग करेंगे। LoRA मॉडल के केवल एक छोटे उपसमुच्चय के पैरामीटर्स को संशोधित करता है, जिससे यह पूर्ण फाइन-ट्यूनिंग की तुलना में अत्यंत मेमोरी-कुशल और तेज़ बनता है।
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 हमें फाइन-ट्यूनिंग प्रक्रिया को कॉन्फ़िगर करने देता है और SFTTrainer मॉडल, डेटासेट, डेटा कोलेटेर, ट्रेनिंग आर्ग्यूमेंट्स और LoRA कॉन्फ़िगरेशन को एक ही वर्कफ़्लो में एकीकृत करके फाइन-ट्यूनिंग को सरल बनाता है।
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,
)
ट्रेनिंग शुरू करने से पहले, कैश को साफ़ करना और अनावश्यक मेमोरी व VRAM फुटप्रिंट हटाना महत्वपूर्ण है ताकि Out of Memory (OOM) त्रुटियों से बचा जा सके।
मेमोरी साफ़ होने के बाद, हम SFTTrainer का उपयोग करके ट्रेनिंग प्रक्रिया शुरू कर सकते हैं।
import gc, torch
gc.collect()
torch.cuda.empty_cache()
model.config.use_cache = False
trainer.train()
ट्रेनिंग के दौरान, आप अपने RunPod डैशबोर्ड पर जाकर GPU की निगरानी कर सकते हैं। आपको GPU उपयोग लगभग 100% के करीब दिखना चाहिए, जो इंगित करता है कि मॉडल GPU (न कि CPU) पर ट्रेन हो रहा है।

जैसे-जैसे ट्रेनिंग आगे बढ़ती है, आपको दिखेगा कि ट्रेनिंग लॉस धीरे-धीरे घट रहा है। यह इंगित करता है कि मॉडल सीख रहा है और सफलतापूर्वक फाइन-ट्यून हो रहा है।

मॉडल को फाइन-ट्यून करने के बाद, हम डेटासेट के उसी 11वें सैंपल प्रश्न को देकर इसकी परफॉर्मेंस का परीक्षण करेंगे। इससे हमें बेस मॉडल के साथ परिणामों की तुलना करने और फाइन-ट्यूनिंग से हुए सुधारों का आकलन करने में मदद मिलेगी।
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])
फाइन-ट्यून किए गए मॉडल की प्रतिक्रिया में उल्लेखनीय सुधार दिखता है:
<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>
फाइन-ट्यून किए गए मॉडल का आगे मूल्यांकन करने के लिए, हम डेटासेट के किसी अन्य सैंपल पर भी परीक्षण करेंगे और परिणाम देखेंगे।
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])
इस सैंपल पर फाइन-ट्यून किया गया मॉडल उत्कृष्ट प्रदर्शन करता है:
<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>
अगला चरण फाइन-ट्यून किए गए मॉडल को सेव करना और उसे Hugging Face Hub पर पुश करना है। इससे अन्य लोग इन्फरेंस या आगे की फाइन-ट्यूनिंग के लिए इस मॉडल का उपयोग कर सकते हैं।
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)
मॉडल सफलतापूर्वक पुश होने के बाद, यह Hugging Face Hub पर उपलब्ध होगा: kingabzpro/DeepSeek-R1-0528-Qwen3-8B-Medical-Reasoning.
फाइन-ट्यून किए गए मॉडल और एडेप्टर को Hugging Face Hub पर सेव करने के बाद, अब हम इसे वापस लोड करके जाँचेंगे कि मॉडल अपेक्षा के अनुसार कार्य करता है या नहीं। इसमें GPU मेमोरी साफ़ करना, बेस मॉडल और LoRA एडेप्टर लोड करना, और एक सैंपल प्रॉम्प्ट पर इन्फरेंस चलाना शामिल है।
1. GPU मेमोरी साफ़ करें ताकि किसी भी संभावित Out of Memory (OOM) समस्या से बचा जा सके। इससे मॉडल लोड करने के लिए एक साफ़ वातावरण सुनिश्चित होता है।
del model
del trainer
torch.cuda.empty_cache()
2. Hugging Face Hub से बेस मॉडल और फाइन-ट्यून किया LoRA एडेप्टर लोड करें। बेस मॉडल मेमोरी उपयोग को अनुकूलित करने के लिए 4-बिट क्वांटाइज़ेशन में लोड होगा, और LoRA एडेप्टर उसके साथ मर्ज किया जाएगा।
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. अब हम एक सैंपल प्रॉम्प्ट देकर फाइन-ट्यून किए गए मॉडल का परीक्षण करेंगे। प्रॉम्प्ट को टोकनाइज़ किया जाएगा, मॉडल से पास किया जाएगा, और प्रतिक्रिया को डिकोड किया जाएगा।
# 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])
फाइन-ट्यून किया मॉडल डेटासेट के समान प्रतिक्रिया देता है, जिससे पुष्टि होती है कि मॉडल और एडेप्टर सही तरीके से लोड हुए।
<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>
यदि उपरोक्त कोड चलाते समय आपको कोई समस्या आती है, तो fine-tuning-Deepseek-new-R1.ipynb नोटबुक देखें। इस नोटबुक का कई बार परीक्षण किया गया है और इसे RunPod या समान वातावरण में लोड करते ही सीधे काम करना चाहिए।
DeepSeek-R1-0528 मॉडल आज उपलब्ध सर्वश्रेष्ठ ओपन-सोर्स रीजनिंग मॉडलों में से एक है। जटिल तर्क कार्यों को करने की इसकी क्षमता, और ओपन-सोर्स प्रकृति, इसे डेवलपर्स और शोधकर्ताओं के लिए उत्कृष्ट विकल्प बनाती है। जबकि फाइन-ट्यून किया मॉडल पहले से ही प्रभावशाली परिणाम देता है, फाइन-ट्यूनिंग के परिणामों को और बेहतर करने के कई तरीके हैं:
इसके अलावा, इस गाइड का उपयोग किसी भी रीजनिंग डेटासेट पर DeepSeek R1 मॉडल को फाइन-ट्यून करने के लिए किया जा सकता है, जिसमें OpenAI के o3 जैसे अन्य मॉडलों से बनाए गए सिंथेटिक डेटासेट भी शामिल हैं। यहाँ दिखाई गई कुछ तकनीकों पर व्यावहारिक अभ्यास करने के लिए हमारे Fine-Tuning With Llama 3 कोर्स देखें। यदि आप मेडिकल डेटासेट्स के साथ अन्य मॉडलों को फाइन-ट्यून करने में रुचि रखते हैं, तो हमारा ट्यूटोरियल देखें, Brain MRI डेटासेट पर MedGemma का फाइन-ट्यूनिंग.
एक प्रमाणित डेटा साइंटिस्ट के रूप में, मैं अत्याधुनिक तकनीक का उपयोग करके नवाचारी मशीन लर्निंग अनुप्रयोग बनाने के लिए उत्साहित रहता/रहती हूँ। स्पीच रिकॉग्निशन, डेटा विश्लेषण और रिपोर्टिंग, MLOps, संवादात्मक AI और NLP में मजबूत पृष्ठभूमि के साथ, मैंने ऐसे बुद्धिमान सिस्टम विकसित करने में अपनी विशेषज्ञता निखारी है जो वास्तविक प्रभाव डाल सकें। तकनीकी दक्षता के अलावा, मैं जटिल अवधारणाओं को स्पष्ट और संक्षिप्त भाषा में प्रस्तुत करने में भी निपुण हूँ। परिणामस्वरूप, मैं डेटा साइंस पर एक मांग में रहने वाला/वाली ब्लॉगर बन गया/गई हूँ, और डेटा प्रोफेशनलों के बढ़ते समुदाय के साथ अपने अनुभव और विचार साझा करता/करती हूँ। वर्तमान में, मैं कंटेंट निर्माण और संपादन पर केंद्रित हूँ, बड़े भाषा मॉडलों के साथ काम करते हुए ऐसा प्रभावशाली और आकर्षक कंटेंट विकसित कर रहा/रही हूँ जो व्यवसायों और व्यक्तियों दोनों को अपने डेटा का अधिकतम लाभ उठाने में मदद कर सके।
शीर्ष DataCamp कोर्स
{count, plural, one {कोर्स} other {कोर्स}}
{count, plural, one {कोर्स} other {कोर्स}}
{count, plural, one {कोर्स} other {कोर्स}}