diff --git a/site/en/gemma/docs/distributed_tuning.ipynb b/site/en/gemma/docs/core/distributed_tuning.ipynb similarity index 97% rename from site/en/gemma/docs/distributed_tuning.ipynb rename to site/en/gemma/docs/core/distributed_tuning.ipynb index 5ee75631b..27b501400 100644 --- a/site/en/gemma/docs/distributed_tuning.ipynb +++ b/site/en/gemma/docs/core/distributed_tuning.ipynb @@ -16,7 +16,7 @@ "id": "Tce3stUlHN0L" }, "source": [ - "##### Copyright 2024 Google LLC." + "##### Copyright 2025 Google LLC." ] }, { @@ -49,19 +49,19 @@ "source": [ "\n", " \n", " \n", " \n", " \n", " \n", "
\n", - " View on ai.google.dev\n", + " View on ai.google.dev\n", " \n", " Run in Google Colab\n", " \n", - " Run in Kaggle\n", + " Run in Kaggle\n", " \n", - " Open in Vertex AI\n", + " Open in Vertex AI\n", " \n", - " View source on GitHub\n", + " View source on GitHub\n", "
" ] @@ -81,10 +81,8 @@ "id": "Tdlq6K0znh3O" }, "source": [ - "## Overview\n", - "\n", "Gemma is a family of lightweight, state-of-the-art open models built from research and technology used to create Google Gemini models. Gemma can be further finetuned to suit specific needs. But Large Language Models, such as Gemma, can be very large in size and some of them may not fit on a sing accelerator for finetuning. In this case there are two general approaches for finetuning them:\n", - "1. Parameter Efficient Fine-Tuning (PEFT), which seeks to shrink the effective model size by sacrificing some fidelity. LoRA falls in this category and the [Fine-tune Gemma models in Keras using LoRA](https://ai.google.dev/gemma/docs/lora_tuning) tutorial demonstrates how to finetune the Gemma 2B model `gemma_2b_en` with LoRA using KerasNLP on a single GPU.\n", + "1. Parameter Efficient Fine-Tuning (PEFT), which seeks to shrink the effective model size by sacrificing some fidelity. LoRA falls in this category and the [Fine-tune Gemma models in Keras using LoRA](https://ai.google.dev/gemma/docs/core/lora_tuning) tutorial demonstrates how to finetune the Gemma 2B model `gemma_2b_en` with LoRA using KerasNLP on a single GPU.\n", "2. Full parameter finetuning with model parallelism. Model parallelism distributes a single model's weights across multiple devices and enables horizontal scaling. You can find out more about distributed training in this [Keras guide](https://keras.io/guides/distribution/).\n", "\n", "This tutorial walks you through using Keras with a JAX backend to finetune the Gemma 7B model with LoRA and model-parallism distributed training on Google's Tensor Processing Unit (TPU). Note that LoRA can be turned off in this tutorial for a slower but more accurate full-parameter tuning." @@ -105,7 +103,7 @@ "Google has 3 products that provide TPUs:\n", "* [Colab](https://colab.sandbox.google.com/) provides TPU v2 for free, which is sufficient for this tutorial.\n", "* [Kaggle](https://www.kaggle.com/) offers TPU v3 for free and they also work for this tutorial.\n", - "* [Cloud TPU](https://cloud.google.com/tpu?hl=en) offers TPU v3 and newer generations. One way to set it up is:\n", + "* [Cloud TPU](https://cloud.google.com/tpu) offers TPU v3 and newer generations. One way to set it up is:\n", " 1. Create a new [TPU VM](https://cloud.google.com/tpu/docs/managing-tpus-tpu-vm#tpu-vms)\n", " 2. Set up [SSH port forwarding](https://cloud.google.com/solutions/connecting-securely#port-forwarding-over-ssh) for your intended Jupyter server port\n", " 3. Install Jupyter and start it on the TPU VM, then connect to Colab through \"Connect to a local runtime\"\n", @@ -963,7 +961,7 @@ "In this tutorial, you learned how to using KerasNLP JAX backend to finetune a Gemma model on the IMDb dataset in a distributed manner on the powerful TPUs. Here are a few suggestions for what else to learn:\n", "\n", "* Learn how to [get started with Keras Gemma](https://ai.google.dev/gemma/docs/get_started).\n", - "* Learn how to [finetune the Gemma model on GPU](https://ai.google.dev/gemma/docs/lora_tuning)." + "* Learn how to [finetune the Gemma model on GPU](https://ai.google.dev/gemma/docs/core/lora_tuning)." ] } ], diff --git a/site/en/gemma/docs/core/gemma_library.ipynb b/site/en/gemma/docs/core/gemma_library.ipynb new file mode 100644 index 000000000..7f732ca5d --- /dev/null +++ b/site/en/gemma/docs/core/gemma_library.ipynb @@ -0,0 +1,422 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "id": "G3MMAcssHTML" + }, + "source": [ + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "Tce3stUlHN0L" + }, + "source": [ + "##### Copyright 2025 Google LLC." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "cellView": "form", + "id": "tuOe1ymfHZPu" + }, + "outputs": [], + "source": [ + "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# you may not use this file except in compliance with the License.\n", + "# You may obtain a copy of the License at\n", + "#\n", + "# https://www.apache.org/licenses/LICENSE-2.0\n", + "#\n", + "# Unless required by applicable law or agreed to in writing, software\n", + "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", + "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", + "# See the License for the specific language governing permissions and\n", + "# limitations under the License." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "SDEExiAk4fLb" + }, + "source": [ + "# Prompt with images and text using Gemma library" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "4qxv4Sn9b8CE" + }, + "source": [ + "\n", + " \n", + " \n", + " \n", + "
\n", + " View on ai.google.dev\n", + " \n", + " Run in Google Colab\n", + " \n", + " Open in Vertex AI\n", + " \n", + " View source on GitHub\n", + "
" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "PXNm5_p_oxMF" + }, + "source": [ + "Using images for prompting Gemma models opens up a whole new range of possibilies for understanding your world and solving problems with visual data. Starting with [Gemma 3](/gemma/docs/core) in 4B sizes and higher, you can use image data as part of your prompt to for richer context and to solve more complex tasks.\n", + "\n", + "This tutorial shows you how to prompt Gemma with images using the [Gemma library](https://gemma-llm.readthedocs.io/) for JAX. Gemma library is a Python package built as an extension of [JAX](https://github.com/jax-ml/jax), letting you use the performance advantages of the JAX framework with dramatically less code.\n", + "\n", + "Note: For more the up-to-data information this library, see the [Gemma library](https://gemma-llm.readthedocs.io/) documentation." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "QQ6W7NzRe1VM" + }, + "source": [ + "## Setup\n", + "\n", + "To complete this tutorial, you'll first need to complete the setup instructions at [Gemma setup](https://ai.google.dev/gemma/docs/setup). The Gemma setup instructions show you how to do the following:\n", + "\n", + "* Get access to Gemma on [kaggle.com](https://www.kaggle.com).\n", + "* Select a Colab runtime with sufficient resources to run\n", + " the Gemma model.\n", + "* Generate and configure a Kaggle username and API key.\n", + "\n", + "After you've completed the Gemma setup, move on to the next section, where you'll set environment variables for your Colab environment." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "z9oy3QUmXtSd" + }, + "source": [ + "### Install libraries\n", + "\n", + "Install the Gemma library." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "UcGLzDeQ8NwN" + }, + "outputs": [], + "source": [ + "!pip install -q gemma" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "_gN-IVRC3dQe" + }, + "source": [ + "### Set environment variables\n", + "\n", + "Set environment variables for `KAGGLE_USERNAME` and `KAGGLE_KEY`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "DrBoa_Urw9Vx" + }, + "outputs": [], + "source": [ + "import os\n", + "from google.colab import userdata\n", + "\n", + "# Note: `userdata.get` is a Colab API. If you're not using Colab, set the env\n", + "# vars as appropriate for your system.\n", + "os.environ[\"KAGGLE_USERNAME\"] = userdata.get('KAGGLE_USERNAME')\n", + "os.environ[\"KAGGLE_KEY\"] = userdata.get('KAGGLE_KEY')" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "nbFs22cT_k_Y" + }, + "source": [ + "Set the JAX environment to use the full GPU memory space." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "Pv5gGAAg_xtQ" + }, + "outputs": [], + "source": [ + "os.environ[\"XLA_PYTHON_CLIENT_MEM_FRACTION\"]=\"1.00\"" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "599765c72722" + }, + "source": [ + "### Import packages\n", + "\n", + "Import the Gemma library and additional support libraries." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "f2fa267d75bc" + }, + "outputs": [], + "source": [ + "# Common imports\n", + "import os\n", + "import jax\n", + "import jax.numpy as jnp\n", + "import tensorflow_datasets as tfds\n", + "\n", + "# Gemma imports\n", + "from gemma import gm" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "ZsxDCbLN555T" + }, + "source": [ + "## Configure a model\n", + "\n", + "Select and configure a Gemma model for use, including a tokenizer, model architecture, and checkpoints. The Gemma libary supports all of Google's official releases of the model. You must use the `Gemma3Tokenizer` and a Gemma 3 or later model to be able to process images as part of your prompt.\n", + "\n", + "To configure the model, run the following code:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "yygIK9DEIldp" + }, + "outputs": [], + "source": [ + "tokenizer = gm.text.Gemma3Tokenizer()\n", + "\n", + "model = gm.nn.Gemma3_4B()\n", + "\n", + "params = gm.ckpts.load_params(gm.ckpts.CheckpointPath.GEMMA3_4B_IT)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "FOBW7piN5-sl" + }, + "source": [ + "## Generate text with text\n", + "\n", + "Start by prompting with text. The Gemma library provides a Sampler function for simple prompting." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "aae5GHrdpj2_" + }, + "outputs": [], + "source": [ + "sampler = gm.text.Sampler(\n", + " model=model,\n", + " params=params,\n", + " tokenizer=tokenizer,\n", + ")\n", + "\n", + "sampler.sample('Roses are red.', max_new_tokens=30)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "qH0eFH_DvYwM" + }, + "source": [ + "Change the prompt and change the maximum number of tokens to generate different output." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "vVlCnY7Gvm7U" + }, + "source": [ + "## Generate text with images\n", + "\n", + "Once you have a text prompt working, you can add images to your prompt. Make sure you have configure a Gemma 3 or later model that is 4B or higher, and configured the `Gemma3Tokenizer`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "U_gKV_cEGAQ_" + }, + "source": [ + "### Load an image\n", + "\n", + "Load an image from a data source or a local file. The following code shows how to load an image from a TensorFlow datasource:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "VEyTnnNGvgGG" + }, + "outputs": [], + "source": [ + "ds = tfds.data_source('oxford_flowers102', split='train')\n", + "image = ds[0]['image']\n", + "\n", + "# display the image\n", + "image" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "Jm6KW0pEI6gX" + }, + "source": [ + "### Prepare prompt with image data\n", + "\n", + "When you prompt with image data, you include a specific tag ``, to include the image with the text your prompt. You then encode the prompt with the image data using the `tokenizer` object to prepare to run it with the model." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "5eIwxSEWKI7u" + }, + "outputs": [], + "source": [ + "prompt = \"\"\"user\n", + "Describe the contents of this image.\n", + "\n", + "\n", + "\n", + "\n", + "model\n", + "\"\"\"" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "VMj0wphLKzQ1" + }, + "source": [ + "If you want to prompt with more than one image, you must include a `` tag for each image included in your prompt." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "cgwSiapfL09z" + }, + "source": [ + "### Run the prompt with image data\n", + "\n", + "After you prepare your image data and the prompt with image tags, you can run the prompt and generate output. The following code shows how to use the `Sampler` function run the prompt:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "46tsdilpMIxb" + }, + "outputs": [], + "source": [ + "sampler = gm.text.Sampler(\n", + " model=model,\n", + " params=params,\n", + " tokenizer=tokenizer,\n", + ")\n", + "\n", + "out = sampler.sample(prompt, images=image, max_new_tokens=500)\n", + "print(out)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "-HUzMDoVtZOw" + }, + "source": [ + "Alternatively, you can use the `gm.text.ChatSampler()` function generate a response without requiring `` tags. For more details, see the [Gemma library for JAX](https://gemma-llm.readthedocs.io/) documentation." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "z4kXWLwwMqOo" + }, + "source": [ + "## Next steps\n", + "\n", + "The Gemma library provides much more additional functionality. See these additional resources for more information:\n", + "\n", + "* [Gemma library sampling](https://gemma-llm.readthedocs.io/en/latest/colab_sampling.html)\n", + "* [Gemma library finetuning](https://gemma-llm.readthedocs.io/en/latest/colab_finetuning.html)\n", + "\n", + "The Gemma library for JAX provides additional functionality, including LoRA, Sharding, Quantization and more. For more details, see the [Gemma library](https://gemma-llm.readthedocs.io) documentation. If you have any feedback, or have issues using Gemma library, submit them through the repository [Issues](https://github.com/google-deepmind/gemma/issues) interface.\n" + ] + } + ], + "metadata": { + "accelerator": "GPU", + "colab": { + "name": "gemma_library.ipynb", + "toc_visible": true + }, + "google": { + "image_path": "/site-assets/images/marketing/gemma.png", + "keywords": [ + "examples", + "gemma", + "python", + "quickstart", + "text" + ] + }, + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/site/en/gemma/docs/keras_inference.ipynb b/site/en/gemma/docs/core/keras_inference.ipynb similarity index 97% rename from site/en/gemma/docs/keras_inference.ipynb rename to site/en/gemma/docs/core/keras_inference.ipynb index bacf75f4c..cf532f3fe 100644 --- a/site/en/gemma/docs/keras_inference.ipynb +++ b/site/en/gemma/docs/core/keras_inference.ipynb @@ -16,7 +16,7 @@ "id": "Tce3stUlHN0L" }, "source": [ - "##### Copyright 2024 Google LLC." + "##### Copyright 2025 Google LLC." ] }, { @@ -49,16 +49,16 @@ "source": [ "\n", " \n", " \n", " \n", " \n", "
\n", - " View on ai.google.dev\n", + " View on ai.google.dev\n", " \n", - " Run in Google Colab\n", + " Run in Google Colab\n", " \n", - " Open in Vertex AI\n", + " Open in Vertex AI\n", " \n", - " View source on GitHub\n", + " View source on GitHub\n", "
" ] @@ -576,8 +576,8 @@ "\n", "In this tutorial, you learned how to generate text using KerasNLP and Gemma. Here are a few suggestions for what to learn next:\n", "\n", - "* Learn how to [finetune a Gemma model](https://ai.google.dev/gemma/docs/lora_tuning).\n", - "* Learn how to perform [distributed fine-tuning and inference on a Gemma model](https://ai.google.dev/gemma/docs/distributed_tuning).\n", + "* Learn how to [finetune a Gemma model](https://ai.google.dev/gemma/docs/core/lora_tuning).\n", + "* Learn how to perform [distributed fine-tuning and inference on a Gemma model](https://ai.google.dev/gemma/docs/core/distributed_tuning).\n", "* Learn about [Gemma integration with Vertex AI](https://ai.google.dev/gemma/docs/integrations/vertex)\n", "* Learn how to [use Gemma models with Vertex AI](https://cloud.google.com/vertex-ai/docs/generative-ai/open-models/use-gemma)." ] diff --git a/site/en/gemma/docs/lora_tuning.ipynb b/site/en/gemma/docs/core/lora_tuning.ipynb similarity index 98% rename from site/en/gemma/docs/lora_tuning.ipynb rename to site/en/gemma/docs/core/lora_tuning.ipynb index 2f6071358..ed8ea92f2 100644 --- a/site/en/gemma/docs/lora_tuning.ipynb +++ b/site/en/gemma/docs/core/lora_tuning.ipynb @@ -16,7 +16,7 @@ "id": "Tce3stUlHN0L" }, "source": [ - "##### Copyright 2024 Google LLC." + "##### Copyright 2025 Google LLC." ] }, { @@ -58,15 +58,15 @@ "source": [ "\n", " \n", " \n", " \n", "
\n", - " View on ai.google.dev\n", + " View on ai.google.dev\n", " \n", - " Run in Google Colab\n", + " Run in Google Colab\n", " \n", - " Open in Vertex AI\n", + " Open in Vertex AI\n", " \n", - " View source on GitHub\n", + " View source on GitHub\n", "
" ] @@ -77,10 +77,6 @@ "id": "lSGRSsRPgkzK" }, "source": [ - "## Overview\n", - "\n", - "Gemma is a family of lightweight, state-of-the art open models built from the same research and technology used to create the Gemini models.\n", - "\n", "Large Language Models (LLMs) like Gemma have been shown to be effective at a variety of NLP tasks. An LLM is first pre-trained on a large corpus of text in a self-supervised fashion. Pre-training helps LLMs learn general-purpose knowledge, such as statistical relationships between words. An LLM can then be fine-tuned with domain-specific data to perform downstream tasks (such as sentiment analysis).\n", "\n", "LLMs are extremely large in size (parameters in the order of billions). Full fine-tuning (which updates all the parameters in the model) is not required for most applications because typical fine-tuning datasets are relatively much smaller than the pre-training datasets.\n", @@ -1000,7 +996,7 @@ "This tutorial covered LoRA fine-tuning on a Gemma model using KerasNLP. Check out the following docs next:\n", "\n", "* Learn how to [generate text with a Gemma model](https://ai.google.dev/gemma/docs/get_started).\n", - "* Learn how to perform [distributed fine-tuning and inference on a Gemma model](https://ai.google.dev/gemma/docs/distributed_tuning).\n", + "* Learn how to perform [distributed fine-tuning and inference on a Gemma model](https://ai.google.dev/gemma/docs/core/distributed_tuning).\n", "* Learn how to [use Gemma open models with Vertex AI](https://cloud.google.com/vertex-ai/docs/generative-ai/open-models/use-gemma).\n", "* Learn how to [fine-tune Gemma using KerasNLP and deploy to Vertex AI](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_gemma_kerasnlp_to_vertexai.ipynb)." ] diff --git a/site/en/gemma/docs/pytorch_gemma.ipynb b/site/en/gemma/docs/core/pytorch_gemma.ipynb similarity index 66% rename from site/en/gemma/docs/pytorch_gemma.ipynb rename to site/en/gemma/docs/core/pytorch_gemma.ipynb index 418c5ca3c..84d2c0e4c 100644 --- a/site/en/gemma/docs/pytorch_gemma.ipynb +++ b/site/en/gemma/docs/core/pytorch_gemma.ipynb @@ -16,7 +16,7 @@ "id": "Tce3stUlHN0L" }, "source": [ - "##### Copyright 2024 Google LLC." + "##### Copyright 2025 Google LLC." ] }, { @@ -49,12 +49,12 @@ "source": [ "\n", " \n", " \n", "
\n", - " View on ai.google.dev\n", + " View on ai.google.dev\n", " \n", - " Run in Google Colab\n", + " Run in Google Colab\n", " \n", - " View source on GitHub\n", + " View source on GitHub\n", "
" ] @@ -65,14 +65,9 @@ "id": "PXNm5_p_oxMF" }, "source": [ - "# Gemma in PyTorch\n", + "# Run Gemma using PyTorch\n", "\n", - "This is a quick demo of running Gemma inference in PyTorch.\n", - "For more details, please check out the Github repo of the official PyTorch implementation [here](https://github.com/google/gemma_pytorch).\n", - "\n", - "**Note that**:\n", - " * The free Colab CPU Python runtime and T4 GPU Python runtime are sufficient for running the Gemma 2B models and 7B int8 quantized models.\n", - " * For advanced use cases for other GPUs or TPU, please refer to [README.md](https://github.com/google/gemma_pytorch/blob/main/README.md) in the official repo." + "This guide shows you how to run Gemma using the PyTorch framework, including how to use image data for prompting Gemma release 3 and later models. For more details on the Gemma PyTorch implementation, see the project repository [README](https://github.com/google/gemma_pytorch)." ] }, { @@ -81,7 +76,29 @@ "id": "jbza6uQdA-0P" }, "source": [ - "### 1. Set up Kaggle access for Gemma\n", + "## Setup\n", + "\n", + "The following sections explain how to set up your development environment, including how get access to Gemma models for downloading from Kaggle, setting authentication variables, installing dependencies, and importing packages." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "5GpF_jcuhfmK" + }, + "source": [ + "### System requirements\n", + "\n", + "This Gemma Pytorch library requires GPU or TPU processors to run the Gemma model. The standard Colab CPU Python runtime and T4 GPU Python runtime are sufficient for running Gemma 1B, 2B, and 4B size models. For advanced use cases for other GPUs or TPU, please refer to [README](https://github.com/google/gemma_pytorch/blob/main/README.md) in the Gemma PyTorch repo." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "-O5qzCnRhoi2" + }, + "source": [ + "### Get access to Gemma on Kaggle\n", "\n", "To complete this tutorial, you first need to follow the setup instructions at [Gemma setup](https://ai.google.dev/gemma/docs/setup), which show you how to do the following:\n", "\n", @@ -89,9 +106,16 @@ "* Select a Colab runtime with sufficient resources to run the Gemma model.\n", "* Generate and configure a Kaggle username and API key.\n", "\n", - "After you've completed the Gemma setup, move on to the next section, where you'll set environment variables for your Colab environment.\n", - "\n", - "### 2. Set environment variables\n", + "After you've completed the Gemma setup, move on to the next section, where you'll set environment variables for your Colab environment." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "ahatg9AKhkw8" + }, + "source": [ + "### Set environment variables\n", "\n", "Set environment variables for `KAGGLE_USERNAME` and `KAGGLE_KEY`. When prompted with the \"Grant access?\" messages, agree to provide secret access." ] @@ -117,7 +141,7 @@ "id": "Fqq3HDVfA6Xm" }, "source": [ - "## Install dependencies" + "### Install dependencies" ] }, { @@ -154,7 +178,7 @@ "id": "ENdjDV3nBG5Z" }, "source": [ - "## Download model weights" + "### Download model weights" ] }, { @@ -166,12 +190,12 @@ "outputs": [], "source": [ "# Choose variant and machine type\n", - "VARIANT = '2b-it' #@param ['2b', '2b-it', '9b', '9b-it', '27b', '27b-it']\n", + "VARIANT = '4b-it' #@param ['1b','1b-it','4b','4b-it','12b','12b-it','27b','27b-it']\n", "MACHINE_TYPE = 'cuda' #@param ['cuda', 'cpu']\n", "\n", "CONFIG = VARIANT[:2]\n", - "if CONFIG == '2b':\n", - " CONFIG = '2b-v2'" + "if CONFIG == '4b':\n", + " CONFIG = '4b-v1'" ] }, { @@ -182,11 +206,19 @@ }, "outputs": [], "source": [ - "import os\n", "import kagglehub\n", "\n", "# Load model weights\n", - "weights_dir = kagglehub.model_download(f'google/gemma-2/pyTorch/gemma-2-{VARIANT}')" + "weights_dir = kagglehub.model_download(f'google/gemma-3/pyTorch/gemma-3-{VARIANT}')" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "rTlLzq9FgtrH" + }, + "source": [ + "Set the tokenizer and checkpoint paths for the model." ] }, { @@ -212,7 +244,20 @@ "id": "hOft88e7BOBB" }, "source": [ - "## Download the model implementation" + "## Configure the run environment\n", + "\n", + "The following sections explain how to prepare an PyTorch environment for running Gemma." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "bcfba5XAiR4q" + }, + "source": [ + "### Prepare the PyTorch run environment\n", + "\n", + "Prepare the PyTorch model execution environment by cloning the Gemma Pytorch repository." ] }, { @@ -237,7 +282,6 @@ } ], "source": [ - "# NOTE: The \"installation\" is just cloning the repo.\n", "!git clone https://github.com/google/gemma_pytorch.git" ] }, @@ -251,7 +295,7 @@ "source": [ "import sys\n", "\n", - "sys.path.append('gemma_pytorch')" + "sys.path.append('gemma_pytorch/gemma')" ] }, { @@ -262,10 +306,9 @@ }, "outputs": [], "source": [ - "from gemma.config import GemmaConfig, get_model_config\n", - "from gemma.model import GemmaForCausalLM\n", - "from gemma.tokenizer import Tokenizer\n", - "import contextlib\n", + "from gemma_pytorch.gemma.config import get_model_config\n", + "from gemma_pytorch.gemma.gemma3_model import Gemma3ForMultimodalLM\n", + "\n", "import os\n", "import torch" ] @@ -276,7 +319,9 @@ "id": "-9PvhVSYBWBt" }, "source": [ - "## Setup the model" + "### Set the model configuration\n", + "\n", + "Before you run the model, you must set some configuration parameters, including the Gemma variant, tokenizer and quantization level." ] }, { @@ -288,16 +333,65 @@ "outputs": [], "source": [ "# Set up model config.\n", - "model_config = get_model_config(CONFIG)\n", - "model_config.tokenizer = tokenizer_path\n", - "model_config.quant = 'quant' in VARIANT\n", + "model_config = get_model_config(VARIANT)\n", + "model_config.dtype = \"float32\" if MACHINE_TYPE == \"cpu\" else \"float16\"\n", + "model_config.tokenizer = tokenizer_path" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "zSp7oLLwjKCa" + }, + "source": [ + "### Configure the device context\n", + "\n", + "The following code configures the device context for running the model:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "596KAf_zjdi5" + }, + "outputs": [], + "source": [ + "@contextlib.contextmanager\n", + "def _set_default_tensor_type(dtype: torch.dtype):\n", + " \"\"\"Sets the default torch dtype to the given dtype.\"\"\"\n", + " torch.set_default_dtype(dtype)\n", + " yield\n", + " torch.set_default_dtype(torch.float)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "rtIQRpbdfyhj" + }, + "source": [ + "### Instantiate and load the model\n", "\n", - "# Instantiate the model and load the weights.\n", - "torch.set_default_dtype(model_config.get_dtype())\n", + "Load the model with its weights to prepare to run requests." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "oQEO8Uf-evZm" + }, + "outputs": [], + "source": [ "device = torch.device(MACHINE_TYPE)\n", - "model = GemmaForCausalLM(model_config)\n", - "model.load_weights(ckpt_path)\n", - "model = model.to(device).eval()" + "with _set_default_tensor_type(model_config.get_dtype()):\n", + " model = Gemma3ForMultimodalLM(model_config)\n", + " model.load_state_dict(torch.load(ckpt_path)['model_state_dict'])\n", + " model = model.to(device).eval()\n", + "print(\"Model loading done.\")\n", + "\n", + "print('Generating requests in chat mode...')" ] }, { @@ -320,15 +414,23 @@ "\n", "- `user`: user turn\n", "- `model`: model turn\n", - "- ``: beginning of dialogue turn\n", - "- ``: end of dialogue turn\n", + "- ``: beginning of dialog turn\n", + "- ``: tag for image data input\n", + "- ``: end of dialog turn\n", "\n", "For more information, read about prompt formatting for instruction tuned Gemma models\n", - "[here](https://ai.google.dev/gemma/docs/formatting).\n", + "[here](https://ai.google.dev/gemma/core/prompt-structure.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "iYNlBv-ak3G2" + }, + "source": [ + "### Generate text with text\n", "\n", - "The following is a sample code snippet demonstrating how to format a prompt for an\n", - "instruction-tuned Gemma model using user and model chat templates in a multi-turn\n", - "conversation.\n" + "The following is a sample code snippet demonstrating how to format a prompt for an instruction-tuned Gemma model using user and model chat templates in a multi-turn conversation." ] }, { @@ -368,8 +470,6 @@ } ], "source": [ - "# Generate with one request in chat mode\n", - "\n", "# Chat templates\n", "USER_CHAT_TEMPLATE = \"user\\n{prompt}\\n\"\n", "MODEL_CHAT_TEMPLATE = \"model\\n{prompt}\\n\"\n", @@ -388,7 +488,7 @@ "model.generate(\n", " USER_CHAT_TEMPLATE.format(prompt=prompt),\n", " device=device,\n", - " output_len=128,\n", + " output_len=256,\n", ")" ] }, @@ -422,6 +522,45 @@ ")" ] }, + { + "cell_type": "markdown", + "metadata": { + "id": "2xprL7RalqVe" + }, + "source": [ + "### Generate text with images\n", + "\n", + "With Gemma release 3 and later, you can use images with your prompt. The following example shows you how to include visual data with your prompt." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "NDWuxqatl-AA" + }, + "outputs": [], + "source": [ + "print('Chat with images...\\n')\n", + "\n", + "def read_image(url):\n", + " import io\n", + " import requests\n", + " import PIL\n", + "\n", + " contents = io.BytesIO(requests.get(url).content)\n", + " return PIL.Image.open(contents)\n", + "\n", + "image_url = 'https://storage.googleapis.com/keras-cv/models/paligemma/cow_beach_1.png'\n", + "image = read_image(image_url)\n", + "\n", + "print(model.generate(\n", + " [['user\\n',image, 'What animal is in this image?\\n', 'model\\n']],\n", + " device=device,\n", + " output_len=OUTPUT_LEN,\n", + "))" + ] + }, { "cell_type": "markdown", "metadata": { @@ -434,9 +573,9 @@ "other things that Gemma can do in [ai.google.dev/gemma](https://ai.google.dev/gemma).\n", "See also these other related resources:\n", "\n", - "- [Gemma model card](https://ai.google.dev/gemma/docs/model_card)\n", - "- [Gemma C++ Tutorial](https://ai.google.dev/gemma/docs/gemma_cpp)\n", - "- [Gemma formatting and system instructions](https://ai.google.dev/gemma/docs/formatting)" + "- [Gemma core models overview](https://ai.google.dev/gemma/docs/core)\n", + "- [Gemma C++ Tutorial](https://ai.google.dev/gemma/docs/core/gemma_cpp)\n", + "- [Gemma prompt and system instructions](https://ai.google.dev/gemma/core/prompt-structure)" ] } ], diff --git a/site/en/gemma/docs/jax_finetune.ipynb b/site/en/gemma/docs/jax_finetune.ipynb deleted file mode 100644 index 7d3aaa230..000000000 --- a/site/en/gemma/docs/jax_finetune.ipynb +++ /dev/null @@ -1,1412 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": { - "id": "G3MMAcssHTML" - }, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "Tce3stUlHN0L" - }, - "source": [ - "##### Copyright 2024 Google LLC." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "id": "tuOe1ymfHZPu" - }, - "outputs": [], - "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", - "# you may not use this file except in compliance with the License.\n", - "# You may obtain a copy of the License at\n", - "#\n", - "# https://www.apache.org/licenses/LICENSE-2.0\n", - "#\n", - "# Unless required by applicable law or agreed to in writing, software\n", - "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", - "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", - "# See the License for the specific language governing permissions and\n", - "# limitations under the License." - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "N_yUpPhqrRrK" - }, - "source": [ - "# Fine-tuning Gemma using JAX and Flax" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "-yDXE-RX835U" - }, - "source": [ - "\n", - " \n", - " \n", - " \n", - " \n", - "
\n", - " View on ai.google.dev\n", - " \n", - " Run in Google Colab\n", - " \n", - " Open in Vertex AI\n", - " \n", - " View source on GitHub\n", - "
" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "MUnQEMHBt3nc" - }, - "source": [ - "## Overview\n", - "\n", - "Gemma is a family of lightweight, state-of-the-art open large language models, based on the Google DeepMind Gemini research and technology. This tutorial demonstrates how to fine-tune the Gemma 2B Instruct model for an English-French translation task using [Google DeepMind's `gemma` library](https://github.com/google-deepmind/gemma), [JAX](https://jax.readthedocs.io) (a high-performance numerical computing library), [Flax](https://flax.readthedocs.io) (the JAX-based neural network library), [Chex](https://chex.readthedocs.io/en/latest/) (a library of utilities for writing reliable JAX code), [Optax](https://optax.readthedocs.io/en/latest/) (the JAX-based gradient processing and optimization library), and the [MTNT (Machine Translation of Noisy Text) dataset](https://arxiv.org/abs/1809.00388). Although Flax is not used directly in this notebook, Flax was used to create Gemma.\n", - "\n", - "The `gemma` library was written with JAX, Flax, [Orbax](https://orbax.readthedocs.io/) (a JAX-based library for training utilities like checkpointing), and [SentencePiece](https://github.com/google/sentencepiece) (a tokenizer/detokenizer library).\n", - "\n", - "**Note:** This notebook runs on A100 GPU in Google Colab. Free Colab hardware acceleration is *insufficient* to run this notebook, as it requires plenty of host memory, such as A100 GPU (available in Colab Pro) or at least Google Cloud TPU v3-8. You can use [a Kaggle VM notebook](https://www.kaggle.com/), which provides free TPU v3-8 acceleration; or [Google Cloud TPU](https://cloud.google.com/tpu?hl=en) offers TPU v3 and newer. Currently, Google Colab provides TPU v2, which is insufficient for this tutorial." - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "dbRLI7Q4-8Ve" - }, - "source": [ - "## Setup" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "n8Ku4iK6PnC0" - }, - "source": [ - "### 1. Set up Kaggle access for Gemma\n", - "\n", - "To complete this tutorial, you first need to follow the setup instructions at [Gemma setup](https://ai.google.dev/gemma/docs/setup), which show you how to do the following:\n", - "\n", - "* Get access to Gemma on [kaggle.com](https://www.kaggle.com/models/google/gemma/).\n", - "* Select a Colab runtime with sufficient resources to run the Gemma model.\n", - "* Generate and configure a Kaggle username and API key.\n", - "\n", - "After you've completed the Gemma setup, move on to the next section, where you'll set environment variables for your Colab environment.\n", - "\n", - "### 2. Set environment variables\n", - "\n", - "Set environment variables for `KAGGLE_USERNAME` and `KAGGLE_KEY`. When prompted with the \"Grant access?\" messages, agree to provide secret access." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": { - "id": "AVH6Y4k2964n" - }, - "outputs": [], - "source": [ - "import os\n", - "from google.colab import userdata # `userdata` is a Colab API.\n", - "\n", - "os.environ[\"KAGGLE_USERNAME\"] = userdata.get('KAGGLE_USERNAME')\n", - "os.environ[\"KAGGLE_KEY\"] = userdata.get('KAGGLE_KEY')" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "m1UE1CEnE9ql" - }, - "source": [ - "### 3. Install the `gemma` library\n", - "\n", - "Free Colab hardware acceleration is currently *insufficient* to run this notebook. If you are using [Colab Pay As You Go or Colab Pro](https://colab.research.google.com/signup), click on **Edit** > **Notebook settings** > Select **A100 GPU** > **Save** to enable hardware acceleration.\n", - "\n", - "Next, you need to install the Google DeepMind `gemma` library from [`github.com/google-deepmind/gemma`](https://github.com/google-deepmind/gemma). If you get an error about \"pip's dependency resolver\", you can usually ignore it.\n", - "\n", - "**Note:** By installing `gemma`, you will also install [`flax`](https://flax.readthedocs.io), core [`jax`](https://jax.readthedocs.io), [`optax`](https://optax.readthedocs.io/en/latest/) (the JAX-based gradient processing and optimization library), [`orbax`](https://orbax.readthedocs.io/), and [`sentencepiece`](https://github.com/google/sentencepiece)." - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": { - "id": "XpSw-_4EEcoY" - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - " Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n", - " Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n", - " Preparing metadata (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n", - "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m133.7/133.7 kB\u001b[0m \u001b[31m1.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", - "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m244.4/244.4 kB\u001b[0m \u001b[31m5.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", - "\u001b[?25h Building wheel for gemma (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n", - "\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n", - "tensorflow-metadata 1.14.0 requires absl-py<2.0.0,>=0.9, but you have absl-py 2.1.0 which is incompatible.\u001b[0m\u001b[31m\n", - "\u001b[0m" - ] - } - ], - "source": [ - "!pip install -q git+https://github.com/google-deepmind/gemma.git" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "-mRkkT-iPYoq" - }, - "source": [ - "### 4. Import libraries\n", - "\n", - "This notebook uses [Flax](https://flax.readthedocs.io) (for neural networks), core [JAX](https://jax.readthedocs.io), [SentencePiece](https://github.com/google/sentencepiece) (for tokenization), [Chex](https://chex.readthedocs.io/en/latest/) (a library of utilities for writing reliable JAX code), and TensorFlow Datasets." - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": { - "id": "ChMf1H4mPVx_" - }, - "outputs": [], - "source": [ - "import os\n", - "import enum\n", - "import re\n", - "import string\n", - "\n", - "import chex\n", - "import jax\n", - "import jax.numpy as jnp\n", - "import optax\n", - "\n", - "import tensorflow as tf\n", - "import tensorflow_datasets as tfds\n", - "\n", - "from gemma import params as params_lib\n", - "from gemma import sampler as sampler_lib\n", - "from gemma import transformer as transformer_lib\n", - "import sentencepiece as spm" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "oNgKIkxMOsit" - }, - "source": [ - "## Load the Gemma model\n", - "\n", - "Load the Gemma model with [`kagglehub.model_download`](https://github.com/Kaggle/kagglehub/blob/bddefc718182282882b72f814d407d89e5d178c4/src/kagglehub/models.py#L12), which takes three arguments:\n", - "\n", - "- `handle`: The model handle from Kaggle\n", - "- `path`: (Optional string) The local path\n", - "- `force_download`: (Optional boolean) Forces to re-download the model\n", - "\n", - "**Note:** Be mindful that the `gemma-2b-it` model is around 3.7Gb in size." - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": { - "id": "X-i10429N-g2" - }, - "outputs": [], - "source": [ - "GEMMA_VARIANT = '2b-it' # @param ['2b', '2b-it'] {type:\"string\"}" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": { - "id": "j_QdPAGyO5zl" - }, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "Downloading from https://www.kaggle.com/api/v1/models/google/gemma/flax/2b-it/2/download...\n", - "100%|██████████| 3.67G/3.67G [00:26<00:00, 147MB/s]\n", - "Extracting model files...\n" - ] - } - ], - "source": [ - "import kagglehub\n", - "\n", - "GEMMA_PATH = kagglehub.model_download(f'google/gemma/flax/{GEMMA_VARIANT}')" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": { - "id": "cjnXlLkWcHIy" - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "GEMMA_PATH: /root/.cache/kagglehub/models/google/gemma/flax/2b-it/2\n" - ] - } - ], - "source": [ - "print('GEMMA_PATH:', GEMMA_PATH)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "E1HzOpDcM04q" - }, - "source": [ - "**Note:** The path from the output above is where the model weights and tokenizer are saved locally, you will need them for later." - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "6ytvcJ8FPEMm" - }, - "source": [ - "Check the location of the model weights and the tokenizer, then set the path variables. The tokenizer directory will be in the main directory where you downloaded the model, while the model weights will be in a sub-directory. For example:\n", - "\n", - "- The `tokenizer.model` file will be in `/LOCAL/PATH/TO/gemma/flax/2b-it/2`).\n", - "- The model checkpoint will be in `/LOCAL/PATH/TO/gemma/flax/2b-it/2/2b-it`)." - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": { - "id": "JAwXvpzbuiB5" - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "CKPT_PATH: /root/.cache/kagglehub/models/google/gemma/flax/2b-it/2/2b-it\n", - "TOKENIZER_PATH: /root/.cache/kagglehub/models/google/gemma/flax/2b-it/2/tokenizer.model\n" - ] - } - ], - "source": [ - "CKPT_PATH = os.path.join(GEMMA_PATH, GEMMA_VARIANT)\n", - "TOKENIZER_PATH = os.path.join(GEMMA_PATH, 'tokenizer.model')\n", - "print('CKPT_PATH:', CKPT_PATH)\n", - "print('TOKENIZER_PATH:', TOKENIZER_PATH)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "U800JRcJVIlF" - }, - "source": [ - "## Load and prepare the MTNT dataset and the Gemma tokenizer\n", - "\n", - "You will use the [MTNT (Machine Translation of Noisy Text)](https://arxiv.org/abs/1809.00388) dataset, which is available from [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/mtnt).\n", - "\n", - "Download the English-to-French dataset portion of the MTNT dataset, and then sample two examples. Each sample in the dataset contains two entries: `src`: the original English sentence; and `dst`: the corresponding French translation." - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": { - "id": "pg8SfQH0EcoY" - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "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...\n" - ] - }, - { - "data": { - "application/vnd.jupyter.widget-view+json": { - "model_id": "4ec9a4a2b77f41e4a7435359338b140c", - "version_major": 2, - "version_minor": 0 - }, - "text/plain": [ - "Dl Completed...: 0 url [00:00, ? url/s]" - ] - }, - "metadata": {}, - "output_type": "display_data" - }, - { - "data": { - "application/vnd.jupyter.widget-view+json": { - "model_id": "f799eec281194b80b8f260224df50ae3", - "version_major": 2, - "version_minor": 0 - }, - "text/plain": [ - "Dl Size...: 0 MiB [00:00, ? MiB/s]" - ] - }, - "metadata": {}, - "output_type": "display_data" - }, - { - "data": { - "application/vnd.jupyter.widget-view+json": { - "model_id": "4804ce26e0b84a5e8a9774bb5dcd1ebc", - "version_major": 2, - "version_minor": 0 - }, - "text/plain": [ - "Extraction completed...: 0 file [00:00, ? file/s]" - ] - }, - "metadata": {}, - "output_type": "display_data" - }, - { - "data": { - "application/vnd.jupyter.widget-view+json": { - "model_id": "04b3ecfe7275446e816804c01da57572", - "version_major": 2, - "version_minor": 0 - }, - "text/plain": [ - "Generating splits...: 0%| | 0/3 [00:00 int:\n", - " \"\"\"Fast access to the pad ID.\"\"\"\n", - " return self._spm_processor.pad_id()\n", - "\n", - " def tokenize(self,\n", - " example: str | bytes,\n", - " prefix: str = '',\n", - " suffix: str = '',\n", - " add_eos: bool = True) -> jax.Array:\n", - " \"\"\"\n", - " The tokenization function.\n", - "\n", - " Args:\n", - " example: Input string to tokenize.\n", - " prefix: Prefix to add to the input string.\n", - " suffix: Suffix to add to the input string.\n", - " add_eos: If True, add an \"end of sentence\" token at the end of the output\n", - " sequence.\n", - " Returns:\n", - " Tokens corresponding to the input string.\n", - " \"\"\"\n", - " int_list = [self._spm_processor.bos_id()]\n", - " int_list.extend(self._spm_processor.EncodeAsIds(prefix + example + suffix))\n", - " if add_eos:\n", - " int_list.append(self._spm_processor.eos_id())\n", - "\n", - " return jnp.array(int_list, dtype=jnp.int32)\n", - "\n", - " def tokenize_tf_op(self,\n", - " str_tensor: tf.Tensor,\n", - " prefix: str = '',\n", - " suffix: str = '',\n", - " add_eos: bool = True) -> tf.Tensor:\n", - " \"\"\"A TensorFlow operator for the tokenize function.\"\"\"\n", - " encoded = tf.numpy_function(\n", - " self.tokenize,\n", - " [str_tensor, prefix, suffix, add_eos],\n", - " tf.int32)\n", - " encoded.set_shape([None])\n", - " return encoded\n", - "\n", - " def to_string(self, tokens: jax.Array) -> str:\n", - " \"\"\"Convert an array of tokens to a string.\"\"\"\n", - " return self._spm_processor.EncodeIds(tokens.tolist())" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "h-oJ2ziwxG1L" - }, - "source": [ - "Try it out by instantiating your new custom `GemmaTokenizer`, and then applying it on a small sample of the MTNT dataset:" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": { - "id": "xEA-97ioEcoY" - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Example 0:\n", - "src: [ 2 49688 736 1280 6987 235292 108 651 2778 576\n", - " 1080 104745 11982 5736 832 8995 901 780 3547 665\n", - " 575 573 4589 235369 2778 235265 108]\n", - "dst: [ 2 2025 29653 581 664 16298 1437 55563 41435 7840\n", - " 581 683 111452 581 533 235303 9776 4108 2459 679\n", - " 485 235303 479 6728 579 1806 2499 709 29653 581\n", - " 533 235303 101323 16054 1]\n", - "\n", - "Example 1:\n", - "src: [ 2 49688 736 1280 6987 235292 108 2437 87150 477\n", - " 476 11709 230461 8045 3636 40268 576 4252 4897 235336\n", - " 108]\n", - "dst: [ 2 213606 477 1455 235290 3510 748 8268 191017 2809\n", - " 581 2032 69972 581 11495 1305 533 235303 65978 1654\n", - " 1]\n", - "\n" - ] - } - ], - "source": [ - "tokenizer = GemmaTokenizer(vocab)\n", - "\n", - "def tokenize_source(tokenizer, example: tf.Tensor):\n", - " return tokenizer.tokenize_tf_op(example,\n", - " prefix='Translate this into French:\\n',\n", - " suffix='\\n',\n", - " add_eos=False)\n", - "def tokenize_destination(tokenizer, example: tf.Tensor):\n", - " return tokenizer.tokenize_tf_op(example,\n", - " add_eos=True)\n", - "\n", - "ds = tfds.load(\"mtnt/en-fr\",split=\"train\")\n", - "ds = ds.take(2)\n", - "ds = ds.map(lambda x: {'src': tokenize_source(tokenizer, x['src']),\n", - " 'dst': tokenize_destination(tokenizer, x['dst'])})\n", - "ds = ds.as_numpy_iterator()\n", - "\n", - "for idx, example in enumerate(ds):\n", - " print(f'Example {idx}:')\n", - " for key, val in example.items():\n", - " print(f'{key}: {val}')\n", - " print()" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "qkY_hThVkkqF" - }, - "source": [ - "Build a data loader for the entire MTNT dataset:" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": { - "id": "Zm30Q2lnknmG" - }, - "outputs": [], - "source": [ - "@chex.dataclass(frozen=True)\n", - "class TrainingInput:\n", - " # Input tokens provided to the model.\n", - " input_tokens: jax.Array\n", - "\n", - " # A mask that determines which tokens contribute to the target loss\n", - " # calculation.\n", - " target_mask: jax.Array\n", - "\n", - "class DatasetSplit(enum.Enum):\n", - " TRAIN = 'train'\n", - " VALIDATION = 'valid'\n", - "\n", - "class MTNTDatasetBuilder:\n", - " \"\"\"The dataset builder for the MTNT dataset.\"\"\"\n", - "\n", - " N_ITEMS = {DatasetSplit.TRAIN: 35_692,\n", - " DatasetSplit.VALIDATION: 811}\n", - "\n", - " BUFFER_SIZE_SHUFFLE = 10_000\n", - " TRANSLATION_PREFIX = 'Translate this into French:\\n'\n", - " TRANSLATION_SUFFIX = '\\n'\n", - "\n", - " def __init__(self,\n", - " tokenizer : GemmaTokenizer,\n", - " max_seq_len: int):\n", - " \"\"\"Constructor.\n", - "\n", - " Args:\n", - " tokenizer: Gemma tokenizer to use.\n", - " max_seq_len: size of each sequence in a given batch.\n", - " \"\"\"\n", - " self._tokenizer = tokenizer\n", - " self._base_data = {\n", - " DatasetSplit.TRAIN: tfds.load(\"mtnt/en-fr\",split=\"train\"),\n", - " DatasetSplit.VALIDATION: tfds.load(\"mtnt/en-fr\",split=\"valid\"),\n", - " }\n", - " self._max_seq_len = max_seq_len\n", - "\n", - " def _tokenize_source(self, example: tf.Tensor):\n", - " \"\"\"Tokenization function for the source.\"\"\"\n", - " return self._tokenizer.tokenize_tf_op(example,\n", - " prefix=self.TRANSLATION_PREFIX,\n", - " suffix=self.TRANSLATION_SUFFIX,\n", - " add_eos=False)\n", - "\n", - " def _tokenize_destination(self, example: tf.Tensor):\n", - " \"\"\"Tokenization function for the French translation.\"\"\"\n", - " return self._tokenizer.tokenize_tf_op(example,\n", - " add_eos=True)\n", - "\n", - " def _pad_up_to_max_len(self,\n", - " input_tensor: tf.Tensor,\n", - " pad_value: int | bool,\n", - " ) -> tf.Tensor:\n", - " \"\"\"Pad the given tensor up to sequence length of a batch.\"\"\"\n", - " seq_len = tf.shape(input_tensor)[0]\n", - " to_pad = tf.maximum(self._max_seq_len - seq_len, 0)\n", - " return tf.pad(input_tensor,\n", - " [[0, to_pad]],\n", - " mode='CONSTANT',\n", - " constant_values=pad_value,\n", - " )\n", - "\n", - " def _to_training_input(self,\n", - " src_tokens: jax.Array,\n", - " dst_tokens: jax.Array,\n", - " ) -> TrainingInput:\n", - " \"\"\"Build a training input from a tuple of source and destination tokens.\"\"\"\n", - "\n", - " # The input sequence fed to the model is simply the concatenation of the\n", - " # source and the destination.\n", - " tokens = tf.concat([src_tokens, dst_tokens], axis=0)\n", - "\n", - " # To prevent the model from updating based on the source (input)\n", - " # tokens, add a target mask to each input.\n", - " q_mask = tf.zeros_like(src_tokens, dtype=tf.bool)\n", - " a_mask = tf.ones_like(dst_tokens, dtype=tf.bool)\n", - " mask = tf.concat([q_mask, a_mask], axis=0)\n", - "\n", - " # If the output tokens sequence is smaller than the target sequence size,\n", - " # then pad it with pad tokens.\n", - " tokens = self._pad_up_to_max_len(tokens, self._tokenizer.pad_id)\n", - "\n", - " # Don't want to perform the backward pass on the pad tokens.\n", - " mask = self._pad_up_to_max_len(mask, False)\n", - "\n", - " return TrainingInput(input_tokens=tokens, target_mask=mask)\n", - "\n", - "\n", - " def get_train_dataset(self, batch_size: int, num_epochs: int):\n", - " \"\"\"Build the training dataset.\"\"\"\n", - "\n", - " # Tokenize each sample.\n", - " ds = self._base_data[DatasetSplit.TRAIN].map(lambda x : (self._tokenize_source(x['src']),\n", - " self._tokenize_destination(x['dst'])))\n", - "\n", - " # Convert the samples to training inputs.\n", - " ds = ds.map(lambda x, y: self._to_training_input(x, y))\n", - "\n", - " # Remove the samples that are too long.\n", - " ds = ds.filter(lambda x: tf.shape(x.input_tokens)[0] <= self._max_seq_len)\n", - "\n", - " # Shuffle the dataset.\n", - " ds = ds.shuffle(buffer_size=self.BUFFER_SIZE_SHUFFLE)\n", - "\n", - " # Repeat if necessary.\n", - " ds = ds.repeat(num_epochs)\n", - "\n", - " # Build batches.\n", - " ds = ds.batch(batch_size, drop_remainder=True)\n", - " return ds\n", - "\n", - " def get_validation_dataset(self, batch_size: int):\n", - " \"\"\"Build the validation dataset.\"\"\"\n", - "\n", - " # Same steps as in `get_train_dataset`, but without shuffling and no repetition.\n", - " ds = self._base_data[DatasetSplit.VALIDATION].map(lambda x : (self._tokenize_source(x['src']),\n", - " self._tokenize_destination(x['dst'])))\n", - " ds = ds.map(lambda x, y: self._to_training_input(x, y))\n", - " ds = ds.filter(lambda x: tf.shape(x.input_tokens)[0] <= self._max_seq_len)\n", - " ds = ds.batch(batch_size, drop_remainder=True)\n", - " return ds" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "A3jRNKosyLUK" - }, - "source": [ - "Try the `MTNTDatasetBuilder` out by instantiating the custom `GemmaTokenizer` again, then applying it on the MTNT dataset, and sampling two examples:" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": { - "id": "bYeduOaNEcoZ" - }, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "WARNING:tensorflow:Mapping types may not work well with tf.nest. Prefer using MutableMapping for \n", - "WARNING:tensorflow:Mapping types may not work well with tf.nest. Prefer using MutableMapping for \n", - "WARNING:tensorflow:Mapping types may not work well with tf.nest. Prefer using MutableMapping for \n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Example 0:\n", - "input_tokens: [[ 2 49688 736 1280 6987 235292 108 10924 665 12302\n", - " 235341 108 2 4397 63011 1437 38696 1241 1 0]\n", - " [ 2 49688 736 1280 6987 235292 108 13835 1517 235265\n", - " 108 2 69875 540 19713 235265 1 0 0 0]\n", - " [ 2 49688 736 1280 6987 235292 108 6956 1586 235297\n", - " 235265 108 2 78368 1586 235297 235265 1 0 0]]\n", - "target_mask: [[False False False False False False False False False False False False\n", - " True True True True True True True False]\n", - " [False False False False False False False False False False False True\n", - " True True True True True False False False]\n", - " [False False False False False False False False False False False False\n", - " True True True True True True False False]]\n", - "\n", - "Example 1:\n", - "input_tokens: [[ 2 49688 736 1280 6987 235292 108 18874 235341 108\n", - " 2 115905 6425 1241 1 0 0 0 0 0]\n", - " [ 2 49688 736 1280 6987 235292 108 7574 3356 235341\n", - " 108 2 7997 20707 1241 1 0 0 0 0]\n", - " [ 2 49688 736 1280 6987 235292 108 8703 665 235265\n", - " 108 2 235338 235303 90006 20133 235265 1 0 0]]\n", - "target_mask: [[False False False False False False False False False False True True\n", - " True True True False False False False False]\n", - " [False False False False False False False False False False False True\n", - " True True True True False False False False]\n", - " [False False False False False False False False False False False True\n", - " True True True True True True False False]]\n", - "\n" - ] - } - ], - "source": [ - "tokenizer = GemmaTokenizer(vocab)\n", - "\n", - "dataset_builder = MTNTDatasetBuilder(tokenizer, max_seq_len=20)\n", - "ds = dataset_builder.get_train_dataset(3, 1)\n", - "ds = ds.take(2)\n", - "ds = ds.as_numpy_iterator()\n", - "\n", - "for idx, example in enumerate(ds):\n", - " print(f'Example {idx}:')\n", - " for key, val in example.items():\n", - " print(f'{key}: {val}')\n", - " print()" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "7IY8Muu1zRF4" - }, - "source": [ - "## Configure the model\n", - "\n", - "Before you begin fine-tuning the Gemma model, you need to configure it.\n", - "\n", - "First, load and format the Gemma model checkpoint with the [`gemma.params.load_and_format_params`](https://github.com/google-deepmind/gemma/blob/c6bd156c246530e1620a7c62de98542a377e3934/gemma/params.py#L27) method:" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": { - "id": "by6eWKtqzxRf" - }, - "outputs": [], - "source": [ - "params = params_lib.load_and_format_params(CKPT_PATH)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "BtJhJkkZzsy1" - }, - "source": [ - "To automatically load the correct configuration from the Gemma model checkpoint, use [`gemma.transformer.TransformerConfig`](https://github.com/google-deepmind/gemma/blob/56e501ce147af4ea5c23cc0ddf5a9c4a6b7bd0d0/gemma/transformer.py#L65). The `cache_size` argument is the number of time steps in the Gemma `Transformer` cache. Afterwards, instantiate the Gemma model as `model_2b` with [`gemma.transformer.Transformer`](https://github.com/google-deepmind/gemma/blob/56e501ce147af4ea5c23cc0ddf5a9c4a6b7bd0d0/gemma/transformer.py#L136) (which inherits from [`flax.linen.Module`](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html)).\n", - "\n", - "**Note:** The vocabulary size is smaller than the number of input embeddings because of unused tokens in the current Gemma release." - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "metadata": { - "id": "_jjlFAkazzit" - }, - "outputs": [], - "source": [ - "config_2b = transformer_lib.TransformerConfig.from_params(\n", - " params,\n", - " cache_size=30\n", - ")\n", - "\n", - "model_2b = transformer_lib.Transformer(config=config_2b)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "t7UL2Af536x_" - }, - "source": [ - "## Fine-tune the model\n", - "\n", - "In this section, you will:\n", - "\n", - "- Use the `gemma.transformer.Transformer` class to create the forward pass and loss function.\n", - "- Build the position and attention mask vectors for tokens\n", - "- Build a training step function with Flax.\n", - "- Build the validation step without the backwards pass.\n", - "- Create the training loop.\n", - "- Fine-tune the Gemma model." - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "aJhtJumH7H8_" - }, - "source": [ - "Define the forward pass and the loss function using the [`gemma.transformer.Transformer`](https://github.com/google-deepmind/gemma/blob/56e501ce147af4ea5c23cc0ddf5a9c4a6b7bd0d0/gemma/transformer.py#L136) class. The Gemma `Transformer` inherits from [`flax.linen.Module`](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html), and offers two essential methods:\n", - "\n", - "- `init`: Initializes the model's parameters.\n", - "- `apply`: Executes the model's `__call__` function using a given set of parameters.\n", - "\n", - " Since you are working with pre-trained Gemma weights, you don't need to use the `init` function." - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": { - "id": "iEcV0XEEEcoZ" - }, - "outputs": [], - "source": [ - "def forward_and_loss_fn(params,\n", - " *,\n", - " model: transformer_lib.Transformer,\n", - " input_tokens: jax.Array, # Shape [B, L]\n", - " input_mask: jax.Array, # Shape [B, L]\n", - " positions: jax.Array, # Shape [B, L]\n", - " attention_mask: jax.Array, # [B, L, L]\n", - " ) -> jax.Array:\n", - " \"\"\"The forward pass and the loss function.\n", - "\n", - " Args:\n", - " params: Model's input parameters.\n", - " model: The Gemma transformer model to call.\n", - " input_tokens: Input tokens sequence, shape [B, L].\n", - " input_mask: Tokens to ignore when computing the loss, shape [B, L].\n", - " positions: Relative position of each token, shape [B, L].\n", - " attention_mask: Input attention mask, shape [B, L].\n", - "\n", - " Returns:\n", - " The softmax cross-entropy loss for the next-token prediction task.\n", - " \"\"\"\n", - "\n", - " # The forward pass on the input data.\n", - " # No attention cache is needed here.\n", - " logits, _ = model.apply(\n", - " params,\n", - " input_tokens,\n", - " positions,\n", - " None, # Attention cache is None.\n", - " attention_mask,\n", - " )\n", - "\n", - " # Exclude the last step as it does not appear in the targets.\n", - " logits = logits[0, :-1]\n", - "\n", - " # Similarly, the first token cannot be predicted.\n", - " target_tokens = input_tokens[0, 1:]\n", - " target_mask = input_mask[0, 1:]\n", - "\n", - " # Convert the target labels to one-hot encoded vectors.\n", - " one_hot = jax.nn.one_hot(target_tokens, logits.shape[-1])\n", - "\n", - " # Don't update on unwanted tokens.\n", - " one_hot = one_hot * target_mask.astype(one_hot.dtype)[...,None]\n", - "\n", - " # Define the normalization factor.\n", - " norm_factor = 1 / (jnp.sum(target_mask) + 1e-8)\n", - "\n", - " # Return the negative log likelihood (NLL) loss.\n", - " return -jnp.sum(jax.nn.log_softmax(logits) * one_hot) * norm_factor" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "WxbxsKcd7Ot7" - }, - "source": [ - "The [`gemma.transformer.Transformer`](https://github.com/google-deepmind/gemma/blob/56e501ce147af4ea5c23cc0ddf5a9c4a6b7bd0d0/gemma/transformer.py#L136) class requires an `attention_mask` and a `positions` vector alongside each input. You can generate these by creating a custom function that uses [`Transformer.build_positions_from_mask`](https://github.com/google-deepmind/gemma/blob/56e501ce147af4ea5c23cc0ddf5a9c4a6b7bd0d0/gemma/transformer.py#L48) and [`Transformer.make_causal_attn_mask`](https://github.com/google-deepmind/gemma/blob/56e501ce147af4ea5c23cc0ddf5a9c4a6b7bd0d0/gemma/transformer.py#L29):\n" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "metadata": { - "id": "cbWfdHf0EcoZ" - }, - "outputs": [], - "source": [ - "def get_attention_mask_and_positions(example: jax.Array,\n", - " pad_id : int,\n", - " )-> tuple[jax.Array, jax.Array]:\n", - " \"\"\"Builds the position and attention mask vectors from the given tokens.\"\"\"\n", - " pad_mask = example != pad_id\n", - " current_token_position = transformer_lib.build_positions_from_mask(pad_mask)\n", - " attention_mask = transformer_lib.make_causal_attn_mask(pad_mask)\n", - " return current_token_position, attention_mask" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "uRkeF6ed8tOI" - }, - "source": [ - "Build the `train_step` function that performs the backward pass and updates the model's parameters accordingly, where:\n", - "\n", - "- [`jax.value_and_grad`](https://jax.readthedocs.io/en/latest/_autosummary/jax.value_and_grad.html) is for evaluating the loss function and gradients during the forward and backward passes.\n", - "- [`optax.apply_updates`](https://optax.readthedocs.io/en/latest/api/apply_updates.html#optax.apply_updates) is for updating the parameters." - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "metadata": { - "id": "cPSfp7ZUEcoZ" - }, - "outputs": [], - "source": [ - "def train_step(model: transformer_lib.Transformer,\n", - " params,\n", - " optimizer: optax.GradientTransformation,\n", - " opt_state: optax.OptState,\n", - " pad_id: int,\n", - " example: TrainingInput):\n", - " \"\"\"Train step.\n", - "\n", - " Args:\n", - " model: The Gemma transformer model.\n", - " params: The model's input parameters.\n", - " optimizer: The Optax optimizer to use.\n", - " opt_state: The input optimizer's state.\n", - " pad_id: ID of the pad token.\n", - " example: Input batch.\n", - "\n", - " Returns:\n", - " The training loss, the updated parameters, and the updated optimizer state.\n", - " \"\"\"\n", - "\n", - " # Build the position and attention mask vectors.\n", - " positions, attention_mask = get_attention_mask_and_positions(example.input_tokens, pad_id)\n", - "\n", - " # The forward and backward passes.\n", - " train_loss, grads = jax.value_and_grad(forward_and_loss_fn)(params,\n", - " model=model,\n", - " input_tokens=example.input_tokens,\n", - " input_mask=example.target_mask,\n", - " positions=positions,\n", - " attention_mask=attention_mask)\n", - " # Update the parameters.\n", - " updates, opt_state = optimizer.update(grads, opt_state)\n", - " params = optax.apply_updates(params, updates)\n", - "\n", - " return train_loss, params, opt_state" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "8ZKSa-jJ809n" - }, - "source": [ - "Build the `validation_step` function without the backward pass:\n" - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "metadata": { - "id": "yU4oR92YEcoa" - }, - "outputs": [], - "source": [ - "def validation_step(model: transformer_lib.Transformer,\n", - " params,\n", - " pad_id: int,\n", - " example: TrainingInput,\n", - " ):\n", - " positions, attention_mask = get_attention_mask_and_positions(example.input_tokens, pad_id)\n", - " val_loss = forward_and_loss_fn(params,\n", - " model=model,\n", - " input_tokens=example.input_tokens,\n", - " input_mask=example.target_mask,\n", - " positions=positions,\n", - " attention_mask=attention_mask)\n", - " return val_loss" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "bNqVhj7v87f4" - }, - "source": [ - "Define the training loop using [`optax.sgd`](https://optax.readthedocs.io/en/latest/api/optimizers.html#optax.sgd) for the SGD optimizer:" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "metadata": { - "id": "xT4bAqNLEcoa" - }, - "outputs": [], - "source": [ - "@chex.dataclass(frozen=True)\n", - "class TrainingConfig:\n", - " learning_rate: float\n", - " num_epochs: int\n", - " eval_every_n: int\n", - " batch_size: int\n", - " max_steps: int | None = None\n", - "\n", - "def train_loop(\n", - " model: transformer_lib.Transformer,\n", - " params,\n", - " dataset_builder: MTNTDatasetBuilder,\n", - " training_cfg: TrainingConfig):\n", - "\n", - " # Apply `jax.jit` on the training step, making the whole loop much more efficient.\n", - " compiled_train_step = jax.jit(train_step, static_argnames=['model', 'optimizer'])\n", - "\n", - " # Apply `jax.jit` on the validation step.\n", - " compiled_validation_step = jax.jit(validation_step, static_argnames=['model'])\n", - "\n", - " # To save memory, use the SGD optimizer instead of the usual Adam optimizer.\n", - " # Note that for this specific example, SGD is more than enough.\n", - " optimizer = optax.sgd(training_cfg.learning_rate)\n", - " opt_state = optimizer.init(params)\n", - "\n", - " # Build the training dataset.\n", - " train_ds = dataset_builder.get_train_dataset(batch_size=training_cfg.batch_size,\n", - " num_epochs=training_cfg.num_epochs)\n", - " train_ds = train_ds.as_numpy_iterator()\n", - "\n", - " # Build the validation dataset, with a limited number of samples for this demo.\n", - " validation_ds = dataset_builder.get_validation_dataset(batch_size=training_cfg.batch_size)\n", - " validation_ds = validation_ds.take(50)\n", - "\n", - " n_steps = 0\n", - " avg_loss=0\n", - "\n", - " # A first round of the validation loss.\n", - " n_steps_eval = 0\n", - " eval_loss = 0\n", - " val_iterator = validation_ds.as_numpy_iterator()\n", - " for val_example in val_iterator:\n", - " eval_loss += compiled_validation_step(model,\n", - " params,\n", - " dataset_builder._tokenizer.pad_id,\n", - " val_example)\n", - " n_steps_eval += 1\n", - " print(f\"Start, validation loss: {eval_loss/n_steps_eval}\")\n", - "\n", - " for train_example in train_ds:\n", - " train_loss, params, opt_state = compiled_train_step(model=model,\n", - " params=params,\n", - " optimizer=optimizer,\n", - " opt_state=opt_state,\n", - " pad_id=dataset_builder._tokenizer.pad_id,\n", - " example=train_example)\n", - " n_steps += 1\n", - " avg_loss += train_loss\n", - " if n_steps % training_cfg.eval_every_n == 0:\n", - " eval_loss = 0\n", - "\n", - " n_steps_eval = 0\n", - " val_iterator = validation_ds.as_numpy_iterator()\n", - " for val_example in val_iterator:\n", - " eval_loss += compiled_validation_step(model,\n", - " params,\n", - " dataset_builder._tokenizer.pad_id,\n", - " val_example)\n", - " n_steps_eval +=1\n", - " avg_loss /= training_cfg.eval_every_n\n", - " eval_loss /= n_steps_eval\n", - " print(f\"STEP {n_steps} training loss: {avg_loss} - eval loss: {eval_loss}\")\n", - " avg_loss=0\n", - " if training_cfg.max_steps is not None and n_steps > training_cfg.max_steps:\n", - " break\n", - " return params" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "ecv6lp5MCzFc" - }, - "source": [ - "Begin fine-tuning the Gemma model on a limited number of steps (`SEQ_SIZE`) to make sure this fits in the memory:" - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "metadata": { - "id": "7SL2VAmVEcoa" - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Start, validation loss: 10.647212982177734\n", - "STEP 20 training loss: 3.3015992641448975 - eval loss: 2.686880111694336\n", - "STEP 40 training loss: 5.375057220458984 - eval loss: 2.6751961708068848\n", - "STEP 60 training loss: 2.6599338054656982 - eval loss: 2.663877010345459\n", - "STEP 80 training loss: 4.822389125823975 - eval loss: 2.3333375453948975\n", - "STEP 100 training loss: 2.0131142139434814 - eval loss: 2.360811948776245\n" - ] - } - ], - "source": [ - "SEQ_SIZE = 25\n", - "tokenizer = GemmaTokenizer(vocab)\n", - "dataset_builder= MTNTDatasetBuilder(tokenizer, SEQ_SIZE)\n", - "training_cfg = TrainingConfig(learning_rate=1e-4,\n", - " num_epochs=1,\n", - " eval_every_n=20,\n", - " batch_size=1,\n", - " max_steps=100)\n", - "\n", - "params = train_loop(model=model_2b,\n", - " params={'params': params['transformer']},\n", - " dataset_builder=dataset_builder,\n", - " training_cfg=training_cfg)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "EtfVo3pDDAZV" - }, - "source": [ - "Both the training loss and the validation loss should have gone down with each step count.\n", - "\n", - "Create a `sampler` with [`gemma.sampler.Sampler`](https://github.com/google-deepmind/gemma/blob/56e501ce147af4ea5c23cc0ddf5a9c4a6b7bd0d0/gemma/sampler.py#L88). It uses the Gemma model checkpoint and the tokenizer." - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "metadata": { - "id": "dQ1oCF10Ecod" - }, - "outputs": [], - "source": [ - "sampler = sampler_lib.Sampler(\n", - " transformer=model_2b,\n", - " vocab=vocab,\n", - " params=params['params'],\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "-61KZz7EHiIS" - }, - "source": [ - "Use the `sampler` to check if your model can perform translation. The `total_generation_steps` argument in [`gemma.sampler.Sampler`](https://github.com/google-deepmind/gemma/blob/56e501ce147af4ea5c23cc0ddf5a9c4a6b7bd0d0/gemma/sampler.py#L88) is the number of steps performed when generating a response. To ensure the input matches the training format, use the prefix `Translate this into French:\\n` with a newline character at the end. This signals the model to begin translation.\n", - "\n", - "**Note:** Due to hardware restrictions, the number of training parameters used in the gemma Transformer may not be sufficient to produce \"stable\" results in this demo.\n", - "\n", - "**Note:** If you run out of memory, click on **Runtime** > **Disconnect and delete runtime**, and then **Runtime** > **Run all**.\n" - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "metadata": { - "id": "S5F3fk22Ecod" - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[\"C'est Bonjour, mon nom est Morgane.C'est Bonjour, mon nom est Morgane.\"]" - ] - }, - "execution_count": 23, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "sampler(\n", - " [\"Translate this into French:\\nHello, my name is Morgane.\\n\"],\n", - " total_generation_steps=100,\n", - " ).text" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "Jao0Qk-ZIqyD" - }, - "source": [ - "## Learn more\n", - "\n", - "- You can learn more about the Google DeepMind [`gemma` library on GitHub](https://github.com/google-deepmind/gemma), which contains docstrings of modules you used in this tutorial, such as [`gemma.params`](https://github.com/google-deepmind/gemma/blob/main/gemma/params.py),\n", - "[`gemma.transformer`](https://github.com/google-deepmind/gemma/blob/main/gemma/transformer.py), and\n", - "[`gemma.sampler`](https://github.com/google-deepmind/gemma/blob/main/gemma/sampler.py).\n", - "- The following libraries have their own documentation sites: [core JAX](https://jax.readthedocs.io), [Flax](https://flax.readthedocs.io), [Chex](https://chex.readthedocs.io/en/latest/), [Optax](https://optax.readthedocs.io/en/latest/), and [Orbax](https://orbax.readthedocs.io/).\n", - "- For `sentencepiece` tokenizer/detokenizer documentation, check out [Google's `sentencepiece` GitHub repo](https://github.com/google/sentencepiece).\n", - "- For `kagglehub` documentation, check out `README.md` on [Kaggle's `kagglehub` GitHub repo](https://github.com/Kaggle/kagglehub).\n", - "- Learn how to [use Gemma models with Google Cloud Vertex AI](https://cloud.google.com/vertex-ai/docs/generative-ai/open-models/use-gemma).\n", - "- If you are using Google Cloud TPUs (v3-8 and newer), make sure to also update to the latest `jax[tpu]` package (`!pip install -U jax[tpu] -f https://storage.googleapis.com/jax-releases/libtpu_releases.html`), restart the runtime, and check that `jax` and `jaxlib` versions match (`!pip list | grep jax`). This can prevent the `RuntimeError` that can arise because of the `jaxlib` and `jax` version mismatch. For more JAX installation instructions, refer to the [JAX docs](https://jax.readthedocs.io/en/latest/tutorials/installation.html#install-google-tpu)." - ] - } - ], - "metadata": { - "accelerator": "GPU", - "colab": { - "name": "jax_finetune.ipynb", - "toc_visible": true - }, - "kernelspec": { - "display_name": "Python 3", - "name": "python3" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} diff --git a/site/en/gemma/docs/jax_inference.ipynb b/site/en/gemma/docs/jax_inference.ipynb deleted file mode 100644 index 67349596c..000000000 --- a/site/en/gemma/docs/jax_inference.ipynb +++ /dev/null @@ -1,1294 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": { - "id": "G3MMAcssHTML" - }, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "Tce3stUlHN0L" - }, - "source": [ - "##### Copyright 2024 Google LLC." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "id": "tuOe1ymfHZPu" - }, - "outputs": [], - "source": [ - "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", - "# you may not use this file except in compliance with the License.\n", - "# You may obtain a copy of the License at\n", - "#\n", - "# https://www.apache.org/licenses/LICENSE-2.0\n", - "#\n", - "# Unless required by applicable law or agreed to in writing, software\n", - "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", - "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", - "# See the License for the specific language governing permissions and\n", - "# limitations under the License." - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "FUOiKRSF7jc1" - }, - "source": [ - "# Inference with Gemma using JAX and Flax" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "60KmTK7o6ppd" - }, - "source": [ - "\n", - " \n", - " \n", - " \n", - " \n", - "
\n", - " View on ai.google.dev\n", - " \n", - " Run in Google Colab\n", - " \n", - " Open in Vertex AI\n", - " \n", - " View source on GitHub\n", - "
" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "Tdlq6K0znh3O" - }, - "source": [ - "## Overview\n", - "\n", - "Gemma is a family of lightweight, state-of-the-art open large language models, based on the Google DeepMind Gemini research and technology. This tutorial demonstrates how to perform basic sampling/inference with the Gemma 2B Instruct model using [Google DeepMind's `gemma` library](https://github.com/google-deepmind/gemma) that was written with [JAX](https://jax.readthedocs.io) (a high-performance numerical computing library), [Flax](https://flax.readthedocs.io) (the JAX-based neural network library), [Orbax](https://orbax.readthedocs.io/) (a JAX-based library for training utilities like checkpointing), and [SentencePiece](https://github.com/google/sentencepiece) (a tokenizer/detokenizer library). Although Flax is not used directly in this notebook, Flax was used to create Gemma.\n", - "\n", - "This notebook can run on Google Colab with free T4 GPU (go to **Edit** > **Notebook settings** > Under **Hardware accelerator** select **T4 GPU**)." - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "aKvTsIkL98BG" - }, - "source": [ - "## Setup" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "WCgCkmQSPxkE" - }, - "source": [ - "### 1. Set up Kaggle access for Gemma\n", - "\n", - "To complete this tutorial, you first need to follow the setup instructions at [Gemma setup](https://ai.google.dev/gemma/docs/setup), which show you how to do the following:\n", - "\n", - "* Get access to Gemma on [kaggle.com](https://www.kaggle.com/models/google/gemma/).\n", - "* Select a Colab runtime with sufficient resources to run the Gemma model.\n", - "* Generate and configure a Kaggle username and API key.\n", - "\n", - "After you've completed the Gemma setup, move on to the next section, where you'll set environment variables for your Colab environment.\n", - "\n", - "### 2. Set environment variables\n", - "\n", - "Set environment variables for `KAGGLE_USERNAME` and `KAGGLE_KEY`. When prompted with the \"Grant access?\" messages, agree to provide secret access." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "lKoW-nhE-gNO" - }, - "outputs": [], - "source": [ - "import os\n", - "from google.colab import userdata # `userdata` is a Colab API.\n", - "\n", - "os.environ[\"KAGGLE_USERNAME\"] = userdata.get('KAGGLE_USERNAME')\n", - "os.environ[\"KAGGLE_KEY\"] = userdata.get('KAGGLE_KEY')" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "AO7a1Q4Yyc9Z" - }, - "source": [ - "### 3. Install the `gemma` library\n", - "\n", - "This notebook focuses on using a free Colab GPU. To enable hardware acceleration, click on **Edit** > **Notebook settings** > Select **T4 GPU** > **Save**.\n", - "\n", - "Next, you need to install the Google DeepMind `gemma` library from [`github.com/google-deepmind/gemma`](https://github.com/google-deepmind/gemma). If you get an error about \"pip's dependency resolver\", you can usually ignore it.\n", - "\n", - "**Note:** By installing `gemma`, you will also install [`flax`](https://flax.readthedocs.io), core [`jax`](https://jax.readthedocs.io), [`optax`](https://optax.readthedocs.io/en/latest/) (the JAX-based gradient processing and optimization library), [`orbax`](https://orbax.readthedocs.io/), and [`sentencepiece`](https://github.com/google/sentencepiece)." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "WWEzVJR4Fx9g" - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - " Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n", - " Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n", - " Preparing metadata (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n", - "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m133.7/133.7 kB\u001b[0m \u001b[31m11.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", - "\u001b[?25h Building wheel for gemma (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n" - ] - } - ], - "source": [ - "!pip install -q git+https://github.com/google-deepmind/gemma.git" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "VKLjBAe1m3Ck" - }, - "source": [ - "## Load and prepare the Gemma model\n", - "\n", - "1. Load the Gemma model with [`kagglehub.model_download`](https://github.com/Kaggle/kagglehub/blob/bddefc718182282882b72f814d407d89e5d178c4/src/kagglehub/models.py#L12), which takes three arguments:\n", - "\n", - "- `handle`: The model handle from Kaggle\n", - "- `path`: (Optional string) The local path\n", - "- `force_download`: (Optional boolean) Forces to re-download the model\n", - "\n", - "**Note:** Be mindful that the `gemma-2b-it` model is around 3.7Gb in size." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "_W3FUd9lt8VT" - }, - "outputs": [], - "source": [ - "GEMMA_VARIANT = 'gemma2-2b-it' # @param ['gemma2-2b', 'gemma2-2b-it'] {type:\"string\"}" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "kFCmWEKdMA_Y" - }, - "outputs": [ - { - "data": { - "application/vnd.jupyter.widget-view+json": { - "model_id": "c5feb22ec5674243b90733e2ffb4c34c", - "version_major": 2, - "version_minor": 0 - }, - "text/plain": [ - "Downloading 11 files: 0%| | 0/11 [00:00 **Disconnect and delete runtime**, and then **Runtime** > **Run all**." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "Gj9jRFI5Hrv2" - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Prompt:\n", - "what is JAX in 3 bullet points?\n", - "Output:\n", - "\n", - "\n", - "* **High-performance numerical computation:** JAX leverages the power of GPUs and TPUs to accelerate complex mathematical operations, making it ideal for scientific computing, machine learning, and data analysis.\n", - "* **Automatic differentiation:** JAX provides automatic differentiation capabilities, allowing you to compute gradients and optimize models efficiently. This simplifies the process of training deep learning models.\n", - "* **Functional programming:** JAX embraces functional programming principles, promoting code readability and maintainability. It offers a flexible and expressive syntax for defining and manipulating data. \n", - "\n", - "\n", - "\n" - ] - } - ], - "source": [ - "prompt = [\n", - " \"what is JAX in 3 bullet points?\",\n", - "]\n", - "\n", - "reply = sampler(input_strings=prompt,\n", - " total_generation_steps=128,\n", - " )\n", - "\n", - "for input_string, out_string in zip(prompt, reply.text):\n", - " print(f\"Prompt:\\n{input_string}\\nOutput:\\n{out_string}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "njxRJy3qsBWw" - }, - "source": [ - "5. (Optional) Run this cell to free up memory if you have completed the notebook and want to try another prompt. Afterwards, you can instantiate the `sampler` again in step 3 and customize and run the prompt in step 4." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "qxX6qfFdNGHy" - }, - "outputs": [], - "source": [ - "del sampler" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "bzKsCGIN0yX5" - }, - "source": [ - "## Learn more\n", - "\n", - "- You can learn more about the Google DeepMind [`gemma` library on GitHub](https://github.com/google-deepmind/gemma), which contains docstrings of modules you used in this tutorial, such as [`gemma.params`](https://github.com/google-deepmind/gemma/blob/main/gemma/params.py),\n", - "[`gemma.transformer`](https://github.com/google-deepmind/gemma/blob/main/gemma/transformer.py), and\n", - "[`gemma.sampler`](https://github.com/google-deepmind/gemma/blob/main/gemma/sampler.py).\n", - "- The following libraries have their own documentation sites: [core JAX](https://jax.readthedocs.io), [Flax](https://flax.readthedocs.io), and [Orbax](https://orbax.readthedocs.io/).\n", - "- For `sentencepiece` tokenizer/detokenizer documentation, check out [Google's `sentencepiece` GitHub repo](https://github.com/google/sentencepiece).\n", - "- For `kagglehub` documentation, check out `README.md` on [Kaggle's `kagglehub` GitHub repo](https://github.com/Kaggle/kagglehub).\n", - "- Learn how to [use Gemma models with Google Cloud Vertex AI](https://cloud.google.com/vertex-ai/docs/generative-ai/open-models/use-gemma)." - ] - } - ], - "metadata": { - "accelerator": "GPU", - "colab": { - "name": "jax_inference.ipynb", - "toc_visible": true - }, - "kernelspec": { - "display_name": "Python 3", - "name": "python3" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -}