Skip to content

Conversation

DavidLandup0
Copy link
Collaborator

Description of the change

WIP

Colab Notebook

Checklist

  • I have added all the necessary unit tests for my change.
  • I have verified that my change does not break existing code and works with all backends (TensorFlow, JAX, and PyTorch).
  • My PR is based on the latest changes of the main branch (if unsure, rebase the code).
  • I have followed the Keras Hub Model contribution guidelines in making these changes.
  • I have followed the Keras Hub API design guidelines in making these changes.
  • I have signed the Contributor License Agreement.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary of Changes

Hello @DavidLandup0, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request, currently a Work In Progress, introduces core utility functions for the SmolLM3 model. It lays the groundwork for the model's backbone and causal language model components by implementing essential attention mechanisms, including helpers for Rotary Positional Embeddings and Grouped Query Attention, culminating in a comprehensive eager attention forward pass.

Highlights

  • New Utility File: A new file keras_hub/src/models/smollm3/smollm3_utils.py has been added to house foundational utility functions for the SmolLM3 model.
  • Rotary Positional Embeddings (RoPE): Helper functions rotate_half (lines 4-7) and apply_rotary_pos_emb (lines 10-15) are introduced to facilitate the application of Rotary Positional Embeddings to query and key tensors.
  • Grouped Query Attention (GQA) / Multi-Query Attention (MQA): The repeat_kv function (lines 18-25) is added to support Grouped Query Attention (GQA) or Multi-Query Attention (MQA) by repeating key/value states as needed.
  • Eager Attention Mechanism: An eager_attention_forward function (lines 28-52) is implemented, providing a complete attention pass including scaling, causal masking, softmax, and dropout, designed for eager execution.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This PR introduces utility functions for a new SmolLM3 model. The changes are a work in progress. My review focuses on ensuring correctness, robustness, and maintainability.

I've identified a critical issue in rotate_half that could cause problems on the JAX backend, a high-severity issue in eager_attention_forward regarding the unconditional application of dropout, and a medium-severity issue about the lack of docstrings for the new public functions.

Providing this feedback now should help in finalizing the implementation.

Comment on lines 5 to 7
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
return ops.concatenate((-x2, x1), axis=-1)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

This implementation of rotate_half is susceptible to a known bug with XLA compilation on JAX when using ops.concatenate, as noted in keras_hub/src/layers/modeling/rotary_embedding.py. To ensure backend compatibility and robustness, adopt the safer implementation pattern used in RotaryEmbedding.

Suggested change
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
return ops.concatenate((-x2, x1), axis=-1)
x1, x2 = ops.split(x, 2, axis=-1)
half_rot_tensor = ops.stack((-x2, x1), axis=-2)
return ops.reshape(half_rot_tensor, ops.shape(x))

value,
attention_mask,
scaling: float,
dropout: float = 0.0,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The eager_attention_forward function should include a training parameter to conditionally apply dropout. This ensures correct behavior during both training and inference.

    dropout: float = 0.0,
    training: bool = False,

attn_weights = ops.add(attn_weights, causal_mask)

attn_weights = ops.softmax(attn_weights, axis=-1)
attn_weights = random.dropout(attn_weights, rate=dropout)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Dropout should only be applied during training to prevent non-deterministic behavior and degraded model performance during inference. Apply dropout conditionally based on the training parameter.

    attn_weights = random.dropout(attn_weights, rate=dropout) if training else attn_weights

@keras-team keras-team deleted a comment from gemini-code-assist bot Jul 16, 2025
Copy link
Member

@mattdangerw mattdangerw left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just some quick drive by comments, know this is still wip! Looking good so far!

layer_types,
mlp_bias,
rms_norm_epsilon,
layer_norm_epsilon,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Usually there's some of these terms (like the epsilon's and rope theta) that have a consistent value across all the presets we care about, and we give them defaults here. Not super important, just for people that wanted an easier time making a custom small version of the arch or something like that.

)


def eager_attention_forward(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is a hf/transforms-ism we'd rather not inherit. perfer just keeping the code on the layer directly, fine to use a private helper to decompose it a bit more.

@divyashreepathihalli
Copy link
Collaborator

/gemini review

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces the SmolLM3 model, including its backbone, causal language model, preprocessor, tokenizer, and associated layers. The changes are comprehensive and add a new model family to the library. My review has identified several critical issues that need to be addressed. These include a runtime error in the score method of the SmolLM3CausalLM class and an incorrect method call in the SmolLM3Tokenizer that will lead to an AttributeError. Additionally, there are several instances of leftover debugging code, style guide violations such as the use of type hints in function signatures, and unused code that should be removed. While the PR is a work in progress, these issues, especially the critical ones, should be resolved to ensure the model's functionality and maintainability.

Comment on lines +295 to +303
position_embeddings = self.backbone.rotary_embedding(x)

for i, transformer_layer in enumerate(self.backbone.transformer_layers):
x = transformer_layer(
hidden_states=x,
position_embeddings=position_embeddings,
attention_mask=padding_mask,
)
x = layer_intercept_fn(x, i)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

The score method appears to be implemented incorrectly. It attempts to access self.backbone.rotary_embedding, but this attribute is not defined on the SmolLM3Backbone. Furthermore, it passes position_embeddings to the transformer layers, which do not accept this argument in their call method. This will lead to a runtime error. Please refactor this method to align with the SmolLM3Backbone's forward pass implementation.

Comment on lines +41 to +50
self._add_special_token(eos_token, "end_token")

bos_token = "<|begin_of_text|>"
self._add_special_token(bos_token, "bos_token")

start_think_token = "<think>"
self._add_special_token(start_think_token, "start_think_token")

end_think_token = "</think>"
self._add_special_token(end_think_token, "end_think_token")

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

The __init__ method calls self._add_special_token, but this method is not defined in the BytePairTokenizer base class or its parents. This will result in an AttributeError. To handle special tokens correctly, you should add them to the vocabulary and pass them to the unsplittable_tokens argument of the parent __init__. Please refer to other tokenizers in the repository, such as Llama3Tokenizer, for the correct implementation pattern.

Comment on lines +196 to +199
print('pre', key.shape, value.shape)
key = ops.repeat(key, repeats=self.num_key_value_groups, axis=2)
value = ops.repeat(value, repeats=self.num_key_value_groups, axis=2)
print('post', key.shape, value.shape)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

These print statements appear to be leftover from debugging. Please remove them.

Suggested change
print('pre', key.shape, value.shape)
key = ops.repeat(key, repeats=self.num_key_value_groups, axis=2)
value = ops.repeat(value, repeats=self.num_key_value_groups, axis=2)
print('post', key.shape, value.shape)
key = ops.repeat(key, repeats=self.num_key_value_groups, axis=2)
value = ops.repeat(value, repeats=self.num_key_value_groups, axis=2)

Comment on lines +573 to +699

self.head_dim = self.hidden_size // self.num_attention_heads

inv_freq_tensor, self.attention_scaling = rope_init(
self.rope_theta, self.partial_rotary_factor, self.head_dim
)

self.inv_freq = self.add_weight(
name="inv_freq",
shape=ops.shape(inv_freq_tensor),
dtype=inv_freq_tensor.dtype,
initializer=initializers.Constant(
ops.convert_to_numpy(inv_freq_tensor)
),
trainable=False, # This weight is not trained
)
self.original_inv_freq = self.inv_freq

def build(self, input_shape):
"""
Builds the layer. For SmolLM3RotaryEmbedding, this mainly ensures
that the parent layer's build is called.
Args:
input_shape: A list/tuple of shapes for the inputs:
[x_shape, position_ids_shape]
- x_shape: (batch_size, ..., head_dim)
- position_ids_shape: (batch_size, seq_len)
"""
# No internal layers to explicitly build here, as inv_freq is added in __init__
super().build(input_shape)

def call(
self,
x,
start_index=0,
):
"""
Forward pass for SmolLM3RotaryEmbedding.

Args:
x: Input tensor, typically query or key states.
Shape can vary, but the last dimension is head_dim.
position_ids: Tensor of position IDs of shape (batch_size, seq_len).
"""
inv_freq_expanded = ops.expand_dims(
ops.expand_dims(self.inv_freq, axis=0), axis=-1
)

batch_size = ops.shape(x)[0]
seq_len = ops.shape(x)[1]
positions = ops.arange(seq_len, dtype="float32")
positions = positions + ops.cast(start_index, dtype="float32")

inv_freq_expanded = ops.broadcast_to(
inv_freq_expanded, (batch_size, ops.shape(self.inv_freq)[0], 1)
)

position_ids_expanded = ops.expand_dims(positions, axis=1).T

freqs = ops.matmul(
ops.cast(inv_freq_expanded, "float32"),
ops.cast(position_ids_expanded, "float32"),
)

freqs = ops.transpose(freqs, axes=(0, 2, 1))

emb = ops.concatenate((freqs, freqs), axis=-1)

cos = ops.cos(emb) * self.attention_scaling
sin = ops.sin(emb) * self.attention_scaling

return ops.cast(cos, x.dtype), ops.cast(sin, x.dtype)

def compute_output_shape(self, input_shape):
"""
Computes the output shape of the layer.

Args:
input_shape: A list/tuple of shapes for the inputs:
[x_shape, position_ids_shape]
- x_shape: (batch_size, ..., head_dim)
- position_ids_shape: (batch_size, seq_len)

Returns:
A list of output shapes for (cos, sin):
[(batch_size, seq_len, head_dim), (batch_size, seq_len, head_dim)]
"""
if input_shape[1] is not None and len(input_shape[1]) >= 2:
batch_size = input_shape[1][0]
seq_len = input_shape[1][1]
else:
# Fallback if position_ids_shape is None or malformed.
# In this case, the batch_size and seq_len are unknown.
batch_size = None
seq_len = None

# The output cos and sin have shape (batch_size, seq_len, head_dim)
output_shape = (batch_size, seq_len, self.head_dim)

return [output_shape, output_shape]

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The SmolLM3RotaryEmbedding class is defined but not used anywhere in the codebase. SmolLM3Attention uses keras_hub.src.layers.modeling.rotary_embedding.RotaryEmbedding instead. This class appears to be dead code and should be removed to improve maintainability.

@@ -193,6 +193,7 @@ def call_with_cache(
self_attention_cache=current_cache,
self_attention_cache_update_index=cache_update_index,
)
#print(next_cache.shape)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Please remove the commented-out debug print statement.

epsilon=layer_norm_epsilon,
name="sequence_output_layernorm",
)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This line contains only whitespace and should be removed.


# Each decoder layer has a cache; we update them separately.
updated_cache = []

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This line contains only whitespace and should be removed.

Comment on lines +44 to +77
Examples:
```python
# Load the preprocessor from a preset.
preprocessor = keras_hub.models.SmolLM3CausalLMPreprocessor.from_preset(
"..."
)

# Tokenize and pack a single sentence.
sentence = tf.constant("...")
preprocessor(sentence)
# Same output.
preprocessor("...")

# Tokenize a batch of sentences.
sentences = tf.constant(["...", "..."])
preprocessor(sentences)
# Same output.
preprocessor(["...", "..."])

# Map a dataset to preprocess a single sentence.
features = tf.constant(
[
"...",
"...",
]
)
labels = tf.constant([1, 0])
ds = tf.data.Dataset.from_tensor_slices((features, labels))
ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)

# Map a dataset to preprocess unlabled sentences.
ds = tf.data.Dataset.from_tensor_slices(features)
ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE)
```

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The examples in the docstring use placeholders like "...". Please provide concrete examples with valid preset names and sample text to help users understand how to use the preprocessor. 1

Style Guide References

Footnotes

  1. Docstrings should include comprehensive examples showing usage patterns. (link)

Comment on lines +32 to +403
intermediate_size: The intermediate size of the MLP.
mlp_bias: Whether to use bias in MLP dense layers.
"""

def __init__(
self, hidden_size: int, intermediate_size: int, mlp_bias: bool, **kwargs
):
super().__init__(**kwargs)
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.mlp_bias = mlp_bias

self.gate_proj = layers.Dense(
self.intermediate_size, use_bias=self.mlp_bias, name="gate_proj"
)
self.up_proj = layers.Dense(
self.intermediate_size, use_bias=self.mlp_bias, name="up_proj"
)
self.down_proj = layers.Dense(
self.hidden_size, use_bias=self.mlp_bias, name="down_proj"
)

def build(self, input_shape):
"""
Builds the internal Dense layers.
Args:
input_shape: The shape of the input to this layer
(batch_size, seq_len, hidden_size).
"""
self.gate_proj.build(input_shape)
self.up_proj.build(input_shape)
# The down_proj takes intermediate_output, which has shape
# (batch_size, seq_len, intermediate_size)
down_proj_input_shape = (
input_shape[0],
input_shape[1],
self.intermediate_size,
)
self.down_proj.build(down_proj_input_shape)
super().build(input_shape)

def call(self, x):
"""
Forward pass for SmolLM3MLP.

Args:
x: Input tensor of shape (batch_size, seq_len, hidden_size).
"""
gate_output = activations.silu(self.gate_proj(x))
up_output = self.up_proj(x)
intermediate_output = gate_output * up_output
down_proj_output = self.down_proj(intermediate_output)
return down_proj_output

def compute_output_shape(self, input_shape):
"""
Computes the output shape of the layer.

Args:
input_shape: The input shape (batch_size, seq_len, hidden_size).

Returns:
The output shape, which is the same as the input shape:
(batch_size, seq_len, hidden_size).
"""
return input_shape


class SmolLM3DecoderLayer(layers.Layer):
"""
Decoder layer for SmolLM3 model, combining self-attention and MLP.

Args:
hidden_size: The hidden size of the layer.
num_attention_heads: The number of attention heads.
num_key_value_heads: The number of key-value heads.
attention_bias: Whether to use bias in attention projections.
attention_dropout: Dropout rate for attention weights.
rope_layer_enabled_list: List indicating if RoPE is enabled for each layer.
layer_types: List of layer types.
layer_idx: Index of the current layer.
intermediate_size: The intermediate size of the MLP.
mlp_bias: Whether to use bias in MLP dense layers.
layer_norm_epsilon: Epsilon for RMSNormalization.
"""

def __init__(
self,
hidden_size: int,
num_attention_heads: int,
num_key_value_heads: int,
attention_bias: bool,
attention_dropout: float,
rope_layer_enabled_list: list[bool],
layer_types: list[str],
layer_idx: int,
intermediate_size: int,
mlp_bias: bool,
layer_norm_epsilon: float,
**kwargs,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The __init__ methods in SmolLM3Attention, SmolLM3MLP, and SmolLM3DecoderLayer use type hints in their signatures (e.g., hidden_size: int). According to the style guide, type hints should not be used in function signatures. Please remove them and document the types in the Args section of the docstrings instead. 1

Style Guide References

Footnotes

  1. KerasHub does not use type hints in function signatures or __init__ methods. Type information is provided in the docstring Args section. (link)

)


def rope_init(rope_theta: float, partial_rotary_factor: float, head_dim: int):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The rope_init function uses type hints in its signature. According to the style guide, type hints should be removed from function signatures and documented in the Args section of the docstring instead. 1

Suggested change
def rope_init(rope_theta: float, partial_rotary_factor: float, head_dim: int):
def rope_init(rope_theta, partial_rotary_factor, head_dim):

Style Guide References

Footnotes

  1. KerasHub does not use type hints in function signatures or __init__ methods. Type information is provided in the docstring Args section. (link)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants