जैक्स और फ़्लैक्स का इस्तेमाल करके जेमा को फ़ाइन-ट्यून करना

ai.google.dev पर देखें Google Colab में चलाएं Vertex AI में खोलें GitHub पर सोर्स देखें

खास जानकारी

Gemma, Google DeepMind Gemini की रिसर्च और टेक्नोलॉजी पर आधारित, लाइटवेट और आधुनिक लार्ज लैंग्वेज मॉडल का फ़ैमिली ग्रुप है. इस ट्यूटोरियल में बताया गया है कि Google DeepMind की gemma लाइब्रेरी, JAX (एक हाई-परफ़ॉर्मेंस न्यूमेरिक कंप्यूटिंग लाइब्रेरी), Fलैक्स (JAX पर आधारित न्यूरल नेटवर्क लाइब्रेरी), Chex (JAN11 और JAX - JAX के भरोसेमंद टेक्स्ट-आधारित ऑप्टिमाइज़ेशन कोड की ऑप्टिमाइज़ेशन लाइब्रेरी), मशीन-द ट्रांसलेशन, ऑप्टिमाइज़ेशन का इस्तेमाल करके अंग्रेज़ी-फ़्रेंच अनुवाद वाले टास्क के लिए, Gemma 2B इंस्ट्रक्शन मॉडल कैसे बेहतर बनाएं. हालांकि, इस notebook में Flux का सीधे तौर पर इस्तेमाल नहीं किया गया है, लेकिन Gemma बनाने के लिए Flax का इस्तेमाल किया गया है.

gemma लाइब्रेरी को JAX, Flax, Orbax (चेकपॉइंटिंग जैसी ट्रेनिंग यूटिलिटी के लिए JAX पर आधारित लाइब्रेरी), और SentencePiece (टोकनाइज़र/डिटोकेनाइज़र लाइब्रेरी) के साथ लिखा गया.

सेटअप

1. Gemma के लिए Kaggle का ऐक्सेस सेट अप करें

इस ट्यूटोरियल को पूरा करने के लिए, आपको सबसे पहले Gemma सेटअप पर जाकर, सेटअप से जुड़े निर्देशों का पालन करना होगा. इसमें, इन निर्देशों का पालन करने के बारे में बताया गया है:

  • kaggle.com पर जाकर, Gemma चैनल का ऐक्सेस पाएं.
  • जेम्मा मॉडल चलाने के लिए, ज़रूरत के मुताबिक संसाधनों वाला Colab रनटाइम चुनें.
  • Kaggle उपयोगकर्ता नाम और एपीआई पासकोड जनरेट और कॉन्फ़िगर करें.

जेम्मा सेटअप पूरा करने के बाद, अगले सेक्शन पर जाएं. यहां आपको Colab के एनवायरमेंट के लिए एनवायरमेंट वैरिएबल सेट करने होंगे.

2. एनवायरमेंट वैरिएबल सेट करना

KAGGLE_USERNAME और KAGGLE_KEY के लिए एनवायरमेंट वैरिएबल सेट करें. जब "ऐक्सेस दें?" मैसेज दिखे, तो सीक्रेट ऐक्सेस देने के लिए सहमति दें.

import os
from google.colab import userdata # `userdata` is a Colab API.

os.environ["KAGGLE_USERNAME"] = userdata.get('KAGGLE_USERNAME')
os.environ["KAGGLE_KEY"] = userdata.get('KAGGLE_KEY')

3. gemma लाइब्रेरी इंस्टॉल करें

फ़िलहाल, इस notebook को चलाने के लिए, Colab में हार्डवेयर से तेज़ी लाने की सुविधा ज़रूरत के मुताबिक नहीं है. अगर Colab Pay As You Go या Colab Pro का इस्तेमाल किया जा रहा है, तो हार्डवेयर से तेज़ी लाने के लिए, बदलाव करें > नोटबुक की सेटिंग > A100 जीपीयू > सेव करें पर क्लिक करें.

इसके बाद, आपको github.com/google-deepmind/gemma से Google DeepMind gemma की लाइब्रेरी इंस्टॉल करनी होगी. अगर आपको "पीआईपी की डिपेंडेंसी रिज़ॉल्वर" के बारे में कोई गड़बड़ी मिलती है, तो आम तौर पर इसे अनदेखा किया जा सकता है.

pip install -q git+https://github.com/google-deepmind/gemma.git

4. लाइब्रेरी इंपोर्ट करें

इस notebook में, Flax (न्यूरल नेटवर्क के लिए), कोर JAX, SentencePiece (टोकनाइज़ेशन के लिए), Chex (भरोसेमंद JAX कोड लिखने के लिए यूटिलिटी की लाइब्रेरी), और TensorFlow डेटासेट का इस्तेमाल किया जाता है.

