KerasHub: 预训练模型 / API 文档 / 模型架构 / Gemma3 / Gemma3CausalLMPreprocessor 层

Gemma3CausalLMPreprocessor 层

[源码]

Gemma3CausalLMPreprocessor

keras_hub.models.Gemma3CausalLMPreprocessor(
    tokenizer,
    image_converter=None,
    sequence_length=1024,
    add_start_token=True,
    add_end_token=True,
    max_images_per_prompt=2,
    num_vision_tokens_per_image=256,
    **kwargs
)

Gemma3 因果语言模型预处理器。

此预处理层旨在与 keras_hub.models.Gemma3CausalLM 一起使用。它可以通过两种方式配置:纯文本或文本+视觉,取决于传入的 image_converter 值是否为 None。对于前者,它接受字符串批次输入;对于后者,它接受图像和字符串批次输入。它返回 (x, y, sample_weight) 格式的输出,其中 y 标签是 x 序列中的下一个 token ID。对于“提示”token,sample_weight 为 0;对于“响应”token,sample_weight 为 1,这样损失只在“响应”token 上计算。

对于文本+视觉情况,此层将提示中的 <start_of_image> token 实例替换为 num_vision_tokens_per_image 占位符 token。它还会返回这些视觉 token 存在的位置索引,以便模型可以将图像嵌入放置在文本嵌入序列中的正确位置。请注意,如果 max_images_per_prompt 为 2,则每个样本可以传入 0、1 或 2 张图像。值为 0 对应于纯文本输入。

对于用于生成,此层还提供了 generate_preprocess()generate_postprocess() 这两个方法。当此预处理器附加到 keras_hub.models.GemmaCausalLM 实例时,这些方法将在 generate() 中隐式调用。它们也可以独立调用(例如,在单独的进程中预计算用于生成的预处理输入)。

参数

  • tokenizer: 一个 keras_hub.models.GemmaTokenizer 实例。
  • image_converter: 一个 keras_hub.layers.ImageConverter 实例。默认为 None
  • sequence_length: 打包输入的长度。默认为 1024。
  • add_start_token: 如果为 True,预处理器将在每个输入序列前添加分词器起始 token。默认为 True
  • add_end_token: 如果为 True,预处理器将在每个输入序列后添加分词器结束 token。默认为 True
  • max_images_per_prompt: int。批处理中每个样本允许的最大图像数量。默认为 2。
  • num_vision_tokens_per_image: int。每张图像的视觉占位符 token 数量。默认为 256。

调用参数

  • x: 一个字符串、tf.Tensor 或 Python 字符串列表。
  • y: 标签数据。应始终为 None,因为该层会生成标签。
  • sample_weight: 标签权重。应始终为 None,因为该层会生成标签权重。
  • sequence_length: 传入此参数以覆盖层配置的 sequence_length

示例

# === Language Gemma3 model ===
# Load the preprocessor from a preset.
preprocessor = keras_hub.models.Gemma3CausalLMPreprocessor.from_preset(
    "gemma3_instruct_1b"
)

# Unbatched inputs.
preprocessor(
    {
        "prompts": "What is the capital of India?",
        "responses": "New Delhi",
    }
)

# Batched inputs.
preprocessor(
    {
        "prompts": [
            "What is the capital of India?",
            "What is the capital of Spain?"
        ],
        "responses": ["New Delhi", "Madrid"],
    }
)

# Apply preprocessing to a [`tf.data.Dataset`](https://tensorflowcn.cn/api_docs/python/tf/data/Dataset).
features = {
    "prompts": [
        "What is the capital of India?",
        "What is the capital of Spain?"
    ],
    "responses": ["New Delhi", "Madrid"],
}

ds = tf.data.Dataset.from_tensor_slices(features)
ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)

# Prepare tokens for generation (no end token).
preprocessor.generate_preprocess(["The quick brown fox jumped."])

# Map generation outputs back to strings.
preprocessor.generate_postprocess({
    'token_ids': np.array([[2, 818, 3823, 8864, 37423, 32694, 236761, 0]]),
    'padding_mask': np.array([[ 1, 1, 1, 1, 1, 1, 1, 0]]),
})

# === Vision and Language Gemma3 model ===
# Load the preprocessor from a preset.
preprocessor = keras_hub.models.Gemma3CausalLMPreprocessor.from_preset(
    "gemma3_instruct_4b"
)

# text-only inputs (unbatched)
preprocessor(
    {
        "prompts": "What is the capital of India?",
        "responses": "New Delhi",
    }
)

# text-only inputs (batched)
preprocessor(
    {
        "prompts": [
            "What is the capital of India?",
            "What is the capital of Spain?"
        ],
        "responses": ["New Delhi", "Madrid"],
    }
)

# Unbatched inputs, with one image.
preprocessor(
    {
        "prompts": "this is a lily <start_of_image>",
        "responses": "pristine!",
        "images": np.ones((896, 896, 3), dtype="float32")
    }
)

# Unbatched inputs, with two images.
preprocessor(
    {
        "prompts": "lily: <start_of_image>, sunflower: <start_of_image>",
        "responses": "pristine!",
        "images": [
            np.ones((896, 896, 3), dtype="float32"),
            np.ones((896, 896, 3), dtype="float32")
        ],
    }
)

# Batched inputs, one image per prompt.
preprocessor(
    {
        "prompts": [
            "this is a lily: <start_of_image>",
            "this is a sunflower: <start_of_image>"
        ],
        "responses": ["pristine!", "radiant!"],
        "images": [
            np.ones((896, 896, 3), dtype="float32"),
            np.ones((896, 896, 3), dtype="float32")
        ]
    }
)

# Can also be written this way.
preprocessor(
    {
        "prompts": [
            "this is a lily: <start_of_image>",
            "this is a sunflower: <start_of_image>"
        ],
        "responses": ["pristine!", "radiant!"],
        "images": [
            [np.ones((896, 896, 3), dtype="float32")],
            [np.ones((896, 896, 3), dtype="float32")]
        ]
    }
)

# Different number of images in every sample.
preprocessor(
    {
        "prompts": [
            "Who is this singer: <start_of_image>?",
            "Who are these musicians <start_of_image>, <start_of_image>?"
        ],
        "responses": ["Arijit Singh", "John Lennon, Paul Mccartney"],
        "images": [
            [
                np.ones((896, 896, 3), dtype="float32"),
                np.ones((896, 896, 3), dtype="float32")
            ],
            [np.ones((896, 896, 3), dtype="float32")]
        ]
    }
)

# Apply preprocessing to a [`tf.data.Dataset`](https://tensorflowcn.cn/api_docs/python/tf/data/Dataset).
inputs = {
    "prompts": [
        "Who are these two: <start_of_image>, <start_of_image>",
        "Who is this: <start_of_image>?",
        "What is the capital of India?"
    ],
    "responses": [
        "John Lennon, Paul Mccartney",
        "Arijit Singh",
        "New Delhi"
    ],
    "images": (
        tf.ragged.constant(
            [
                [np.ones((10, 10, 3)), np.ones((10, 10, 3))],
                [np.ones((10, 10, 3))],
                [],
            ]
        )
    )
}
ds = tf.data.Dataset.from_tensor_slices(inputs)
ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)

[源码]

from_preset 方法

Gemma3CausalLMPreprocessor.from_preset(
    preset, config_file="preprocessor.json", **kwargs
)

从模型预设实例化一个 keras_hub.models.Preprocessor

预设是用于保存和加载预训练模型的配置、权重和其他文件资产的目录。preset 可以作为以下之一传入:

  1. 内置预设标识符,例如 'bert_base_en'
  2. Kaggle Models 句柄,例如 'kaggle://user/bert/keras/bert_base_en'
  3. Hugging Face 句柄,例如 'hf://user/bert_base_en'
  4. 本地预设目录的路径,例如 './bert_base_en'

对于任何 Preprocessor 子类,您可以运行 cls.presets.keys() 来列出该类上所有可用的内置预设。

由于一个给定模型通常有多个预处理类,因此应在特定的子类上调用此方法,例如 keras_hub.models.BertTextClassifierPreprocessor.from_preset()

参数

  • preset: string。内置预设标识符、Kaggle Models 句柄、Hugging Face 句柄或本地目录路径。

示例

# Load a preprocessor for Gemma generation.
preprocessor = keras_hub.models.CausalLMPreprocessor.from_preset(
    "gemma_2b_en",
)

# Load a preprocessor for Bert classification.
preprocessor = keras_hub.models.TextClassifierPreprocessor.from_preset(
    "bert_base_en",
)
预设 参数 描述
gemma3_1b 999.89M 10亿参数,26层,纯文本预训练 Gemma3 模型。
gemma3_instruct_1b 999.89M 10亿参数,26层,纯文本指令调优 Gemma3 模型。
gemma3_4b_text 3.88B 40亿参数,34层,纯文本预训练 Gemma3 模型。
gemma3_instruct_4b_text 3.88B 40亿参数,34层,纯文本指令调优 Gemma3 模型。
gemma3_4b 4.30B 40亿参数,34层,视觉+文本预训练 Gemma3 模型。
gemma3_instruct_4b 4.30B 40亿参数,34层,视觉+文本指令调优 Gemma3 模型。
gemma3_12b_text 11.77B 120亿参数,48层,纯文本预训练 Gemma3 模型。
gemma3_instruct_12b_text 11.77B 120亿参数,48层,纯文本指令调优 Gemma3 模型。
gemma3_12b 12.19B 120亿参数,48层,视觉+文本预训练 Gemma3 模型。
gemma3_instruct_12b 12.19B 120亿参数,48层,视觉+文本指令调优 Gemma3 模型。
gemma3_27b_text 27.01B 270亿参数,62层,纯文本预训练 Gemma3 模型。
gemma3_instruct_27b_text 27.01B 270亿参数,62层,纯文本指令调优 Gemma3 模型。
gemma3_27b 27.43B 270亿参数,62层,视觉+文本预训练 Gemma3 模型。
gemma3_instruct_27b 27.43B 270亿参数,62层,视觉+文本指令调优 Gemma3 模型。

tokenizer 属性

keras_hub.models.Gemma3CausalLMPreprocessor.tokenizer

用于对字符串进行分词的分词器。