翻篇收录说明
翻篇网页快照

Run Gemma with Keras - Gemma Docs

https://gemma.ai/deployment/keras/

最近抓取:2026-12-04 04:17:32(北京时间)

最近内容变化:2026-11-29 20:15:36(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

Run Gemma 4 inference with Keras and KerasHub for text and multimodal image generation in Python.

正文摘录

Run Gemma with Keras¶ Models Gemma 4 Uses Keras Colab View as markdown Generating content, summarizing, and analysing content are just some of the tasks you can accomplish with Gemma open models. This tutorial shows you how to get started running Gemma using Keras, including generating text content with text and image input. Keras provides implementations for running Gemma and other models using JAX, PyTorch, and TensorFlow. If you're new to Keras, you might want to read Getting started with Keras before you begin. Gemma 3 and later models support text and image input. Earlier versions of Gemma only support text input, except for some variants, including PaliGemma. Note This notebook won't run on T4 if you try with Gemma 4. Use L4 or higher GPUs. Install Keras packages¶ Install the Keras and KerasHub Python packages. pip install -q -U keras keras-hub keras-nlp Select a backend¶ Keras is a high-level, multi-framework deep learning API designed for simplicity and ease of use. Keras 3 lets you choose the backend: TensorFlow, JAX, or PyTorch. All three will work for this tutorial. For this tutorial, configure the backend for JAX as it typically provides the better performance. import os os.environ["KERAS_BACKEND"] = "jax" # Or "tensorflow" or "torch". os.environ["XLA_PYTHON_CLIENT_MEM_FRACTION"] = "1.00" Import packages¶ Import the Keras and KerasHub packages. import keras import keras_hub Load model¶ Keras provides implementations of many popular model architectures. Download and configure a Gemma model using the Gemma4CausalLM class to build an end-to-end, causal language modeling implementation for Gemma 4 models. Create the model using the from_preset() method, as shown in the following code example: gemma_lm = keras_hub.models.Gemma4CausalLM.from_preset( "gemma4_instruct_2b", dtype="bfloat16", ) Keras presets Presets are gemma4_instruct_{SIZE} for the instruction-tuned weights and gemma4_{SIZE} for base. There is no 12B preset, so the selector above offers the four sizes KerasHub publishes. Each instruction-tuned preset also has a _assistant MTP drafter — see Multi-Token Prediction — which must never be loaded on its own. The Gemma4CausalLM.from_preset() method instantiates the model from a preset architecture and weights. In the code above, the string "gemma#_xxxxxxx" specifies a preset version and parameter size for Gemma. You can find the code strings for Gemma models in their Model Variation listings on Kaggle. Once you have the model downloaded, Use the summary() function to get more info about the model: gemma_lm.summary() Preprocessor: "gemma4_causal_lm_preprocessor" ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ Layer (type) ┃ Config ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩ │ gemma4_tokenizer_1 (Gemma4Tokenizer) │ Vocab size: 262,144 │ ├───────────────────────────────────────────────────────────────┼──────────────────────────────────────────┤ │ gemma4_image_converter (Gemma4ImageConverter) │ Image size: (1, 1) │ ├───────────────────────────────────────────────────────────────┼──────────────────────────────────────────┤ │ gemma4_audio_converter (Gemma4AudioConverter) │ Audio shape: (3,000, 128) │ ├───────────────────────────────────────────────────────────────┼──────────────────────────────────────────┤ │ gemma4_video_converter (Gemma4ImageConverter) │ Image size: (1, 1) │ ├───────────────────────────────────────────────────────────────┼──────────────────────────────────────────┤ │ gemma4_video_converter (ImageConverter) │ Image size: (None, None) │ └───────────────────────────────────────────────────────────────┴──────────────────────────────────────────┘ Model: "gemma4_causal_lm_1" ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ Layer (type) ┃ Output Shape ┃ Param # ┃ Connected to ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩ │ audio_indices (InputLayer) │ (None, None) │ 0 │ - │ ├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤ │ audio_mask (InputLayer) │ (None, None) │ 0 │ - │ ├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤ │ audio_mel (InputLayer) │ (None, None, None, 128) │ 0 │ - │ ├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤ │ audio_mel_mask (InputLayer) │ (None, None, None) │ 0 │ - │ ├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤ │ padding_mask (InputLayer) │ (None, None) │ 0 │ - │ ├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤ │ pixel_position_ids │ (None, None, None, 2) │ 0 │ - │ │ (InputLayer) │ │ │ │ ├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤ │ pixel_values (InputLayer) │ (None, None, None, None) │ 0 │ - │ ├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤ │ position_ids (InputLayer) │ (None, None) │ 0 │ - │ ├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤ │ token_ids (InputLayer) │ (None, None) │ 0 │ - │ ├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤ │ vision_indices (InputLayer) │ (None, None) │ 0 │ - │ ├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤ │ vision_mask (InputLayer) │ (None, None) │ 0 │ - │ ├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤ │ gemma4_backbone_1 │ (None, None, 1536) │ 5,104,298,467 │ audio_indices[0][0], │ │ (Gemma4Backbone) │ │ │ audio_mask[0][0], │ │ │ │ │ audio_mel[0][0], │ │ │ │ │ audio_mel_mask[0][0], │ │ │ │ │ padding_mask[0][0], │ │ │ │ │ pixel_position_ids[0][0], │ │ │ │ │ pixel_values[0][0], │ │ │ │ │ position_ids[0][0], │ │ │ │ │ token_ids[0][0], │ │ │ │ │ vision_indices[0][0], │ │ │ │ │ vision_mask[0][0] │ ├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤ │ token_embedding │ (None, None, 262144) │ 402,653,184 │ gemma4_backbone_1[0][0] │ │ (ReversibleEmbedding) │ │ │ │ ├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤ │ true_divide (TrueDivide) │ (None, None, 262144) │ 0 │ token_embedding[1][0] │ ├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤ │ tanh (Tanh) │ (None, None, 262144) │ 0 │ true_divide[0][0] │ ├───────────────────────────────┼───────────────────────────┼─────────────────┼────────────────────────────┤ │ multiply_40 (Multiply) │ (None, None, 262144) │ 0 │ tanh[0][0] │ └───────────────────────────────┴───────────────────────────┴─────────────────┴────────────────────────────┘ Total params: 5,104,298,467 (10.39 GB) Trainable params: 5,104,186,912 (10.39 GB) Non-trainable params: 111,555 (435.69 KB) The output of the summary shows the models total number of trainable parameters. For purposes of naming the model, the embedding layer is not counted against the number of parameters. Note To run larger Gemma models with Google Colab, you need access to the premium GPUs available in paid plans. Alternatively, you can perform inferences using Kaggle notebooks or Google Cloud projects. Generate text with text¶ Generate text with a text prompt with using generate() method of the Gemma model object you configured in the previous steps. The optional max_length argument specifies the maximum length of the generated sequence. The following code examples shows a few ways to prompt the model. output = gemma_lm.generate("what is keras in 3 bullet points?", max_length=64) print(output) what is keras in 3 bullet points? * **A Deep Learning Framework:** Keras is a high-level API that makes it easy to build and train deep learning models by providing a user-friendly interface. * **User-Friendly and Fast:** It abstracts away complex mathematical details, allowing users to You can also provide batched prompts using a list as input: output = gemma_lm.generate( ["what is keras in 3 bullet points?", "The universe is"], max_length=64) for item in output: print(item) print("-"*80) what is keras in 3 bullet points? * **A Deep Learning Framework:** Keras is a high-level API that makes it easy to build and train deep learning models by providing a user-friendly interface. * **User-Friendly and Fast:** It abstracts away complex underlying computations, allowing users to --- The universe is vast and mysterious. It stretches beyond our comprehension, filled with wonders we are only beginning to uncover. From the swirling galaxies to the silent depths of the ocean, the universe whispers secrets of existence, inviting us to explore, to question, and to marvel at the sheer scale of it all. This --- If you're running on JAX or TensorFlow backends, you should notice that the second generate() call returns an answer more quickly. This performance improvement is because each call to generate() for a given batch size and max_length is compiled with XLA. The first run is expensive, but subsequent runs are faster. Use a prompt template¶ When building more complex requests or multi-turn chat interactions use a prompt template to structure your request. The following code creates a standard template for Gemma prompts: PROMPT_TEMPLATE = """<|turn>user {question} <turn|> <|turn>model """ The following code shows how to use the template to format a simple request: question = """what is keras in 3 bullet points?""" prompt = PROMPT_TEMPLATE.format(question=question) output = gemma_lm.generate(prompt) p