import os
import enum
import re
import string

import chex
import jax
import jax.numpy as jnp
import optax

import tensorflow as tf
import tensorflow_datasets as tfds

from gemma import params as params_lib
from gemma import sampler as sampler_lib
from gemma import transformer as transformer_lib
import sentencepiece as spm

जेम्मा मॉडल लोड करें

Gemma मॉडल को kagglehub.model_download के साथ लोड करें, जिसमें तीन आर्ग्युमेंट होते हैं:

  • handle: Kaggle का मॉडल हैंडल
  • path: (वैकल्पिक स्ट्रिंग) लोकल पाथ
  • force_download: (ज़रूरी नहीं बूलियन) मॉडल को फिर से डाउनलोड करता है
GEMMA_VARIANT = '2b-it' # @param ['2b', '2b-it'] {type:"string"}
import kagglehub

GEMMA_PATH = kagglehub.model_download(f'google/gemma/flax/{GEMMA_VARIANT}')
Downloading from https://www.kaggle.com/api/v1/models/google/gemma/flax/2b-it/2/download...
100%|██████████| 3.67G/3.67G [00:26<00:00, 147MB/s]
Extracting model files...
print('GEMMA_PATH:', GEMMA_PATH)
GEMMA_PATH: /root/.cache/kagglehub/models/google/gemma/flax/2b-it/2

मॉडल वेट और टोकनाइज़र की लोकेशन देखें. इसके बाद, पाथ वैरिएबल सेट करें. टोकनाइज़र डायरेक्ट्री उस मुख्य डायरेक्ट्री में होगी जहां से आपने मॉडल डाउनलोड किया है. वहीं, मॉडल वेट किसी सब-डायरेक्ट्री में होगा. उदाहरण के लिए:

  • tokenizer.model फ़ाइल, /LOCAL/PATH/TO/gemma/flax/2b-it/2 में होगी).
  • मॉडल चेकपॉइंट /LOCAL/PATH/TO/gemma/flax/2b-it/2/2b-it में होगा).
CKPT_PATH = os.path.join(GEMMA_PATH, GEMMA_VARIANT)
TOKENIZER_PATH = os.path.join(GEMMA_PATH, 'tokenizer.model')
print('CKPT_PATH:', CKPT_PATH)
print('TOKENIZER_PATH:', TOKENIZER_PATH)
CKPT_PATH: /root/.cache/kagglehub/models/google/gemma/flax/2b-it/2/2b-it
TOKENIZER_PATH: /root/.cache/kagglehub/models/google/gemma/flax/2b-it/2/tokenizer.model

MTNT डेटासेट और जेमा टोकनाइज़र को लोड और तैयार करना

आपको एमटीएनटी (शोज़ी टेक्स्ट का मशीन ट्रांसलेशन) डेटासेट इस्तेमाल करना होगा, जो TensorFlow डेटासेट से उपलब्ध है.

MTNT डेटासेट के अंग्रेज़ी से फ़्रेंच डेटासेट का हिस्सा डाउनलोड करें और फिर दो उदाहरणों के सैंपल लें. डेटासेट के हर सैंपल में दो एंट्री हैं: src: मूल अंग्रेज़ी वाक्य और dst: उससे जुड़ा फ़्रेंच अनुवाद.

ds = tfds.load("mtnt/en-fr", split="train")

ds = ds.take(2)
ds = ds.as_numpy_iterator()

for idx, example in enumerate(ds):
  print(f'Example {idx}:')
  for key, val in example.items():
    print(f'{key}: {val}')
  print()
Downloading and preparing dataset 35.08 MiB (download: 35.08 MiB, generated: 11.33 MiB, total: 46.41 MiB) to /root/tensorflow_datasets/mtnt/en-fr/1.0.0...
Dl Completed...: 0 url [00:00, ? url/s]
Dl Size...: 0 MiB [00:00, ? MiB/s]
Extraction completed...: 0 file [00:00, ? file/s]
Generating splits...:   0%|          | 0/3 [00:00<?, ? splits/s]
Generating train examples...:   0%|          | 0/35692 [00:00<?, ? examples/s]
Shuffling /root/tensorflow_datasets/mtnt/en-fr/1.0.0.incomplete6YJMND/mtnt-train.tfrecord*...:   0%|          …
Generating test examples...:   0%|          | 0/1020 [00:00<?, ? examples/s]
Shuffling /root/tensorflow_datasets/mtnt/en-fr/1.0.0.incomplete6YJMND/mtnt-test.tfrecord*...:   0%|          |…
Generating valid examples...:   0%|          | 0/811 [00:00<?, ? examples/s]
Shuffling /root/tensorflow_datasets/mtnt/en-fr/1.0.0.incomplete6YJMND/mtnt-valid.tfrecord*...:   0%|          …
Dataset mtnt downloaded and prepared to /root/tensorflow_datasets/mtnt/en-fr/1.0.0. Subsequent calls will reuse this data.
Example 0:
dst: b'Le groupe de " toutes les \xc3\xa9toiles potentielles de la conf\xc3\xa9rence de l\'Est mais qui ne s\'en sortent pas dans le groupe de l\'Ouest ".'
src: b'The group of \xe2\x80\x9ceastern conference potential all stars but not making it in the West\xe2\x80\x9d group.'

