বাক্য ট্রান্সফরমারের সাথে এমবেডিং তৈরি করুন

ai.google.dev-এ দেখুন Google Colab-এ চালান কাগলে চালান Vertex AI-তে খুলুন GitHub-এ উৎস দেখুন

EmbeddingGemma হল একটি হালকা ওজনের, খোলা এম্বেডিং মডেল যা মোবাইল ফোনের মতো দৈনন্দিন ডিভাইসে দ্রুত, উচ্চ-মানের পুনরুদ্ধারের জন্য ডিজাইন করা হয়েছে। মাত্র 308 মিলিয়ন প্যারামিটারে, এটি উন্নত AI কৌশলগুলি চালানোর জন্য যথেষ্ট দক্ষ, যেমন Retrieval Augmented Generation (RAG), সরাসরি আপনার স্থানীয় মেশিনে ইন্টারনেট সংযোগের প্রয়োজন নেই৷

সেটআপ

এই টিউটোরিয়ালটি শুরু করার আগে, নিম্নলিখিত পদক্ষেপগুলি সম্পূর্ণ করুন:

  • Hugging Face- এ লগ ইন করে Gemma মডেলের জন্য Acknowledge লাইসেন্স নির্বাচন করে Gemma-এ অ্যাক্সেস পান।
  • একটি আলিঙ্গন ফেস অ্যাক্সেস টোকেন তৈরি করুন এবং Colab থেকে লগইন করতে এটি ব্যবহার করুন।

এই নোটবুকটি CPU বা GPU-তে চলবে।

পাইথন প্যাকেজ ইনস্টল করুন

EmbeddingGemma মডেল চালানো এবং এম্বেডিং তৈরি করার জন্য প্রয়োজনীয় লাইব্রেরিগুলি ইনস্টল করুন। সেন্টেন্স ট্রান্সফরমার হল টেক্সট এবং ইমেজ এম্বেডিংয়ের জন্য একটি পাইথন ফ্রেমওয়ার্ক। আরও তথ্যের জন্য, বাক্য ট্রান্সফরমার ডকুমেন্টেশন দেখুন।

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

লোড মডেল

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

এম্বেডিং তৈরি করা হচ্ছে

একটি এম্বেডিং পাঠ্যের একটি সংখ্যাসূচক উপস্থাপনা, যেমন একটি শব্দ বা বাক্য, যা এর শব্দার্থগত অর্থ ক্যাপচার করে। মূলত, এটি সংখ্যার একটি তালিকা (একটি ভেক্টর) যা কম্পিউটারকে শব্দের সম্পর্ক এবং প্রসঙ্গ বুঝতে দেয়।

আসুন দেখি কিভাবে এমবেডিংগেমা তিনটি ভিন্ন শব্দ ["apple", "banana", "car"] প্রক্রিয়া করবে।

EmbeddingGemma প্রচুর পরিমাণে পাঠ্যের উপর প্রশিক্ষিত হয়েছে এবং শব্দ এবং ধারণার মধ্যে সম্পর্ক শিখেছে।

words = ["apple", "banana", "car"]

# Calculate embeddings by calling model.encode()
embeddings = model.encode(words)

print(embeddings)
for idx, embedding in enumerate(embeddings):
  print(f"Embedding {idx+1} (shape): {embedding.shape}")
[[-0.18476306  0.00167681  0.03773484 ... -0.07996225 -0.02348064
   0.00976741]
 [-0.21189538 -0.02657359  0.02513712 ... -0.08042689 -0.01999852
   0.00512146]
 [-0.18924113 -0.02551468  0.04486253 ... -0.06377774 -0.03699806
   0.03973572]]
Embedding 1: (768,)
Embedding 2: (768,)
Embedding 3: (768,)

মডেলটি প্রতিটি বাক্যের জন্য একটি সংখ্যাসূচক ভেক্টর বের করে। প্রকৃত ভেক্টরগুলি খুব দীর্ঘ (768), কিন্তু সরলতার জন্য, সেগুলিকে কয়েকটি মাত্রা সহ উপস্থাপন করা হয়।

