জেমার সাথে একটি চ্যাটবট তৈরি করা

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

লার্জ ল্যাঙ্গুয়েজ মডেল (LLMs) যেমন Gemma তথ্যপূর্ণ প্রতিক্রিয়া তৈরি করতে পারদর্শী, ভার্চুয়াল সহকারী এবং চ্যাটবট তৈরির জন্য তাদের আদর্শ করে।

প্রচলিতভাবে, এলএলএমগুলি একটি রাষ্ট্রহীন পদ্ধতিতে কাজ করে, যার অর্থ অতীতের কথোপকথনগুলি সংরক্ষণ করার জন্য তাদের অন্তর্নিহিত স্মৃতির অভাব রয়েছে। প্রতিটি প্রম্পট বা প্রশ্ন পূর্বের মিথস্ক্রিয়া উপেক্ষা করে স্বাধীনভাবে প্রক্রিয়া করা হয়। যাইহোক, প্রাকৃতিক কথোপকথনের একটি গুরুত্বপূর্ণ দিক হল পূর্বের মিথস্ক্রিয়া থেকে প্রসঙ্গ ধরে রাখার ক্ষমতা। এই সীমাবদ্ধতা কাটিয়ে ওঠার জন্য এবং কথোপকথনের প্রেক্ষাপট বজায় রাখতে এলএলএমগুলিকে সক্ষম করতে, তাদের অবশ্যই এলএলএম-কে উপস্থাপিত প্রতিটি নতুন প্রম্পটে কথোপকথনের ইতিহাস (বা প্রাসঙ্গিক অংশ) এর মতো প্রাসঙ্গিক তথ্য সরবরাহ করতে হবে।

এই টিউটোরিয়ালটি আপনাকে দেখায় কিভাবে Gemma-এর নির্দেশ-টিউনড মডেল ভেরিয়েন্ট ব্যবহার করে একটি চ্যাটবট তৈরি করতে হয়।

সেটআপ

জেমা সেটআপ

এই টিউটোরিয়ালটি সম্পূর্ণ করতে, আপনাকে প্রথমে Gemma সেটআপে সেটআপ নির্দেশাবলী সম্পূর্ণ করতে হবে। জেমা সেটআপ নির্দেশাবলী আপনাকে দেখায় যে কীভাবে নিম্নলিখিতগুলি করতে হবে:

  • kaggle.com-এ Gemma-এ অ্যাক্সেস পান।
  • Gemma 2B মডেল চালানোর জন্য পর্যাপ্ত সম্পদ সহ একটি Colab রানটাইম বেছে নিন।
  • একটি Kaggle ব্যবহারকারীর নাম এবং API কী তৈরি এবং কনফিগার করুন।

আপনি জেমা সেটআপ সম্পূর্ণ করার পরে, পরবর্তী বিভাগে যান, যেখানে আপনি আপনার Colab পরিবেশের জন্য পরিবেশের ভেরিয়েবল সেট করবেন।

পরিবেশের ভেরিয়েবল সেট করুন

KAGGLE_USERNAME এবং KAGGLE_KEY এর জন্য পরিবেশ ভেরিয়েবল সেট করুন।

import os
from google.colab import userdata

# Note: `userdata.get` is a Colab API. If you're not using Colab, set the env
# vars as appropriate for your system.
os.environ["KAGGLE_USERNAME"] = userdata.get('KAGGLE_USERNAME')
os.environ["KAGGLE_KEY"] = userdata.get('KAGGLE_KEY')

নির্ভরতা ইনস্টল করুন

Keras এবং KerasNLP ইনস্টল করুন।

# Install Keras 3 last. See https://keras.io/getting_started/ for more details.
pip install -q tensorflow-cpu
pip install -q -U keras-nlp tensorflow-hub
pip install -q -U keras>=3
pip install -q -U tensorflow-text

একটি ব্যাকএন্ড নির্বাচন করুন

কেরাস হল একটি উচ্চ-স্তরের, মাল্টি-ফ্রেমওয়ার্ক ডিপ লার্নিং API যা সরলতা এবং ব্যবহারের সহজতার জন্য ডিজাইন করা হয়েছে। Keras 3 আপনাকে ব্যাকএন্ড বেছে নিতে দেয়: TensorFlow, JAX, বা PyTorch। তিনটিই এই টিউটোরিয়ালের জন্য কাজ করবে।

import os

# Select JAX as the backend
os.environ["KERAS_BACKEND"] = "jax"

