Skip to content

Conversation

@wcrzlh
Copy link
Contributor

@wcrzlh wcrzlh commented Nov 24, 2025

What does this PR do?

Fixes # (issue)
✅ fix index bug to support glm4.1v bs>1 generation

Sample:

import argparse
import numpy as np
import mindspore as ms

from mindone.transformers import AutoProcessor, Glm4vForConditionalGeneration


def generate(args):
    model = Glm4vForConditionalGeneration.from_pretrained(
        args.model_name,
        mindspore_dtype=ms.bfloat16,
        attn_implementation=args.attn_implementation,
    )

    processor = AutoProcessor.from_pretrained(
        args.model_name,
    )

    messages1 = [
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "url": args.image,
                },
                {
                    "type": "text",
                    "text": args.prompt,
                },
            ],
        }
    ]
    
    messages2 = [
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "url": args.image2,
                },
                {
                    "type": "text",
                    "text": args.prompt,
                },
            ],
        }
    ]

    messages_batch = [message1, message2]

    inputs = processor.apply_chat_template(
        messages_batch, add_generation_prompt=True, tokenize=True, padding=True, return_dict=True, return_tensors="np"
    )

    # convert input to Tensor
    for key, value in inputs.items():
        if isinstance(value, np.ndarray):
            inputs[key] = ms.tensor(value)
        elif isinstance(value, list):
            inputs[key] = ms.tensor(value)
        if inputs[key].dtype == ms.int64:
            inputs[key] = inputs[key].to(ms.int32)

    generated_ids = model.generate(**inputs, max_new_tokens=128)
    generated_ids_trimmed = [out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
    output_text = processor.batch_decode(
        generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
    )
    print(output_text)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Glm4.1V demo.")

    parser.add_argument("--prompt", type=str, default="Describe this image.")
    parser.add_argument(
        "--image",
        type=str,
        default="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg",
    )
    parser.add_argument(
        "--image2",
        type=str,
        default="https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen3-Omni/demo/cars.jpg",
    )
    parser.add_argument(
        "--model_name", type=str, default="THUDM/GLM-4.1V-9B-Thinking", help="Path to the pre-trained model."
    )
    parser.add_argument(
        "--attn_implementation",
        type=str,
        default="flash_attention_2",
        choices=["flash_attention_2", "eager"],
    )

    # Parse the arguments
    args = parser.parse_args()

    generate(args)

Before submitting

  • This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
  • Did you read the contributor guideline?
  • Did you make sure to update the documentation with your changes? E.g. record bug fixes or new features in What's New. Here are the
    documentation guidelines
  • Did you build and run the code without any errors?
  • Did you report the running environment (NPU type/MS version) and performance in the doc? (better record it for data loading, model inference, or training tasks)
  • Did you write any new necessary tests?

Who can review?

Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.

@xxx

@wcrzlh wcrzlh requested a review from vigo999 as a code owner November 24, 2025 12:14
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @wcrzlh, 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 a critical indexing bug within the GLM4.1v model's get_rope_index function. The fix is essential for enabling stable and correct generation when processing multiple inputs (batch size > 1), particularly concerning the handling of video data. By refining how video-related indices are managed, the change ensures that the model can properly process diverse input modalities in batched operations.

Highlights

  • Indexing Correction for GLM4.1v: Corrected an indexing bug within the get_rope_index function that previously prevented proper generation for GLM4.1v models when the batch size was greater than 1.
  • Improved Video Index Management: Refactored the logic for video_index and introduced video_group_index to accurately track and increment video-related indices, ensuring correct processing of multiple video segments within a batch.
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 correctly fixes a bug in get_rope_index for batched generation (batch size > 1) by moving the initialization of image_index and video_index outside the batch loop. It also introduces more robust logic for handling videos composed of multiple frames using video_group_index. While the changes are a significant improvement, I've identified a potential issue regarding the inconsistent handling of video frame counters, which could lead to incorrect temporal position embeddings in certain scenarios.

)

image_index, video_index = 0, 0
video_group_index = 0
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 introduction of video_group_index is a good step towards correctly handling batched video data. However, its lifecycle is inconsistent with the existing video_frame_num variable (initialized at L1089, incremented at L1148). video_frame_num is reset to 1 for non-video modalities, while video_group_index is not. This can lead to incorrect temporal position IDs if video frames are interleaved with text or images.

To improve robustness and simplify the logic, consider using a single variable to track the video frame count. You could remove video_frame_num and derive the temporal dimension t directly from video_group_index.

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