Example 1:
dst: b"Kameron est-elle un peu aigrie de son manque de temps \xc3\xa0 l'\xc3\xa9cran ?"
src: b'Is Kameron a Little Salty About Her Lack of Air Time?'

sentencepiece.SentencePieceProcessor का इस्तेमाल करके बनाया गया जेमा टोकनाइज़र लोड करें:

vocab = spm.SentencePieceProcessor()
vocab.Load(TOKENIZER_PATH)
True

अंग्रेज़ी से फ़्रेंच अनुवाद वाले टास्क के लिए, SentencePieceProcessor को पसंद के मुताबिक बनाएं. चूंकि आप जेम्मा मॉडल के अंग्रेज़ी वाले हिस्से को बेहतर बनाएंगे, इसलिए आपको कुछ समायोजन करने होंगे, जैसे:

  • इनपुट प्रीफ़िक्स: हर इनपुट में एक सामान्य प्रीफ़िक्स जोड़ने से, अनुवाद के टास्क का संकेत मिलता है. उदाहरण के लिए, Translate this into French: [INPUT_SENTENCE] जैसे प्रीफ़िक्स वाले प्रॉम्प्ट का इस्तेमाल किया जा सकता है.

  • अनुवाद शुरू होने का सफ़िक्स: हर प्रॉम्प्ट के आखिर में सफ़िक्स जोड़ने से, जेम्मा मॉडल को यह निर्देश मिल जाता है कि अनुवाद की प्रक्रिया कब शुरू होगी. एक नई लाइन से काम हो जाना चाहिए.

  • भाषा के मॉडल के टोकन: जेम्मा मॉडल, हर क्रम की शुरुआत में "सीक्वेंस की शुरुआत" टोकन की उम्मीद करते हैं. इसलिए, ट्रेनिंग के हर उदाहरण के आखिर में, "सीक्वेंस की शुरुआत" टोकन जोड़ना काफ़ी होना चाहिए.

    SentencePieceProcessor के आस-पास इस तरीके से कस्टम रैपर बनाएं:

class GemmaTokenizer:

  def __init__(self,
               spm_processor: spm.SentencePieceProcessor):
    self._spm_processor = spm_processor

  @property
  def pad_id(self) -> int:
    """Fast access to the pad ID."""
    return self._spm_processor.pad_id()

  def tokenize(self,
               example: str | bytes,
               prefix: str = '',
               suffix: str = '',
               add_eos: bool = True) -> jax.Array:
    """
    The tokenization function.

    Args:
      example: Input string to tokenize.
      prefix:  Prefix to add to the input string.
      suffix:  Suffix to add to the input string.
      add_eos: If True, add an "end of sentence" token at the end of the output
               sequence.
    Returns:
      Tokens corresponding to the input string.
    """
    int_list = [self._spm_processor.bos_id()]
    int_list.extend(self._spm_processor.EncodeAsIds(prefix + example + suffix))
    if add_eos:
      int_list.append(self._spm_processor.eos_id())

    return jnp.array(int_list, dtype=jnp.int32)

  def tokenize_tf_op(self,
                     str_tensor: tf.Tensor,
                     prefix: str = '',
                     suffix: str = '',
                     add_eos: bool = True) -> tf.Tensor:
    """A TensorFlow operator for the tokenize function."""
    encoded = tf.numpy_function(
        self.tokenize,
        [str_tensor, prefix, suffix, add_eos],
        tf.int32)
    encoded.set_shape([None])
    return encoded

  def to_string(self, tokens: jax.Array) -> str:
    """Convert an array of tokens to a string."""
    return self._spm_processor.EncodeIds(tokens.tolist())

इसे आज़माएं. इसके लिए, अपने नए कस्टम GemmaTokenizer को इंस्टैंशिएट करें. इसके बाद, इसे MTNT डेटासेट के छोटे से सैंपल पर लागू करें:

tokenizer = GemmaTokenizer(vocab)

def tokenize_source(tokenizer, example: tf.Tensor):
  return tokenizer.tokenize_tf_op(example,
                                  prefix='Translate this into French:\n',
                                  suffix='\n',
                                  add_eos=False)
def tokenize_destination(tokenizer, example: tf.Tensor):
  return tokenizer.tokenize_tf_op(example,
                                  add_eos=True)

ds = tfds.load("mtnt/en-fr",split="train")
ds = ds.take(2)
ds = ds.map(lambda x: {'src': tokenize_source(tokenizer, x['src']),
                       'dst': tokenize_destination(tokenizer, x['dst'])})
ds = ds.as_numpy_iterator()

for idx, example in enumerate(ds):
  print(f'Example {idx}:')
  for key, val in example.items():
    print(f'{key}: {val}')
  print()
Example 0:
src: [     2  49688    736   1280   6987 235292    108    651   2778    576
   1080 104745  11982   5736    832   8995    901    780   3547    665
    575    573   4589 235369   2778 235265    108]
dst: [     2   2025  29653    581    664  16298   1437  55563  41435   7840
    581    683 111452    581    533 235303   9776   4108   2459    679
    485 235303    479   6728    579   1806   2499    709  29653    581
    533 235303 101323  16054      1]

Example 1:
src: [     2  49688    736   1280   6987 235292    108   2437  87150    477
    476  11709 230461   8045   3636  40268    576   4252   4897 235336
    108]
dst: [     2 213606    477   1455 235290   3510    748   8268 191017   2809
    581   2032  69972    581  11495   1305    533 235303  65978   1654
      1]

पूरे MTNT डेटासेट के लिए डेटा लोड करने वाला टूल बनाएं:

@chex.dataclass(frozen=True)
class TrainingInput:
  # Input tokens provided to the model.
  input_tokens: jax.Array

  # A mask that determines which tokens contribute to the target loss
  # calculation.
  target_mask: jax.Array

class DatasetSplit(enum.Enum):
  TRAIN = 'train'
  VALIDATION = 'valid'

class MTNTDatasetBuilder:
  """The dataset builder for the MTNT dataset."""

  N_ITEMS = {DatasetSplit.TRAIN: 35_692,
             DatasetSplit.VALIDATION: 811}

  BUFFER_SIZE_SHUFFLE = 10_000
  TRANSLATION_PREFIX = 'Translate this into French:\n'
  TRANSLATION_SUFFIX = '\n'

  def __init__(self,
               tokenizer : GemmaTokenizer,
               max_seq_len: int):
    """Constructor.

    Args:
      tokenizer: Gemma tokenizer to use.
      max_seq_len: size of each sequence in a given batch.
    """
    self._tokenizer = tokenizer
    self._base_data = {
        DatasetSplit.TRAIN: tfds.load("mtnt/en-fr",split="train"),
        DatasetSplit.VALIDATION: tfds.load("mtnt/en-fr",split="valid"),
    }
    self._max_seq_len = max_seq_len

  def _tokenize_source(self, example: tf.Tensor):
    """Tokenization function for the source."""
    return self._tokenizer.tokenize_tf_op(example,
                                          prefix=self.TRANSLATION_PREFIX,
                                          suffix=self.TRANSLATION_SUFFIX,
                                          add_eos=False)

  def _tokenize_destination(self, example: tf.Tensor):
    """Tokenization function for the French translation."""
    return self._tokenizer.tokenize_tf_op(example,
                                          add_eos=True)

  def _pad_up_to_max_len(self,
                         input_tensor: tf.Tensor,
                         pad_value: int | bool,
                         ) -> tf.Tensor:
    """Pad the given tensor up to sequence length of a batch."""
    seq_len = tf.shape(input_tensor)[0]
    to_pad = tf.maximum(self._max_seq_len - seq_len, 0)
    return tf.pad(input_tensor,
                  [[0, to_pad]],
                  mode='CONSTANT',
                  constant_values=pad_value,
                  )

  def _to_training_input(self,
                         src_tokens: jax.Array,
                         dst_tokens: jax.Array,
                         ) -> TrainingInput:
    """Build a training input from a tuple of source and destination tokens."""

    # The input sequence fed to the model is simply the concatenation of the
    # source and the destination.
    tokens = tf.concat([src_tokens, dst_tokens], axis=0)

    # To prevent the model from updating based on the source (input)
    # tokens, add a target mask to each input.
    q_mask = tf.zeros_like(src_tokens, dtype=tf.bool)
    a_mask = tf.ones_like(dst_tokens, dtype=tf.bool)
    mask = tf.concat([q_mask, a_mask], axis=0)

    # If the output tokens sequence is smaller than the target sequence size,
    # then pad it with pad tokens.
    tokens = self._pad_up_to_max_len(tokens, self._tokenizer.pad_id)

    # Don't want to perform the backward pass on the pad tokens.
    mask = self._pad_up_to_max_len(mask, False)

    return TrainingInput(input_tokens=tokens, target_mask=mask)


  def get_train_dataset(self, batch_size: int, num_epochs: int):
    """Build the training dataset."""

    # Tokenize each sample.
    ds = self._base_data[DatasetSplit.TRAIN].map(lambda x : (self._tokenize_source(x['src']),
                                                             self._tokenize_destination(x['dst'])))

    # Convert the samples to training inputs.
    ds = ds.map(lambda x, y: self._to_training_input(x, y))

    # Remove the samples that are too long.
    ds = ds.filter(lambda x: tf.shape(x.input_tokens)[0] <= self._max_seq_len)

    # Shuffle the dataset.
    ds = ds.shuffle(buffer_size=self.BUFFER_SIZE_SHUFFLE)

    # Repeat if necessary.
    ds = ds.repeat(num_epochs)

    # Build batches.
    ds = ds.batch(batch_size, drop_remainder=True)
    return ds

  def get_validation_dataset(self, batch_size: int):
    """Build the validation dataset."""

    # Same steps as in `get_train_dataset`, but without shuffling and no repetition.
    ds = self._base_data[DatasetSplit.VALIDATION].map(lambda x : (self._tokenize_source(x['src']),
                                                                  self._tokenize_destination(x['dst'])))
    ds = ds.map(lambda x, y: self._to_training_input(x, y))
    ds = ds.filter(lambda x: tf.shape(x.input_tokens)[0] <= self._max_seq_len)
    ds = ds.batch(batch_size, drop_remainder=True)
    return ds