# Pre-allocate 100% of TPU memory to minimize memory fragmentation
os.environ["XLA_PYTHON_CLIENT_MEM_FRACTION"] = "1.0"

প্যাকেজ আমদানি করুন

কেরাস এবং কেরাসএনএলপি আমদানি করুন।

import keras
import keras_nlp

# for reproducibility
keras.utils.set_random_seed(42)

মডেল ইনস্ট্যান্ট

KerasNLP অনেক জনপ্রিয় মডেল আর্কিটেকচারের বাস্তবায়ন প্রদান করে। এই টিউটোরিয়ালে, আপনি GemmaCausalLM ব্যবহার করে মডেলটিকে ইনস্ট্যান্টিয়েট করবেন, কার্যকারণ ভাষার মডেলিংয়ের জন্য এন্ড-টু-এন্ড জেমা মডেল। একটি কার্যকারণ ভাষা মডেল পূর্ববর্তী টোকেনগুলির উপর ভিত্তি করে পরবর্তী টোকেনের পূর্বাভাস দেয়।

from_preset পদ্ধতি ব্যবহার করে মডেলটি ইনস্ট্যান্ট করুন:

gemma_lm = keras_nlp.models.GemmaCausalLM.from_preset("gemma_1.1_instruct_2b_en")
Attaching 'metadata.json' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'metadata.json' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'task.json' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'config.json' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'metadata.json' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'metadata.json' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'config.json' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'config.json' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'model.weights.h5' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'metadata.json' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'metadata.json' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'preprocessor.json' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'tokenizer.json' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'tokenizer.json' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'assets/tokenizer/vocabulary.spm' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...

GemmaCausalLM.from_preset() ফাংশন একটি প্রিসেট আর্কিটেকচার এবং ওজন থেকে মডেলটিকে ইনস্ট্যান্টিয়েট করে। উপরের কোডে, "gemma_1.1_instruct_2b_en" স্ট্রিংটি 2 বিলিয়ন প্যারামিটার সহ Gemma 2B মডেলের প্রিসেটটি নির্দিষ্ট করে। 7B, 9B, এবং 27B প্যারামিটার সহ জেমা মডেলগুলিও উপলব্ধ। আপনি Gemma মডেলের জন্য কোড স্ট্রিংগুলি তাদের Kaggle-মডেল বৈচিত্র্যের তালিকায় খুঁজে পেতে পারেন।

মডেল সম্পর্কে আরও তথ্য পেতে summary পদ্ধতি ব্যবহার করুন:

gemma_lm.summary()

আপনি সারাংশ থেকে দেখতে পাচ্ছেন, মডেলটিতে 2.5 বিলিয়ন প্রশিক্ষণযোগ্য পরামিতি রয়েছে।

ফরম্যাটিং সহায়ক ফাংশন সংজ্ঞায়িত করুন

from IPython.display import Markdown
import textwrap

def display_chat(prompt, text):
  formatted_prompt = "<font size='+1' color='brown'>🙋‍♂️<blockquote>" + prompt + "</blockquote></font>"
  text = text.replace('•', '  *')
  text = textwrap.indent(text, '> ', predicate=lambda _: True)
  formatted_text = "<font size='+1' color='teal'>🤖\n\n" + text + "\n</font>"
  return Markdown(formatted_prompt+formatted_text)

def to_markdown(text):
  text = text.replace('•', '  *')
  return Markdown(textwrap.indent(text, '> ', predicate=lambda _: True))

চ্যাটবট তৈরি করা

Gemma instruction-tuned মডেল gemma_1.1_instruct_2b_en নিম্নলিখিত টার্ন টোকেনগুলি বোঝার জন্য সূক্ষ্ম-টিউন করা হয়েছে:

<start_of_turn>user\n  ... <end_of_turn>\n
<start_of_turn>model\n ... <end_of_turn>\n

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

কথোপকথনের অবস্থা পরিচালনা করতে একটি চ্যাট সহায়ক তৈরি করুন৷

