EmbeddingGemma را به خوبی تنظیم کنید

مشاهده در ai.google.dev در گوگل کولب اجرا کنید دویدن در کاگل باز کردن در Vertex AI مشاهده منبع در گیت‌هاب

تنظیم دقیق به از بین بردن شکاف بین درک عمومی یک مدل و دقت تخصصی و عملکرد بالای مورد نیاز برنامه شما کمک می‌کند. از آنجایی که هیچ مدل واحدی برای هر کاری کامل نیست، تنظیم دقیق آن را با دامنه خاص شما تطبیق می‌دهد.

تصور کنید شرکت شما، «شیبویا فایننشال»، محصولات مالی پیچیده و متنوعی مانند صندوق‌های سرمایه‌گذاری، حساب‌های NISA (یک حساب پس‌انداز با مزایای مالیاتی) و وام مسکن ارائه می‌دهد. تیم پشتیبانی مشتری شما از یک پایگاه دانش داخلی برای یافتن سریع پاسخ به سوالات مشتریان استفاده می‌کند.

راه‌اندازی

قبل از شروع این آموزش، مراحل زیر را انجام دهید:

  • با ورود به Hugging Face و انتخاب گزینه Acknowledge license for a Gemma model، به EmbeddingGemma دسترسی پیدا کنید.
  • یک توکن دسترسی به چهره‌ی در آغوش‌گیرنده ایجاد کنید و از آن برای ورود به سیستم از Colab استفاده کنید.

این نوت‌بوک یا با CPU یا با GPU کار خواهد کرد.

نصب بسته‌های پایتون

کتابخانه‌های مورد نیاز برای اجرای مدل EmbeddingGemma و ایجاد جاسازی‌ها را نصب کنید. Sentence Transformers یک چارچوب پایتون برای جاسازی متن و تصویر است. برای اطلاعات بیشتر، به مستندات Sentence Transformers مراجعه کنید.

pip install -U sentence-transformers git+https://github.com/huggingface/transformers@v4.56.0-Embedding-Gemma-preview

پس از پذیرش مجوز، برای دسترسی به مدل به یک توکن چهره در آغوش گیرنده معتبر نیاز دارید.

# Login into Hugging Face Hub
from huggingface_hub import login
login()

مدل بار

از کتابخانه‌های sentence-transformers برای ایجاد یک نمونه از کلاس مدل با EmbeddingGemma استفاده کنید.

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
})

قبل از تنظیم دقیق

جستجوی عبارت «سرمایه‌گذاری معاف از مالیات» ممکن است نتایج زیر را با امتیازهای تشابه ارائه دهد:

  1. سند: افتتاح حساب NISA (امتیاز: 0.51)
  2. سند: افتتاح حساب پس‌انداز عادی (امتیاز: 0.50) <- امتیاز مشابه، احتمالاً گیج‌کننده
  3. سند: راهنمای درخواست وام مسکن (امتیاز: 0.44)
task_name = "STS"

def get_scores(query, documents):
  # Calculate embeddings by calling model.encode()
  query_embeddings = model.encode(query, prompt_name=task_name)
  doc_embeddings = model.encode(documents, prompt_name=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.51571906
Document:  Opening a Regular Savings Account -> 🤖 Score:  0.5035889
Document:  Home Loan Application Guide -> 🤖 Score:  0.4406476

آموزش

با استفاده از چارچوبی مانند 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.6459116
Document:  Opening a Regular Savings Account -> 🤖 Score:  0.42690125
Document:  Home Loan Application Guide -> 🤖 Score:  0.40419024
Step 6 finished. Running evaluation:
Document:  Opening a NISA Account -> 🤖 Score:  0.68530923
Document:  Opening a Regular Savings Account -> 🤖 Score:  0.3611964
Document:  Home Loan Application Guide -> 🤖 Score:  0.40812016
Step 9 finished. Running evaluation:
Document:  Opening a NISA Account -> 🤖 Score:  0.7168733
Document:  Opening a Regular Savings Account -> 🤖 Score:  0.3449782
Document:  Home Loan Application Guide -> 🤖 Score:  0.44477722
Step 12 finished. Running evaluation:
Document:  Opening a NISA Account -> 🤖 Score:  0.73008573
Document:  Opening a Regular Savings Account -> 🤖 Score:  0.34124148
Document:  Home Loan Application Guide -> 🤖 Score:  0.4676212
Step 15 finished. Running evaluation:
Document:  Opening a NISA Account -> 🤖 Score:  0.73378766
Document:  Opening a Regular Savings Account -> 🤖 Score:  0.34055778
Document:  Home Loan Application Guide -> 🤖 Score:  0.47503752
Step 15 finished. Running evaluation:
Document:  Opening a NISA Account -> 🤖 Score:  0.73378766
Document:  Opening a Regular Savings Account -> 🤖 Score:  0.34055778
Document:  Home Loan Application Guide -> 🤖 Score:  0.47503752
TrainOutput(global_step=15, training_loss=0.009651267528511198, metrics={'train_runtime': 195.3004, 'train_samples_per_second': 0.077, 'train_steps_per_second': 0.077, 'total_flos': 0.0, 'train_loss': 0.009651267528511198, 'epoch': 5.0})

پس از تنظیم دقیق

همان جستجو اکنون نتایج بسیار واضح‌تری ارائه می‌دهد:

  1. سند: افتتاح حساب NISA (امتیاز: 0.73) <- اعتماد به نفس بسیار بیشتر
  2. سند: افتتاح حساب پس‌انداز عادی (امتیاز: ۰.۳۴) <- واضح است که ارتباط کمتری دارد
  3. سند: راهنمای درخواست وام مسکن (امتیاز: 0.47)
get_scores(query, documents)
Document:  Opening a NISA Account -> 🤖 Score:  0.73378766
Document:  Opening a Regular Savings Account -> 🤖 Score:  0.34055778
Document:  Home Loan Application Guide -> 🤖 Score:  0.47503752

برای آپلود مدل خود در Hugging Face Hub، می‌توانید از متد push_to_hub از کتابخانه Sentence Transformers استفاده کنید.

آپلود مدل شما، دسترسی به استنتاج مستقیم از Hub، اشتراک‌گذاری با دیگران و نسخه‌بندی کار شما را آسان می‌کند. پس از آپلود، هر کسی می‌تواند مدل شما را با یک خط کد، صرفاً با ارجاع به شناسه مدل منحصر به فرد آن <username>/my-embedding-gemma بارگذاری کند.

# Push to Hub
model.push_to_hub("my-embedding-gemma")

خلاصه و مراحل بعدی

اکنون یاد گرفته‌اید که چگونه یک مدل EmbeddingGemma را با تنظیم دقیق آن با کتابخانه Sentence Transformers برای یک دامنه خاص تطبیق دهید.

ببینید با EmbeddingGemma چه کارهای بیشتری می‌توانید انجام دهید: