Skip to content

fix: jax & NNX TraceContextError in T5Backbone#2602

Open
maitry63 wants to merge 8 commits intokeras-team:masterfrom
maitry63:T5_incompatible_error
Open

fix: jax & NNX TraceContextError in T5Backbone#2602
maitry63 wants to merge 8 commits intokeras-team:masterfrom
maitry63:T5_incompatible_error

Conversation

@maitry63
Copy link

This PR fixes the JAX & NNX TraceContextError with T5 Backbone Model.

Fixes: 2591

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @maitry63, 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 addresses and resolves a TraceContextError that was preventing the T5Backbone model from functioning correctly when used in environments where JAX and NNX are enabled. The solution involves implementing conditional logic during the model's initialization to adapt its construction process, thereby ensuring compatibility and stable operation across different Keras configurations.

Highlights

  • JAX & NNX Compatibility: Introduced conditional logic within the T5Backbone initialization to handle JAX and NNX environments. When NNX is enabled, the functional model construction is bypassed to prevent TraceContextError.
  • Error Resolution: Fixed a TraceContextError that occurred when using the T5Backbone model with JAX and NNX, as reported in issue T5Backbone incompatible with KERAS_NNX_ENABLED mode #2591.
  • Code Structure: Refactored the T5Backbone's __init__ method to conditionally call super().__init__ based on whether NNX is active, ensuring proper initialization for both NNX and non-NNX modes.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • keras_hub/src/models/t5/t5_backbone.py
    • Added a check for keras.config.is_nnx_enabled() at the beginning of the __init__ method.
    • Wrapped the functional model construction and the super().__init__ call for the functional model in an if not nnx_enabled: block.
    • Added an else block to call super().__init__(dtype=dtype, **kwargs) when NNX is enabled, providing an NNX-safe subclassed model path.
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 by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

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 pull request 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 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. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

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
Contributor

@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 aims to resolve a TraceContextError in T5Backbone when using JAX with NNX enabled by switching to a subclassed model implementation instead of the Keras Functional API.

While the approach is correct, the implementation is incomplete. The functional model definition is conditionally removed, but the required call method for the subclassed model path is missing, which will make the model non-functional when NNX is enabled. I've added a critical comment with a suggested implementation for the call method.

I also found a minor issue with a redundant import statement. Please see my comments for details.

Comment on lines +230 to +232
else:
# NNX-safe subclassed model path
super().__init__(dtype=dtype, **kwargs)
Copy link
Contributor

Choose a reason for hiding this comment

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

critical

This change is intended to fix an issue with JAX and NNX by avoiding the Functional API. However, by only calling super().__init__() for the NNX path, the model becomes a subclassed model without a call method. This will cause a NotImplementedError when the model is called.

To complete the fix, you need to implement the call method to define the forward pass. The logic for this method is the same as what's currently inside the if not nnx_enabled: block.

Here is a suggested implementation for the call method to be added to the T5Backbone class:

    def call(self, inputs, training=False):
        encoder_token_ids = inputs["encoder_token_ids"]
        encoder_padding_mask = inputs["encoder_padding_mask"]
        decoder_token_ids = inputs["decoder_token_ids"]
        decoder_padding_mask = inputs["decoder_padding_mask"]

        # Encoder.
        x = self.token_embedding(encoder_token_ids)
        x = self.encoder_embedding_dropout(x, training=training)
        encoder_attention_mask = encoder_padding_mask[:, None, :]
        position_bias = None
        for transformer_layer in self.encoder_transformer_layers:
            output = transformer_layer(
                x,
                attention_mask=encoder_attention_mask,
                position_bias=position_bias,
                use_causal_mask=False,
                training=training,
            )
            if isinstance(output, tuple):
                x, position_bias = output
        x = self.encoder_layer_norm(x)
        x = self.encoder_dropout(x, training=training)
        encoder_output = x

        # Decoder.
        x = self.token_embedding(decoder_token_ids)
        x = self.decoder_embedding_dropout(x, training=training)
        decoder_attention_mask = decoder_padding_mask[:, None, :]
        position_bias = None
        for transformer_layer in self.decoder_transformer_layers:
            output = transformer_layer(
                x,
                attention_mask=decoder_attention_mask,
                position_bias=position_bias,
                encoder_hidden_states=encoder_output,
                encoder_attention_mask=encoder_attention_mask,
                use_causal_mask=True,
                training=training,
            )
            if isinstance(output, tuple):
                x, position_bias = output
        x = self.decoder_layer_norm(x)
        x = self.decoder_dropout(x, training=training)
        decoder_output = x

        return {
            "encoder_sequence_output": encoder_output,
            "decoder_sequence_output": decoder_output,
        }

Comment on lines +78 to +79
import keras

Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The import keras statement is redundant as keras is already imported at the top of the file. This local import and the following blank line can be removed.

@maitry63
Copy link
Author

@gemini-code-assist review

Copy link
Contributor

@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

The pull request addresses a TraceContextError in the T5 Backbone Model by refactoring the functional model definition into a _forward method and conditionally initializing the functional model based on whether NNX is enabled. This change correctly separates the functional model construction from the __init__ method, which is a common pattern to avoid tracing issues with JAX/NNX. The added call method then dispatches to this _forward method. The changes are well-implemented and directly resolve the reported issue.

attention_mask=encoder_attention_mask,
position_bias=position_bias,
use_causal_mask=False,
def _forward(inputs, training=None):
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The _forward method is a private helper method and should ideally be placed after all public methods and properties, or at least consistently grouped with other private methods. While not a functional bug, this is a maintainability improvement.

decoder_padding_mask = inputs["decoder_padding_mask"]
# Encoder
x = self.token_embedding(encoder_token_ids)
x = self.encoder_embedding_dropout(x, training=training)
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The training argument should be passed to the token_embedding layer call as well, to ensure consistent behavior, especially if the embedding layer has any dropout or batch normalization components that behave differently during training and inference. While ReversibleEmbedding might not directly use training, it's good practice for consistency.

            # Encoder
            x = self.token_embedding(encoder_token_ids, training=training)
            x = self.encoder_embedding_dropout(x, training=training)

x = self.encoder_dropout(x, training=training)
encoder_output = x
# Decoder
x = self.token_embedding(decoder_token_ids)
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

Similar to the encoder, the training argument should be passed to the token_embedding layer call for the decoder path to ensure consistent behavior.

            encoder_output = x
            # Decoder
            x = self.token_embedding(decoder_token_ids, training=training)
            x = self.decoder_embedding_dropout(x, training=training)

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.

T5Backbone incompatible with KERAS_NNX_ENABLED mode

1 participant