class ChatState():
  """
  Manages the conversation history for a turn-based chatbot
  Follows the turn-based conversation guidelines for the Gemma family of models
  documented at https://ai.google.dev/gemma/docs/formatting
  """

  __START_TURN_USER__ = "<start_of_turn>user\n"
  __START_TURN_MODEL__ = "<start_of_turn>model\n"
  __END_TURN__ = "<end_of_turn>\n"

  def __init__(self, model, system=""):
    """
    Initializes the chat state.

    Args:
        model: The language model to use for generating responses.
        system: (Optional) System instructions or bot description.
    """
    self.model = model
    self.system = system
    self.history = []

  def add_to_history_as_user(self, message):
      """
      Adds a user message to the history with start/end turn markers.
      """
      self.history.append(self.__START_TURN_USER__ + message + self.__END_TURN__)

  def add_to_history_as_model(self, message):
      """
      Adds a model response to the history with start/end turn markers.
      """
      self.history.append(self.__START_TURN_MODEL__ + message + self.__END_TURN__)

  def get_history(self):
      """
      Returns the entire chat history as a single string.
      """
      return "".join([*self.history])

  def get_full_prompt(self):
    """
    Builds the prompt for the language model, including history and system description.
    """
    prompt = self.get_history() + self.__START_TURN_MODEL__
    if len(self.system)>0:
      prompt = self.system + "\n" + prompt
    return prompt

  def send_message(self, message):
    """
    Handles sending a user message and getting a model response.

    Args:
        message: The user's message.

    Returns:
        The model's response.
    """
    self.add_to_history_as_user(message)
    prompt = self.get_full_prompt()
    response = self.model.generate(prompt, max_length=1024)
    result = response.replace(prompt, "")  # Extract only the new response
    self.add_to_history_as_model(result)
    return result

মডেলের সাথে চ্যাট করুন

মডেলের সাথে চ্যাট শুরু করুন।

chat = ChatState(gemma_lm)
message = "Tell me, in a few words,  how to compute all prime numbers up to 1000?"
display_chat(message, chat.send_message(message))

🙋‍♂️

আমাকে কয়েক কথায় বলুন, কিভাবে 1000 পর্যন্ত সমস্ত মৌলিক সংখ্যা গণনা করা যায়?
🤖

Eratosthenes চালনি একটি প্রদত্ত সীমা পর্যন্ত সমস্ত মৌলিক সংখ্যা গণনা করার জন্য একটি বহুল ব্যবহৃত পদ্ধতি। এটি পুনরাবৃত্তিমূলকভাবে প্রতিটি মৌলিক সংখ্যার গুণিতক চিহ্নিত করে।

কথোপকথন চালিয়ে যান।

message = "Now in Python! No numpy, please!"
display_chat(message, chat.send_message(message))

🙋‍♂️

এখন পাইথনে! নোম্পি, প্লিজ!
🤖
def prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

message = "Thank you, it works! Can you explain the code in plain English?"
display_chat(message, chat.send_message(message))

🙋‍♂️

আপনাকে ধন্যবাদ, এটা কাজ করে! আপনি সরল ইংরেজিতে কোড ব্যাখ্যা করতে পারেন?
🤖

প্রদত্ত কোডটি একটি ফাংশন prime সংজ্ঞায়িত করে যা একটি প্রদত্ত সংখ্যা প্রাইম কিনা তা পরীক্ষা করে।

কিভাবে এটা কাজ করে:

  • ফাংশনটি একটি একক আর্গুমেন্ট নেয়, n , যা চেক করার সংখ্যা।

  • এটি প্রথমে পরীক্ষা করে যে n 1 এর থেকে কম বা সমান। যদি এটি হয়, সংখ্যাটি মৌলিক নয়, তাই ফাংশনটি False প্রদান করে।

  • তারপরে এটি একটি লুপে প্রবেশ করে যা 2 থেকে n এর বর্গমূল পর্যন্ত সংখ্যার মাধ্যমে পুনরাবৃত্তি করে।

  • প্রতিটি সংখ্যার জন্য i , এটি পরীক্ষা করে যে n সমানভাবে i দ্বারা বিভাজ্য কিনা (অর্থাৎ, n % i == 0 )।

  • n যদি i দ্বারা বিভাজ্য হয়, তাহলে ফাংশনটি False প্রদান করে কারণ n এর একটি ভাজক থাকলে প্রাইম হতে পারে না।

  • n এর জন্য কোনো ভাজক না খুঁজে যদি লুপটি সম্পূর্ণ হয়, তাহলে ফাংশনটি True প্রদান করে, যা নির্দেশ করে যে n একটি মৌলিক সংখ্যা।

উদাহরণ ব্যবহার:

>>> prime(2)
True
>>> prime(3)
True
>>> prime(4)
False
>>> prime(5)
True

এই কোডের সুবিধা:

  • মৌলিক সংখ্যা খোঁজার জন্য এটি একটি সহজ এবং দক্ষ অ্যালগরিদম।
  • এটি বিভিন্ন কম্পিউটার বিজ্ঞান এবং গাণিতিক অ্যাপ্লিকেশনে ব্যাপকভাবে ব্যবহৃত হয়।
