-
Notifications
You must be signed in to change notification settings - Fork 383
[FEAT] Support GLM4.1V series #534
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
Open
ZiyiTsang
wants to merge
10
commits into
hiyouga:main
Choose a base branch
from
ZiyiTsang:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
e19a20f
.
ZiyiTsang ba5f06c
.
ZiyiTsang 5933a34
.
ZiyiTsang d328f42
.
ZiyiTsang fe3e6e6
.
ZiyiTsang 7b79dcb
.
ZiyiTsang 84e564f
Merge remote-tracking branch 'upstream/main'
ZiyiTsang c6cbb3d
.
ZiyiTsang 97b2520
.
ZiyiTsang 9743a59
Update verl/workers/fsdp_workers.py
ZiyiTsang File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| #!/bin/bash | ||
|
|
||
| set -x | ||
|
|
||
| MODEL_PATH=zai-org/GLM-4.1V-9B-Thinking # replace it with your local file path | ||
|
|
||
| python3 -m verl.trainer.main \ | ||
| config=examples/config.yaml \ | ||
| data.train_files=hiyouga/geometry3k@train \ | ||
| data.val_files=hiyouga/geometry3k@test \ | ||
| worker.actor.model.model_path=${MODEL_PATH} \ | ||
| trainer.experiment_name=glm4.1v_thinking_geo_grpo \ | ||
| worker.actor.padding_free=False \ | ||
| trainer.n_gpus_per_node=8 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| #!/bin/bash | ||
|
|
||
| set -x | ||
|
|
||
| MODEL_PATH=zai-org/GLM-4.1V-9B-Base # replace it with your local file path | ||
|
|
||
| python3 -m verl.trainer.main \ | ||
| config=examples/config.yaml \ | ||
| data.train_files=hiyouga/geometry3k@train \ | ||
| data.val_files=hiyouga/geometry3k@test \ | ||
| worker.actor.model.model_path=${MODEL_PATH} \ | ||
| trainer.experiment_name=glm4.1v_base_geo_grpo \ | ||
| worker.actor.padding_free=False \ | ||
| trainer.n_gpus_per_node=8 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -35,6 +35,8 @@ | |
|
|
||
| QWEN2_VL_MODELS = ("qwen2_vl", "qwen2_5_vl") | ||
| QWEN3_VL_MODELS = ("qwen3_vl", "qwen3_vl_moe") | ||
| # TODO support monkey patch for glm4.1v | ||
| GLM_VL_MODELS = ("glm4.1v_base", "glm4.1v_thinking") | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. the patch is essential IMO
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The 'padding_free' haven been tested, I suggest putting it in the future |
||
|
|
||
|
|
||
| def apply_ulysses_patch(model_type: str) -> None: | ||
|
|
@@ -44,7 +46,7 @@ def apply_ulysses_patch(model_type: str) -> None: | |
| if model_type in SUPPORTED_MODEL_TYPE: | ||
| ALL_ATTENTION_FUNCTIONS["flash_attention_2"] = flash_attention_forward | ||
| else: | ||
| raise NotImplementedError(f"Model architecture {model_type} is not supported yet.") | ||
| raise NotImplementedError(f"Model architecture {model_type} is not supported ulysses_patch (patch_free) yet.") | ||
|
|
||
| if model_type in QWEN2_VL_MODELS: | ||
| from transformers.models.qwen2_5_vl.modeling_qwen2_5_vl import ( | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,165 @@ | ||
| # Copyright 2024 Bytedance Ltd. and/or its affiliates | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| import inspect | ||
| import itertools | ||
| import logging | ||
| import os | ||
| from dataclasses import dataclass | ||
| from typing import Optional | ||
|
|
||
| import torch | ||
| import torch.distributed as dist | ||
| from transformers.modeling_flash_attention_utils import _flash_attention_forward, fa_peft_integration_check | ||
| from transformers.models.glm4v.modeling_glm4v import ( | ||
| Glm4vCausalLMOutputWithPast, | ||
| Glm4vForConditionalGeneration, | ||
| Glm4vTextAttention, | ||
| ) | ||
| from transformers.utils import is_flash_attn_2_available, is_flash_attn_greater_or_equal_2_10 | ||
|
|
||
| # from verl.utils.device import is_npu_available | ||
| from verl.utils.ulysses import ( | ||
| gather_heads_scatter_seq, | ||
| gather_seq_scatter_heads, | ||
| get_ulysses_sequence_parallel_group, | ||
| get_ulysses_sequence_parallel_world_size, | ||
| validate_ulysses_config, | ||
| ) | ||
|
|
||
| logger = logging.getLogger(__file__) | ||
| logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN")) | ||
|
|
||
|
|
||
|
|
||
| def get_rope_index( | ||
| processor, | ||
| input_ids: torch.Tensor, | ||
| image_grid_thw: Optional[torch.LongTensor] = None, | ||
| video_grid_thw: Optional[torch.LongTensor] = None, | ||
| attention_mask: Optional[torch.Tensor] = None, | ||
| ) -> torch.Tensor: | ||
| """ | ||
| Gets the position ids for GLM4V in padding-free format. | ||
| The batch dim has been removed and the input_ids should be a 1D tensor representing a single example. | ||
| """ | ||
| spatial_merge_size = processor.image_processor.merge_size | ||
| image_token_id = processor.tokenizer.convert_tokens_to_ids("<|image|>") | ||
| video_start_token_id = processor.tokenizer.convert_tokens_to_ids("<|begin_of_video|>") | ||
| video_end_token_id = processor.tokenizer.convert_tokens_to_ids("<|end_of_video|>") | ||
|
|
||
| if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None): | ||
| if attention_mask is None: | ||
| attention_mask = torch.ones_like(input_ids) | ||
|
|
||
| position_ids = torch.ones(3, input_ids.size(0), dtype=input_ids.dtype, device=input_ids.device) # (3, seqlen) | ||
| image_index, video_index = 0, 0 | ||
| video_group_index = 0 | ||
|
|
||
| input_ids_filtered = input_ids[attention_mask == 1] | ||
| input_tokens = input_ids_filtered.tolist() | ||
|
ZiyiTsang marked this conversation as resolved.
|
||
|
|
||
| input_token_type = [] | ||
| video_check_flg = False | ||
| for token in input_tokens: | ||
| if token == video_start_token_id: | ||
| video_check_flg = True | ||
| elif token == video_end_token_id: | ||
| video_check_flg = False | ||
|
|
||
| if token == image_token_id and not video_check_flg: | ||
| input_token_type.append("image") | ||
| elif token == image_token_id and video_check_flg: | ||
| input_token_type.append("video") | ||
| else: | ||
| input_token_type.append("text") | ||
|
|
||
| input_type_group = [] | ||
| for key, group in itertools.groupby(enumerate(input_token_type), lambda x: x[1]): | ||
| group = list(group) | ||
| start_index = group[0][0] | ||
| end_index = group[-1][0] + 1 | ||
| input_type_group.append((key, start_index, end_index)) | ||
|
|
||
| llm_pos_ids_list = [] | ||
| video_frame_num = 1 | ||
|
|
||
| for modality_type, start_idx, end_idx in input_type_group: | ||
| st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0 | ||
|
|
||
| if modality_type == "image": | ||
| t, h, w = ( | ||
| image_grid_thw[image_index][0], | ||
| image_grid_thw[image_index][1], | ||
| image_grid_thw[image_index][2], | ||
| ) | ||
| llm_grid_t, llm_grid_h, llm_grid_w = ( | ||
| t.item(), | ||
| h.item() // spatial_merge_size, | ||
| w.item() // spatial_merge_size, | ||
| ) | ||
|
|
||
| t_index = torch.arange(llm_grid_t).view(-1, 1).expand(-1, llm_grid_h * llm_grid_w).flatten() | ||
| h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten() | ||
| w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten() | ||
| llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + st_idx) | ||
|
|
||
| image_index += 1 | ||
| video_frame_num = 1 | ||
|
|
||
| elif modality_type == "video": | ||
| t, h, w = ( | ||
| video_frame_num, | ||
| video_grid_thw[video_index][1], | ||
| video_grid_thw[video_index][2], | ||
| ) | ||
|
|
||
| llm_grid_t, llm_grid_h, llm_grid_w = ( | ||
| t, | ||
| h.item() // spatial_merge_size, | ||
| w.item() // spatial_merge_size, | ||
| ) | ||
|
|
||
| for t_idx in range(llm_grid_t): | ||
| t_index = torch.tensor(t_idx).view(-1, 1).expand(-1, llm_grid_h * llm_grid_w).flatten() | ||
| h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(1, -1, llm_grid_w).flatten() | ||
| w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(1, llm_grid_h, -1).flatten() | ||
| llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + st_idx) | ||
|
|
||
| video_group_index += 1 | ||
|
|
||
| if video_group_index >= video_grid_thw[video_index][0]: | ||
| video_index += 1 | ||
| video_group_index = 0 | ||
|
|
||
| video_frame_num += 1 | ||
|
|
||
|
ZiyiTsang marked this conversation as resolved.
|
||
| else: | ||
| text_len = end_idx - start_idx | ||
| llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx) | ||
| video_frame_num = 1 | ||
|
|
||
| llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1) | ||
| position_ids[..., attention_mask == 1] = llm_positions.to(position_ids.device) | ||
| else: | ||
| if attention_mask is not None: | ||
| position_ids = attention_mask.long().cumsum(-1) - 1 | ||
| position_ids.masked_fill_(attention_mask == 0, 1) | ||
| position_ids = position_ids.unsqueeze(0).expand(3, -1).to(input_ids.device) | ||
| else: | ||
| position_ids = torch.arange(input_ids.shape[0], device=input_ids.device).view(1, -1).expand(3, -1) | ||
|
|
||
| return position_ids | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.