MTNTDatasetBuilder को आज़माएं. इसके लिए, कस्टम GemmaTokenizer को फिर से इंस्टैंशिएट करें. इसके बाद, इसे MTNT डेटासेट पर लागू करें और इन दो उदाहरणों के ज़रिए सैंपलिंग करें:

tokenizer = GemmaTokenizer(vocab)

dataset_builder = MTNTDatasetBuilder(tokenizer, max_seq_len=20)
ds = dataset_builder.get_train_dataset(3, 1)
ds = ds.take(2)
ds = ds.as_numpy_iterator()

for idx, example in enumerate(ds):
  print(f'Example {idx}:')
  for key, val in example.items():
    print(f'{key}: {val}')
  print()
WARNING:tensorflow:Mapping types may not work well with tf.nest. Prefer using MutableMapping for <class '__main__.TrainingInput'>
WARNING:tensorflow:Mapping types may not work well with tf.nest. Prefer using MutableMapping for <class '__main__.TrainingInput'>
WARNING:tensorflow:Mapping types may not work well with tf.nest. Prefer using MutableMapping for <class '__main__.TrainingInput'>
Example 0:
input_tokens: [[     2  49688    736   1280   6987 235292    108  10924    665  12302
  235341    108      2   4397  63011   1437  38696   1241      1      0]
 [     2  49688    736   1280   6987 235292    108  13835   1517 235265
     108      2  69875    540  19713 235265      1      0      0      0]
 [     2  49688    736   1280   6987 235292    108   6956   1586 235297
  235265    108      2  78368   1586 235297 235265      1      0      0]]
target_mask: [[False False False False False False False False False False False False
   True  True  True  True  True  True  True False]
 [False False False False False False False False False False False  True
   True  True  True  True  True False False False]
 [False False False False False False False False False False False False
   True  True  True  True  True  True False False]]

Example 1:
input_tokens: [[     2  49688    736   1280   6987 235292    108  18874 235341    108
       2 115905   6425   1241      1      0      0      0      0      0]
 [     2  49688    736   1280   6987 235292    108   7574   3356 235341
     108      2   7997  20707   1241      1      0      0      0      0]
 [     2  49688    736   1280   6987 235292    108   8703    665 235265
     108      2 235338 235303  90006  20133 235265      1      0      0]]
target_mask: [[False False False False False False False False False False  True  True
   True  True  True False False False False False]
 [False False False False False False False False False False False  True
   True  True  True  True False False False False]
 [False False False False False False False False False False False  True
   True  True  True  True  True  True False False]]

मॉडल कॉन्फ़िगर करना

जेम्मा मॉडल को बेहतर बनाने से पहले, आपको इसे कॉन्फ़िगर करना होगा.

सबसे पहले, gemma.params.load_and_format_params तरीके का इस्तेमाल करके, जेम्मा मॉडल चेकपॉइंट लोड और फ़ॉर्मैट करें:

params = params_lib.load_and_format_params(CKPT_PATH)

Gemma मॉडल चेकपॉइंट से सही कॉन्फ़िगरेशन अपने-आप लोड करने के लिए, gemma.transformer.TransformerConfig का इस्तेमाल करें. cache_size आर्ग्युमेंट, जेम Transformer कैश में कुल चरणों की संख्या है. इसके बाद, gemma.transformer.Transformer (जो flax.linen.Module से इनहेरिट किया जाता है) की मदद से, जेम्मा मॉडल को model_2b के तौर पर इंस्टैंशिएट करें.

config_2b = transformer_lib.TransformerConfig.from_params(
    params,
    cache_size=30
)

model_2b = transformer_lib.Transformer(config=config_2b)

मॉडल को बेहतर बनाएं

इस सेक्शन में, आपको ये काम करने होंगे:

  • फ़ॉरवर्ड पास और लॉस फ़ंक्शन बनाने के लिए, gemma.transformer.Transformer क्लास का इस्तेमाल करें.
  • टोकन के लिए, पोज़िशन और अटेंशन मास्क वेक्टर बनाएं
  • Flux के साथ ट्रेनिंग स्टेप फ़ंक्शन बनाएं.
  • बैकवर्ड पास के बिना, पुष्टि करने वाला चरण बनाएं.
  • ट्रेनिंग लूप बनाएं.
  • जेम्मा मॉडल को बेहतर बनाएं.

gemma.transformer.Transformer क्लास का इस्तेमाल करके, फ़ॉरवर्ड पास और लॉस फ़ंक्शन तय करें. जेम्मा Transformer, flax.linen.Module से इनहेरिट करती है और इसमें दो ज़रूरी तरीके बताई गई हैं:

  • init: मॉडल के पैरामीटर को शुरू करता है.
  • apply: पैरामीटर के दिए गए सेट का इस्तेमाल करके, मॉडल का __call__ फ़ंक्शन एक्ज़ीक्यूट करता है.

    आप पहले से ट्रेन किए गए जेम्मा वेट के साथ काम कर रहे हैं, इसलिए आपको init फ़ंक्शन का इस्तेमाल करने की ज़रूरत नहीं है.

def forward_and_loss_fn(params,
                        *,
                        model: transformer_lib.Transformer,
                        input_tokens: jax.Array,            # Shape [B, L]
                        input_mask: jax.Array,              # Shape [B, L]
                        positions: jax.Array,               # Shape [B, L]
                        attention_mask: jax.Array,          # [B, L, L]
                        ) -> jax.Array:
  """The forward pass and the loss function.

  Args:
    params: Model's input parameters.
    model: The Gemma transformer model to call.
    input_tokens: Input tokens sequence, shape [B, L].
    input_mask: Tokens to ignore when computing the loss, shape [B, L].
    positions: Relative position of each token, shape [B, L].
    attention_mask: Input attention mask, shape [B, L].

  Returns:
    The softmax cross-entropy loss for the next-token prediction task.
  """

  # The forward pass on the input data.
  # No attention cache is needed here.
  logits, _ = model.apply(
        params,
        input_tokens,
        positions,
        None,              # Attention cache is None.
        attention_mask,
    )

  # Exclude the last step as it does not appear in the targets.
  logits = logits[0, :-1]

  # Similarly, the first token cannot be predicted.
  target_tokens = input_tokens[0, 1:]
  target_mask = input_mask[0, 1:]

  # Convert the target labels to one-hot encoded vectors.
  one_hot = jax.nn.one_hot(target_tokens, logits.shape[-1])

  # Don't update on unwanted tokens.
  one_hot = one_hot * target_mask.astype(one_hot.dtype)[...,None]

  # Define the normalization factor.
  norm_factor = 1 / (jnp.sum(target_mask) + 1e-8)

  # Return the negative log likelihood (NLL) loss.
  return -jnp.sum(jax.nn.log_softmax(logits) * one_hot) * norm_factor

gemma.transformer.Transformer क्लास के लिए, हर इनपुट के साथ एक attention_mask और positions वेक्टर होना चाहिए. Transformer.build_positions_from_mask और Transformer.make_causal_attn_mask का इस्तेमाल करने वाला कस्टम फ़ंक्शन बनाकर, इन्हें जनरेट किया जा सकता है:

def get_attention_mask_and_positions(example: jax.Array,
                                     pad_id : int,
                                     )-> tuple[jax.Array, jax.Array]:
  """Builds the position and attention mask vectors from the given tokens."""
  pad_mask = example != pad_id
  current_token_position = transformer_lib.build_positions_from_mask(pad_mask)
  attention_mask = transformer_lib.make_causal_attn_mask(pad_mask)
  return current_token_position, attention_mask

ऐसा train_step फ़ंक्शन बनाएं जो बैकवर्ड पास करता है और मॉडल के पैरामीटर को ज़रूरत के मुताबिक अपडेट करता है. यहां:

  • jax.value_and_grad का इस्तेमाल, फ़ॉरवर्ड और पिछले पास के दौरान, लॉस फ़ंक्शन और ग्रेडिएंट का आकलन करने के लिए किया जाता है.
  • optax.apply_updates, पैरामीटर अपडेट करने के लिए है.
def train_step(model: transformer_lib.Transformer,
               params,
               optimizer: optax.GradientTransformation,
               opt_state: optax.OptState,
               pad_id: int,
               example: TrainingInput):
  """Train step.

  Args:
    model: The Gemma transformer model.
    params: The model's input parameters.
    optimizer: The Optax optimizer to use.
    opt_state: The input optimizer's state.
    pad_id: ID of the pad token.
    example: Input batch.

  Returns:
    The training loss, the updated parameters, and the updated optimizer state.
  """

  # Build the position and attention mask vectors.
  positions, attention_mask = get_attention_mask_and_positions(example.input_tokens, pad_id)

  # The forward and backward passes.
  train_loss, grads = jax.value_and_grad(forward_and_loss_fn)(params,
                                                             model=model,
                                                             input_tokens=example.input_tokens,
                                                             input_mask=example.target_mask,
                                                             positions=positions,
                                                             attention_mask=attention_mask)
  # Update the parameters.
  updates, opt_state = optimizer.update(grads, opt_state)
  params = optax.apply_updates(params, updates)

  return train_loss, params, opt_state

बैकवर्ड पास के बिना validation_step फ़ंक्शन बनाएं:

def validation_step(model: transformer_lib.Transformer,
                    params,
                    pad_id: int,
                    example: TrainingInput,
                    ):
  positions, attention_mask = get_attention_mask_and_positions(example.input_tokens, pad_id)
  val_loss = forward_and_loss_fn(params,
                                 model=model,
                                 input_tokens=example.input_tokens,
                                 input_mask=example.target_mask,
                                 positions=positions,
                                 attention_mask=attention_mask)
  return val_loss

SGD ऑप्टिमाइज़र के लिए optax.sgd का इस्तेमाल करके ट्रेनिंग लूप तय करें:

@chex.dataclass(frozen=True)
class TrainingConfig:
  learning_rate: float
  num_epochs: int
  eval_every_n: int
  batch_size: int
  max_steps: int | None = None

def train_loop(
    model: transformer_lib.Transformer,
    params,
    dataset_builder: MTNTDatasetBuilder,
    training_cfg: TrainingConfig):

  # Apply `jax.jit` on the training step, making the whole loop much more efficient.
  compiled_train_step = jax.jit(train_step, static_argnames=['model', 'optimizer'])

  # Apply `jax.jit` on the validation step.
  compiled_validation_step = jax.jit(validation_step, static_argnames=['model'])

  # To save memory, use the SGD optimizer instead of the usual Adam optimizer.
  # Note that for this specific example, SGD is more than enough.
  optimizer = optax.sgd(training_cfg.learning_rate)
  opt_state = optimizer.init(params)

  # Build the training dataset.
  train_ds = dataset_builder.get_train_dataset(batch_size=training_cfg.batch_size,
                                               num_epochs=training_cfg.num_epochs)
  train_ds = train_ds.as_numpy_iterator()

  # Build the validation dataset, with a limited number of samples for this demo.
  validation_ds = dataset_builder.get_validation_dataset(batch_size=training_cfg.batch_size)
  validation_ds = validation_ds.take(50)

  n_steps = 0
  avg_loss=0

  # A first round of the validation loss.
  n_steps_eval = 0
  eval_loss = 0
  val_iterator = validation_ds.as_numpy_iterator()
  for val_example in val_iterator:
    eval_loss += compiled_validation_step(model,
                                          params,
                                          dataset_builder._tokenizer.pad_id,
                                          val_example)
    n_steps_eval += 1
  print(f"Start, validation loss: {eval_loss/n_steps_eval}")

  for train_example in train_ds:
    train_loss, params, opt_state = compiled_train_step(model=model,
                                                        params=params,
                                                        optimizer=optimizer,
                                                        opt_state=opt_state,
                                                        pad_id=dataset_builder._tokenizer.pad_id,
                                                        example=train_example)
    n_steps += 1
    avg_loss += train_loss
    if n_steps % training_cfg.eval_every_n == 0:
      eval_loss = 0

      n_steps_eval = 0
      val_iterator = validation_ds.as_numpy_iterator()
      for val_example in val_iterator:
        eval_loss += compiled_validation_step(model,
                                              params,
                                              dataset_builder._tokenizer.pad_id,
                                              val_example)
        n_steps_eval +=1
      avg_loss /= training_cfg.eval_every_n
      eval_loss /= n_steps_eval
      print(f"STEP {n_steps} training loss: {avg_loss} - eval loss: {eval_loss}")
      avg_loss=0
    if training_cfg.max_steps is not None and n_steps > training_cfg.max_steps:
      break
  return params

