Skip to content

Optimize code of FastV and fix SparseVLM's bugs related to LLaVA. #402

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

Merged
merged 1 commit into from
Jul 8, 2025

Conversation

zhangbilang
Copy link
Collaborator

pruning_pars['attn_logits'] 对llavaHf运行存在BUG,

        # 使用layer_outputs[1]运行llavaHf无问题,但精度没对上
        # llava:attn_logits = pruning_pars['attn_logits']
        # llavahf:attn_logits = layer_outputs[1]

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 @SmudgedWings, 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 primarily focuses on optimizing the FastV component and fixing critical bugs within SparseVLM, specifically addressing compatibility and accuracy issues when working with LLaVA models. The core changes involve a custom approach to attention logit calculation for LLaVA, alongside general improvements to token handling and the underlying hook management system.

Highlights

  • Improved LLaVA Model Compatibility: Addressed a bug in SparseVLM's handling of LLaVA models by introducing a custom mechanism to calculate and utilize attention logits, resolving accuracy issues that arose when relying solely on layer_outputs[1].
  • Enhanced Token Handling: Refined the process for identifying and managing image and text tokens, including more robust attention_mask processing and pre_prompt_length_list calculation for improved accuracy and stability.
  • Optimized Hook Management: Streamlined the registration of model hooks, differentiating behavior for Llava and LlavaHf models to ensure correct attention logit extraction and processing based on the model type.
  • Code Refinement: Performed general code cleanup, including the removal of redundant lines, commented-out code, and improved import statements for better maintainability.
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

The pull request focuses on optimizing the code of FastV and fixing bugs related to LLaVA in SparseVLM. The changes include adding a wrapper for the input hook in FastV, modifying the input hook for LLaVA in SparseVLM, and adding a hook to get attention logits. The code also includes changes to the attention mask and position IDs.

Comment on lines +71 to +74
if attention_mask is None:
attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
else:
attention_mask = attention_mask.bool()

Choose a reason for hiding this comment

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

medium

It's better to avoid using torch.ones_like with dtype=torch.bool directly. Instead, create a boolean tensor and then use it to create the ones tensor. This can prevent potential issues with type casting and ensure that the resulting tensor has the correct boolean type.

Consider using input_ids.bool().fill_(True) instead.

                    attention_mask = input_ids.bool().fill_(True)

Comment on lines +79 to +83
image_token_index = (
[-1]
+ torch.where(seq == IMAGE_TOKEN_INDEX)[0].tolist()
+ [seq.shape[0]]
)

Choose a reason for hiding this comment

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

medium

The list concatenation [-1] + ... + [seq.shape[0]] creates a new list in each iteration. This can be inefficient, especially when dealing with long sequences. Consider using torch.cat to concatenate tensors instead, which is generally more efficient for PyTorch tensors.

                        image_token_index = torch.cat([
                            torch.tensor([-1]),
                            torch.where(seq == IMAGE_TOKEN_INDEX)[0],
                            torch.tensor([seq.shape[0]])
                        ]).tolist()

scale_factor = 1 / math.sqrt(query_states.size(-1))
attn_bias = torch.zeros(L, S, dtype=query_states.dtype)
if module.is_causal:
assert attention_mask is None

Choose a reason for hiding this comment

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

medium

Asserting that attention_mask is None might not be the best approach. It's possible that the attention mask is not None but still needs to be handled. Consider checking if the module is causal and if the attention mask is needed based on the specific logic of the module.

            # assert attention_mask is None

Comment on lines +194 to +196
temp_mask = torch.ones(L, S, dtype=torch.bool).tril(diagonal=0)
attn_bias.masked_fill_(temp_mask.logical_not(), float('-inf'))
attn_bias.to(query_states.dtype)

Choose a reason for hiding this comment

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

medium

Instead of creating a temporary mask and then masking the attention bias, you can directly create the attention bias with the desired values. This can simplify the code and potentially improve performance.

                attn_bias = torch.where(torch.tril(torch.ones(L, S, dtype=torch.bool)),
                                      torch.zeros(L, S, dtype=query_states.dtype),
                                      torch.tensor(float('-inf'))).to(query_states.dtype)

Comment on lines +360 to +368
elif self.model.__class__.__name__ == 'Llava':
self.blocks[block_idx].self_attn.register_forward_pre_hook(
functools.partial(
get_attn_logits_hook,
pruning_pars=self.pruning_paras,
layer_idx=block_idx,
),
with_kwargs=True
)

Choose a reason for hiding this comment

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

medium

Registering the self_attn.register_forward_pre_hook only for the 'Llava' model might lead to unexpected behavior if the attention mechanism is used differently in other models. Consider making this registration more generic or providing a clear explanation of why it's only needed for 'Llava'.

                    # if self.model.__class__.__name__ == 'Llava':
                    self.blocks[block_idx].self_attn.register_forward_pre_hook(
                        functools.partial(
                            get_attn_logits_hook,
                            pruning_pars=self.pruning_paras,
                            layer_idx=block_idx,
                        ),
                        with_kwargs=True
                    )

@zhangbilang zhangbilang merged commit 2c61449 into ModelTC:main Jul 8, 2025
2 checks passed
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.

2 participants