মূলটি পৃথক সংখ্যাগুলি নয়, ভেক্টরগুলির মধ্যে দূরত্ব । যদি আমরা এই ভেক্টরগুলিকে বহুমাত্রিক স্থানে প্লট করি, apple এবং banana ভেক্টরগুলি একে অপরের খুব কাছাকাছি হবে। এবং car ভেক্টর অন্য দুটি থেকে অনেক দূরে থাকবে।

সাদৃশ্য নির্ধারণ

এই বিভাগে, আমরা নির্ণয় করতে এমবেডিং ব্যবহার করি কতটা শব্দগতভাবে ভিন্ন ভিন্ন বাক্য। এখানে আমরা উচ্চ, মাঝারি, এবং নিম্ন সাদৃশ্য স্কোর সহ উদাহরণ দেখাই।

  • উচ্চ মিল:

    • বাক্য A: "শেফ অতিথিদের জন্য একটি সুস্বাদু খাবার প্রস্তুত করেছেন।"
    • বাক্য B: "একটি সুস্বাদু রাতের খাবার রান্না করা হয়েছিল দর্শকদের জন্য শেফ দ্বারা।"
    • যুক্তি: উভয় বাক্যই ভিন্ন শব্দ এবং ব্যাকরণগত কাঠামো (সক্রিয় বনাম প্যাসিভ ভয়েস) ব্যবহার করে একই ঘটনা বর্ণনা করে। তারা একই মূল অর্থ প্রকাশ করে।
  • মাঝারি সাদৃশ্য:

    • বাক্য A: "তিনি মেশিন লার্নিংয়ে একজন বিশেষজ্ঞ।"
    • বাক্য B: "তার কৃত্রিম বুদ্ধিমত্তার প্রতি গভীর আগ্রহ আছে।"
    • যুক্তি: মেশিন লার্নিং কৃত্রিম বুদ্ধিমত্তার একটি উপক্ষেত্র হিসাবে বাক্যগুলি সম্পর্কিত। যাইহোক, তারা বিভিন্ন স্তরের ব্যস্ততা (বিশেষজ্ঞ বনাম আগ্রহ) সহ বিভিন্ন ব্যক্তি সম্পর্কে কথা বলে।
  • কম মিল:

    • বাক্য A: "টোকিওর আবহাওয়া আজ রৌদ্রোজ্জ্বল।"
    • বাক্য B: "আমাকে সপ্তাহের জন্য মুদি কিনতে হবে।"
    • যুক্তি: দুটি বাক্য সম্পূর্ণরূপে সম্পর্কহীন বিষয়ের উপর এবং কোন শব্দার্থিক ওভারল্যাপ শেয়ার করে না।
# The sentences to encode
sentence_high = [
    "The chef prepared a delicious meal for the guests.",
    "A tasty dinner was cooked by the chef for the visitors."
]
sentence_medium = [
    "She is an expert in machine learning.",
    "He has a deep interest in artificial intelligence."
]
sentence_low = [
    "The weather in Tokyo is sunny today.",
    "I need to buy groceries for the week."
]

for sentence in [sentence_high, sentence_medium, sentence_low]:
  print("🙋‍♂️")
  print(sentence)
  embeddings = model.encode(sentence)
  similarities = model.similarity(embeddings[0], embeddings[1])
  print("`-> 🤖 score: ", similarities.numpy()[0][0])
🙋‍♂️
['The chef prepared a delicious meal for the guests.', 'A tasty dinner was cooked by the chef for the visitors.']
`-> 🤖 score:  0.8002148
🙋‍♂️
['She is an expert in machine learning.', 'He has a deep interest in artificial intelligence.']
`-> 🤖 score:  0.45417833
🙋‍♂️
['The weather in Tokyo is sunny today.', 'I need to buy groceries for the week.']
`-> 🤖 score:  0.22262995

EmbeddingGemma এর সাথে প্রম্পট ব্যবহার করা

EmbeddingGemma দিয়ে সেরা এম্বেডিং তৈরি করতে, আপনার ইনপুট পাঠ্যের শুরুতে একটি "নির্দেশমূলক প্রম্পট" বা "টাস্ক" যোগ করা উচিত। এই প্রম্পটগুলি নির্দিষ্ট কাজের জন্য এমবেডিংগুলিকে অপ্টিমাইজ করে, যেমন নথি পুনরুদ্ধার বা প্রশ্নের উত্তর, এবং মডেলটিকে বিভিন্ন ইনপুট প্রকারের মধ্যে পার্থক্য করতে সাহায্য করে, যেমন একটি অনুসন্ধান ক্যোয়ারী বনাম একটি নথি।

কিভাবে প্রম্পট প্রয়োগ করবেন

আপনি তিনটি উপায়ে অনুমানের সময় একটি প্রম্পট প্রয়োগ করতে পারেন।

  1. prompt যুক্তি ব্যবহার করে
    encode পদ্ধতিতে সরাসরি সম্পূর্ণ প্রম্পট স্ট্রিংটি পাস করুন। এটি আপনাকে সুনির্দিষ্ট নিয়ন্ত্রণ দেয়।

    embeddings = model.encode(
        sentence,
        prompt="task: sentence similarity | query: "
    )
    
  2. prompt_name আর্গুমেন্ট ব্যবহার করে
    এর নামের দ্বারা একটি পূর্বনির্ধারিত প্রম্পট নির্বাচন করুন। এই প্রম্পটগুলি মডেলের কনফিগারেশন থেকে বা এটির শুরুর সময় লোড করা হয়।

    embeddings = model.encode(sentence, prompt_name="STS")
    
  3. ডিফল্ট প্রম্পট ব্যবহার করে
    আপনি যদি prompt বা prompt_name নির্দিষ্ট না করেন, তাহলে সিস্টেম স্বয়ংক্রিয়ভাবে প্রম্পট সেটটিকে default_prompt_name হিসাবে ব্যবহার করবে, যদি কোনো ডিফল্ট সেট না থাকে, তাহলে কোনো প্রম্পট প্রয়োগ করা হবে না।

    embeddings = model.encode(sentence)
    
print("Available tasks:")
for name, prefix in model.prompts.items():
  print(f" {name}: \"{prefix}\"")
print("-"*80)

for sentence in [sentence_high, sentence_medium, sentence_low]:
  print("🙋‍♂️")
  print(sentence)
  embeddings = model.encode(sentence, prompt_name="STS")
  similarities = model.similarity(embeddings[0], embeddings[1])
  print("`-> 🤖 score: ", similarities.numpy()[0][0])
Available tasks:
 query: "task: search result | query: "
 document: "title: none | text: "
 BitextMining: "task: search result | query: "
 Clustering: "task: clustering | query: "
 Classification: "task: classification | query: "
 InstructionRetrieval: "task: code retrieval | query: "
 MultilabelClassification: "task: classification | query: "
 PairClassification: "task: sentence similarity | query: "
 Reranking: "task: search result | query: "
 Retrieval: "task: search result | query: "
 Retrieval-query: "task: search result | query: "
 Retrieval-document: "title: none | text: "
 STS: "task: sentence similarity | query: "
 Summarization: "task: summarization | query: "
--------------------------------------------------------------------------------
🙋‍♂️
['The chef prepared a delicious meal for the guests.', 'A tasty dinner was cooked by the chef for the visitors.']
`-> 🤖 score:  0.9363755
🙋‍♂️
['She is an expert in machine learning.', 'He has a deep interest in artificial intelligence.']
`-> 🤖 score:  0.6425841
🙋‍♂️
['The weather in Tokyo is sunny today.', 'I need to buy groceries for the week.']
`-> 🤖 score:  0.38587403

ব্যবহারের ক্ষেত্রে: পুনরুদ্ধার-অগমেন্টেড জেনারেশন (RAG)

RAG সিস্টেমের জন্য, আপনার প্রশ্ন এবং নথিগুলির জন্য বিশেষায়িত এম্বেডিং তৈরি করতে নিম্নলিখিত prompt_name মানগুলি ব্যবহার করুন:

  • প্রশ্নের জন্য: prompt_name="Retrieval-query" ব্যবহার করুন।

    query_embedding = model.encode(
        "How do I use prompts with this model?",
        prompt_name="Retrieval-query"
    )
    
  • নথির জন্য: prompt_name="Retrieval-document" ব্যবহার করুন। ডকুমেন্ট এম্বেডিং আরও উন্নত করতে, আপনি সরাসরি prompt আর্গুমেন্ট ব্যবহার করে একটি শিরোনামও অন্তর্ভুক্ত করতে পারেন:

    • একটি শিরোনাম সহ:
    doc_embedding = model.encode(
        "The document text...",
        prompt="title: Using Prompts in RAG | text: "
    )
    
    • শিরোনাম ছাড়া:
    doc_embedding = model.encode(
        "The document text...",
        prompt="title: none | text: "
    )
    

আরও পড়া

শ্রেণীবিভাগ

শ্রেণিবিন্যাস হল এক বা একাধিক পূর্বনির্ধারিত বিভাগ বা লেবেলে পাঠ্যের একটি অংশ বরাদ্দ করা। এটি প্রাকৃতিক ভাষা প্রক্রিয়াকরণের (NLP) সবচেয়ে মৌলিক কাজগুলির মধ্যে একটি।

পাঠ্য শ্রেণীবিভাগের একটি ব্যবহারিক প্রয়োগ হল গ্রাহক সহায়তা টিকেট রাউটিং। এই প্রক্রিয়াটি স্বয়ংক্রিয়ভাবে গ্রাহকের প্রশ্নগুলিকে সঠিক বিভাগে নির্দেশ করে, সময় বাঁচায় এবং ম্যানুয়াল কাজ হ্রাস করে।

labels = ["Billing Issue", "Technical Support", "Sales Inquiry"]

sentence = [
  "Excuse me, the app freezes on the login screen. It won't work even when I try to reset my password.",
  "I would like to inquire about your enterprise plan pricing and features for a team of 50 people.",
]

# Calculate embeddings by calling model.encode()
label_embeddings = model.encode(labels, prompt_name="Classification")
embeddings = model.encode(sentence, prompt_name="Classification")

# Calculate the embedding similarities
similarities = model.similarity(embeddings, label_embeddings)
print(similarities)

idx = similarities.argmax(1)
print(idx)

for example in sentence:
  print("🙋‍♂️", example, "-> 🤖", labels[idx[sentence.index(example)]])
tensor([[0.4673, 0.5145, 0.3604],
        [0.4191, 0.5010, 0.5966]])
tensor([1, 2])
🙋‍♂️ Excuse me, the app freezes on the login screen. It won't work even when I try to reset my password. -> 🤖 Technical Support
🙋‍♂️ I would like to inquire about your enterprise plan pricing and features for a team of 50 people. -> 🤖 Sales Inquiry

ম্যাট্রিওশকা রিপ্রেজেন্টেশন লার্নিং (MRL)

EmbeddingGemma একটি মডেল থেকে একাধিক এমবেডিং মাপ প্রদান করতে MRL ব্যবহার করে। এটি একটি চতুর প্রশিক্ষণ পদ্ধতি যা একটি একক, উচ্চ-মানের এম্বেডিং তৈরি করে যেখানে সবচেয়ে গুরুত্বপূর্ণ তথ্য ভেক্টরের শুরুতে কেন্দ্রীভূত হয়।

এর অর্থ হল আপনি সম্পূর্ণ এম্বেডিংয়ের প্রথম N মাত্রাগুলি গ্রহণ করে একটি ছোট কিন্তু এখনও খুব দরকারী এম্বেডিং পেতে পারেন৷ ছোট, ছেঁটে যাওয়া এম্বেডিংগুলি ব্যবহার করা সঞ্চয় করার জন্য উল্লেখযোগ্যভাবে সস্তা এবং প্রক্রিয়া করার জন্য দ্রুত, তবে এই দক্ষতা এম্বেডিংয়ের সম্ভাব্য নিম্ন মানের মূল্যে আসে। MRL আপনাকে আপনার অ্যাপ্লিকেশনের নির্দিষ্ট প্রয়োজনের জন্য এই গতি এবং নির্ভুলতার মধ্যে সর্বোত্তম ভারসাম্য বেছে নেওয়ার ক্ষমতা দেয়।

আসুন তিনটি শব্দ ["apple", "banana", "car"] ব্যবহার করি এবং এমআরএল কীভাবে কাজ করে তা দেখতে সরলীকৃত এম্বেডিং তৈরি করি।

def check_word_similarities():
  # Calculate the embedding similarities
  print("similarity function: ", model.similarity_fn_name)
  similarities = model.similarity(embeddings[0], embeddings[1:])
  print(similarities)

  for idx, word in enumerate(words[1:]):
    print("🙋‍♂️ apple vs.", word, "-> 🤖 score: ", similarities.numpy()[0][idx])

# Calculate embeddings by calling model.encode()
embeddings = model.encode(words, prompt_name="STS")

check_word_similarities()
similarity function:  cosine
tensor([[0.7510, 0.6685]])
🙋‍♂️ apple vs. banana -> 🤖 score:  0.75102395
🙋‍♂️ apple vs. car -> 🤖 score:  0.6684626

এখন, একটি দ্রুত অ্যাপ্লিকেশনের জন্য, আপনার একটি নতুন মডেলের প্রয়োজন নেই৷ প্রথম 512 মাত্রায় সম্পূর্ণ এমবেডিংগুলিকে সহজভাবে ছেঁটে দিন ৷ সর্বোত্তম ফলাফলের জন্য, normalize_embeddings=True সেট করারও সুপারিশ করা হয়, যা ভেক্টরকে 1 এর একক দৈর্ঘ্যে স্কেল করে।

embeddings = model.encode(words, truncate_dim=512, normalize_embeddings=True)

for idx, embedding in enumerate(embeddings):
  print(f"Embedding {idx+1}: {embedding.shape}")

print("-"*80)
check_word_similarities()
Embedding 1: (512,)
Embedding 2: (512,)
Embedding 3: (512,)
--------------------------------------------------------------------------------
similarity function:  cosine
tensor([[0.7674, 0.7041]])
🙋‍♂️ apple vs. banana -> 🤖 score:  0.767427
🙋‍♂️ apple vs. car -> 🤖 score:  0.7040509

অত্যন্ত সীমাবদ্ধ পরিবেশে, আপনি এম্বেডিংগুলিকে আরও ছোট করতে পারেন মাত্র 256 মাত্রায় ৷ আপনি স্ট্যান্ডার্ড কোসাইন সাদৃশ্যের পরিবর্তে সাদৃশ্য গণনার জন্য আরও দক্ষ ডট-পণ্য ব্যবহার করতে পারেন।

model = SentenceTransformer(model_id, truncate_dim=256, similarity_fn_name="dot").to(device=device)
embeddings = model.encode(words, prompt_name="STS", normalize_embeddings=True)

for idx, embedding in enumerate(embeddings):
  print(f"Embedding {idx+1}: {embedding.shape}")

print("-"*80)
check_word_similarities()
Embedding 1: (256,)
Embedding 2: (256,)
Embedding 3: (256,)
--------------------------------------------------------------------------------
similarity function:  dot
tensor([[0.7855, 0.7382]])
🙋‍♂️ apple vs. banana -> 🤖 score:  0.7854644
🙋‍♂️ apple vs. car -> 🤖 score:  0.7382126

সারাংশ এবং পরবর্তী পদক্ষেপ

আপনি এখন EmbeddingGemma এবং Sentence Transformers লাইব্রেরি ব্যবহার করে উচ্চ-মানের টেক্সট এম্বেডিং তৈরি করতে সজ্জিত। শব্দার্থগত মিল, পাঠ্য শ্রেণিবিন্যাস এবং পুনরুদ্ধার-অগমেন্টেড জেনারেশন (RAG) সিস্টেমের মতো শক্তিশালী বৈশিষ্ট্যগুলি তৈরি করতে এই দক্ষতাগুলি প্রয়োগ করুন এবং জেমা মডেলগুলির সাথে কী সম্ভব তা অন্বেষণ চালিয়ে যান।

পরবর্তীতে নিম্নলিখিত নথিগুলি দেখুন: