Notebooks
G
Google Gemini
[Gemma 1]Data Parallel Inference In Jax Tpu

[Gemma 1]Data Parallel Inference In Jax Tpu

recurrentgemmagemmapaligemmagemma-cookbookcodegemma
Copyright 2024 Google LLC.
[ ]

Unlocking Gemma's Power: Data-Parallel Inference on TPUs with JAX

Intro

  • This notebook demonstrates how to leverage TPUs and JAX for data-parallel inference with the Gemma large language model.

  • This tutorial helps you tackling various movie review tasks simultaneously within a single prompt. Imagine identifying key characters, summarizing plots, and classifying genres of a movie – all at blazing-fast speeds!

  • While this tutorial emphasizes movie reviews, the core concepts of data-parallel inference with Gemma extend to various real-world applications.

JAX Data Parallel Inference

JAX supports data parallelism for efficient inference on multiple devices (TPUs, GPUs, etc.). In this approach, each device holds a replica of the model and processes a separate chunk of the input data (per-replica batch). This distribution reduces inference time for large datasets compared to running on a single device.

Key Points:

  • Each device has a copy of the model.
  • Data is split into per-replica batches distributed across devices.
  • JAX automatically handles data distribution, so you don't need to worry about the order in which data lands on each device. This simplifies data loading: each device can independently receive its per-replica batch stream.

Let's get started!

Connect to a TPU:

  • To connect to a TPU v2, click on the button Connect TPU in the top right-hand corner of the screen.

You can now run the following code cell to see the TPU devices you have available:

[ ]
[TpuDevice(id=0, process_index=0, coords=(0,0,0), core_on_chip=0),
, TpuDevice(id=1, process_index=0, coords=(0,0,0), core_on_chip=1),
, TpuDevice(id=2, process_index=0, coords=(1,0,0), core_on_chip=0),
, TpuDevice(id=3, process_index=0, coords=(1,0,0), core_on_chip=1),
, TpuDevice(id=4, process_index=0, coords=(0,1,0), core_on_chip=0),
, TpuDevice(id=5, process_index=0, coords=(0,1,0), core_on_chip=1),
, TpuDevice(id=6, process_index=0, coords=(1,1,0), core_on_chip=0),
, TpuDevice(id=7, process_index=0, coords=(1,1,0), core_on_chip=1)]

Awesome! Our setup includes a TPU with 8 cores. This notebook will take advantage of this by splitting our workload across all cores (data parallelism). Each core will receive a fraction of the data (1/8th) and generate results simultaneously.

Import libraries

[ ]

How to Access Gemma:

Before using Gemma for the first time, you need to request access to the model through Hugging Face. This ensures you've accepted the model's terms-of-use.

Since you'll be downloading the Gemma model weights from the Hugging Face Hub, you'll need a Hugging Face token to verify your acceptance.

If you don't already have a Hugging Face account, you can register for one at Hugging Face. Once you have an account, follow these steps:

  1. Go to the Hugging Face Gemma Model Card and select Request Access.
  2. Complete the consent form and accept the terms and conditions.
  3. Go to Hugging Face Hub account settings and create a new access token.
  4. Copy your Token.
  5. Then, in Colab, select Secrets (🔑) in the left pane and add your Token name (choose a secure name like hugging_face_token_key) and store your Token value under that name.
[ ]

Load the Model

You will use the latest Gemma-2B, this model offers 2 billion parameters, ensuring a lightweight footprint.

The Gemma model can be loaded using the familiar from_pretrained method in Transformers. This method downloads the model weights from the Hugging Face Hub the first time it is called, and subsequently initializes the Gemma model using these weights.

