{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "G3MMAcssHTML" }, "source": [ "\n", "" ] }, { "cell_type": "markdown", "metadata": { "id": "3_lX1k54KKrx" }, "source": [ "Copyright 2024 Google LLC." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "Gr4W9nspKGtb" }, "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": "Q5_nIe-8gdJV" }, "source": [ "# Generate PaliGemma output with Keras\n", "\n", "\n", "\n", "\n", "\n", "
\n", "View on ai.google.dev\n", "\n", "Run in Google Colab\n", "\n", "View source on GitHub\n", "
" ] }, { "cell_type": "markdown", "metadata": { "id": "9hhIuS9sEKHx" }, "source": [ "PaliGemma models have *multimodal* capabilities, allowing you to generate output using both text and image input data. You can use image data with these models to provide additional context for your requests, or use the model to analyze the content of images. This tutorial shows you how to use PaliGemma with Keras to can analyze images and answer questions about them." ] }, { "cell_type": "markdown", "metadata": { "id": "9JaII1xxfbfz" }, "source": [ "## What's in this notebook\n", "\n", "This notebook uses PaliGemma with Keras and shows you how to:\n", "\n", "* Install Keras and the required dependencies\n", "* Download `PaliGemmaCausalLM`, a pre-trained PaliGemma variant for causal visual language modeling, and use it to create a model\n", "* Test the model's ability to infer information about supplied images" ] }, { "cell_type": "markdown", "metadata": { "id": "Bf7AUi02fcPL" }, "source": [ "## Before you begin\n", "\n", "Before going through this notebook, you should be familiar with Python code, as well as how large language models (LLMs) are trained. You don't need to be familiar with Keras, but basic knowledge about Keras is helpful when reading through the example code." ] }, { "cell_type": "markdown", "metadata": { "id": "380it9kIhzmm" }, "source": [ "## Setup\n", "\n", "The following sections explain the preliminary steps for getting a notebook to use a PaliGemma model, including model access, getting an API key, and configuring the notebook runtime." ] }, { "cell_type": "markdown", "metadata": { "id": "6uN0EpPJh7t5" }, "source": [ "### Get access to PaliGemma\n", "\n", "Before using PaliGemma for the first time, you must request access to the model through Kaggle by completing the following steps:\n", "\n", "1. Log in to [Kaggle](https://www.kaggle.com), or create a new Kaggle account if you don't already have one.\n", "1. Go to the [PaliGemma model card](https://www.kaggle.com/models/google/paligemma-2/) and click **Request Access**.\n", "1. Complete the consent form and accept the terms and conditions." ] }, { "cell_type": "markdown", "metadata": { "id": "Uz_pBNrWiDqe" }, "source": [ "### Configure your API key\n", "\n", "To use PaliGemma, you must provide your Kaggle username and a Kaggle API key.\n", "\n", "To generate a Kaggle API key, open your [**Settings** page in Kaggle](https://www.kaggle.com/settings) and click **Create New Token**. This triggers the download of a `kaggle.json` file containing your API credentials.\n", "\n", "Then, in Colab, select **Secrets** (πŸ”‘) in the left pane and add your Kaggle username and Kaggle API key. Store your username under the name `KAGGLE_USERNAME` and your API key under the name `KAGGLE_KEY`." ] }, { "cell_type": "markdown", "metadata": { "id": "wUB4JE0Hlxce" }, "source": [ "### Select the runtime\n", "\n", "To complete this tutorial, you'll need to have a Colab runtime with sufficient resources to run the PaliGemma model. In this case, you can use a T4 GPU:\n", "\n", "1. In the upper-right of the Colab window, click the **β–Ύ (Additional connection options)** dropdown menu.\n", "1. Select **Change runtime type**.\n", "1. Under **Hardware accelerator**, select **T4 GPU**." ] }, { "cell_type": "markdown", "metadata": { "id": "mIvv2Yo3lycQ" }, "source": [ "### Set environment variables\n", "\n", "Set the environment variables for `KAGGLE_USERNAME`, `KAGGLE_KEY`, and `KERAS_BACKEND`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "rdgwLyZLQBkP" }, "outputs": [], "source": [ "import os\n", "from google.colab import userdata\n", "\n", "# Set up environmental variables\n", "os.environ[\"KAGGLE_USERNAME\"] = userdata.get('KAGGLE_USERNAME')\n", "os.environ[\"KAGGLE_KEY\"] = userdata.get('KAGGLE_KEY')\n", "os.environ[\"KERAS_BACKEND\"] = \"jax\"" ] }, { "cell_type": "markdown", "metadata": { "id": "4a3Q4VCLljR9" }, "source": [ "### Install Keras\n", "\n", "Run the below cell to install Keras." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "DoYMMytAaMRJ" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m792.1/792.1 kB\u001b[0m \u001b[31m9.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[?25h" ] } ], "source": [ "!pip install -U -q keras-nlp keras-hub kagglehub" ] }, { "cell_type": "markdown", "metadata": { "id": "y2Y7BRtRgfvG" }, "source": [ "### Import dependencies and configure Keras\n", "\n", "Install the dependencies needed for this notebook and configure Keras' backend. You'll also set Keras to use `bfloat16` so that the framework uses less memory." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "MHECpBe6LE7y" }, "outputs": [], "source": [ "import keras\n", "import keras_hub\n", "import numpy as np\n", "import PIL\n", "import requests\n", "import io\n", "import matplotlib\n", "import re\n", "import matplotlib.pyplot as plt\n", "import matplotlib.patches as patches\n", "from PIL import Image\n", "\n", "keras.config.set_floatx(\"bfloat16\")" ] }, { "cell_type": "markdown", "metadata": { "id": "X-LE2E1uiSpP" }, "source": [ "## Load the model\n", "\n", "Now that you've set everything up, you can download the pre-trained model and create some utility methods to help your model generate its responses.\n", "In this step, you download a model using `PaliGemmaCausalLM` from Keras Hub. This class helps you manage and run the causal visual language model structure of PaliGemma. A *causal visual language model* predicts the next token based on previous tokens. Keras Hub provides implementations of many popular [model architectures](https://keras.io/keras_hub/api/models/).\n", "\n", "\n", "Create the model using the `from_preset` method and print its summary. This process will take about a minute to complete." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "abNuIP8D_9At" }, "outputs": [], "source": [ "paligemma = keras_hub.models.PaliGemmaCausalLM.from_preset(\"kaggle://keras/paligemma2/keras/pali_gemma2_mix_3b_224\")\n", "paligemma.summary()" ] }, { "cell_type": "markdown", "metadata": { "id": "FBsWvKEvoGMe" }, "source": [ "## Create utility methods\n", "\n", "To help you generate responses from your model, create two utility methods:\n", "\n", "* **`crop_and_resize`:** Helper method for `read_img`. This method crops and resizes the image to the passed in size so that the final image is resized without skewing the proportions of the image.\n", "* **`read_img`:** Helper method for `read_img_from_url`. This method is what actually opens the image, resizes it so that it fits in the model's constraints, and puts it into an array that can be interpreted by the model.\n", "* **`read_img_from_url`:** Takes in an image via a valid URL. You need this method to pass the image to the model.\n", "\n", "You'll use `read_img_from_url` in the next step of this notebook.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "S6_XQjhpvXiG" }, "outputs": [], "source": [ "def crop_and_resize(image, target_size):\n", " width, height = image.size\n", " source_size = min(image.size)\n", " left = width // 2 - source_size // 2\n", " top = height // 2 - source_size // 2\n", " right, bottom = left + source_size, top + source_size\n", " return image.resize(target_size, box=(left, top, right, bottom))\n", "\n", "def read_image(url, target_size):\n", " contents = io.BytesIO(requests.get(url).content)\n", " image = PIL.Image.open(contents)\n", " image = crop_and_resize(image, target_size)\n", " image = np.array(image)\n", " # Remove alpha channel if necessary.\n", " if image.shape[2] == 4:\n", " image = image[:, :, :3]\n", " return image\n", "\n", "def parse_bbox_and_labels(detokenized_output: str):\n", " matches = re.finditer(\n", " '\\d\\d\\d\\d)>\\d\\d\\d\\d)>\\d\\d\\d\\d)>\\d\\d\\d\\d)>'\n", " ' (?P