Notebooks
G
Google Gemini
[Gemma 2]Finetune With JORA

[Gemma 2]Finetune With JORA

recurrentgemmagemmapaligemmagemma-cookbookcodegemma
Copyright 2024 Google LLC.
[ ]

Fine-Tuning Gemma for Retrieval-Augmented Generation with JORA

Scaling Large Language Models (LLMs) for retrieval-based tasks, particularly in Retrieval-Augmented Generation (RAG), poses significant memory challenges, especially when fine-tuning extensive prompt sequences.

Gemma is a family of lightweight, state-of-the-art open models from Google, built from the same research and technology used to create the Gemini models. They are text-to-text, decoder-only large language models, available in English, with open weights, pre-trained variants, and instruction-tuned variants. Gemma models are well-suited for a variety of text generation tasks, including question answering, summarization, and reasoning. Their relatively small size makes it possible to deploy them in environments with limited resources such as a laptop, desktop or your own cloud infrastructure, democratizing access to state of the art AI models and helping foster innovation for everyone.

Existing open-source libraries support full-model inference and fine-tuning across multiple GPUs but often fall short in efficiently distributing parameters required for retrieved context. To address this limitation, JORA introduced a novel framework for Parameter-Efficient Fine-Tuning (PEFT) of Llama/Gemma models using distributed training, leveraging JAX. This framework uniquely utilizes JAX's just-in-time (JIT) compilation and tensor-sharding for efficient resource management, enabling accelerated fine-tuning with reduced memory requirements. This advancement significantly improves the scalability and feasibility of fine-tuning LLMs for complex RAG applications, even on systems with limited GPU resources.

The experiments demonstrate more than 12x improvement in runtime compared to Hugging Face/DeepSpeed implementations with four GPUs while consuming less than half the VRAM per GPU.

In this tutorial, you will understand the end-to-end process of fine-tuning a Gemma model using JORA and converting the trained model back to the Hugging Face format for inference.



Kaggle

Setup

Selecting the Runtime Environment

To start, you can choose either Google Colab or Kaggle as your platform. Select one, and proceed from there.

  • Google Colab Google Colab

    1. Click Open in Colab.
    2. You'll need access to a Colab Pro/Pro+ runtime with sufficient resources to run the Gemma model.
    3. In the menu, go to Runtime > Change runtime type.
    4. Ensure that the GPU is set to A100.
  • Kaggle Kaggle

    1. Click Open in Kaggle.
    2. Click on Session options in the right sidebar.
    3. Under Accelerator, select GPU T4 x2.
      • Note: This instance comes with 15 GB x2 (15 GB for each T4 GPU) of VRAM and 30 GB of RAM.
    4. Save the settings, and the notebook will restart with GPU support.

Gemma setup

Kaggle Models

To complete this tutorial and download and fine-tune using the necessary Kaggle Gemma Flax models, you'll first need to complete the setup instructions at Gemma setup. The Gemma setup instructions show you how to do the following:

  • Get access to Gemma on kaggle.com.
  • Select a Colab/Kaggle runtime with sufficient resources to run the Gemma model.
  • You'll generate and configure a Kaggle username and an API key as Colab secrets later in the guide.

Hugging Face Hub

You'll also be logging in to Hugging Face Hub to download the exact Gemma model used while fine-tuning so that you can convert the Flax model to the Hugging Face format and run inference later. Let's get you set up with Gemma:

  1. Hugging Face Account: If you don't already have one, you can create a free Hugging Face account by clicking here.
  2. Gemma Model Access: Head over to the Gemma model page and accept the usage conditions.
  3. Colab/Kaggle with Gemma Power: For this tutorial, you'll need a Colab/Kaggle runtime with enough resources to handle the Gemma model. Choose an appropriate runtime when starting your Colab/Kaggle session.
  4. Hugging Face Token: Generate a Hugging Face access (preferably write permission) token by clicking here. This token will come in handy later.

After you've completed the Gemma setup, move on to the next section, where you'll set environment variables for your Colab environment.

Configure Your Credentials

To access private models and datasets, you need to log in to the Hugging Face (HF) and Kaggle ecosystem.

  • Google Colab Google Colab

    If you're using Colab, you can securely store your Hugging Face token (HF_TOKEN) using the Colab Secrets manager:

    1. Open your Google Colab notebook and click on the πŸ”‘ Secrets tab in the left panel. The Secrets tab is found on the left panel.
    2. Add Hugging Face Token:
    • Create a new secret with the name HF_TOKEN.
    • Copy/paste your token key into the Value input box of HF_TOKEN.
    • Toggle the button on the left to allow notebook access to the secret
    1. Add Kaggle Token:
    • Same as before, but you repeat it for KAGGLE_USERNAME and KAGGLE_KEY.
  • Kaggle Kaggle

    To securely use your Hugging Face token (HF_TOKEN) in this notebook, you'll need to add it as a secret in your Kaggle environment:

    1. Open your Kaggle notebook and locate the Addons menu at the top in your notebook interface.
    2. Click on Secrets to manage your environment secrets. The Secrets option is found at the top.
    3. Add Hugging Face Token:
      • Click on the Add secret button.
      • In the Label field, enter HF_TOKEN.
      • In the Value field, paste your Hugging Face token.
      • Click Save to add the secret.
    4. Add Kaggle Token:
      • Same as before, but you repeat it for KAGGLE_USERNAME and KAGGLE_KEY.
[ ]

Clone JORA and install dependencies

[ ]
Cloning into 'JORA'...
remote: Enumerating objects: 299, done.
remote: Counting objects: 100% (299/299), done.
remote: Compressing objects: 100% (216/216), done.
remote: Total 299 (delta 151), reused 203 (delta 71), pack-reused 0 (from 0)
Receiving objects: 100% (299/299), 6.99 MiB | 17.66 MiB/s, done.
Resolving deltas: 100% (151/151), done.
/content/JORA
  Preparing metadata (setup.py) ... done
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 87.2/87.2 kB 1.8 MB/s eta 0:00:00
  Preparing metadata (setup.py) ... done
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 57.1/57.1 MB 42.0 MB/s eta 0:00:00
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 320.1/320.1 kB 30.8 MB/s eta 0:00:00
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 94.9/94.9 kB 9.7 MB/s eta 0:00:00
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 11.1/11.1 MB 122.3 MB/s eta 0:00:00
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 73.2/73.2 kB 6.9 MB/s eta 0:00:00
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 63.8/63.8 kB 6.3 MB/s eta 0:00:00
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 130.2/130.2 kB 13.6 MB/s eta 0:00:00
  Building wheel for fire (setup.py) ... done
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... done
  Building wheel for gemma (pyproject.toml) ... done
Looking in links: https://storage.googleapis.com/jax-releases/jax_nightly_releases.html
Requirement already satisfied: jax==0.4.33 in /usr/local/lib/python3.10/dist-packages (0.4.33)
Requirement already satisfied: jaxlib==0.4.33 in /usr/local/lib/python3.10/dist-packages (0.4.33)
Requirement already satisfied: jax-cuda12-plugin==0.4.33 in /usr/local/lib/python3.10/dist-packages (from jax-cuda12-plugin[with_cuda]==0.4.33) (0.4.33)
Requirement already satisfied: jax-cuda12-pjrt==0.4.33 in /usr/local/lib/python3.10/dist-packages (0.4.33)
Requirement already satisfied: ml-dtypes>=0.2.0 in /usr/local/lib/python3.10/dist-packages (from jax==0.4.33) (0.4.1)
Requirement already satisfied: numpy>=1.24 in /usr/local/lib/python3.10/dist-packages (from jax==0.4.33) (1.26.4)
Requirement already satisfied: opt-einsum in /usr/local/lib/python3.10/dist-packages (from jax==0.4.33) (3.4.0)
Requirement already satisfied: scipy>=1.10 in /usr/local/lib/python3.10/dist-packages (from jax==0.4.33) (1.13.1)
Requirement already satisfied: nvidia-cublas-cu12>=12.1.3.1 in /usr/local/lib/python3.10/dist-packages (from jax-cuda12-plugin[with_cuda]==0.4.33) (12.6.3.3)
Requirement already satisfied: nvidia-cuda-cupti-cu12>=12.1.105 in /usr/local/lib/python3.10/dist-packages (from jax-cuda12-plugin[with_cuda]==0.4.33) (12.6.80)
Requirement already satisfied: nvidia-cuda-nvcc-cu12>=12.1.105 in /usr/local/lib/python3.10/dist-packages (from jax-cuda12-plugin[with_cuda]==0.4.33) (12.6.77)
Requirement already satisfied: nvidia-cuda-runtime-cu12>=12.1.105 in /usr/local/lib/python3.10/dist-packages (from jax-cuda12-plugin[with_cuda]==0.4.33) (12.6.77)
Requirement already satisfied: nvidia-cudnn-cu12<10.0,>=9.1 in /usr/local/lib/python3.10/dist-packages (from jax-cuda12-plugin[with_cuda]==0.4.33) (9.5.1.17)
Requirement already satisfied: nvidia-cufft-cu12>=11.0.2.54 in /usr/local/lib/python3.10/dist-packages (from jax-cuda12-plugin[with_cuda]==0.4.33) (11.3.0.4)
Requirement already satisfied: nvidia-cusolver-cu12>=11.4.5.107 in /usr/local/lib/python3.10/dist-packages (from jax-cuda12-plugin[with_cuda]==0.4.33) (11.7.1.2)
Requirement already satisfied: nvidia-cusparse-cu12>=12.1.0.106 in /usr/local/lib/python3.10/dist-packages (from jax-cuda12-plugin[with_cuda]==0.4.33) (12.5.4.2)
Requirement already satisfied: nvidia-nccl-cu12>=2.18.1 in /usr/local/lib/python3.10/dist-packages (from jax-cuda12-plugin[with_cuda]==0.4.33) (2.23.4)
Requirement already satisfied: nvidia-nvjitlink-cu12>=12.1.105 in /usr/local/lib/python3.10/dist-packages (from jax-cuda12-plugin[with_cuda]==0.4.33) (12.6.77)

Import the dependencies

[ ]
[ ]

Download the Gemma Model

Now, you can download the Gemma model using kagglehub:

[ ]
Downloading 11 files:   0%|          | 0/11 [00:00<?, ?it/s]
Downloading from https://www.kaggle.com/api/v1/models/google/gemma-2/Flax/gemma2-2b-it/1/download/gemma2-2b-it/_METADATA...
Downloading from https://www.kaggle.com/api/v1/models/google/gemma-2/Flax/gemma2-2b-it/1/download/gemma2-2b-it/_CHECKPOINT_METADATA...
Downloading from https://www.kaggle.com/api/v1/models/google/gemma-2/Flax/gemma2-2b-it/1/download/gemma2-2b-it/ocdbt.process_0/d/bf69258061ae5f35eb7a5669fe6877d4...
Downloading from https://www.kaggle.com/api/v1/models/google/gemma-2/Flax/gemma2-2b-it/1/download/gemma2-2b-it/d/b5a4695f4be0a2f41ec1e25616ebd7e7...
Downloading from https://www.kaggle.com/api/v1/models/google/gemma-2/Flax/gemma2-2b-it/1/download/gemma2-2b-it/ocdbt.process_0/d/834bb4bf1e3854eb09f6208c95c071b2...
Downloading from https://www.kaggle.com/api/v1/models/google/gemma-2/Flax/gemma2-2b-it/1/download/gemma2-2b-it/descriptor/descriptor.pbtxt...
Downloading from https://www.kaggle.com/api/v1/models/google/gemma-2/Flax/gemma2-2b-it/1/download/gemma2-2b-it/ocdbt.process_0/manifest.ocdbt...
Downloading from https://www.kaggle.com/api/v1/models/google/gemma-2/Flax/gemma2-2b-it/1/download/gemma2-2b-it/ocdbt.process_0/d/fc20151969d7ca91ea9d8275bda0e219...
Downloading from https://www.kaggle.com/api/v1/models/google/gemma-2/Flax/gemma2-2b-it/1/download/gemma2-2b-it/manifest.ocdbt...
Downloading from https://www.kaggle.com/api/v1/models/google/gemma-2/Flax/gemma2-2b-it/1/download/tokenizer.model...
Downloading from https://www.kaggle.com/api/v1/models/google/gemma-2/Flax/gemma2-2b-it/1/download/gemma2-2b-it/checkpoint...
GEMMA_PATH: /root/.cache/kagglehub/models/google/gemma-2/Flax/gemma2-2b-it/1
[ ]
{'7b-it', '2b-it', 'gemma2-2b-it', '7b', '2b'}
{'2b': GemmaConfig(n_heads=8, n_kv=1), '2b-it': GemmaConfig(n_heads=8, n_kv=1), '7b': GemmaConfig(n_heads=16, n_kv=16), '7b-it': GemmaConfig(n_heads=16, n_kv=16), '1.1-2b-it': GemmaConfig(n_heads=8, n_kv=1), '1.1-7b-it': GemmaConfig(n_heads=16, n_kv=16), 'gemma2-2b-it': GemmaConfig(n_heads=8, n_kv=1)}

Note: By default, kagglehub stores the model in the ~/.cache/kagglehub directory.

Verify that JAX recognizes the GPU devices:

[ ]
[CudaDevice(id=0)]

Configure JORA and Prepare the Dataset

Here, you'll configure the Gemma model and also the training process for LoRA fine-tuning.

In order to fine-tune Gemma, you will use the Alpaca dataset. Ensure you have the dataset file alpaca_data_cleaned.json in the appropriate directory. You can download it from here or use the one that's bundled in the repository. For demonstration purposes, let's use the bundled one.

Credits: Stanford Alpaca

The generate_alpaca_dataset function is used to generate the dataset from an Alpaca format JSON file. This helps with instruct format training since the dataset processing, tokenization, and batching is handled by the library. Alternatively, torch Dataset and DataLoader can be used for custom datasets.

[ ]
Processing data...

The ParagemmaConfig class is used to set up the configuration for training while generate_alpaca_dataset_gemma processes the dataset, handles tokenization, and prepares it for training.

[ ]
ParagemmaConfig(GEMMA_MODEL_PATH='/root/.cache/kagglehub/models/google/gemma-2/Flax/gemma2-2b-it/1', MODEL_VERSION='gemma2-2b-it', NUM_SHARDS=None, LORA_R=8, LORA_ALPHA=16, LORA_DROPOUT=0.05, LR=1e-05, BATCH_SIZE=2, N_ACCUMULATION_STEPS=8, MAX_SEQ_LEN=512, N_EPOCHS=1, SEED=420, CACHE_SIZE=30)

Fine-tune Gemma with JORA

Now, you can proceed to fine-tuning the model using the train_lora_gemma function which initiates the fine-tuning process using LoRA (Low-Rank Adaptation). The checkpoints will be saved in the folder specified by checkpoint_path.

[ ]
Successfully loaded and sharded model parameters!
Output()

Note: Fine-tuning on the entire dataset can be time-consuming and may exceed available GPU quotas on Kaggle or consume significant compute units on Google Colab. Using a smaller split helps in managing resource usage and staying within platform-imposed limits.

Convert the model to the Hugging Face Format

After fine-tuning, you need to convert the trained model to the Hugging Face format for compatibility with the Hugging Face ecosystem so that you can easily run inference later.

Usage:

lorize_huggingface(HUGGINGFACE_PATH, JAX_PATH, SAVE_PATH, gemma=True)
  • HUGGINGFACE_PATH: Path to the Hugging Face Gemma model (the base model before fine-tuning).
  • JAX_PATH: Path to the LoRA merged parameters (the trained LoRA weights).
  • SAVE_PATH: Path to save the fine-tuned Hugging Face Gemma model.
  • gemma: Flag indicating you're working with a Gemma model.

First, specify the paths:

[ ]
Fetching 11 files:   0%|          | 0/11 [00:00<?, ?it/s]
generation_config.json:   0%|          | 0.00/187 [00:00<?, ?B/s]
special_tokens_map.json:   0%|          | 0.00/636 [00:00<?, ?B/s]
model.safetensors.index.json:   0%|          | 0.00/24.2k [00:00<?, ?B/s]
model-00001-of-00002.safetensors:   0%|          | 0.00/4.99G [00:00<?, ?B/s]
README.md:   0%|          | 0.00/29.1k [00:00<?, ?B/s]
.gitattributes:   0%|          | 0.00/1.57k [00:00<?, ?B/s]
config.json:   0%|          | 0.00/838 [00:00<?, ?B/s]
model-00002-of-00002.safetensors:   0%|          | 0.00/241M [00:00<?, ?B/s]
tokenizer_config.json:   0%|          | 0.00/47.0k [00:00<?, ?B/s]
tokenizer.model:   0%|          | 0.00/4.24M [00:00<?, ?B/s]
tokenizer.json:   0%|          | 0.00/17.5M [00:00<?, ?B/s]

Then, run the converter:

[ ]
Loading checkpoint shards:   0%|          | 0/2 [00:00<?, ?it/s]
model loaded
model saved to gemma-ft
  • The jora.hf module converts the JAX-trained model back to the Hugging Face format.
  • It merges the LoRA weights with the original model parameters.
  • The converted model is saved in the specified SAVE_PATH.

Load the Model and Generate Text

Finally, you can load the converted model using Hugging Face's Transformers library.

[ ]
Loading checkpoint shards:   0%|          | 0/3 [00:00<?, ?it/s]
WARNING:accelerate.big_modeling:Some parameters are on the meta device because they were offloaded to the cpu.

Here, both the tokenizer and the model are first loaded and then the model is moved automatically to the appropriate device. Finally, you generate text using the model while relying on the Alpaca prompt format:

[ ]
[ ]
Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.

### Instruction:
Identify 3 common mistakes in the following sentence. Suggest changes.

### Input:
She seems to believe that the real key to sucsess is working smart and hard.

### Response:
1. "sucsess" should be "success"
2. "seems to believe" is a weak phrase.
3. "working smart and hard" is a clichΓ©.
[ ]
Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.

### Instruction:
Make a prediction about what will happen in the next paragraph.

### Input:
Mary had been living in the small town for many years and had never seen anything like what was coming.

### Response:
She will be surprised by the event.
[ ]
Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.

### Instruction:
Identify a suitable <verb> in the following sentence.

### Input:
The cat <verb> in the garden.

### Response:
played
[ ]
Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.

### Instruction:
Explain why the quote is appropriate or not for a yoga class.

### Input:
Don't quit. Suffer now and live the rest of your life as a champion.

### Response:
This quote is not appropriate for a yoga class because it promotes a competitive mindset and ignores the importance of self-compassion and acceptance.

Push the model to your Hugging Face Hub

Optionally, Hugging Face allows to you easily store trained models in their hub.

[ ]

In this tutorial, you have learnt how to fine-tune a Gemma model using JORA and convert it to the Hugging Face model format for inference. By leveraging JAX's JIT compilation and tensor-sharding capabilities, you can achieve efficient resource management, enabling accelerated fine-tuning with reduced memory requirements.