Skip to content

Conversation

@divyashreepathihalli
Copy link
Collaborator

No description provided.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @divyashreepathihalli, 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 introduces a significant improvement to the model export functionality by enabling a streaming approach for saving Keras model weights to the Hugging Face safetensors format. This change is crucial for handling large models efficiently, as it prevents out-of-memory issues by processing and writing weights incrementally rather than requiring all weights to be held in memory at once. The update involves refactoring weight mapping functions to act as generators and implementing a custom safetensors writer that can handle this streaming data.

Highlights

  • Streaming Safetensors Export: Implemented a new save_safetensors_streaming utility to export model weights to Hugging Face safetensors format without loading all weights into memory simultaneously, which is crucial for large models.
  • Generator-based Weight Mapping: Modified the get_gemma_weights_map function to use yield instead of building a full dictionary, enabling a streaming flow for Gemma model weights.
  • Unified Backend Handling: Replaced backend-specific safetensors saving logic (for PyTorch, TensorFlow, JAX) with a single, unified streaming function, simplifying the export process.
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 a streaming approach for exporting models to the Hugging Face SafeTensors format, which is a great way to reduce memory consumption during the export process. The core idea of changing the weight mapping functions to generators and implementing a two-pass streaming writer is sound. However, I've identified a couple of issues in the new save_safetensors_streaming function that could affect correctness and robustness, particularly regarding the handling of empty models and bfloat16 data types.

Comment on lines 181 to 185
# If dtype was bfloat16 and we got float32, we are in trouble?
# Or if we got a custom bfloat16 type.
# Let's assume standard behavior for now.

f.write(np_val.tobytes())
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The comments here correctly identify a potential for silent data corruption when handling bfloat16 tensors on systems with older NumPy versions that lack bfloat16 support. If a bfloat16 tensor is upcast to float32, tobytes() will write more data than specified in the header, corrupting the file. To prevent this, it's crucial to validate that the size of the tensor's byte representation matches the expected size from the header before writing to the file.

            # Verify byte size to prevent corruption from dtype upcasting (e.g. bfloat16->float32).
            data_bytes = np_val.tobytes()
            expected_size = header[key]["data_offsets"][1] - header[key]["data_offsets"][0]
            if len(data_bytes) != expected_size:
                raise ValueError(
                    f"Size mismatch for tensor '{key}'. Expected {expected_size} "
                    f"bytes, got {len(data_bytes)} bytes. This can happen with "
                    f"bfloat16 on systems with older numpy versions that lack "
                    f"bfloat16 support."
                )
            f.write(data_bytes)

}
offset += size

# Prepare header
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 check for empty weights in export_backbone is no longer effective since get_weights_fn now returns a generator. A generator object is always truthy, so the check will not prevent the creation of an empty safetensors file for a model with no weights. To fix this and restore the original behavior of raising an error, I suggest adding a check here to ensure the header is not empty after the first pass.

Suggested change
# Prepare header
if not header:
raise ValueError("No weights to save.")
# Prepare header

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.

1 participant