यह पक्का करने के लिए कि यह मेमोरी में फ़िट हो जाए, जेम्मा मॉडल को सीमित चरणों (SEQ_SIZE) के हिसाब से फ़ाइन-ट्यून करना शुरू करें:

SEQ_SIZE = 25
tokenizer = GemmaTokenizer(vocab)
dataset_builder= MTNTDatasetBuilder(tokenizer, SEQ_SIZE)
training_cfg = TrainingConfig(learning_rate=1e-4,
                              num_epochs=1,
                              eval_every_n=20,
                              batch_size=1,
                              max_steps=100)

params = train_loop(model=model_2b,
                    params={'params': params['transformer']},
                    dataset_builder=dataset_builder,
                    training_cfg=training_cfg)
Start, validation loss: 10.647212982177734
STEP 20 training loss: 3.3015992641448975 - eval loss: 2.686880111694336
STEP 40 training loss: 5.375057220458984 - eval loss: 2.6751961708068848
STEP 60 training loss: 2.6599338054656982 - eval loss: 2.663877010345459
STEP 80 training loss: 4.822389125823975 - eval loss: 2.3333375453948975
STEP 100 training loss: 2.0131142139434814 - eval loss: 2.360811948776245

हर चरण की संख्या के साथ-साथ ट्रेनिंग में हुए नुकसान और पुष्टि की समस्या, दोनों की संख्या कम होनी चाहिए.

gemma.sampler.Sampler की मदद से sampler बनाएं. यह जेम्मा मॉडल चेकपॉइंट और टोकनाइज़र का इस्तेमाल करता है.

sampler = sampler_lib.Sampler(
    transformer=model_2b,
    vocab=vocab,
    params=params['params'],
)

आपका मॉडल अनुवाद कर सकता है या नहीं, यह देखने के लिए sampler का इस्तेमाल करें. gemma.sampler.Sampler में मौजूद total_generation_steps आर्ग्युमेंट, जवाब जनरेट करने के दौरान पूरे किए गए चरणों की संख्या है. यह पक्का करने के लिए कि इनपुट, ट्रेनिंग के फ़ॉर्मैट से मेल खाता हो, Translate this into French:\n प्रीफ़िक्स का इस्तेमाल करें. इसके आखिर में न्यूलाइन वर्ण का इस्तेमाल करें. इससे, मॉडल को अनुवाद शुरू करने के लिए संकेत मिलता है.

sampler(
    ["Translate this into French:\nHello, my name is Morgane.\n"],
    total_generation_steps=100,
    ).text
["C'est Bonjour, mon nom est Morgane.C'est Bonjour, mon nom est Morgane."]

ज़्यादा जानें

  • Google DeepMind GitHub पर gemma लाइब्रेरी के बारे में ज़्यादा जानें. इसमें, इस ट्यूटोरियल में इस्तेमाल किए गए मॉड्यूल की डॉकस्ट्रिंग शामिल है. जैसे, gemma.params, gemma.transformer, और gemma.sampler.
  • इन लाइब्रेरी की अपनी दस्तावेज़ साइटें हैं: core JAX, Flax, Chex, Optax, और Orbax.
  • sentencepiece टोकनाइज़र/डिटोकेनाइज़र दस्तावेज़ के लिए, Google का sentencepiece GitHub रेपो देखें.
  • kagglehub दस्तावेज़ के लिए, Kaggle के kagglehub GitHub रेपो पर README.md देखें.
  • Google Cloud Vertex AI के साथ Gemma मॉडल इस्तेमाल करने का तरीका जानें.
  • अगर Google Cloud TPU (v3-8 और इसके बाद के वर्शन) का इस्तेमाल किया जा रहा है, तो यह भी पक्का करें कि आपने jax[tpu] के नए पैकेज (!pip install -U jax[tpu] -f https://storage.googleapis.com/jax-releases/libtpu_releases.html) में अपडेट किया हो. साथ ही, रनटाइम को रीस्टार्ट करें. साथ ही, यह देखें कि jax और jaxlib वर्शन एक जैसे हों (!pip list | grep jax). इससे, jaxlib और jax वर्शन के मेल न खाने की वजह से आने वाले RuntimeError को रोका जा सकता है. JAX इंस्टॉल करने के बारे में ज़्यादा जानकारी पाने के लिए, JAX दस्तावेज़ देखें.