[ ]
/usr/local/lib/python3.10/dist-packages/huggingface_hub/utils/_token.py:89: UserWarning: 
The secret `HF_TOKEN` does not exist in your Colab secrets.
To authenticate with the Hugging Face Hub, create a token in your settings tab (https://huggingface.co/settings/tokens), set it as secret in your Google Colab and restart your session.
You will be able to reuse this secret in all of your notebooks.
Please note that authentication is recommended but still optional to access public models or datasets.
  warnings.warn(
config.json:   0%|          | 0.00/618 [00:00<?, ?B/s]
flax_model.msgpack:   0%|          | 0.00/5.01G [00:00<?, ?B/s]
Some of the weights of FlaxGemmaForCausalLM were initialized in bfloat16 precision from the model checkpoint at google/gemma-1.1-2b-it:
[('model', 'embed_tokens', 'embedding'), ('model', 'layers', '0', 'input_layernorm', 'weight'), ('model', 'layers', '0', 'mlp', 'down_proj', 'kernel'), ('model', 'layers', '0', 'mlp', 'gate_proj', 'kernel'), ('model', 'layers', '0', 'mlp', 'up_proj', 'kernel'), ('model', 'layers', '0', 'post_attention_layernorm', 'weight'), ('model', 'layers', '0', 'self_attn', 'k_proj', 'kernel'), ('model', 'layers', '0', 'self_attn', 'o_proj', 'kernel'), ('model', 'layers', '0', 'self_attn', 'q_proj', 'kernel'), ('model', 'layers', '0', 'self_attn', 'v_proj', 'kernel'), ('model', 'layers', '1', 'input_layernorm', 'weight'), ('model', 'layers', '1', 'mlp', 'down_proj', 'kernel'), ('model', 'layers', '1', 'mlp', 'gate_proj', 'kernel'), ('model', 'layers', '1', 'mlp', 'up_proj', 'kernel'), ('model', 'layers', '1', 'post_attention_layernorm', 'weight'), ('model', 'layers', '1', 'self_attn', 'k_proj', 'kernel'), ('model', 'layers', '1', 'self_attn', 'o_proj', 'kernel'), ('model', 'layers', '1', 'self_attn', 'q_proj', 'kernel'), ('model', 'layers', '1', 'self_attn', 'v_proj', 'kernel'), ('model', 'layers', '10', 'input_layernorm', 'weight'), ('model', 'layers', '10', 'mlp', 'down_proj', 'kernel'), ('model', 'layers', '10', 'mlp', 'gate_proj', 'kernel'), ('model', 'layers', '10', 'mlp', 'up_proj', 'kernel'), ('model', 'layers', '10', 'post_attention_layernorm', 'weight'), ('model', 'layers', '10', 'self_attn', 'k_proj', 'kernel'), ('model', 'layers', '10', 'self_attn', 'o_proj', 'kernel'), ('model', 'layers', '10', 'self_attn', 'q_proj', 'kernel'), ('model', 'layers', '10', 'self_attn', 'v_proj', 'kernel'), ('model', 'layers', '11', 'input_layernorm', 'weight'), ('model', 'layers', '11', 'mlp', 'down_proj', 'kernel'), ('model', 'layers', '11', 'mlp', 'gate_proj', 'kernel'), ('model', 'layers', '11', 'mlp', 'up_proj', 'kernel'), ('model', 'layers', '11', 'post_attention_layernorm', 'weight'), ('model', 'layers', '11', 'self_attn', 'k_proj', 'kernel'), ('model', 'layers', '11', 'self_attn', 'o_proj', 'kernel'), ('model', 'layers', '11', 'self_attn', 'q_proj', 'kernel'), ('model', 'layers', '11', 'self_attn', 'v_proj', 'kernel'), ('model', 'layers', '12', 'input_layernorm', 'weight'), ('model', 'layers', '12', 'mlp', 'down_proj', 'kernel'), ('model', 'layers', '12', 'mlp', 'gate_proj', 'kernel'), ('model', 'layers', '12', 'mlp', 'up_proj', 'kernel'), ('model', 'layers', '12', 'post_attention_layernorm', 'weight'), ('model', 'layers', '12', 'self_attn', 'k_proj', 'kernel'), ('model', 'layers', '12', 'self_attn', 'o_proj', 'kernel'), ('model', 'layers', '12', 'self_attn', 'q_proj', 'kernel'), ('model', 'layers', '12', 'self_attn', 'v_proj', 'kernel'), ('model', 'layers', '13', 'input_layernorm', 'weight'), ('model', 'layers', '13', 'mlp', 'down_proj', 'kernel'), ('model', 'layers', '13', 'mlp', 'gate_proj', 'kernel'), ('model', 'layers', '13', 'mlp', 'up_proj', 'kernel'), ('model', 'layers', '13', 'post_attention_layernorm', 'weight'), ('model', 'layers', '13', 'self_attn', 'k_proj', 'kernel'), ('model', 'layers', '13', 'self_attn', 'o_proj', 'kernel'), ('model', 'layers', '13', 'self_attn', 'q_proj', 'kernel'), ('model', 'layers', '13', 'self_attn', 'v_proj', 'kernel'), ('model', 'layers', '14', 'input_layernorm', 'weight'), ('model', 'layers', '14', 'mlp', 'down_proj', 'kernel'), ('model', 'layers', '14', 'mlp', 'gate_proj', 'kernel'), ('model', 'layers', '14', 'mlp', 'up_proj', 'kernel'), ('model', 'layers', '14', 'post_attention_layernorm', 'weight'), ('model', 'layers', '14', 'self_attn', 'k_proj', 'kernel'), ('model', 'layers', '14', 'self_attn', 'o_proj', 'kernel'), ('model', 'layers', '14', 'self_attn', 'q_proj', 'kernel'), ('model', 'layers', '14', 'self_attn', 'v_proj', 'kernel'), ('model', 'layers', '15', 'input_layernorm', 'weight'), ('model', 'layers', '15', 'mlp', 'down_proj', 'kernel'), ('model', 'layers', '15', 'mlp', 'gate_proj', 'kernel'), ('model', 'layers', '15', 'mlp', 'up_proj', 'kernel'), ('model', 'layers', '15', 'post_attention_layernorm', 'weight'), ('model', 'layers', '15', 'self_attn', 'k_proj', 'kernel'), ('model', 'layers', '15', 'self_attn', 'o_proj', 'kernel'), ('model', 'layers', '15', 'self_attn', 'q_proj', 'kernel'), ('model', 'layers', '15', 'self_attn', 'v_proj', 'kernel'), ('model', 'layers', '16', 'input_layernorm', 'weight'), ('model', 'layers', '16', 'mlp', 'down_proj', 'kernel'), ('model', 'layers', '16', 'mlp', 'gate_proj', 'kernel'), ('model', 'layers', '16', 'mlp', 'up_proj', 'kernel'), ('model', 'layers', '16', 'post_attention_layernorm', 'weight'), ('model', 'layers', '16', 'self_attn', 'k_proj', 'kernel'), ('model', 'layers', '16', 'self_attn', 'o_proj', 'kernel'), ('model', 'layers', '16', 'self_attn', 'q_proj', 'kernel'), ('model', 'layers', '16', 'self_attn', 'v_proj', 'kernel'), ('model', 'layers', '17', 'input_layernorm', 'weight'), ('model', 'layers', '17', 'mlp', 'down_proj', 'kernel'), ('model', 'layers', '17', 'mlp', 'gate_proj', 'kernel'), ('model', 'layers', '17', 'mlp', 'up_proj', 'kernel'), ('model', 'layers', '17', 'post_attention_layernorm', 'weight'), ('model', 'layers', '17', 'self_attn', 'k_proj', 'kernel'), ('model', 'layers', '17', 'self_attn', 'o_proj', 'kernel'), ('model', 'layers', '17', 'self_attn', 'q_proj', 'kernel'), ('model', 'layers', '17', 'self_attn', 'v_proj', 'kernel'), ('model', 'layers', '2', 'input_layernorm', 'weight'), ('model', 'layers', '2', 'mlp', 'down_proj', 'kernel'), ('model', 'layers', '2', 'mlp', 'gate_proj', 'kernel'), ('model', 'layers', '2', 'mlp', 'up_proj', 'kernel'), ('model', 'layers', '2', 'post_attention_layernorm', 'weight'), ('model', 'layers', '2', 'self_attn', 'k_proj', 'kernel'), ('model', 'layers', '2', 'self_attn', 'o_proj', 'kernel'), ('model', 'layers', '2', 'self_attn', 'q_proj', 'kernel'), ('model', 'layers', '2', 'self_attn', 'v_proj', 'kernel'), ('model', 'layers', '3', 'input_layernorm', 'weight'), ('model', 'layers', '3', 'mlp', 'down_proj', 'kernel'), ('model', 'layers', '3', 'mlp', 'gate_proj', 'kernel'), ('model', 'layers', '3', 'mlp', 'up_proj', 'kernel'), ('model', 'layers', '3', 'post_attention_layernorm', 'weight'), ('model', 'layers', '3', 'self_attn', 'k_proj', 'kernel'), ('model', 'layers', '3', 'self_attn', 'o_proj', 'kernel'), ('model', 'layers', '3', 'self_attn', 'q_proj', 'kernel'), ('model', 'layers', '3', 'self_attn', 'v_proj', 'kernel'), ('model', 'layers', '4', 'input_layernorm', 'weight'), ('model', 'layers', '4', 'mlp', 'down_proj', 'kernel'), ('model', 'layers', '4', 'mlp', 'gate_proj', 'kernel'), ('model', 'layers', '4', 'mlp', 'up_proj', 'kernel'), ('model', 'layers', '4', 'post_attention_layernorm', 'weight'), ('model', 'layers', '4', 'self_attn', 'k_proj', 'kernel'), ('model', 'layers', '4', 'self_attn', 'o_proj', 'kernel'), ('model', 'layers', '4', 'self_attn', 'q_proj', 'kernel'), ('model', 'layers', '4', 'self_attn', 'v_proj', 'kernel'), ('model', 'layers', '5', 'input_layernorm', 'weight'), ('model', 'layers', '5', 'mlp', 'down_proj', 'kernel'), ('model', 'layers', '5', 'mlp', 'gate_proj', 'kernel'), ('model', 'layers', '5', 'mlp', 'up_proj', 'kernel'), ('model', 'layers', '5', 'post_attention_layernorm', 'weight'), ('model', 'layers', '5', 'self_attn', 'k_proj', 'kernel'), ('model', 'layers', '5', 'self_attn', 'o_proj', 'kernel'), ('model', 'layers', '5', 'self_attn', 'q_proj', 'kernel'), ('model', 'layers', '5', 'self_attn', 'v_proj', 'kernel'), ('model', 'layers', '6', 'input_layernorm', 'weight'), ('model', 'layers', '6', 'mlp', 'down_proj', 'kernel'), ('model', 'layers', '6', 'mlp', 'gate_proj', 'kernel'), ('model', 'layers', '6', 'mlp', 'up_proj', 'kernel'), ('model', 'layers', '6', 'post_attention_layernorm', 'weight'), ('model', 'layers', '6', 'self_attn', 'k_proj', 'kernel'), ('model', 'layers', '6', 'self_attn', 'o_proj', 'kernel'), ('model', 'layers', '6', 'self_attn', 'q_proj', 'kernel'), ('model', 'layers', '6', 'self_attn', 'v_proj', 'kernel'), ('model', 'layers', '7', 'input_layernorm', 'weight'), ('model', 'layers', '7', 'mlp', 'down_proj', 'kernel'), ('model', 'layers', '7', 'mlp', 'gate_proj', 'kernel'), ('model', 'layers', '7', 'mlp', 'up_proj', 'kernel'), ('model', 'layers', '7', 'post_attention_layernorm', 'weight'), ('model', 'layers', '7', 'self_attn', 'k_proj', 'kernel'), ('model', 'layers', '7', 'self_attn', 'o_proj', 'kernel'), ('model', 'layers', '7', 'self_attn', 'q_proj', 'kernel'), ('model', 'layers', '7', 'self_attn', 'v_proj', 'kernel'), ('model', 'layers', '8', 'input_layernorm', 'weight'), ('model', 'layers', '8', 'mlp', 'down_proj', 'kernel'), ('model', 'layers', '8', 'mlp', 'gate_proj', 'kernel'), ('model', 'layers', '8', 'mlp', 'up_proj', 'kernel'), ('model', 'layers', '8', 'post_attention_layernorm', 'weight'), ('model', 'layers', '8', 'self_attn', 'k_proj', 'kernel'), ('model', 'layers', '8', 'self_attn', 'o_proj', 'kernel'), ('model', 'layers', '8', 'self_attn', 'q_proj', 'kernel'), ('model', 'layers', '8', 'self_attn', 'v_proj', 'kernel'), ('model', 'layers', '9', 'input_layernorm', 'weight'), ('model', 'layers', '9', 'mlp', 'down_proj', 'kernel'), ('model', 'layers', '9', 'mlp', 'gate_proj', 'kernel'), ('model', 'layers', '9', 'mlp', 'up_proj', 'kernel'), ('model', 'layers', '9', 'post_attention_layernorm', 'weight'), ('model', 'layers', '9', 'self_attn', 'k_proj', 'kernel'), ('model', 'layers', '9', 'self_attn', 'o_proj', 'kernel'), ('model', 'layers', '9', 'self_attn', 'q_proj', 'kernel'), ('model', 'layers', '9', 'self_attn', 'v_proj', 'kernel'), ('model', 'norm', 'weight')]
You should probably UPCAST the model weights to float32 if this was not intended. See [`~FlaxPreTrainedModel.to_fp32`] for further information on how to do this.
generation_config.json:   0%|          | 0.00/132 [00:00<?, ?B/s]

You see a warning that the model parameters were loaded in bfloat16 precision - this is fine since you also want to keep the parameters in bfloat16 for inference.

The corresponding tokenizer can now be loaded using a similar API:

[ ]
tokenizer_config.json:   0%|          | 0.00/34.2k [00:00<?, ?B/s]
tokenizer.model:   0%|          | 0.00/4.24M [00:00<?, ?B/s]
tokenizer.json:   0%|          | 0.00/17.5M [00:00<?, ?B/s]
special_tokens_map.json:   0%|          | 0.00/636 [00:00<?, ?B/s]

Define Inputs

Next, you will define the text inputs. Since you have 8 TPU cores over which you want to perform data parallelism, you need our batch size to be a multiple of 8. This is to ensure that each TPU core receives the same amount of data (bsz / 8 samples). You will change the input text later.

[ ]

You can pre-process our input text to token ids using the tokenizer. TPUs expect inputs of static shape, so you'll define our maximum prompt length to be 64, and always pad our inputs to this sequence length:

[ ]

You now need to copy the model parameters to each TPU core. Each core will hold it's own copy of the parameters, such that it can run a model generation in parallel with the others. Copying the parameters across devices is achieved simply with the replicate method from Flax.

[ ]

Similarly, you need to split (or shard) our inputs across TPU cores. Sharding our inputs is achieved with the Flax helper function shard:

[ ]

Inference

You can now define our data-parallel method for inference. The Transformers generate method provides functionality for auto-regressive generation with batching, sampling, beam-search, etc. To reap the benefits of JAX, you'll compile the generate method end-to-end, such that the operations are fused into XLA-optimised kernels and executed efficiently on our hardware accelerator.

To achieve this, you'll wrap the generate method with the jax.pmap transformation. The jax.pmap transformation compiles the generate method with XLA, and prepares a function that can be executed in parallel across TPU devices.

[ ]

To avoid re-compiling the generate function for different values of max_new_tokens, you'll define it as a global variable here, and pass it to the generate function each time:

[ ]

You can now compile our parallel generate function.

[ ]

Now that the function is compiled, you can run it again much faster using the optimised kernels:

[ ]

After generate function compiled, the model outputs token IDs, which are then decoded by the tokenizer back into human-readable text:

[ ]

Analyze Movie Reviews with Parallel Processing on TPUs

This code demonstrates analyzing film critiques using multiple tasks processed concurrently on TPUs. The model performs the following tasks on each movie review:

  • Identify Key Characters: Find the two main characters in the film.
  • Summarize Plot: Briefly condense the story's key points.
  • Predict Genre: Classify the film genre based on the critique (e.g., comedy, drama).
  • Recommend Similar Films: Suggest two films with similar titles or themes.

Parallel Processing Power:

This approach leverages all available TPU cores to analyze multiple movies and tasks simultaneously. This significantly speeds up the analysis compared to processing each movie and task sequentially.

[ ]
[ ]
[ ]

Now, the model has finished its predictions using all 8 TPU cores. Let's see what it generated for each task and each movie.

[ ]

=============**Movie Title:**Titanic (1997 film)
**Task:Main Characters (2 max): Who are the 2 key characters?
=============**

In the movie Titanic (1997), there are two key characters that drive the plot forward: Jack Dawson and Rose DeWitt Bukater. Jack is a charming and wealthy young man from a poor background who dreams of escaping his humble life and achieving greatness. Rose is a strong-willed and independent young woman who represents the aspirations and resilience of women in the 19th century.

=============**Movie Title:**Titanic (1997 film)
**Task:Plot Summary (1 sentence): Briefly summarize the story.
=============**

In the year 1997, James Cameron crafts a tale of love, loss, and survival aboard the luxurious cruise ship RMS Titanic. With its opulent grand staircase, lavish cabins, and doomed romance, the film explores themes of class distinction, human capacity, and the fragility of life.

=============**Movie Title:**Titanic (1997 film)
**Task:Genre: What is the most likely genre (e.g. science fiction, comedy, drama)?
=============**

The provided text suggests that the genre of the movie Titanic (1997) is likely to be **drama**.

=============**Movie Title:**Titanic (1997 film)
**Task:Recommendation: Suggest 2 movies with similar titles or themes.
=============**

**Movie 1:** The Wolf of Wall Street (2013)
**Movie 2:** The Greatest Showman (2017)
[ ]

=============**Movie Title:**Avatar (2009 film)
**Task:Main Characters (2 max): Who are the 2 key characters?
=============**

The main characters of the 2009 film Avatar are Jake Sully and Neytiri.

=============**Movie Title:**Avatar (2009 film)
**Task:Plot Summary (1 sentence): Briefly summarize the story.
=============**

In the distant future, Jake Sully and his team of explorers travel to a remote planet called Pandora in search of the native species, the Na'vi. Guided by Neytiri, the Na'vi leader, they soon discover the planet's natural resources are being exploited. In the ensuing battle between colonization and preservation, Jake and Neytiri must make a choice that will determine the fate of Pandora.

=============**Movie Title:**Avatar (2009 film)
**Task:Genre: What is the most likely genre (e.g. science fiction, comedy, drama)?
=============**

The genre of the movie Avatar (2009) is most likely science fiction.

The movie deals with themes of environmentalism, colonization, and the relationships between humans and nature. It also features advanced technology and special effects that are characteristic of science fiction.

=============**Movie Title:**Avatar (2009 film)
**Task:Recommendation: Suggest 2 movies with similar titles or themes.
=============**

**Movie 1:** The Curious Case of Benjamin Button (2008)
**Movie 2:** Life of Pi (2012)

Conclusion

  • This notebook showcased efficient multi-task movie reviews using Gemma, TPUs and JAX for parallel inference tasks (character ID, plot, genre, and recommendations) all in a single prompt.