![]() |
![]() |
![]() |
|
![]() |
फ़ाइन-ट्यूनिंग से, मॉडल की सामान्य जानकारी और आपके ऐप्लिकेशन के लिए ज़रूरी खास जानकारी के बीच के अंतर को कम करने में मदद मिलती है. इससे, मॉडल की परफ़ॉर्मेंस बेहतर होती है और वह ज़्यादा सटीक जवाब देता है. कोई भी मॉडल हर टास्क के लिए सही नहीं होता. इसलिए, फ़ाइन-ट्यूनिंग की मदद से इसे आपके डोमेन के हिसाब से बनाया जाता है.
मान लें कि आपकी कंपनी "Shibuya Financial" कई तरह के जटिल फ़ाइनेंशियल प्रॉडक्ट ऑफ़र करती है. जैसे, इन्वेस्टमेंट ट्रस्ट, NISA खाते (टैक्स में छूट वाला बचत खाता), और होम लोन. आपकी ग्राहक सहायता टीम, इंटरनल नॉलेज बेस का इस्तेमाल करती है. इससे, वह ग्राहकों के सवालों के जवाब तुरंत ढूंढ पाती है.
सेटअप
इस ट्यूटोरियल को शुरू करने से पहले, यह तरीका अपनाएं:
- EmbeddingGemma को ऐक्सेस करने के लिए, Hugging Face में लॉग इन करें. इसके बाद, Gemma मॉडल के लिए लाइसेंस स्वीकार करें को चुनें.
- Hugging Face का ऐक्सेस टोकन जनरेट करें और Colab से लॉगिन करने के लिए इसका इस्तेमाल करें.
यह नोटबुक, सीपीयू या जीपीयू पर चलेगी.
Python पैकेज इंस्टॉल करना
EmbeddingGemma मॉडल को चलाने और एम्बेडिंग जनरेट करने के लिए ज़रूरी लाइब्रेरी इंस्टॉल करें. Sentence Transformers, टेक्स्ट और इमेज एम्बेडिंग के लिए Python फ़्रेमवर्क है. ज़्यादा जानकारी के लिए, Sentence Transformers का दस्तावेज़ देखें.
pip install -U sentence-transformers git+https://github.com/huggingface/transformers@v4.56.0-Embedding-Gemma-preview
लाइसेंस स्वीकार करने के बाद, मॉडल को ऐक्सेस करने के लिए आपके पास मान्य Hugging Face टोकन होना चाहिए.
# Login into Hugging Face Hub
from huggingface_hub import login
login()
मॉडल लोड करें
EmbeddingGemma की मदद से मॉडल क्लास का इंस्टेंस बनाने के लिए, sentence-transformers
लाइब्रेरी का इस्तेमाल करें.
import torch
from sentence_transformers import SentenceTransformer
device = "cuda" if torch.cuda.is_available() else "cpu"
model_id = "google/embeddinggemma-300M"
model = SentenceTransformer(model_id).to(device=device)
print(f"Device: {model.device}")
print(model)
print("Total number of parameters in the model:", sum([p.numel() for _, p in model.named_parameters()]))
Device: cuda:0 SentenceTransformer( (0): Transformer({'max_seq_length': 2048, 'do_lower_case': False, 'architecture': 'Gemma3TextModel'}) (1): Pooling({'word_embedding_dimension': 768, 'pooling_mode_cls_token': False, 'pooling_mode_mean_tokens': True, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False, 'pooling_mode_weightedmean_tokens': False, 'pooling_mode_lasttoken': False, 'include_prompt': True}) (2): Dense({'in_features': 768, 'out_features': 3072, 'bias': False, 'activation_function': 'torch.nn.modules.linear.Identity'}) (3): Dense({'in_features': 3072, 'out_features': 768, 'bias': False, 'activation_function': 'torch.nn.modules.linear.Identity'}) (4): Normalize() ) Total number of parameters in the model: 307581696
फ़ाइन-ट्यूनिंग के लिए डेटासेट तैयार करना
यह सबसे अहम हिस्सा है. आपको एक ऐसा डेटासेट बनाना होगा जो मॉडल को यह सिखाए कि आपके खास संदर्भ में "मिलता-जुलता" का क्या मतलब है. इस डेटा को अक्सर ट्रिपलेट के तौर पर स्ट्रक्चर किया जाता है: (ऐंकर, पॉज़िटिव, नेगेटिव)
- ऐंकर: ओरिजनल क्वेरी या वाक्य.
- पॉज़िटिव: ऐसा वाक्य जो अर्थ के हिसाब से ऐंकर वाक्य से काफ़ी मिलता-जुलता हो या बिलकुल एक जैसा हो.
- नेगेटिव: ऐसा वाक्य जो मिलते-जुलते विषय पर हो, लेकिन उसका मतलब अलग हो.
इस उदाहरण में, हमने सिर्फ़ तीन ट्रिपलेट तैयार किए हैं. हालांकि, किसी असली ऐप्लिकेशन के लिए, आपको बेहतर परफ़ॉर्मेंस पाने के लिए बहुत बड़े डेटासेट की ज़रूरत होगी.
from datasets import Dataset
dataset = [
["How do I open a NISA account?", "What is the procedure for starting a new tax-free investment account?", "I want to check the balance of my regular savings account."],
["Are there fees for making an early repayment on a home loan?", "If I pay back my house loan early, will there be any costs?", "What is the management fee for this investment trust?"],
["What is the coverage for medical insurance?", "Tell me about the benefits of the health insurance plan.", "What is the cancellation policy for my life insurance?"],
]
# Convert the list-based dataset into a list of dictionaries.
data_as_dicts = [ {"anchor": row[0], "positive": row[1], "negative": row[2]} for row in dataset ]
# Create a Hugging Face `Dataset` object from the list of dictionaries.
train_dataset = Dataset.from_list(data_as_dicts)
print(train_dataset)
Dataset({ features: ['anchor', 'positive', 'negative'], num_rows: 3 })
फ़ाइन ट्यूनिंग से पहले
"टैक्स-फ़्री निवेश" के लिए की गई खोज के नतीजे, समानता स्कोर के साथ इस तरह से दिख सकते हैं:
- दस्तावेज़: NISA खाता खोलना (स्कोर: 0.45)
- दस्तावेज़: सामान्य बचत खाता खोलना (स्कोर: 0.48) <- मिलता-जुलता स्कोर, भ्रम पैदा कर सकता है
- दस्तावेज़: होम लोन के लिए आवेदन करने से जुड़ी गाइड (स्कोर: 0.42)
task_name = "STS"
def get_scores(query, documents):
# Calculate embeddings by calling model.encode()
query_embeddings = model.encode(query, prompt=task_name)
doc_embeddings = model.encode(documents, prompt=task_name)
# Calculate the embedding similarities
similarities = model.similarity(query_embeddings, doc_embeddings)
for idx, doc in enumerate(documents):
print("Document: ", doc, "-> 🤖 Score: ", similarities.numpy()[0][idx])
query = "I want to start a tax-free installment investment, what should I do?"
documents = ["Opening a NISA Account", "Opening a Regular Savings Account", "Home Loan Application Guide"]
get_scores(query, documents)
Document: Opening a NISA Account -> 🤖 Score: 0.45698774 Document: Opening a Regular Savings Account -> 🤖 Score: 0.48092696 Document: Home Loan Application Guide -> 🤖 Score: 0.42127067
ट्रेनिंग
Python में sentence-transformers
जैसे फ़्रेमवर्क का इस्तेमाल करके, बेस मॉडल धीरे-धीरे आपकी वित्तीय शब्दावली में मौजूद बारीकियों को सीखता है.
from sentence_transformers import SentenceTransformerTrainer, SentenceTransformerTrainingArguments
from sentence_transformers.losses import MultipleNegativesRankingLoss
from transformers import TrainerCallback
loss = MultipleNegativesRankingLoss(model)
args = SentenceTransformerTrainingArguments(
# Required parameter:
output_dir="my-embedding-gemma",
# Optional training parameters:
prompts=model.prompts[task_name], # use model's prompt to train
num_train_epochs=5,
per_device_train_batch_size=1,
learning_rate=2e-5,
warmup_ratio=0.1,
# Optional tracking/debugging parameters:
logging_steps=train_dataset.num_rows,
report_to="none",
)
class MyCallback(TrainerCallback):
"A callback that evaluates the model at the end of eopch"
def __init__(self, evaluate):
self.evaluate = evaluate # evaluate function
def on_log(self, args, state, control, **kwargs):
# Evaluate the model using text generation
print(f"Step {state.global_step} finished. Running evaluation:")
self.evaluate()
def evaluate():
get_scores(query, documents)
trainer = SentenceTransformerTrainer(
model=model,
args=args,
train_dataset=train_dataset,
loss=loss,
callbacks=[MyCallback(evaluate)]
)
trainer.train()
Step 3 finished. Running evaluation: Document: Opening a NISA Account -> 🤖 Score: 0.6449194 Document: Opening a Regular Savings Account -> 🤖 Score: 0.44123 Document: Home Loan Application Guide -> 🤖 Score: 0.46752414 Step 6 finished. Running evaluation: Document: Opening a NISA Account -> 🤖 Score: 0.68873787 Document: Opening a Regular Savings Account -> 🤖 Score: 0.34069622 Document: Home Loan Application Guide -> 🤖 Score: 0.50065553 Step 9 finished. Running evaluation: Document: Opening a NISA Account -> 🤖 Score: 0.7148906 Document: Opening a Regular Savings Account -> 🤖 Score: 0.30480516 Document: Home Loan Application Guide -> 🤖 Score: 0.52454984 Step 12 finished. Running evaluation: Document: Opening a NISA Account -> 🤖 Score: 0.72614634 Document: Opening a Regular Savings Account -> 🤖 Score: 0.29255486 Document: Home Loan Application Guide -> 🤖 Score: 0.5370023 Step 15 finished. Running evaluation: Document: Opening a NISA Account -> 🤖 Score: 0.7294032 Document: Opening a Regular Savings Account -> 🤖 Score: 0.2893038 Document: Home Loan Application Guide -> 🤖 Score: 0.54087913 Step 15 finished. Running evaluation: Document: Opening a NISA Account -> 🤖 Score: 0.7294032 Document: Opening a Regular Savings Account -> 🤖 Score: 0.2893038 Document: Home Loan Application Guide -> 🤖 Score: 0.54087913 TrainOutput(global_step=15, training_loss=0.009651281436261646, metrics={'train_runtime': 63.2486, 'train_samples_per_second': 0.237, 'train_steps_per_second': 0.237, 'total_flos': 0.0, 'train_loss': 0.009651281436261646, 'epoch': 5.0})
फ़ाइन-ट्यूनिंग के बाद
अब उसी खोज के लिए, ज़्यादा सटीक नतीजे मिलते हैं:
- दस्तावेज़: NISA खाता खोलना (स्कोर: 0.72) <- ज़्यादा भरोसेमंद
- दस्तावेज़: रेगुलर सेविंग खाता खोलना (स्कोर: 0.28) <- ज़ाहिर तौर पर कम काम का है
- दस्तावेज़: होम लोन के लिए आवेदन करने से जुड़ी गाइड (स्कोर: 0.54)
get_scores(query, documents)
Document: Opening a NISA Account -> 🤖 Score: 0.7294032 Document: Opening a Regular Savings Account -> 🤖 Score: 0.2893038 Document: Home Loan Application Guide -> 🤖 Score: 0.54087913
अपने मॉडल को Hugging Face Hub पर अपलोड करने के लिए, Sentence Transformers लाइब्रेरी से push_to_hub
तरीके का इस्तेमाल किया जा सकता है.
अपने मॉडल को अपलोड करने से, इसे सीधे तौर पर Hub से ऐक्सेस करना आसान हो जाता है. साथ ही, इसे दूसरों के साथ शेयर किया जा सकता है और अपने काम का वर्शन बनाया जा सकता है. अपलोड करने के बाद, कोई भी व्यक्ति कोड की एक लाइन की मदद से आपके मॉडल को लोड कर सकता है. इसके लिए, उसे सिर्फ़ मॉडल के यूनीक आईडी <username>/my-embedding-gemma
का रेफ़रंस देना होगा
# Push to Hub
model.push_to_hub("my-embedding-gemma")
खास जानकारी और अगले चरण
अब आपने Sentence Transformers लाइब्रेरी का इस्तेमाल करके, EmbeddingGemma मॉडल को किसी खास डोमेन के लिए फ़ाइन-ट्यून करने का तरीका जान लिया है.
जानें कि EmbeddingGemma की मदद से और क्या-क्या किया जा सकता है:
- Sentence Transformers के दस्तावेज़ में ट्रेनिंग की खास जानकारी
- Sentence Transformers की मदद से एम्बेडिंग जनरेट करना
- Gemma कुकबुक में RAG का सामान्य उदाहरण