message = "Great! Now add those explanations as comments in the code."
display_chat(message, chat.send_message(message))

🙋‍♂️

দারুণ! এখন কোডে মন্তব্য হিসাবে সেই ব্যাখ্যা যোগ করুন।
🤖
def prime(n):
    """
    Checks whether a given number is prime or not.

    Args:
        n: The number to check.

    Returns:
        True if n is prime, False otherwise.
    """

    # Check if n is less than or equal to 1.
    if n <= 1:
        return False

    # Iterate through numbers from 2 to the square root of n.
    for i in range(2, int(n**0.5) + 1):
        # Check if n is divisible by i.
        if n % i == 0:
            return False

    # If the loop completes without finding any divisors for n, then n is prime.
    return True

জেনারেট কোড চালানোর মাধ্যমে উত্পন্ন প্রতিক্রিয়া পরীক্ষা করুন:

def is_prime(n):
  """
  Checks if a number is prime.

  Args:
    n: The number to check.

  Returns:
    True if n is prime, False otherwise.
  """

  # If n is less than or equal to 1, it is not prime.
  if n <= 1:
    return False

  # Iterate through all the numbers from 2 to the square root of n.
  for i in range(2, int(n**0.5) + 1):
    # If n is divisible by any of the numbers in the range from 2 to the square root of n, it is not prime.
    if n % i == 0:
      return False

  # If no divisors are found, n is prime.
  return True


# Initialize an empty list to store prime numbers.
primes = []

# Iterate through all the numbers from 2 to 1000.
for i in range(2, 1001):
  # If the number is prime, add it to the list.
  if is_prime(i):
    primes.append(i)

# Print the prime numbers.
print(primes)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]

Chat ক্লাসের সমস্ত প্রসঙ্গ কীভাবে ধরে রাখা হয়েছে তা দেখতে get_history পদ্ধতি ব্যবহার করুন।

print(chat.get_history())
<start_of_turn>user
Tell me, in a few words,  how to compute all prime numbers up to 1000?<end_of_turn>
<start_of_turn>model
The Sieve of Eratosthenes is a widely used method to compute all prime numbers up to a given limit. It involves iteratively marking out multiples of each prime number.<end_of_turn>
<start_of_turn>user
Now in Python! No numpy, please!<end_of_turn>
<start_of_turn>model

```python
def prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True
```<end_of_turn>
<start_of_turn>user
Thank you, it works! Can you explain the code in plain English?<end_of_turn>
<start_of_turn>model
The provided code defines a function `prime` that checks whether a given number is prime or not.

**How it works:**

- The function takes a single argument, `n`, which is the number to check.


- It first checks if `n` is less than or equal to 1. If it is, the number is not prime, so the function returns `False`.


- It then enters a loop that iterates through numbers from 2 to the square root of `n`.


- For each number `i`, it checks if `n` is divisible evenly by `i` (i.e., `n % i == 0`).


- If `n` is divisible by `i`, the function returns `False` because `n` cannot be prime if it has a divisor.


- If the loop completes without finding any divisors for `n`, the function returns `True`, indicating that `n` is a prime number.


**Example Usage:**

```python
>>> prime(2)
True
>>> prime(3)
True
>>> prime(4)
False
>>> prime(5)
True
```

**Benefits of this Code:**

- It is a simple and efficient algorithm for finding prime numbers.
- It is widely used in various computer science and mathematical applications.<end_of_turn>
<start_of_turn>user
Great! Now add those explanations as comments in the code.<end_of_turn>
<start_of_turn>model
```python
def prime(n):
    """
    Checks whether a given number is prime or not.

    Args:
        n: The number to check.

    Returns:
        True if n is prime, False otherwise.
    """

    # Check if n is less than or equal to 1.
    if n <= 1:
        return False

    # Iterate through numbers from 2 to the square root of n.
    for i in range(2, int(n**0.5) + 1):
        # Check if n is divisible by i.
        if n % i == 0:
            return False

    # If the loop completes without finding any divisors for n, then n is prime.
    return True
```<end_of_turn>

সারাংশ এবং আরও পড়া

এই টিউটোরিয়ালে, আপনি শিখেছেন কিভাবে JAX-এ Keras ব্যবহার করে Gemma 2B নির্দেশনা টিউন করা মডেলের সাথে চ্যাট করতে হয়।

জেমা সম্পর্কে আরও জানতে এই গাইড এবং টিউটোরিয়ালগুলি দেখুন: