Skip to content

Shard input data for generate() for causal_lm model#2597

Open
dvadym wants to merge 1 commit intokeras-team:masterfrom
dvadym:data_sharding
Open

Shard input data for generate() for causal_lm model#2597
dvadym wants to merge 1 commit intokeras-team:masterfrom
dvadym:data_sharding

Conversation

@dvadym
Copy link

@dvadym dvadym commented Feb 13, 2026

Description of the change

This change introduces sharding of inputs for causal_lm.py model for interence.

The current behavior with Jax backend, DataDistribution (I only tested with Jax backend and Gemma3): there is no sharding of inputs, as a result when embeddings computed (code) `embeddings' replicated over multiple accelerators.
And further all computations are replicated on all accelerators.

This change ensures that inputs is sharded and all computations are sharded.

I haven't have unit tests to cover this code. Please advice.

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.

@github-actions github-actions bot added the Gemma Gemma model specific issues label Feb 13, 2026
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @dvadym, 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 optimizes the inference process for causal language models, particularly when using the Jax backend. By implementing input data sharding, it resolves an inefficiency where input embeddings and subsequent computations were unnecessarily replicated across multiple accelerators. This change ensures that data is properly distributed, leading to more efficient memory usage and computation during inference.

Highlights

  • Input Data Sharding: Introduced sharding of input data for the causal_lm.py model during inference, specifically addressing issues with the Jax backend where embeddings and computations were replicated across accelerators.
  • Distribution Integration: Integrated keras.src.distribution.distribution_lib to enable proper data distribution and sharding for inputs, ensuring that computations are sharded rather than replicated.
  • New Shard Utility: Added a new helper function shard within the CausalLM model's call method to apply distribution logic to input tensors based on the active distribution strategy.

🧠 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/causal_lm.py
    • Imported distribution_lib from keras.src.distribution.
    • Added a new nested function shard to handle input tensor distribution based on the active Keras distribution strategy.
    • Applied the shard function to the inputs list before passing them to the generate function, ensuring inputs are sharded.
Activity
  • The author (dvadym) has explicitly stated that unit tests for this new code are not yet available and has requested advice on how to proceed.
  • The author has completed several checklist items, including basing the PR on the latest main branch, following Keras Hub model and API design guidelines, and signing the Contributor License Agreement.
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 introduces input sharding for the generate() method in CausalLM, which is an important fix for distributed inference, especially with the JAX backend. The implementation of the shard function is clean and correctly handles both distributed and non-distributed scenarios. However, as you've noted in the description, the change lacks unit tests. According to the repository's contribution guidelines, testing is a mandatory requirement. I've added a specific comment with a suggestion on how to add a unit test for this sharding logic by using mocking, which would validate the new code path without requiring a full distributed test environment. Please add tests to ensure the correctness and prevent future regressions.

if self.preprocessor is not None:
inputs = [preprocess(x) for x in inputs]

inputs = [shard(x) for x in inputs]
Copy link
Contributor

Choose a reason for hiding this comment

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

high

This change introduces important logic for distributed execution, but it lacks corresponding unit tests. The contribution guidelines are very clear on the requirement for testing for all new logic.

Since testing distributed code can be complex, you can add a unit test that verifies the sharding logic is correctly invoked by using mocks. Here's a possible approach:

  1. In your test case, use unittest.mock.patch to mock keras.src.distribution.distribution_lib.distribution.
  2. Make the mock return a mock Distribution object.
  3. This mock distribution object should have mock methods for get_data_layout and distribute_tensor.
  4. Call the generate() method on a CausalLM instance.
  5. Assert that distribution_lib.distribution() was called, and that get_data_layout and distribute_tensor were called on your mock object for the input tensors.

This will ensure that your sharding code path is exercised and correctly integrated, even without a real distributed environment.

Here is a conceptual example of what the test could look like:

from unittest import mock

# Inside a test method for CausalLM
mock_dist_layout = mock.Mock()
mock_dist = mock.Mock()
mock_dist.get_data_layout.return_value = mock_dist_layout
mock_dist.distribute_tensor.return_value = "sharded_tensor"

with mock.patch(
    "keras_hub.src.models.causal_lm.distribution_lib.distribution",
    return_value=mock_dist,
) as mock_distribution_fn:
    causal_lm = CausalLM.from_preset(...)
    causal_lm.generate("test prompt")

    mock_distribution_fn.assert_called()
    mock_dist.get_data_layout.assert_called()
    mock_dist.distribute_tensor.assert_called_with(
        mock.ANY, mock_dist_layout
    )

Please add tests to validate this new functionality.

References
  1. The contribution guidelines state that testing is a non-negotiable part of every contribution (line 403). Every file containing logic must have a corresponding test file to ensure all core functionality is covered (line 406). (link)

Copy link
Collaborator

@sachinprasadhs sachinprasadhs left a comment

Choose a reason for hiding this comment

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

Thanks for the PR, for the unit test, you can follow something similar to what Keras has for mock setup https://github.com/keras-team/keras/blob/master/keras/src/distribution/distribution_lib_test.py

If you have tested in distributed settings, may be you can attach the screenshots of the findings for any model like Gemma3.
Can you also test with TensorFlow backend

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

Comments