-
Notifications
You must be signed in to change notification settings - Fork 301
Changes to the Gemma3 backbone for Embedding Gemma model #2428
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,5 @@ | ||
import keras | ||
from keras import layers | ||
from keras import ops | ||
|
||
from keras_hub.src.api_export import keras_hub_export | ||
|
@@ -424,3 +425,129 @@ def from_config(cls, config): | |
) | ||
|
||
return super().from_config(config) | ||
|
||
|
||
class MeanPooling(layers.Layer): | ||
""" | ||
Mean pooling layer that computes the average of token embeddings, | ||
respecting a padding mask. | ||
|
||
This layer correctly handles variable-length sequences by ignoring | ||
padded tokens in the mean calculation. | ||
|
||
Call arguments: | ||
inputs: A tuple of `(sequence_output, padding_mask)`. | ||
`sequence_output` is a tensor of shape `(batch_size, seq_len, | ||
hidden_dim)`. `padding_mask` is a tensor of shape `(batch_size, | ||
seq_len)` with `1` for valid tokens and `0` for padded tokens. | ||
|
||
Returns: | ||
A tensor of shape `(batch_size, hidden_dim)`. | ||
|
||
Example: | ||
```python | ||
sequence_output = np.random.rand(2, 4, 8).astype("float32") | ||
padding_mask = np.array([[1, 1, 1, 0], [1, 1, 0, 0]]) | ||
mean_pool_layer = MeanPooling() | ||
pooled = mean_pool_layer((sequence_output, padding_mask)) | ||
# pooled.shape -> (2, 8) | ||
``` | ||
""" | ||
|
||
def __init__(self, **kwargs): | ||
super().__init__(**kwargs) | ||
self.supports_masking = True | ||
|
||
def call(self, inputs): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Instead of a tuple, can we just pass these arguments to |
||
sequence_output, padding_mask = inputs | ||
|
||
mask = ops.expand_dims( | ||
ops.cast(padding_mask, sequence_output.dtype), axis=-1 | ||
) | ||
masked_output = sequence_output * mask | ||
sum_embeddings = ops.sum(masked_output, axis=1) | ||
num_tokens = ops.sum( | ||
ops.cast(padding_mask, sequence_output.dtype), axis=1 | ||
) | ||
num_tokens = ops.expand_dims(num_tokens, axis=1) | ||
|
||
num_tokens = ops.maximum(num_tokens, 1e-9) | ||
|
||
mean_embeddings = sum_embeddings / num_tokens | ||
return mean_embeddings | ||
|
||
def compute_output_shape(self, input_shape): | ||
sequence_output_shape, padding_mask_shape = input_shape | ||
return (sequence_output_shape[0], sequence_output_shape[2]) | ||
|
||
def get_config(self): | ||
return super().get_config() | ||
|
||
|
||
@keras_hub_export("keras_hub.models.Gemma3Embedding") | ||
class Gemma3EmbeddingModel(keras.Model): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think we should just stick the layers on top in Can probably add an argument, named What do you think? |
||
"""An end-to-end Gemma3 model for embedding tasks. | ||
|
||
This model takes token ids as input and returns a fixed-size embedding | ||
vector for the input sequence. It uses a `Gemma3Backbone` to generate | ||
contextualized token embeddings, a `MeanPooling` layer to pool them into a | ||
single vector, and a final `Dense` layer to project to the desired | ||
embedding dimension. | ||
|
||
This model can be loaded with a pre-trained `Gemma3Backbone` and used for | ||
tasks like semantic similarity, retrieval, or as a feature extractor. | ||
|
||
Args: | ||
backbone: A `keras_hub.models.Gemma3Backbone` instance. | ||
embedding_dim (int): The dimension of the output embedding. | ||
|
||
Example: | ||
```python | ||
# backbone = keras_hub.models.Gemma3Backbone.from_preset( | ||
# "gemma3_instruct_1b" | ||
# ) | ||
# embedding_model = keras_hub.models.Gemma3EmbeddingModel( | ||
# backbone=backbone, | ||
# embedding_dim=768, | ||
# ) | ||
# input_data = { | ||
# "token_ids": np.array([[651, 4320, 8426, 25341, 235265]]), | ||
# "padding_mask": np.ones((1, 5), dtype="int32"), | ||
# } | ||
# embeddings = embedding_model.predict(input_data) | ||
``` | ||
""" | ||
|
||
def __init__(self, backbone, embedding_dim, **kwargs): | ||
super().__init__(**kwargs) | ||
self.backbone = backbone | ||
self.pooling_layer = MeanPooling( | ||
dtype=backbone.dtype, name="mean_pooling" | ||
) | ||
self.projection_layer = layers.Dense( | ||
embedding_dim, dtype=backbone.dtype, name="embedding_projection" | ||
Comment on lines
+527
to
+528
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is there just one dense layer for Embedding Gemma? I thought there were several. |
||
) | ||
self.embedding_dim = embedding_dim | ||
|
||
def call(self, inputs): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We don't generally have |
||
sequence_output = self.backbone(inputs) | ||
padding_mask = inputs["padding_mask"] | ||
|
||
pooled_output = self.pooling_layer((sequence_output, padding_mask)) | ||
embedding = self.projection_layer(pooled_output) | ||
return embedding | ||
|
||
def get_config(self): | ||
config = super().get_config() | ||
config.update( | ||
{ | ||
"backbone": layers.serialize(self.backbone), | ||
"embedding_dim": self.embedding_dim, | ||
} | ||
) | ||
return config | ||
|
||
@classmethod | ||
def from_config(cls, config): | ||
config["backbone"] = layers.deserialize(config["backbone"]) | ||
return cls(**config) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Let's move this to
gemma3_mean_pooling.py
?