fix Glm4v batch videos forward
Author: Kuangdd01
Pull request: yes
Labels: name: for patch

# What does this PR do?

<!--
Congratulations! You've made it this far! You're not quite done yet though.

Once merged, your PR is going to appear in the release notes with the title you set, so make sure it's a great title that fully reflects the extent of your awesome contribution.

Then, please replace this with a description of the change and which issue is fixed (if applicable). Please also include relevant motivation and context. List any dependencies (if any) that are required for this change.

Once you're done, someone will review your PR shortly (see the section "Who can review?" below to tag some potential reviewers). They may suggest changes to make the code even better. If no one reviewed your PR after a week has passed, don't hesitate to post a new comment @-mentioning the same persons---sometimes notifications get lost.
-->

<!-- Remove if not applicable -->

Fixes the issues of video_processing and get_video_features for GLM4V.

Have tested with following scripts
```python
import torch
from transformers import AutoProcessor, Glm4vForConditionalGeneration
from PIL import Image
import numpy as np
import cv2
import os
from dataclasses import dataclass
from transformers.video_utils import VideoMetadata

def prepare_video_metadata(videos):
    video_metadata = []
    for video in videos:
        if isinstance(video, list):
            num_frames = len(video)
        elif hasattr(video, "shape"):
            if len(video.shape) == 4:  # (T, H, W, C)
                num_frames = video.shape[0]
            else:
                num_frames = 1
        else:
            num_frames = 8
            print("eeeeee")

        metadata = {
            "fps": 2,
            "duration": num_frames / 2,
            "total_frames": num_frames,
        }
        video_metadata.append(metadata)
    return video_metadata

def test_video_processing(video_path_list, num_frames=4):
    selected_frames = []
    for video_path in video_path_list:
        cap = cv2.VideoCapture(video_path)
        frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        print(f"Total frames: {frame_count}")

    video_metadata = []
    for video_path in video_path_list:
        temp_frames = []
        cap = cv2.VideoCapture(video_path)
        frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        step = max(frame_count // num_frames, 1)
        for i in range(0, frame_count, step):
            cap.set(cv2.CAP_PROP_POS_FRAMES, i)
            ret, frame = cap.read()
            if not ret:
                continue
            frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            pil_img = Image.fromarray(frame_rgb)
            temp_frames.append(pil_img)
        selected_frames.append(temp_frames)

    video_metadata = prepare_video_metadata(selected_frames)
    video_inputs = processor.video_processor(videos=selected_frames, video_metadata=video_metadata)

    questions = ["What kind of dog is this?", "Describe the background."]

    messages_batch = [
        [
            {
                "role": "user",
                "content": [
                    {"type": "video"},
                    {"type": "text", "text": question},
                ],
            }
        ]
        for question in questions
    ]

    texts = [
        processor.apply_chat_template(msg, tokenize=False, add_generation_prompt=True)
        for msg in messages_batch
    ]

    inputs_batch = processor(text=texts, videos=selected_frames, video_metadata=video_metadata, return_tensors="pt", padding=True)

    print(processor.batch_decode(inputs_batch['input_ids'])[0])
    rope_pos, deltas = model.model.get_rope_index(
        inputs_batch["input_ids"],
        None,
        inputs_batch["video_grid_thw"],
        inputs_batch["attention_mask"]
    )

    print(rope_pos.shape, "\n", deltas)

processor_name = "THUDM/GLM-4.1V-9B-Thinking"
processor = AutoProcessor.from_pretrained(processor_name)
model = Glm4vForConditionalGeneration.from_pretrained(processor_name)

if __name__ == "__main__":
    # image_path = "./data/mllm_demo_data/1.jpg"
    video_path_1 = "./data/mllm_demo_data/1.mp4"
    video_path_2 = "./data/mllm_demo_data/2.avi"

    test_video_processing([video_path_1, video_path_2])
```

For forward logits checking, @zRzRzRzRzRzRzR 

## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [x] Did you read the [contributor guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#create-a-pull-request),
      Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the [forum](https://discuss.huggingface.co/)? Please add a link
      to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes? Here are the
      [documentation guidelines](https://github.com/huggingface/transformers/tree/main/docs), and
      [here are tips on formatting docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [x] Did you write any new necessary tests?


## Who can review?
@zucchini-nlp  cc @zRzRzRzRzRzRzR 

<!-- Your PR will be replied to more quickly if you can figure out the right person to tag with @

 If you know how to use git blame, that is the easiest way, otherwise, here is a rough guide of **who to tag**.
 Please tag fewer than 3 people.

Models:

- text models: @ArthurZucker
- vision models: @amyeroberts, @qubvel
- speech models: @eustlb
- graph models: @clefourrier

Library:

- flax: @gante and @Rocketknight1
- generate: @zucchini-nlp (visual-language models) or @gante (all others)
- pipelines: @Rocketknight1
- tensorflow: @gante and @Rocketknight1
- tokenizers: @ArthurZucker
- trainer: @zach-huggingface, @SunMarc and @qgallouedec
- chat templates: @Rocketknight1

Integrations:

- deepspeed: HF Trainer/Accelerate: @SunMarc @zach-huggingface
- ray/raytune: @richardliaw, @amogkam
- Big Model Inference: @SunMarc
- quantization (bitsandbytes, autogpt): @SunMarc @MekkCyber

Documentation: @stevhliu

HF projects:

- accelerate: [different repo](https://github.com/huggingface/accelerate)
- datasets: [different repo](https://github.com/huggingface/datasets)
- diffusers: [different repo](https://github.com/huggingface/diffusers)
- rust tokenizers: [different repo](https://github.com/huggingface/tokenizers)

Maintained examples (not research project or legacy):

- Flax: @Rocketknight1
- PyTorch: See Models above and tag the person corresponding to the modality of the example.
- TensorFlow: @Rocketknight1

 -->


Comments:
Failed for changing the `get_video_features` which is not consistent with that generated from modular. 😂

😀Do I need to write more unit tests for this change? 

> 😀Do I need to write more unit tests for this change?

we can add integration test with batched/unbatched video inference, similar to https://github.com/huggingface/transformers/blob/b0a8e0b8d7eba2af7346331dd1d48c50892867b2/tests/models/glm4v/test_modeling_glm4v.py#L325-L326 

> > 😀Do I need to write more unit tests for this change?
> 
> we can add integration test with batched/unbatched video inference, similar to
> 
> https://github.com/huggingface/transformers/blob/b0a8e0b8d7eba2af7346331dd1d48c50892867b2/tests/models/glm4v/test_modeling_glm4v.py#L325-L326

Thanks, I have tested this `test_small_model_integration_test_with_video` locally. BTW, should we remove `@unittest.skip("Model checkpoint not yet released")` in this tester?

Yeeah, the checkpoints were updated in https://github.com/huggingface/transformers/pull/39247. Can you rebase?

Failed tests following now after run `pytest tests/models/glm4v/test_modeling_glm4v.py` locally
```
FAILED tests/models/glm4v/test_modeling_glm4v.py::Glm4vModelTest::test_generate_from_inputs_embeds_0_greedy - ValueError: You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one
FAILED tests/models/glm4v/test_modeling_glm4v.py::Glm4vModelTest::test_generate_from_inputs_embeds_1_beam_search - ValueError: You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one
FAILED tests/models/glm4v/test_modeling_glm4v.py::Glm4vModelTest::test_resize_embeddings_untied_with_deepspeed - ModuleNotFoundError: No module named 'mpi4py'
FAILED tests/models/glm4v/test_modeling_glm4v.py::Glm4vModelTest::test_resize_embeddings_untied_with_deepspeed_multi_gpu - ModuleNotFoundError: No module named 'mpi4py'
FAILED tests/models/glm4v/test_modeling_glm4v.py::Glm4vModelTest::test_resize_tokens_embeddings_with_deepspeed - ModuleNotFoundError: No module named 'mpi4py'
FAILED tests/models/glm4v/test_modeling_glm4v.py::Glm4vModelTest::test_resize_tokens_embeddings_with_deepspeed_multi_gpu - ModuleNotFoundError: No module named 'mpi4py'
```

run-slow: glm4v

This comment contains run-slow, running the specified jobs: 

models: ['models/glm4v']
quantizations: [] ...

The docs for this PR live [here](https://moon-ci-docs.huggingface.co/docs/transformers/pr_39172). All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

`tests/models/glm4v/test_modeling_glm4v.py::Glm4vModelTest::test_inputs_embeds PASSED`
It seems that tests failed for OOM, shall we resize the video frame to pass this test, or do not use batch videos inference?

> resize the video frame to pass this test

yep, lets' use smaller size then :)

Can you retry this test? The peak GPU memory consumption is about ~21GB now.

run-slow: glm4v

This comment contains run-slow, running the specified jobs: 

models: ['models/glm4v']
quantizations: [] ...

Hmm, don't know why this test failed. Do `test_modeling` and `test_video*` share one `video_processor`?

Nice, the test passed but the `tests/models/glm4v/test_video_processing_glm4v.py::Glm4vVideoProcessingTest::test_call_numpy` started failing, probably it was processing only one video prev instead of batch. Can you fix that and let's merge!

I guess this test will pass. 

> Do test_modeling and test_video* share one video_processor?

No, they don't. I see the last commit changes the `self.processor`, we usually don't change global var within test cases, it might cause unexpected errors. The test cases are run in random order afaik so if we change `longest_edge`, the subsequent tests might fail to match to `expected_output`

No idea tbh why the `test_video_*` failed, is it passing locally? Guess it was some unlucky randomness in tests, let me trigger again and see

run-slow: glm4v

This comment contains run-slow, running the specified jobs: 

models: ['models/glm4v']
quantizations: [] ...

> No, they don't. I see the last commit changes the `self.processor`, we usually don't change global var within test cases, it might cause unexpected errors. The test cases are run in random order afaik so if we change `longest_edge`, the subsequent tests might fail to match to `expected_output`

Yes, I think it fails due to the changes in this global var. After I ran `test_with_video`, `test_with_numpy` would fail. But it seems that all tests pass finally.




cc @ydshieh , do you know anything about test files sharing the same `processor`? Happy to keep the fix if you agree, but looks weird to me 👀 

Not really a regression, but maybe can have in patch

> cc @ydshieh , do you know anything about test files sharing the same processor? Happy to keep the fix if you agree, but looks weird to me 👀

Hi, may I have a bit of context here 🙏 . I guess you are talking about

> Hmm, don't know why this test failed. Do test_modeling and test_video* share one video_processor?

But at this moment, I don't know what the issues you faced. A bit more details would be very appreciated. Thank you


Oh yeah, sorry @ydshieh . The issue is that a test failed in slow CI when we ran it last time. The test is `tests/models/glm4v/test_video_processing_glm4v.py::Glm4vVideoProcessingTest::test_call_numpy`. There are two weird things about it:

1. It is failing only in slow CI, but not in fast one. The test isn't marked as `slow` so I assumed it would have been triggered already. Maybe it want' triggered then it's fine
2. To fix the test, contributor had to change `test_modeling_*.py` file, specifically the `self.processor` in IntegrationTest. I don't know how `self.processor` from modeling test is being re-used in processing test, and if this is expected. As per the last comment, it fixes the issue magically. Have you encountered anything similar before?

    > Yes, I think it fails due to the changes in this global var. After I ran test_with_video, test_with_numpy would fail. But it seems that all tests pass finally.

Thanks. I will take a look today.

@zucchini-nlp Those are class attributes, so if an instance change the values, it will affect the other places!

Do you know why we use class attributes 😭 

```
class Glm4vVideoProcessor(BaseVideoProcessor):
    resample = PILImageResampling.BICUBIC
    size = {"shortest_edge": 112 * 112, "longest_edge": 28 * 28 * 2 * 30000}
    max_image_size = {"longest_edge": 28 * 28 * 2 * 30000}
    image_mean = OPENAI_CLIP_MEAN
    image_std = OPENAI_CLIP_STD
    do_resize = True
    do_rescale = True
    do_normalize = True
    do_convert_rgb = True
    do_sample_frames = True
    patch_size = 14
    temporal_patch_size = 2
    max_duration = 300
    merge_size = 2
    valid_kwargs = Glm4vVideoProcessorInitKwargs
    num_frames = 16
    fps = 2
```

> Do you know why we use class attributes 😭

This is copied from image processors, because video inherits from it. I believe it was done to have defaults for kwargs, and keep core processing code in one place. @yonigozlan can say more on that

I didn't see that the new test changes processor attribute, in the meanwhile we can fix and merge the PR. We can move discussion later to internal slack if needed :)

run-slow: glm4v

This comment contains run-slow, running the specified jobs: 

models: ['models/glm4v']
quantizations: [] ...

Hmm, failed again
```
FAILED tests/models/glm4v/test_video_processing_glm4v.py::Glm4vVideoProcessingTest::test_call_numpy 
- AssertionError: Lists differ: [64, 1176] != [144, 1176]
```

Oh wait, i didn't check the changes, It's because we're still re-assigning the value of `max_length`. I meant to load with the new value like `processor = AutoProcessor.from_pretrained("glm4V", max_image_size="{NEW_SMALL_SIZE}")`. It doesn't change class attribute I think

Sorry about that, I finally realized Yih-Dar's words. I'll fix that dangerous code. 😭

**[For maintainers]** Suggested jobs to run (before merge)

run-slow: glm4v

run-slow: glm4v

This comment contains run-slow, running the specified jobs: 

models: ['models/glm4v']
quantizations: [] ...

> > Do you know why we use class attributes 😭
> 
> This is copied from image processors, because video inherits from it. I believe it was done to have defaults for kwargs, and keep core processing code in one place. @yonigozlan can say more on that
> 
> I didn't see that the new test changes processor attribute, in the meanwhile we can fix and merge the PR. We can move discussion later to internal slack if needed :)

Just want to point out that if an attribute makes sense to be as an instance attribute (i.e. we could have instances that are allowed to have different values for that attribute, then make it as class attribute is not a great idea and will sometimes cause chaos. I remember my nightmare when debugging `Instructblip` that has `keep_fp32_....` class attribute back then.

Might be a good time to rethink of this @yonigozlan  

Yaay, test passing, can merge now 🎉 

> Just want to point out that if an attribute makes sense to be as an instance attribute (i.e. we could have instances that are allowed to have different values for that attribute, then make it as class attribute is not a great idea and will sometimes cause chaos. I remember my nightmare when debugging Instructblip that has keep_fp32_.... class attribute back then.

And now on this topic, I had some local branch where I am trying to use `dataclasses` to store all processor values, and thus remove iterating over `TypedDict.__annotations__` for checking/setting values. I can go back and work on that if we think that it makes sense