EastBrook
commited on
Upload folder using huggingface_hub
Browse files- .gitattributes +1 -0
- added_tokens.json +27 -0
- chat_template.json +3 -0
- config.json +96 -0
- configuration_qwen2_mm.py +194 -0
- generation_config.json +14 -0
- latest +1 -0
- merges.txt +0 -0
- model-00001-of-00007.safetensors +3 -0
- model-00002-of-00007.safetensors +3 -0
- model-00003-of-00007.safetensors +3 -0
- model-00004-of-00007.safetensors +3 -0
- model-00005-of-00007.safetensors +3 -0
- model-00006-of-00007.safetensors +3 -0
- model-00007-of-00007.safetensors +3 -0
- model.safetensors.index.json +0 -0
- modeling_qwen2_mm.py +371 -0
- preprocessor_config.json +40 -0
- processing_qwen2_mm.py +202 -0
- special_tokens_map.json +34 -0
- tokenizer.json +3 -0
- tokenizer_config.json +235 -0
- trainer_state.json +0 -0
- training_args.bin +3 -0
- vocab.json +0 -0
- zero_to_fp32.py +604 -0
.gitattributes
CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
added_tokens.json
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"</tool_call>": 151658,
|
3 |
+
"<tool_call>": 151657,
|
4 |
+
"<|audio_end|>": 151667,
|
5 |
+
"<|audio_pad|>": 151665,
|
6 |
+
"<|audio_start|>": 151666,
|
7 |
+
"<|box_end|>": 151649,
|
8 |
+
"<|box_start|>": 151648,
|
9 |
+
"<|endoftext|>": 151643,
|
10 |
+
"<|file_sep|>": 151664,
|
11 |
+
"<|fim_middle|>": 151660,
|
12 |
+
"<|fim_pad|>": 151662,
|
13 |
+
"<|fim_prefix|>": 151659,
|
14 |
+
"<|fim_suffix|>": 151661,
|
15 |
+
"<|im_end|>": 151645,
|
16 |
+
"<|im_start|>": 151644,
|
17 |
+
"<|image_pad|>": 151655,
|
18 |
+
"<|object_ref_end|>": 151647,
|
19 |
+
"<|object_ref_start|>": 151646,
|
20 |
+
"<|quad_end|>": 151651,
|
21 |
+
"<|quad_start|>": 151650,
|
22 |
+
"<|repo_name|>": 151663,
|
23 |
+
"<|video_pad|>": 151656,
|
24 |
+
"<|vision_end|>": 151653,
|
25 |
+
"<|vision_pad|>": 151654,
|
26 |
+
"<|vision_start|>": 151652
|
27 |
+
}
|
chat_template.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"chat_template": "{% set image_count = namespace(value=0) %}{% set video_count = namespace(value=0) %}{% set audio_count = namespace(value=0) %}{% for message in messages %}{% if loop.first and message['role'] != 'system' %}<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n{% endif %}<|im_start|>{{ message['role'] }}\n{% if message['content'] is string %}{{ message['content'] }}<|im_end|>\n{% else %}{% for content in message['content'] %}{% if content['type'] == 'image' or 'image' in content or 'image_url' in content %}{% set image_count.value = image_count.value + 1 %}{% if add_vision_id %}Picture {{ image_count.value }}: {% endif %}<|vision_start|><|image_pad|><|vision_end|>{% elif content['type'] == 'video' or 'video' in content %}{% set video_count.value = video_count.value + 1 %}{% if add_vision_id %}Video {{ video_count.value }}: {% endif %}<|vision_start|><|video_pad|><|vision_end|>{% elif content['type'] == 'audio' or 'audio' in content %}{% set audio_count.value = audio_count.value + 1 %}{% if add_audio_id %}Audio {{ audio_count.value }}: {% endif %}<|audio_start|><|audio_pad|><|audio_end|>{% elif 'text' in content %}{{ content['text'] }}{% endif %}{% endfor %}<|im_end|>\n{% endif %}{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant\n{% endif %}"
|
3 |
+
}
|
config.json
ADDED
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "/mnt/disk2/home/wujianfeng/LLaMA-Factory_audio/qwen2_mm_14B_pt_1/checkpoint-12000/",
|
3 |
+
"architectures": [
|
4 |
+
"Qwen2MMForConditionalGeneration"
|
5 |
+
],
|
6 |
+
"attention_dropout": 0.0,
|
7 |
+
"audio_config": {
|
8 |
+
"_attn_implementation_autoset": true,
|
9 |
+
"activation_dropout": 0.0,
|
10 |
+
"activation_function": "relu",
|
11 |
+
"architectures": [
|
12 |
+
"SeamlessM4Tv2Model"
|
13 |
+
],
|
14 |
+
"attention_dropout": 0.1,
|
15 |
+
"dropout": 0.1,
|
16 |
+
"encoder_attention_heads": 16,
|
17 |
+
"encoder_ffn_dim": 8192,
|
18 |
+
"encoder_layerdrop": 0.05,
|
19 |
+
"encoder_layers": 24,
|
20 |
+
"hidden_size": 1024,
|
21 |
+
"initializer_range": 0.02,
|
22 |
+
"is_encoder_decoder": true,
|
23 |
+
"layer_norm_eps": 1e-05,
|
24 |
+
"leaky_relu_slope": 0.1,
|
25 |
+
"max_new_tokens": 256,
|
26 |
+
"max_position_embeddings": 4096,
|
27 |
+
"model_type": "qwen2_seamless_encoder",
|
28 |
+
"num_attention_heads": 16,
|
29 |
+
"num_hidden_layers": 24,
|
30 |
+
"pad_token_id": 0,
|
31 |
+
"resblock_dilation_sizes": [
|
32 |
+
[
|
33 |
+
1,
|
34 |
+
3,
|
35 |
+
5
|
36 |
+
],
|
37 |
+
[
|
38 |
+
1,
|
39 |
+
3,
|
40 |
+
5
|
41 |
+
],
|
42 |
+
[
|
43 |
+
1,
|
44 |
+
3,
|
45 |
+
5
|
46 |
+
]
|
47 |
+
],
|
48 |
+
"resblock_kernel_sizes": [
|
49 |
+
3,
|
50 |
+
7,
|
51 |
+
11
|
52 |
+
],
|
53 |
+
"sampling_rate": 16000,
|
54 |
+
"scale_embedding": true,
|
55 |
+
"spkr_embed_dim": 256,
|
56 |
+
"use_cache": true
|
57 |
+
},
|
58 |
+
"audio_end_token_id": 151667,
|
59 |
+
"audio_start_token_id": 151666,
|
60 |
+
"audio_token_id": 151665,
|
61 |
+
"auto_map": {
|
62 |
+
"AutoConfig": "configuration_qwen2_mm.Qwen2MMConfig",
|
63 |
+
"AutoModel": "modeling_qwen2_mm.Qwen2MMForConditionalGeneration",
|
64 |
+
"AutoModelForCausalLM": "modeling_qwen2_mm.Qwen2MMForConditionalGeneration"
|
65 |
+
},
|
66 |
+
"bos_token_id": 151643,
|
67 |
+
"eos_token_id": 151645,
|
68 |
+
"hidden_act": "silu",
|
69 |
+
"hidden_size": 5120,
|
70 |
+
"image_token_id": 151655,
|
71 |
+
"initializer_range": 0.02,
|
72 |
+
"intermediate_size": 13824,
|
73 |
+
"llm_path": "/mnt/diskhd/Backup/DownloadModel/Qwen2.5-14B-Instruct/",
|
74 |
+
"max_position_embeddings": 32768,
|
75 |
+
"max_window_layers": 70,
|
76 |
+
"model_type": "qwen2_mm",
|
77 |
+
"num_attention_heads": 40,
|
78 |
+
"num_hidden_layers": 48,
|
79 |
+
"num_key_value_heads": 8,
|
80 |
+
"rms_norm_eps": 1e-06,
|
81 |
+
"rope_scaling": null,
|
82 |
+
"rope_theta": 1000000.0,
|
83 |
+
"sliding_window": 131072,
|
84 |
+
"torch_dtype": "bfloat16",
|
85 |
+
"transformers_version": "4.45.0",
|
86 |
+
"use_cache": false,
|
87 |
+
"use_sliding_window": false,
|
88 |
+
"video_token_id": 151656,
|
89 |
+
"vision_config": {
|
90 |
+
"model_type": "qwen2_vl"
|
91 |
+
},
|
92 |
+
"vision_end_token_id": 151653,
|
93 |
+
"vision_start_token_id": 151652,
|
94 |
+
"vision_token_id": 151654,
|
95 |
+
"vocab_size": 152064
|
96 |
+
}
|
configuration_qwen2_mm.py
ADDED
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2024 Microsoft Research & University of Wisconsin-Madison and the HuggingFace Inc. team. All rights reserved.
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
"""Qwen2Audio model configuration"""
|
15 |
+
|
16 |
+
from transformers.configuration_utils import PretrainedConfig
|
17 |
+
from transformers.utils import logging
|
18 |
+
from transformers import CONFIG_MAPPING
|
19 |
+
|
20 |
+
import os
|
21 |
+
from typing import Union
|
22 |
+
|
23 |
+
logger = logging.get_logger(__name__)
|
24 |
+
|
25 |
+
|
26 |
+
class Qwen2SeamlessEncoderConfig(PretrainedConfig):
|
27 |
+
|
28 |
+
model_type = "qwen2_seamless_encoder"
|
29 |
+
|
30 |
+
def __init__(
|
31 |
+
self,
|
32 |
+
speech_encoder_layers=24,
|
33 |
+
speech_encoder_attention_heads=16,
|
34 |
+
speech_encoder_intermediate_size=4096,
|
35 |
+
speech_encoder_hidden_act="swish",
|
36 |
+
speech_encoder_dropout=0.0,
|
37 |
+
add_adapter=True,
|
38 |
+
speech_encoder_layerdrop=0.1,
|
39 |
+
feature_projection_input_dim=160,
|
40 |
+
adaptor_kernel_size=8,
|
41 |
+
adaptor_stride=8,
|
42 |
+
adaptor_dropout=0.1,
|
43 |
+
num_adapter_layers=1,
|
44 |
+
position_embeddings_type="relative_key",
|
45 |
+
conv_depthwise_kernel_size=31,
|
46 |
+
left_max_position_embeddings=64,
|
47 |
+
right_max_position_embeddings=8,
|
48 |
+
speech_encoder_chunk_size=20000,
|
49 |
+
speech_encoder_left_chunk_num=128,
|
50 |
+
**kwargs,
|
51 |
+
):
|
52 |
+
super().__init__(**kwargs)
|
53 |
+
|
54 |
+
self.speech_encoder_layers = speech_encoder_layers
|
55 |
+
self.speech_encoder_hidden_act = speech_encoder_hidden_act
|
56 |
+
self.speech_encoder_dropout = speech_encoder_dropout
|
57 |
+
self.speech_encoder_attention_heads = speech_encoder_attention_heads
|
58 |
+
self.speech_encoder_layerdrop = speech_encoder_layerdrop
|
59 |
+
self.speech_encoder_intermediate_size = speech_encoder_intermediate_size
|
60 |
+
self.feature_projection_input_dim = feature_projection_input_dim
|
61 |
+
self.adaptor_kernel_size = adaptor_kernel_size
|
62 |
+
self.adaptor_stride = adaptor_stride
|
63 |
+
self.adaptor_dropout = adaptor_dropout
|
64 |
+
self.num_adapter_layers = num_adapter_layers
|
65 |
+
self.position_embeddings_type = position_embeddings_type
|
66 |
+
self.conv_depthwise_kernel_size = conv_depthwise_kernel_size
|
67 |
+
self.add_adapter = add_adapter
|
68 |
+
self.left_max_position_embeddings = left_max_position_embeddings
|
69 |
+
self.right_max_position_embeddings = right_max_position_embeddings
|
70 |
+
self.speech_encoder_chunk_size = speech_encoder_chunk_size
|
71 |
+
self.speech_encoder_left_chunk_num = speech_encoder_left_chunk_num
|
72 |
+
self.audio_path = "/mnt/diskhd/Backup/DownloadModel/seamless-m4t-v2-large/"
|
73 |
+
|
74 |
+
|
75 |
+
|
76 |
+
class Qwen2VLVisionConfig(PretrainedConfig):
|
77 |
+
model_type = "qwen2_vl"
|
78 |
+
|
79 |
+
def __init__(
|
80 |
+
self,
|
81 |
+
depth=32,
|
82 |
+
embed_dim=1280,
|
83 |
+
hidden_size=3584,
|
84 |
+
hidden_act="quick_gelu",
|
85 |
+
mlp_ratio=4,
|
86 |
+
num_heads=16,
|
87 |
+
in_channels=3,
|
88 |
+
patch_size=14,
|
89 |
+
spatial_merge_size=2,
|
90 |
+
temporal_patch_size=2,
|
91 |
+
**kwargs,
|
92 |
+
):
|
93 |
+
super().__init__(**kwargs)
|
94 |
+
|
95 |
+
self.depth = depth
|
96 |
+
self.embed_dim = embed_dim
|
97 |
+
self.hidden_size = hidden_size
|
98 |
+
self.hidden_act = hidden_act
|
99 |
+
self.mlp_ratio = mlp_ratio
|
100 |
+
self.num_heads = num_heads
|
101 |
+
self.in_channels = in_channels
|
102 |
+
self.patch_size = patch_size
|
103 |
+
self.spatial_merge_size = spatial_merge_size
|
104 |
+
self.temporal_patch_size = temporal_patch_size
|
105 |
+
|
106 |
+
@classmethod
|
107 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
|
108 |
+
cls._set_token_in_kwargs(kwargs)
|
109 |
+
|
110 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
111 |
+
|
112 |
+
if 1:#config_dict.get("model_type") == "qwen2_vl":
|
113 |
+
config_dict = config_dict["vision_config"]
|
114 |
+
|
115 |
+
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
|
116 |
+
logger.warning(
|
117 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
118 |
+
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
|
119 |
+
)
|
120 |
+
|
121 |
+
return cls.from_dict(config_dict, **kwargs)
|
122 |
+
|
123 |
+
|
124 |
+
|
125 |
+
class Qwen2MMConfig(PretrainedConfig):
|
126 |
+
|
127 |
+
model_type = "qwen2_mm"
|
128 |
+
is_composition = False
|
129 |
+
|
130 |
+
def __init__(
|
131 |
+
self,
|
132 |
+
vocab_size=152064,
|
133 |
+
hidden_size=8192,
|
134 |
+
intermediate_size=29568,
|
135 |
+
num_hidden_layers=80,
|
136 |
+
num_attention_heads=64,
|
137 |
+
num_key_value_heads=8,
|
138 |
+
hidden_act="silu",
|
139 |
+
max_position_embeddings=32768,
|
140 |
+
initializer_range=0.02,
|
141 |
+
rms_norm_eps=1e-05,
|
142 |
+
use_cache=True,
|
143 |
+
tie_word_embeddings=False,
|
144 |
+
rope_theta=1000000.0,
|
145 |
+
use_sliding_window=False,
|
146 |
+
sliding_window=4096,
|
147 |
+
max_window_layers=80,
|
148 |
+
attention_dropout=0.0,
|
149 |
+
audio_config=None,
|
150 |
+
vision_config=None,
|
151 |
+
rope_scaling=None,
|
152 |
+
**kwargs,
|
153 |
+
):
|
154 |
+
if isinstance(vision_config, dict):
|
155 |
+
self.vision_config = Qwen2VLVisionConfig(**vision_config)
|
156 |
+
elif vision_config is None:
|
157 |
+
self.vision_config = Qwen2VLVisionConfig()
|
158 |
+
|
159 |
+
if isinstance(audio_config, dict):
|
160 |
+
self.audio_config = Qwen2SeamlessEncoderConfig(**audio_config)
|
161 |
+
elif audio_config is None:
|
162 |
+
self.audio_config = Qwen2SeamlessEncoderConfig()
|
163 |
+
|
164 |
+
self.vocab_size = vocab_size
|
165 |
+
self.max_position_embeddings = max_position_embeddings
|
166 |
+
self.hidden_size = hidden_size
|
167 |
+
self.intermediate_size = intermediate_size
|
168 |
+
self.num_hidden_layers = num_hidden_layers
|
169 |
+
self.num_attention_heads = num_attention_heads
|
170 |
+
self.use_sliding_window = use_sliding_window
|
171 |
+
self.sliding_window = sliding_window
|
172 |
+
self.max_window_layers = max_window_layers
|
173 |
+
|
174 |
+
# for backward compatibility
|
175 |
+
if num_key_value_heads is None:
|
176 |
+
num_key_value_heads = num_attention_heads
|
177 |
+
|
178 |
+
self.num_key_value_heads = num_key_value_heads
|
179 |
+
self.hidden_act = hidden_act
|
180 |
+
self.initializer_range = initializer_range
|
181 |
+
self.rms_norm_eps = rms_norm_eps
|
182 |
+
self.use_cache = use_cache
|
183 |
+
self.rope_theta = rope_theta
|
184 |
+
self.attention_dropout = attention_dropout
|
185 |
+
self.llm_path = "/mnt/diskhd/Backup/DownloadModel/Qwen2.5-3B-Instruct/"
|
186 |
+
self.auto_map = {
|
187 |
+
"AutoConfig": "configuration_qwen2_seamless.Qwen2MMConfig",
|
188 |
+
"AutoModel": "modeling_qwen2_seamless.Qwen2SeamlessForConditionalGeneration"
|
189 |
+
}
|
190 |
+
self.rope_scaling = rope_scaling
|
191 |
+
|
192 |
+
super().__init__(**kwargs)
|
193 |
+
|
194 |
+
|
generation_config.json
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token_id": 151643,
|
3 |
+
"do_sample": true,
|
4 |
+
"eos_token_id": [
|
5 |
+
151645,
|
6 |
+
151643
|
7 |
+
],
|
8 |
+
"pad_token_id": 151643,
|
9 |
+
"repetition_penalty": 1.05,
|
10 |
+
"temperature": 0.7,
|
11 |
+
"top_k": 20,
|
12 |
+
"top_p": 0.8,
|
13 |
+
"transformers_version": "4.45.0"
|
14 |
+
}
|
latest
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
global_step64000
|
merges.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
model-00001-of-00007.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b0794c18bb2c565a22ee9898edaa9271602e93e4c2ef093a37facc6f588eaa8a
|
3 |
+
size 4898405744
|
model-00002-of-00007.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:4fc1082232aa0cfe6b881ec653bb8d4a01b26c6b1e2fec8f811db3574529702f
|
3 |
+
size 4954848288
|
model-00003-of-00007.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9ddc816cefec6d9de513c9f363b539da87ef731e27dd61a130cea7f5d90d2135
|
3 |
+
size 4954848360
|
model-00004-of-00007.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c0cbfc3ac73940b374fb776b60569fcd43aaef97f2a95231ea1f1686060d008e
|
3 |
+
size 4954848360
|
model-00005-of-00007.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:52a83a5947cd1a9d8e69e3f60dde0e3e744330982be91d107638496bf151b66a
|
3 |
+
size 4954848360
|
model-00006-of-00007.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:fe08358609b86a8d4b31ca8828d15c60b57311ec46b949636b26d18b20adaeaa
|
3 |
+
size 4545898608
|
model-00007-of-00007.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:961282a7d1b18000f29487a35cc8e5357190a5222db03c2434bdf25e6d97731f
|
3 |
+
size 1557135488
|
model.safetensors.index.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
modeling_qwen2_mm.py
ADDED
@@ -0,0 +1,371 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2024 the HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
"""PyTorch Qwen2Audio model."""
|
16 |
+
|
17 |
+
import math
|
18 |
+
from dataclasses import dataclass
|
19 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
20 |
+
|
21 |
+
import torch
|
22 |
+
import torch.utils.checkpoint
|
23 |
+
from torch import nn
|
24 |
+
from functools import lru_cache
|
25 |
+
|
26 |
+
from transformers.activations import ACT2FN
|
27 |
+
from transformers.cache_utils import Cache, EncoderDecoderCache, StaticCache
|
28 |
+
from transformers.generation import GenerationMixin
|
29 |
+
from transformers.modeling_outputs import BaseModelOutput, ModelOutput, CausalLMOutputWithPast
|
30 |
+
from transformers.modeling_utils import PreTrainedModel
|
31 |
+
from transformers.utils import (
|
32 |
+
add_start_docstrings,
|
33 |
+
add_start_docstrings_to_model_forward,
|
34 |
+
is_flash_attn_2_available,
|
35 |
+
is_flash_attn_greater_or_equal_2_10,
|
36 |
+
logging,
|
37 |
+
replace_return_docstrings,
|
38 |
+
)
|
39 |
+
from transformers import AutoModel, AutoModelForCausalLM, AutoConfig, SeamlessM4Tv2Model, Qwen2ForCausalLM, Qwen2PreTrainedModel, Qwen2Model
|
40 |
+
from transformers.models.seamless_m4t_v2.modeling_seamless_m4t_v2 import SeamlessM4Tv2SpeechEncoder
|
41 |
+
from .configuration_qwen2_mm import Qwen2MMConfig
|
42 |
+
from torch.nn import CrossEntropyLoss, LayerNorm
|
43 |
+
|
44 |
+
if is_flash_attn_2_available():
|
45 |
+
from transformers.modeling_flash_attention_utils import _flash_attention_forward
|
46 |
+
|
47 |
+
|
48 |
+
logger = logging.get_logger(__name__)
|
49 |
+
|
50 |
+
_CONFIG_FOR_DOC = "Qwen2MMConfig"
|
51 |
+
|
52 |
+
|
53 |
+
|
54 |
+
class Qwen2AudioMultiModalProjector(nn.Module):
|
55 |
+
def __init__(self, config: Qwen2MMConfig):
|
56 |
+
super().__init__()
|
57 |
+
self.linear = nn.Linear(config.audio_config.hidden_size, config.hidden_size, bias=True)
|
58 |
+
|
59 |
+
def forward(self, audio_features):
|
60 |
+
hidden_states = self.linear(audio_features)
|
61 |
+
return hidden_states
|
62 |
+
|
63 |
+
|
64 |
+
class Qwen2MMPreTrainedModel(PreTrainedModel):
|
65 |
+
config_class = Qwen2MMConfig
|
66 |
+
base_model_prefix = "model"
|
67 |
+
supports_gradient_checkpointing = True
|
68 |
+
_supports_flash_attn_2 = True
|
69 |
+
_supports_sdpa = True
|
70 |
+
|
71 |
+
|
72 |
+
|
73 |
+
class Qwen2MMForConditionalGeneration(Qwen2MMPreTrainedModel, GenerationMixin):
|
74 |
+
|
75 |
+
def __init__(self, config):
|
76 |
+
super().__init__(config)
|
77 |
+
#self.audio_tower = SeamlessM4Tv2Model.from_pretrained("/mnt/diskhd/Backup/DownloadModel/seamless-m4t-v2-large/").speech_encoder
|
78 |
+
self.audio_tower = SeamlessM4Tv2SpeechEncoder(config.audio_config)
|
79 |
+
|
80 |
+
self.audio_projector = Qwen2AudioMultiModalProjector(config)
|
81 |
+
|
82 |
+
self.vocab_size = config.vocab_size
|
83 |
+
'''
|
84 |
+
tmp = AutoModelForCausalLM.from_pretrained("/mnt/diskhd/Backup/DownloadModel/Qwen2.5-7B-Instruct/")
|
85 |
+
self.language_model = tmp.model
|
86 |
+
self.lm_head = tmp.lm_head
|
87 |
+
'''
|
88 |
+
|
89 |
+
#self.language_model = AutoModelForCausalLM.from_pretrained("/mnt/diskhd/Backup/DownloadModel/Qwen2.5-7B-Instruct/")#.to("cuda")
|
90 |
+
#self.language_model = Qwen2ForCausalLM(config)
|
91 |
+
|
92 |
+
|
93 |
+
self.language_model = Qwen2Model(config)
|
94 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
95 |
+
|
96 |
+
|
97 |
+
self.padding_side = "left"
|
98 |
+
|
99 |
+
|
100 |
+
# Initialize weights and apply final processing
|
101 |
+
self.post_init()
|
102 |
+
|
103 |
+
|
104 |
+
# Copied from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration.get_input_embeddings
|
105 |
+
def get_input_embeddings(self):
|
106 |
+
return self.language_model.get_input_embeddings()
|
107 |
+
|
108 |
+
# Copied from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration.set_input_embeddings
|
109 |
+
def set_input_embeddings(self, value):
|
110 |
+
self.language_model.set_input_embeddings(value)
|
111 |
+
|
112 |
+
# Copied from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration.get_output_embeddings
|
113 |
+
def get_output_embeddings(self):
|
114 |
+
return self.language_model.get_output_embeddings()
|
115 |
+
|
116 |
+
# Copied from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration.set_output_embeddings
|
117 |
+
def set_output_embeddings(self, new_embeddings):
|
118 |
+
self.language_model.set_output_embeddings(new_embeddings)
|
119 |
+
'''
|
120 |
+
|
121 |
+
|
122 |
+
def get_input_embeddings(self):
|
123 |
+
return self.language_model.embed_tokens
|
124 |
+
|
125 |
+
def set_input_embeddings(self, value):
|
126 |
+
self.language_model.embed_tokens = value
|
127 |
+
|
128 |
+
def get_output_embeddings(self):
|
129 |
+
return self.lm_head
|
130 |
+
|
131 |
+
def set_output_embeddings(self, new_embeddings):
|
132 |
+
self.lm_head = new_embeddings
|
133 |
+
|
134 |
+
def set_decoder(self, decoder):
|
135 |
+
self.language_model = decoder
|
136 |
+
|
137 |
+
def get_decoder(self):
|
138 |
+
return self.language_model
|
139 |
+
|
140 |
+
'''
|
141 |
+
|
142 |
+
def _update_model_kwargs_for_generation(
|
143 |
+
self,
|
144 |
+
outputs: ModelOutput,
|
145 |
+
model_kwargs: Dict[str, Any],
|
146 |
+
is_encoder_decoder: bool = False,
|
147 |
+
num_new_tokens: int = 1,
|
148 |
+
) -> Dict[str, Any]:
|
149 |
+
model_kwargs = super()._update_model_kwargs_for_generation(
|
150 |
+
outputs=outputs,
|
151 |
+
model_kwargs=model_kwargs,
|
152 |
+
is_encoder_decoder=is_encoder_decoder,
|
153 |
+
num_new_tokens=num_new_tokens,
|
154 |
+
)
|
155 |
+
|
156 |
+
if getattr(outputs, "rope_deltas", None) is not None:
|
157 |
+
model_kwargs["rope_deltas"] = outputs.rope_deltas
|
158 |
+
|
159 |
+
return model_kwargs
|
160 |
+
|
161 |
+
|
162 |
+
def forward(
|
163 |
+
self,
|
164 |
+
input_ids: torch.LongTensor = None,
|
165 |
+
attention_mask: Optional[torch.Tensor] = None,
|
166 |
+
position_ids: Optional[torch.LongTensor] = None,
|
167 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
168 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
169 |
+
labels: Optional[torch.LongTensor] = None,
|
170 |
+
use_cache: Optional[bool] = None,
|
171 |
+
output_attentions: Optional[bool] = None,
|
172 |
+
output_hidden_states: Optional[bool] = None,
|
173 |
+
return_dict: Optional[bool] = None,
|
174 |
+
pixel_values: Optional[torch.Tensor] = None,
|
175 |
+
pixel_values_videos: Optional[torch.FloatTensor] = None,
|
176 |
+
audio_values: Optional[torch.Tensor] = None,
|
177 |
+
image_grid_thw: Optional[torch.LongTensor] = None,
|
178 |
+
video_grid_thw: Optional[torch.LongTensor] = None,
|
179 |
+
audio_grid_thw: Optional[torch.LongTensor] = None,
|
180 |
+
audio_attention_mask: Optional[torch.LongTensor] = None,
|
181 |
+
rope_deltas: Optional[torch.LongTensor] = None,
|
182 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
183 |
+
r"""
|
184 |
+
Args:
|
185 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
186 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
187 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
188 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
189 |
+
|
190 |
+
Returns:
|
191 |
+
|
192 |
+
Example:
|
193 |
+
|
194 |
+
```python
|
195 |
+
>>> from PIL import Image
|
196 |
+
>>> import requests
|
197 |
+
>>> from transformers import AutoProcessor, Qwen2VLForConditionalGeneration
|
198 |
+
|
199 |
+
>>> model = Qwen2VLForConditionalGeneration.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
|
200 |
+
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
|
201 |
+
|
202 |
+
>>> messages = [
|
203 |
+
{
|
204 |
+
"role": "user",
|
205 |
+
"content": [
|
206 |
+
{"type": "image"},
|
207 |
+
{"type": "text", "text": "What is shown in this image?"},
|
208 |
+
],
|
209 |
+
},
|
210 |
+
]
|
211 |
+
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
|
212 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
213 |
+
|
214 |
+
>>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
215 |
+
>>> inputs = processor(text=[text], images=[image], vision_infos=[vision_infos])
|
216 |
+
|
217 |
+
>>> # Generate
|
218 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
219 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
220 |
+
"The image shows a street scene with a red stop sign in the foreground. In the background, there is a large red gate with Chinese characters ..."
|
221 |
+
```"""
|
222 |
+
|
223 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
224 |
+
output_hidden_states = (
|
225 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
226 |
+
)
|
227 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
228 |
+
|
229 |
+
if inputs_embeds is None:
|
230 |
+
inputs_embeds = self.language_model.embed_tokens(input_ids)
|
231 |
+
if audio_values is not None:
|
232 |
+
audio_values = audio_values.type(self.audio_tower.dtype)
|
233 |
+
audio_embeds = self.audio_tower(input_features = audio_values, attention_mask = audio_attention_mask).last_hidden_state
|
234 |
+
audio_embeds = self.audio_projector(audio_embeds)
|
235 |
+
#print("audio_embeds: ", [audio_embeds.shape, audio_grid_thw])
|
236 |
+
|
237 |
+
tmp = []
|
238 |
+
for audio_embed, audio_token_num in zip(audio_embeds, audio_grid_thw):
|
239 |
+
#print(audio_token_num)
|
240 |
+
tmp.append(audio_embed[:audio_token_num, :])
|
241 |
+
audio_embeds = torch.cat(tmp)
|
242 |
+
|
243 |
+
|
244 |
+
n_audio_tokens = (input_ids == self.config.audio_token_id).sum().item()
|
245 |
+
n_audio_features = audio_embeds.shape[0]
|
246 |
+
if n_audio_tokens != n_audio_features:
|
247 |
+
print(
|
248 |
+
f"Audio features and audio tokens do not match: tokens: {n_audio_tokens}, features {n_audio_features}"
|
249 |
+
)
|
250 |
+
audio_mask = (
|
251 |
+
(input_ids == self.config.audio_token_id)
|
252 |
+
.unsqueeze(-1)
|
253 |
+
.expand_as(inputs_embeds)
|
254 |
+
.to(inputs_embeds.device)
|
255 |
+
)
|
256 |
+
audio_embeds = audio_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
|
257 |
+
inputs_embeds = inputs_embeds.masked_scatter(audio_mask, audio_embeds)
|
258 |
+
|
259 |
+
|
260 |
+
if attention_mask is not None:
|
261 |
+
attention_mask = attention_mask.to(inputs_embeds.device)
|
262 |
+
|
263 |
+
outputs = self.language_model(
|
264 |
+
attention_mask=attention_mask,
|
265 |
+
position_ids=position_ids,
|
266 |
+
past_key_values=past_key_values,
|
267 |
+
inputs_embeds=inputs_embeds,
|
268 |
+
use_cache=use_cache,
|
269 |
+
output_attentions=output_attentions,
|
270 |
+
output_hidden_states=output_hidden_states,
|
271 |
+
return_dict=return_dict,
|
272 |
+
)
|
273 |
+
#for name, param in self.language_model.named_parameters():
|
274 |
+
# print(f"Parameter name: {name}", f"Parameter shape: {param.shape} {param.dtype}")
|
275 |
+
|
276 |
+
|
277 |
+
hidden_states = outputs[0]
|
278 |
+
logits = self.lm_head(hidden_states)
|
279 |
+
#print("logits:", logits.shape)
|
280 |
+
|
281 |
+
|
282 |
+
loss = None
|
283 |
+
if labels is not None:
|
284 |
+
# Upcast to float if we need to compute the loss to avoid potential precision issues
|
285 |
+
logits = logits.float()
|
286 |
+
# Shift so that tokens < n predict n
|
287 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
288 |
+
shift_labels = labels[..., 1:].contiguous()
|
289 |
+
# Flatten the tokens
|
290 |
+
loss_fct = CrossEntropyLoss()
|
291 |
+
#print("shift_logits: ", shift_logits)
|
292 |
+
#print("shift_labels: ", shift_labels)
|
293 |
+
|
294 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
295 |
+
shift_labels = shift_labels.view(-1)
|
296 |
+
# Enable model parallelism
|
297 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
298 |
+
loss = loss_fct(shift_logits, shift_labels)
|
299 |
+
|
300 |
+
if not return_dict:
|
301 |
+
output = (logits,) + outputs[1:]
|
302 |
+
return (loss,) + output if loss is not None else output
|
303 |
+
|
304 |
+
return CausalLMOutputWithPast(
|
305 |
+
loss=loss,
|
306 |
+
logits=logits,
|
307 |
+
past_key_values=outputs.past_key_values,
|
308 |
+
hidden_states=outputs.hidden_states,
|
309 |
+
attentions=outputs.attentions,
|
310 |
+
)
|
311 |
+
|
312 |
+
|
313 |
+
|
314 |
+
def prepare_inputs_for_generation(
|
315 |
+
self,
|
316 |
+
input_ids,
|
317 |
+
past_key_values=None,
|
318 |
+
attention_mask=None,
|
319 |
+
inputs_embeds=None,
|
320 |
+
cache_position=None,
|
321 |
+
position_ids=None,
|
322 |
+
use_cache=True,
|
323 |
+
pixel_values=None,
|
324 |
+
pixel_values_videos=None,
|
325 |
+
audio_values=None,
|
326 |
+
image_grid_thw=None,
|
327 |
+
video_grid_thw=None,
|
328 |
+
audio_grid_thw=None,
|
329 |
+
audio_attention_mask=None,
|
330 |
+
**kwargs,
|
331 |
+
):
|
332 |
+
# Overwritten -- in specific circumstances we don't want to forward image inputs to the model
|
333 |
+
|
334 |
+
# If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
|
335 |
+
# Exception 1: when passing input_embeds, input_ids may be missing entries
|
336 |
+
# Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
|
337 |
+
if past_key_values is not None:
|
338 |
+
if inputs_embeds is not None: # Exception 1
|
339 |
+
input_ids = input_ids[:, -cache_position.shape[0] :]
|
340 |
+
elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
|
341 |
+
input_ids = input_ids[:, cache_position]
|
342 |
+
|
343 |
+
|
344 |
+
if cache_position[0] != 0:
|
345 |
+
pixel_values = None
|
346 |
+
pixel_values_videos = None
|
347 |
+
audio_values = None
|
348 |
+
|
349 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
350 |
+
if inputs_embeds is not None and cache_position[0] == 0:
|
351 |
+
model_inputs = {"inputs_embeds": inputs_embeds, "input_ids": None}
|
352 |
+
else:
|
353 |
+
model_inputs = {"input_ids": input_ids, "inputs_embeds": None}
|
354 |
+
|
355 |
+
|
356 |
+
model_inputs.update(
|
357 |
+
{
|
358 |
+
"position_ids": position_ids,
|
359 |
+
"past_key_values": past_key_values,
|
360 |
+
"use_cache": use_cache,
|
361 |
+
"attention_mask": attention_mask,
|
362 |
+
"pixel_values": pixel_values,
|
363 |
+
"pixel_values_videos": pixel_values_videos,
|
364 |
+
"audio_values": audio_values,
|
365 |
+
"image_grid_thw": image_grid_thw,
|
366 |
+
"video_grid_thw": video_grid_thw,
|
367 |
+
"audio_grid_thw": audio_grid_thw,
|
368 |
+
}
|
369 |
+
)
|
370 |
+
#print("model_inputs: ", model_inputs)
|
371 |
+
return model_inputs
|
preprocessor_config.json
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"audio_processor_type": "SeamlessM4TFeatureExtractor",
|
3 |
+
"auto_map": {
|
4 |
+
"AutoProcessor": "processing_qwen2_mm.Qwen2MMProcessor"
|
5 |
+
},
|
6 |
+
"do_convert_rgb": true,
|
7 |
+
"do_normalize": true,
|
8 |
+
"do_rescale": true,
|
9 |
+
"do_resize": true,
|
10 |
+
"feature_size": 80,
|
11 |
+
"image_mean": [
|
12 |
+
0.48145466,
|
13 |
+
0.4578275,
|
14 |
+
0.40821073
|
15 |
+
],
|
16 |
+
"image_processor_type": "Qwen2VLImageProcessor",
|
17 |
+
"image_std": [
|
18 |
+
0.26862954,
|
19 |
+
0.26130258,
|
20 |
+
0.27577711
|
21 |
+
],
|
22 |
+
"max_pixels": 12845056,
|
23 |
+
"merge_size": 2,
|
24 |
+
"min_pixels": 3136,
|
25 |
+
"num_mel_bins": 80,
|
26 |
+
"padding_side": "right",
|
27 |
+
"padding_value": 0.0,
|
28 |
+
"patch_size": 14,
|
29 |
+
"processor_class": "Qwen2MMProcessor",
|
30 |
+
"resample": 3,
|
31 |
+
"rescale_factor": 0.00392156862745098,
|
32 |
+
"return_attention_mask": true,
|
33 |
+
"sampling_rate": 16000,
|
34 |
+
"size": {
|
35 |
+
"max_pixels": 12845056,
|
36 |
+
"min_pixels": 3136
|
37 |
+
},
|
38 |
+
"stride": 2,
|
39 |
+
"temporal_patch_size": 2
|
40 |
+
}
|
processing_qwen2_mm.py
ADDED
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
5 |
+
# and OPT implementations in this library. It has been modified from its
|
6 |
+
# original forms to accommodate minor architectural differences compared
|
7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
8 |
+
#
|
9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
10 |
+
# you may not use this file except in compliance with the License.
|
11 |
+
# You may obtain a copy of the License at
|
12 |
+
#
|
13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
14 |
+
#
|
15 |
+
# Unless required by applicable law or agreed to in writing, software
|
16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
18 |
+
# See the License for the specific language governing permissions and
|
19 |
+
# limitations under the License.
|
20 |
+
"""
|
21 |
+
Processor class for Qwen2-VL.
|
22 |
+
"""
|
23 |
+
|
24 |
+
from typing import List, Union
|
25 |
+
|
26 |
+
from transformers.image_processing_utils import BatchFeature
|
27 |
+
from transformers.image_utils import ImageInput, VideoInput
|
28 |
+
from transformers.processing_utils import ProcessorMixin, ProcessingKwargs, Unpack
|
29 |
+
from transformers.tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy, AudioInput
|
30 |
+
from transformers.utils import TensorType, requires_backends, is_torch_dtype, is_torch_device, logging
|
31 |
+
|
32 |
+
import torch
|
33 |
+
logger = logging.get_logger(__name__)
|
34 |
+
|
35 |
+
|
36 |
+
class Qwen2VLProcessorKwargs(ProcessingKwargs, total=False):
|
37 |
+
_defaults = {
|
38 |
+
"text_kwargs": {
|
39 |
+
"padding": False,
|
40 |
+
},
|
41 |
+
}
|
42 |
+
|
43 |
+
|
44 |
+
class Qwen2MMProcessor(ProcessorMixin):
|
45 |
+
r"""
|
46 |
+
Constructs a Qwen2-VL processor which wraps a Qwen2-VL image processor and a Qwen2 tokenizer into a single processor.
|
47 |
+
[`Qwen2VLProcessor`] offers all the functionalities of [`Qwen2VLImageProcessor`] and [`Qwen2TokenizerFast`]. See the
|
48 |
+
[`~Qwen2VLProcessor.__call__`] and [`~Qwen2VLProcessor.decode`] for more information.
|
49 |
+
Args:
|
50 |
+
image_processor ([`Qwen2VLImageProcessor`], *optional*):
|
51 |
+
The image processor is a required input.
|
52 |
+
tokenizer ([`Qwen2TokenizerFast`], *optional*):
|
53 |
+
The tokenizer is a required input.
|
54 |
+
chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
|
55 |
+
in a chat into a tokenizable string.
|
56 |
+
"""
|
57 |
+
|
58 |
+
attributes = ["image_processor", "tokenizer", "audio_processor"]
|
59 |
+
valid_kwargs = ["chat_template"]
|
60 |
+
image_processor_class = "Qwen2VLImageProcessor"
|
61 |
+
audio_processor_class = "SeamlessM4TFeatureExtractor"
|
62 |
+
tokenizer_class = ("Qwen2Tokenizer", "Qwen2TokenizerFast")
|
63 |
+
|
64 |
+
def __init__(self, image_processor=None, tokenizer=None, audio_processor=None, chat_template=None, **kwargs):
|
65 |
+
super().__init__(image_processor, tokenizer, audio_processor, chat_template=chat_template)
|
66 |
+
#print("image_processor: ", image_processor)
|
67 |
+
#print("audio_processor: ", audio_processor)
|
68 |
+
|
69 |
+
|
70 |
+
def __call__(
|
71 |
+
self,
|
72 |
+
images: ImageInput = None,
|
73 |
+
text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
|
74 |
+
videos: VideoInput = None,
|
75 |
+
audios: AudioInput = None,
|
76 |
+
**kwargs: Unpack[Qwen2VLProcessorKwargs],
|
77 |
+
) -> BatchFeature:
|
78 |
+
"""
|
79 |
+
Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
|
80 |
+
and `kwargs` arguments to Qwen2TokenizerFast's [`~Qwen2TokenizerFast.__call__`] if `text` is not `None` to encode
|
81 |
+
the text. To prepare the vision inputs, this method forwards the `vision_infos` and `kwrags` arguments to
|
82 |
+
Qwen2VLImageProcessor's [`~Qwen2VLImageProcessor.__call__`] if `vision_infos` is not `None`.
|
83 |
+
|
84 |
+
Args:
|
85 |
+
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
|
86 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
87 |
+
tensor. Both channels-first and channels-last formats are supported.
|
88 |
+
text (`str`, `List[str]`, `List[List[str]]`):
|
89 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
90 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
91 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
92 |
+
videos (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`):
|
93 |
+
The image or batch of videos to be prepared. Each video can be a 4D NumPy array or PyTorch
|
94 |
+
tensor, or a nested list of 3D frames. Both channels-first and channels-last formats are supported.
|
95 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
96 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
97 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
98 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
99 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
100 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
101 |
+
|
102 |
+
Returns:
|
103 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
104 |
+
|
105 |
+
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
|
106 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
107 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
108 |
+
`None`).
|
109 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
110 |
+
- **pixel_values_videos** -- Pixel values of videos to be fed to a model. Returned when `videos` is not `None`.
|
111 |
+
- **image_grid_thw** -- List of image 3D grid in LLM. Returned when `images` is not `None`.
|
112 |
+
- **video_grid_thw** -- List of video 3D grid in LLM. Returned when `videos` is not `None`.
|
113 |
+
"""
|
114 |
+
output_kwargs = self._merge_kwargs(
|
115 |
+
Qwen2VLProcessorKwargs,
|
116 |
+
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
|
117 |
+
**kwargs,
|
118 |
+
)
|
119 |
+
if images is not None:
|
120 |
+
image_inputs = self.image_processor(images=images, videos=None, **output_kwargs["images_kwargs"])
|
121 |
+
image_grid_thw = image_inputs["image_grid_thw"]
|
122 |
+
else:
|
123 |
+
image_inputs = {}
|
124 |
+
image_grid_thw = None
|
125 |
+
|
126 |
+
if videos is not None:
|
127 |
+
videos_inputs = self.image_processor(images=None, videos=videos, **output_kwargs["videos_kwargs"])
|
128 |
+
video_grid_thw = videos_inputs["video_grid_thw"]
|
129 |
+
else:
|
130 |
+
videos_inputs = {}
|
131 |
+
video_grid_thw = None
|
132 |
+
|
133 |
+
if audios is not None:
|
134 |
+
print("audios: ", audios)
|
135 |
+
audio_inputs = self.audio_processor(audios, sampling_rate=16000, return_tensors="pt")
|
136 |
+
audio_grid_thw = torch.tensor([torch.sum(attention_mask == 1).item() // 8 + 1 for attention_mask in audio_inputs["attention_mask"]])
|
137 |
+
audio_inputs = {"audio_values": audio_inputs["input_features"], "audio_attention_mask": audio_inputs["attention_mask"], "audio_grid_thw": audio_grid_thw}
|
138 |
+
|
139 |
+
else:
|
140 |
+
audio_inputs = {}
|
141 |
+
audio_grid_thw = None
|
142 |
+
|
143 |
+
if not isinstance(text, list):
|
144 |
+
text = [text]
|
145 |
+
|
146 |
+
if image_grid_thw is not None:
|
147 |
+
merge_length = self.image_processor.merge_size**2
|
148 |
+
index = 0
|
149 |
+
for i in range(len(text)):
|
150 |
+
while "<|image_pad|>" in text[i]:
|
151 |
+
text[i] = text[i].replace(
|
152 |
+
"<|image_pad|>", "<|placeholder|>" * (image_grid_thw[index].prod() // merge_length), 1
|
153 |
+
)
|
154 |
+
index += 1
|
155 |
+
text[i] = text[i].replace("<|placeholder|>", "<|image_pad|>")
|
156 |
+
|
157 |
+
if video_grid_thw is not None:
|
158 |
+
merge_length = self.image_processor.merge_size**2
|
159 |
+
index = 0
|
160 |
+
for i in range(len(text)):
|
161 |
+
while "<|video_pad|>" in text[i]:
|
162 |
+
text[i] = text[i].replace(
|
163 |
+
"<|video_pad|>", "<|placeholder|>" * (video_grid_thw[index].prod() // merge_length), 1
|
164 |
+
)
|
165 |
+
index += 1
|
166 |
+
text[i] = text[i].replace("<|placeholder|>", "<|video_pad|>")
|
167 |
+
|
168 |
+
if audio_grid_thw is not None:
|
169 |
+
index = 0
|
170 |
+
for i in range(len(text)):
|
171 |
+
while "<|audio_pad|>" in text[i]:
|
172 |
+
text[i] = text[i].replace(
|
173 |
+
"<|audio_pad|>", "<|placeholder|>" * audio_grid_thw[index], 1
|
174 |
+
)
|
175 |
+
index += 1
|
176 |
+
text[i] = text[i].replace("<|placeholder|>", "<|audio_pad|>")
|
177 |
+
|
178 |
+
|
179 |
+
text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
|
180 |
+
|
181 |
+
return BatchFeature(data={**text_inputs, **image_inputs, **videos_inputs, **audio_inputs})
|
182 |
+
|
183 |
+
def batch_decode(self, *args, **kwargs):
|
184 |
+
"""
|
185 |
+
This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
|
186 |
+
refer to the docstring of this method for more information.
|
187 |
+
"""
|
188 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
189 |
+
|
190 |
+
def decode(self, *args, **kwargs):
|
191 |
+
"""
|
192 |
+
This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
|
193 |
+
the docstring of this method for more information.
|
194 |
+
"""
|
195 |
+
return self.tokenizer.decode(*args, **kwargs)
|
196 |
+
|
197 |
+
@property
|
198 |
+
def model_input_names(self):
|
199 |
+
tokenizer_input_names = self.tokenizer.model_input_names
|
200 |
+
image_processor_input_names = self.image_processor.model_input_names
|
201 |
+
audio_processor_input_names = self.audio_processor.model_input_names
|
202 |
+
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
|
special_tokens_map.json
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"additional_special_tokens": [
|
3 |
+
"<|im_start|>",
|
4 |
+
"<|im_end|>",
|
5 |
+
"<|object_ref_start|>",
|
6 |
+
"<|object_ref_end|>",
|
7 |
+
"<|box_start|>",
|
8 |
+
"<|box_end|>",
|
9 |
+
"<|quad_start|>",
|
10 |
+
"<|quad_end|>",
|
11 |
+
"<|vision_start|>",
|
12 |
+
"<|vision_end|>",
|
13 |
+
"<|vision_pad|>",
|
14 |
+
"<|image_pad|>",
|
15 |
+
"<|video_pad|>",
|
16 |
+
"<|audio_pad|>",
|
17 |
+
"<|audio_start|>",
|
18 |
+
"<|audio_end|>"
|
19 |
+
],
|
20 |
+
"eos_token": {
|
21 |
+
"content": "<|im_end|>",
|
22 |
+
"lstrip": false,
|
23 |
+
"normalized": false,
|
24 |
+
"rstrip": false,
|
25 |
+
"single_word": false
|
26 |
+
},
|
27 |
+
"pad_token": {
|
28 |
+
"content": "<|endoftext|>",
|
29 |
+
"lstrip": false,
|
30 |
+
"normalized": false,
|
31 |
+
"rstrip": false,
|
32 |
+
"single_word": false
|
33 |
+
}
|
34 |
+
}
|
tokenizer.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:26be3e5cc56af49a7e8179660a697ed62eb8808cdc8f086faa3c6e91037cb37b
|
3 |
+
size 11422468
|
tokenizer_config.json
ADDED
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_bos_token": false,
|
3 |
+
"add_prefix_space": false,
|
4 |
+
"added_tokens_decoder": {
|
5 |
+
"151643": {
|
6 |
+
"content": "<|endoftext|>",
|
7 |
+
"lstrip": false,
|
8 |
+
"normalized": false,
|
9 |
+
"rstrip": false,
|
10 |
+
"single_word": false,
|
11 |
+
"special": true
|
12 |
+
},
|
13 |
+
"151644": {
|
14 |
+
"content": "<|im_start|>",
|
15 |
+
"lstrip": false,
|
16 |
+
"normalized": false,
|
17 |
+
"rstrip": false,
|
18 |
+
"single_word": false,
|
19 |
+
"special": true
|
20 |
+
},
|
21 |
+
"151645": {
|
22 |
+
"content": "<|im_end|>",
|
23 |
+
"lstrip": false,
|
24 |
+
"normalized": false,
|
25 |
+
"rstrip": false,
|
26 |
+
"single_word": false,
|
27 |
+
"special": true
|
28 |
+
},
|
29 |
+
"151646": {
|
30 |
+
"content": "<|object_ref_start|>",
|
31 |
+
"lstrip": false,
|
32 |
+
"normalized": false,
|
33 |
+
"rstrip": false,
|
34 |
+
"single_word": false,
|
35 |
+
"special": true
|
36 |
+
},
|
37 |
+
"151647": {
|
38 |
+
"content": "<|object_ref_end|>",
|
39 |
+
"lstrip": false,
|
40 |
+
"normalized": false,
|
41 |
+
"rstrip": false,
|
42 |
+
"single_word": false,
|
43 |
+
"special": true
|
44 |
+
},
|
45 |
+
"151648": {
|
46 |
+
"content": "<|box_start|>",
|
47 |
+
"lstrip": false,
|
48 |
+
"normalized": false,
|
49 |
+
"rstrip": false,
|
50 |
+
"single_word": false,
|
51 |
+
"special": true
|
52 |
+
},
|
53 |
+
"151649": {
|
54 |
+
"content": "<|box_end|>",
|
55 |
+
"lstrip": false,
|
56 |
+
"normalized": false,
|
57 |
+
"rstrip": false,
|
58 |
+
"single_word": false,
|
59 |
+
"special": true
|
60 |
+
},
|
61 |
+
"151650": {
|
62 |
+
"content": "<|quad_start|>",
|
63 |
+
"lstrip": false,
|
64 |
+
"normalized": false,
|
65 |
+
"rstrip": false,
|
66 |
+
"single_word": false,
|
67 |
+
"special": true
|
68 |
+
},
|
69 |
+
"151651": {
|
70 |
+
"content": "<|quad_end|>",
|
71 |
+
"lstrip": false,
|
72 |
+
"normalized": false,
|
73 |
+
"rstrip": false,
|
74 |
+
"single_word": false,
|
75 |
+
"special": true
|
76 |
+
},
|
77 |
+
"151652": {
|
78 |
+
"content": "<|vision_start|>",
|
79 |
+
"lstrip": false,
|
80 |
+
"normalized": false,
|
81 |
+
"rstrip": false,
|
82 |
+
"single_word": false,
|
83 |
+
"special": true
|
84 |
+
},
|
85 |
+
"151653": {
|
86 |
+
"content": "<|vision_end|>",
|
87 |
+
"lstrip": false,
|
88 |
+
"normalized": false,
|
89 |
+
"rstrip": false,
|
90 |
+
"single_word": false,
|
91 |
+
"special": true
|
92 |
+
},
|
93 |
+
"151654": {
|
94 |
+
"content": "<|vision_pad|>",
|
95 |
+
"lstrip": false,
|
96 |
+
"normalized": false,
|
97 |
+
"rstrip": false,
|
98 |
+
"single_word": false,
|
99 |
+
"special": true
|
100 |
+
},
|
101 |
+
"151655": {
|
102 |
+
"content": "<|image_pad|>",
|
103 |
+
"lstrip": false,
|
104 |
+
"normalized": false,
|
105 |
+
"rstrip": false,
|
106 |
+
"single_word": false,
|
107 |
+
"special": true
|
108 |
+
},
|
109 |
+
"151656": {
|
110 |
+
"content": "<|video_pad|>",
|
111 |
+
"lstrip": false,
|
112 |
+
"normalized": false,
|
113 |
+
"rstrip": false,
|
114 |
+
"single_word": false,
|
115 |
+
"special": true
|
116 |
+
},
|
117 |
+
"151657": {
|
118 |
+
"content": "<tool_call>",
|
119 |
+
"lstrip": false,
|
120 |
+
"normalized": false,
|
121 |
+
"rstrip": false,
|
122 |
+
"single_word": false,
|
123 |
+
"special": false
|
124 |
+
},
|
125 |
+
"151658": {
|
126 |
+
"content": "</tool_call>",
|
127 |
+
"lstrip": false,
|
128 |
+
"normalized": false,
|
129 |
+
"rstrip": false,
|
130 |
+
"single_word": false,
|
131 |
+
"special": false
|
132 |
+
},
|
133 |
+
"151659": {
|
134 |
+
"content": "<|fim_prefix|>",
|
135 |
+
"lstrip": false,
|
136 |
+
"normalized": false,
|
137 |
+
"rstrip": false,
|
138 |
+
"single_word": false,
|
139 |
+
"special": false
|
140 |
+
},
|
141 |
+
"151660": {
|
142 |
+
"content": "<|fim_middle|>",
|
143 |
+
"lstrip": false,
|
144 |
+
"normalized": false,
|
145 |
+
"rstrip": false,
|
146 |
+
"single_word": false,
|
147 |
+
"special": false
|
148 |
+
},
|
149 |
+
"151661": {
|
150 |
+
"content": "<|fim_suffix|>",
|
151 |
+
"lstrip": false,
|
152 |
+
"normalized": false,
|
153 |
+
"rstrip": false,
|
154 |
+
"single_word": false,
|
155 |
+
"special": false
|
156 |
+
},
|
157 |
+
"151662": {
|
158 |
+
"content": "<|fim_pad|>",
|
159 |
+
"lstrip": false,
|
160 |
+
"normalized": false,
|
161 |
+
"rstrip": false,
|
162 |
+
"single_word": false,
|
163 |
+
"special": false
|
164 |
+
},
|
165 |
+
"151663": {
|
166 |
+
"content": "<|repo_name|>",
|
167 |
+
"lstrip": false,
|
168 |
+
"normalized": false,
|
169 |
+
"rstrip": false,
|
170 |
+
"single_word": false,
|
171 |
+
"special": false
|
172 |
+
},
|
173 |
+
"151664": {
|
174 |
+
"content": "<|file_sep|>",
|
175 |
+
"lstrip": false,
|
176 |
+
"normalized": false,
|
177 |
+
"rstrip": false,
|
178 |
+
"single_word": false,
|
179 |
+
"special": false
|
180 |
+
},
|
181 |
+
"151665": {
|
182 |
+
"content": "<|audio_pad|>",
|
183 |
+
"lstrip": false,
|
184 |
+
"normalized": false,
|
185 |
+
"rstrip": false,
|
186 |
+
"single_word": false,
|
187 |
+
"special": true
|
188 |
+
},
|
189 |
+
"151666": {
|
190 |
+
"content": "<|audio_start|>",
|
191 |
+
"lstrip": false,
|
192 |
+
"normalized": false,
|
193 |
+
"rstrip": false,
|
194 |
+
"single_word": false,
|
195 |
+
"special": true
|
196 |
+
},
|
197 |
+
"151667": {
|
198 |
+
"content": "<|audio_end|>",
|
199 |
+
"lstrip": false,
|
200 |
+
"normalized": false,
|
201 |
+
"rstrip": false,
|
202 |
+
"single_word": false,
|
203 |
+
"special": true
|
204 |
+
}
|
205 |
+
},
|
206 |
+
"additional_special_tokens": [
|
207 |
+
"<|im_start|>",
|
208 |
+
"<|im_end|>",
|
209 |
+
"<|object_ref_start|>",
|
210 |
+
"<|object_ref_end|>",
|
211 |
+
"<|box_start|>",
|
212 |
+
"<|box_end|>",
|
213 |
+
"<|quad_start|>",
|
214 |
+
"<|quad_end|>",
|
215 |
+
"<|vision_start|>",
|
216 |
+
"<|vision_end|>",
|
217 |
+
"<|vision_pad|>",
|
218 |
+
"<|image_pad|>",
|
219 |
+
"<|video_pad|>",
|
220 |
+
"<|audio_pad|>",
|
221 |
+
"<|audio_start|>",
|
222 |
+
"<|audio_end|>"
|
223 |
+
],
|
224 |
+
"bos_token": null,
|
225 |
+
"chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0]['role'] == 'system' %}\n {{- messages[0]['content'] }}\n {%- else %}\n {{- 'You are Qwen, created by Alibaba Cloud. You are a helpful assistant.' }}\n {%- endif %}\n {{- \"\\n\\n# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0]['role'] == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0]['content'] + '<|im_end|>\\n' }}\n {%- else %}\n {{- '<|im_start|>system\\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- for message in messages %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) or (message.role == \"assistant\" and not message.tool_calls) %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {{- '<|im_start|>' + message.role }}\n {%- if message.content %}\n {{- '\\n' + message.content }}\n {%- endif %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '\\n<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {{- tool_call.arguments | tojson }}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}\n",
|
226 |
+
"clean_up_tokenization_spaces": false,
|
227 |
+
"eos_token": "<|im_end|>",
|
228 |
+
"errors": "replace",
|
229 |
+
"model_max_length": 131072,
|
230 |
+
"pad_token": "<|endoftext|>",
|
231 |
+
"padding_side": "right",
|
232 |
+
"split_special_tokens": false,
|
233 |
+
"tokenizer_class": "Qwen2Tokenizer",
|
234 |
+
"unk_token": null
|
235 |
+
}
|
trainer_state.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
training_args.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:38fed174c068c00c7bc9a0279312ca2eaa70226fb1aa27ec7e01ad0e7102f2e9
|
3 |
+
size 6520
|
vocab.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
zero_to_fp32.py
ADDED
@@ -0,0 +1,604 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
|
3 |
+
# Copyright (c) Microsoft Corporation.
|
4 |
+
# SPDX-License-Identifier: Apache-2.0
|
5 |
+
|
6 |
+
# DeepSpeed Team
|
7 |
+
|
8 |
+
# This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets
|
9 |
+
# copied into the top level checkpoint dir, so the user can easily do the conversion at any point in
|
10 |
+
# the future. Once extracted, the weights don't require DeepSpeed and can be used in any
|
11 |
+
# application.
|
12 |
+
#
|
13 |
+
# example: python zero_to_fp32.py . pytorch_model.bin
|
14 |
+
|
15 |
+
import argparse
|
16 |
+
import torch
|
17 |
+
import glob
|
18 |
+
import math
|
19 |
+
import os
|
20 |
+
import re
|
21 |
+
from collections import OrderedDict
|
22 |
+
from dataclasses import dataclass
|
23 |
+
|
24 |
+
# while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with
|
25 |
+
# DeepSpeed data structures it has to be available in the current python environment.
|
26 |
+
from deepspeed.utils import logger
|
27 |
+
from deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS,
|
28 |
+
FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES,
|
29 |
+
FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
|
30 |
+
|
31 |
+
|
32 |
+
@dataclass
|
33 |
+
class zero_model_state:
|
34 |
+
buffers: dict()
|
35 |
+
param_shapes: dict()
|
36 |
+
shared_params: list
|
37 |
+
ds_version: int
|
38 |
+
frozen_param_shapes: dict()
|
39 |
+
frozen_param_fragments: dict()
|
40 |
+
|
41 |
+
|
42 |
+
debug = 0
|
43 |
+
|
44 |
+
# load to cpu
|
45 |
+
device = torch.device('cpu')
|
46 |
+
|
47 |
+
|
48 |
+
def atoi(text):
|
49 |
+
return int(text) if text.isdigit() else text
|
50 |
+
|
51 |
+
|
52 |
+
def natural_keys(text):
|
53 |
+
'''
|
54 |
+
alist.sort(key=natural_keys) sorts in human order
|
55 |
+
http://nedbatchelder.com/blog/200712/human_sorting.html
|
56 |
+
(See Toothy's implementation in the comments)
|
57 |
+
'''
|
58 |
+
return [atoi(c) for c in re.split(r'(\d+)', text)]
|
59 |
+
|
60 |
+
|
61 |
+
def get_model_state_file(checkpoint_dir, zero_stage):
|
62 |
+
if not os.path.isdir(checkpoint_dir):
|
63 |
+
raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
|
64 |
+
|
65 |
+
# there should be only one file
|
66 |
+
if zero_stage <= 2:
|
67 |
+
file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt")
|
68 |
+
elif zero_stage == 3:
|
69 |
+
file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
|
70 |
+
|
71 |
+
if not os.path.exists(file):
|
72 |
+
raise FileNotFoundError(f"can't find model states file at '{file}'")
|
73 |
+
|
74 |
+
return file
|
75 |
+
|
76 |
+
|
77 |
+
def get_checkpoint_files(checkpoint_dir, glob_pattern):
|
78 |
+
# XXX: need to test that this simple glob rule works for multi-node setup too
|
79 |
+
ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
|
80 |
+
|
81 |
+
if len(ckpt_files) == 0:
|
82 |
+
raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
|
83 |
+
|
84 |
+
return ckpt_files
|
85 |
+
|
86 |
+
|
87 |
+
def get_optim_files(checkpoint_dir):
|
88 |
+
return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
|
89 |
+
|
90 |
+
|
91 |
+
def get_model_state_files(checkpoint_dir):
|
92 |
+
return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
|
93 |
+
|
94 |
+
|
95 |
+
def parse_model_states(files):
|
96 |
+
zero_model_states = []
|
97 |
+
for file in files:
|
98 |
+
state_dict = torch.load(file, map_location=device)
|
99 |
+
|
100 |
+
if BUFFER_NAMES not in state_dict:
|
101 |
+
raise ValueError(f"{file} is not a model state checkpoint")
|
102 |
+
buffer_names = state_dict[BUFFER_NAMES]
|
103 |
+
if debug:
|
104 |
+
print("Found buffers:", buffer_names)
|
105 |
+
|
106 |
+
# recover just the buffers while restoring them to fp32 if they were saved in fp16
|
107 |
+
buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names}
|
108 |
+
param_shapes = state_dict[PARAM_SHAPES]
|
109 |
+
|
110 |
+
# collect parameters that are included in param_shapes
|
111 |
+
param_names = []
|
112 |
+
for s in param_shapes:
|
113 |
+
for name in s.keys():
|
114 |
+
param_names.append(name)
|
115 |
+
|
116 |
+
# update with frozen parameters
|
117 |
+
frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None)
|
118 |
+
if frozen_param_shapes is not None:
|
119 |
+
if debug:
|
120 |
+
print(f"Found frozen_param_shapes: {frozen_param_shapes}")
|
121 |
+
param_names += list(frozen_param_shapes.keys())
|
122 |
+
|
123 |
+
# handle shared params
|
124 |
+
shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
|
125 |
+
|
126 |
+
ds_version = state_dict.get(DS_VERSION, None)
|
127 |
+
|
128 |
+
frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
|
129 |
+
|
130 |
+
z_model_state = zero_model_state(buffers=buffers,
|
131 |
+
param_shapes=param_shapes,
|
132 |
+
shared_params=shared_params,
|
133 |
+
ds_version=ds_version,
|
134 |
+
frozen_param_shapes=frozen_param_shapes,
|
135 |
+
frozen_param_fragments=frozen_param_fragments)
|
136 |
+
zero_model_states.append(z_model_state)
|
137 |
+
|
138 |
+
return zero_model_states
|
139 |
+
|
140 |
+
|
141 |
+
def parse_optim_states(files, ds_checkpoint_dir):
|
142 |
+
|
143 |
+
total_files = len(files)
|
144 |
+
state_dicts = []
|
145 |
+
for f in files:
|
146 |
+
state_dict = torch.load(f, map_location=device)
|
147 |
+
# immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights
|
148 |
+
# and also handle the case where it was already removed by another helper script
|
149 |
+
state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None)
|
150 |
+
state_dicts.append(state_dict)
|
151 |
+
|
152 |
+
if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]:
|
153 |
+
raise ValueError(f"{files[0]} is not a zero checkpoint")
|
154 |
+
zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE]
|
155 |
+
world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
|
156 |
+
|
157 |
+
# For ZeRO-2 each param group can have different partition_count as data parallelism for expert
|
158 |
+
# parameters can be different from data parallelism for non-expert parameters. So we can just
|
159 |
+
# use the max of the partition_count to get the dp world_size.
|
160 |
+
|
161 |
+
if type(world_size) is list:
|
162 |
+
world_size = max(world_size)
|
163 |
+
|
164 |
+
if world_size != total_files:
|
165 |
+
raise ValueError(
|
166 |
+
f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. "
|
167 |
+
"Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes."
|
168 |
+
)
|
169 |
+
|
170 |
+
# the groups are named differently in each stage
|
171 |
+
if zero_stage <= 2:
|
172 |
+
fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS
|
173 |
+
elif zero_stage == 3:
|
174 |
+
fp32_groups_key = FP32_FLAT_GROUPS
|
175 |
+
else:
|
176 |
+
raise ValueError(f"unknown zero stage {zero_stage}")
|
177 |
+
|
178 |
+
if zero_stage <= 2:
|
179 |
+
fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))]
|
180 |
+
elif zero_stage == 3:
|
181 |
+
# if there is more than one param group, there will be multiple flattened tensors - one
|
182 |
+
# flattened tensor per group - for simplicity merge them into a single tensor
|
183 |
+
#
|
184 |
+
# XXX: could make the script more memory efficient for when there are multiple groups - it
|
185 |
+
# will require matching the sub-lists of param_shapes for each param group flattened tensor
|
186 |
+
|
187 |
+
fp32_flat_groups = [
|
188 |
+
torch.cat(state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key], 0) for i in range(len(state_dicts))
|
189 |
+
]
|
190 |
+
|
191 |
+
return zero_stage, world_size, fp32_flat_groups
|
192 |
+
|
193 |
+
|
194 |
+
def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters):
|
195 |
+
"""
|
196 |
+
Returns fp32 state_dict reconstructed from ds checkpoint
|
197 |
+
|
198 |
+
Args:
|
199 |
+
- ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
|
200 |
+
|
201 |
+
"""
|
202 |
+
print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
|
203 |
+
|
204 |
+
optim_files = get_optim_files(ds_checkpoint_dir)
|
205 |
+
zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir)
|
206 |
+
print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
|
207 |
+
|
208 |
+
model_files = get_model_state_files(ds_checkpoint_dir)
|
209 |
+
|
210 |
+
zero_model_states = parse_model_states(model_files)
|
211 |
+
print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
|
212 |
+
|
213 |
+
if zero_stage <= 2:
|
214 |
+
return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
|
215 |
+
exclude_frozen_parameters)
|
216 |
+
elif zero_stage == 3:
|
217 |
+
return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
|
218 |
+
exclude_frozen_parameters)
|
219 |
+
|
220 |
+
|
221 |
+
def _zero2_merge_frozen_params(state_dict, zero_model_states):
|
222 |
+
if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
|
223 |
+
return
|
224 |
+
|
225 |
+
frozen_param_shapes = zero_model_states[0].frozen_param_shapes
|
226 |
+
frozen_param_fragments = zero_model_states[0].frozen_param_fragments
|
227 |
+
|
228 |
+
if debug:
|
229 |
+
num_elem = sum(s.numel() for s in frozen_param_shapes.values())
|
230 |
+
print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
|
231 |
+
|
232 |
+
wanted_params = len(frozen_param_shapes)
|
233 |
+
wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
|
234 |
+
avail_numel = sum([p.numel() for p in frozen_param_fragments.values()])
|
235 |
+
print(f'Frozen params: Have {avail_numel} numels to process.')
|
236 |
+
print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
|
237 |
+
|
238 |
+
total_params = 0
|
239 |
+
total_numel = 0
|
240 |
+
for name, shape in frozen_param_shapes.items():
|
241 |
+
total_params += 1
|
242 |
+
unpartitioned_numel = shape.numel()
|
243 |
+
total_numel += unpartitioned_numel
|
244 |
+
|
245 |
+
state_dict[name] = frozen_param_fragments[name]
|
246 |
+
|
247 |
+
if debug:
|
248 |
+
print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
|
249 |
+
|
250 |
+
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
|
251 |
+
|
252 |
+
|
253 |
+
def _has_callable(obj, fn):
|
254 |
+
attr = getattr(obj, fn, None)
|
255 |
+
return callable(attr)
|
256 |
+
|
257 |
+
|
258 |
+
def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
|
259 |
+
param_shapes = zero_model_states[0].param_shapes
|
260 |
+
|
261 |
+
# Reconstruction protocol:
|
262 |
+
#
|
263 |
+
# XXX: document this
|
264 |
+
|
265 |
+
if debug:
|
266 |
+
for i in range(world_size):
|
267 |
+
for j in range(len(fp32_flat_groups[0])):
|
268 |
+
print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
|
269 |
+
|
270 |
+
# XXX: memory usage doubles here (zero2)
|
271 |
+
num_param_groups = len(fp32_flat_groups[0])
|
272 |
+
merged_single_partition_of_fp32_groups = []
|
273 |
+
for i in range(num_param_groups):
|
274 |
+
merged_partitions = [sd[i] for sd in fp32_flat_groups]
|
275 |
+
full_single_fp32_vector = torch.cat(merged_partitions, 0)
|
276 |
+
merged_single_partition_of_fp32_groups.append(full_single_fp32_vector)
|
277 |
+
avail_numel = sum(
|
278 |
+
[full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
|
279 |
+
|
280 |
+
if debug:
|
281 |
+
wanted_params = sum([len(shapes) for shapes in param_shapes])
|
282 |
+
wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes])
|
283 |
+
# not asserting if there is a mismatch due to possible padding
|
284 |
+
print(f"Have {avail_numel} numels to process.")
|
285 |
+
print(f"Need {wanted_numel} numels in {wanted_params} params.")
|
286 |
+
|
287 |
+
# params
|
288 |
+
# XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
|
289 |
+
# out-of-core computing solution
|
290 |
+
total_numel = 0
|
291 |
+
total_params = 0
|
292 |
+
for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups):
|
293 |
+
offset = 0
|
294 |
+
avail_numel = full_single_fp32_vector.numel()
|
295 |
+
for name, shape in shapes.items():
|
296 |
+
|
297 |
+
unpartitioned_numel = shape.numel() if _has_callable(shape, 'numel') else math.prod(shape)
|
298 |
+
total_numel += unpartitioned_numel
|
299 |
+
total_params += 1
|
300 |
+
|
301 |
+
if debug:
|
302 |
+
print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
|
303 |
+
state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape)
|
304 |
+
offset += unpartitioned_numel
|
305 |
+
|
306 |
+
# Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and
|
307 |
+
# avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex
|
308 |
+
# paddings performed in the code it's almost impossible to predict the exact numbers w/o the
|
309 |
+
# live optimizer object, so we are checking that the numbers are within the right range
|
310 |
+
align_to = 2 * world_size
|
311 |
+
|
312 |
+
def zero2_align(x):
|
313 |
+
return align_to * math.ceil(x / align_to)
|
314 |
+
|
315 |
+
if debug:
|
316 |
+
print(f"original offset={offset}, avail_numel={avail_numel}")
|
317 |
+
|
318 |
+
offset = zero2_align(offset)
|
319 |
+
avail_numel = zero2_align(avail_numel)
|
320 |
+
|
321 |
+
if debug:
|
322 |
+
print(f"aligned offset={offset}, avail_numel={avail_numel}")
|
323 |
+
|
324 |
+
# Sanity check
|
325 |
+
if offset != avail_numel:
|
326 |
+
raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
|
327 |
+
|
328 |
+
print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
|
329 |
+
|
330 |
+
|
331 |
+
def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
|
332 |
+
exclude_frozen_parameters):
|
333 |
+
state_dict = OrderedDict()
|
334 |
+
|
335 |
+
# buffers
|
336 |
+
buffers = zero_model_states[0].buffers
|
337 |
+
state_dict.update(buffers)
|
338 |
+
if debug:
|
339 |
+
print(f"added {len(buffers)} buffers")
|
340 |
+
|
341 |
+
if not exclude_frozen_parameters:
|
342 |
+
_zero2_merge_frozen_params(state_dict, zero_model_states)
|
343 |
+
|
344 |
+
_zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
|
345 |
+
|
346 |
+
# recover shared parameters
|
347 |
+
for pair in zero_model_states[0].shared_params:
|
348 |
+
if pair[1] in state_dict:
|
349 |
+
state_dict[pair[0]] = state_dict[pair[1]]
|
350 |
+
|
351 |
+
return state_dict
|
352 |
+
|
353 |
+
|
354 |
+
def zero3_partitioned_param_info(unpartitioned_numel, world_size):
|
355 |
+
remainder = unpartitioned_numel % world_size
|
356 |
+
padding_numel = (world_size - remainder) if remainder else 0
|
357 |
+
partitioned_numel = math.ceil(unpartitioned_numel / world_size)
|
358 |
+
return partitioned_numel, padding_numel
|
359 |
+
|
360 |
+
|
361 |
+
def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states):
|
362 |
+
if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
|
363 |
+
return
|
364 |
+
|
365 |
+
if debug:
|
366 |
+
for i in range(world_size):
|
367 |
+
num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values())
|
368 |
+
print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
|
369 |
+
|
370 |
+
frozen_param_shapes = zero_model_states[0].frozen_param_shapes
|
371 |
+
wanted_params = len(frozen_param_shapes)
|
372 |
+
wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
|
373 |
+
avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size
|
374 |
+
print(f'Frozen params: Have {avail_numel} numels to process.')
|
375 |
+
print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
|
376 |
+
|
377 |
+
total_params = 0
|
378 |
+
total_numel = 0
|
379 |
+
for name, shape in zero_model_states[0].frozen_param_shapes.items():
|
380 |
+
total_params += 1
|
381 |
+
unpartitioned_numel = shape.numel()
|
382 |
+
total_numel += unpartitioned_numel
|
383 |
+
|
384 |
+
param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states)
|
385 |
+
state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
|
386 |
+
|
387 |
+
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
|
388 |
+
|
389 |
+
if debug:
|
390 |
+
print(
|
391 |
+
f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
|
392 |
+
)
|
393 |
+
|
394 |
+
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
|
395 |
+
|
396 |
+
|
397 |
+
def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
|
398 |
+
param_shapes = zero_model_states[0].param_shapes
|
399 |
+
avail_numel = fp32_flat_groups[0].numel() * world_size
|
400 |
+
# Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each
|
401 |
+
# param, re-consolidating each param, while dealing with padding if any
|
402 |
+
|
403 |
+
# merge list of dicts, preserving order
|
404 |
+
param_shapes = {k: v for d in param_shapes for k, v in d.items()}
|
405 |
+
|
406 |
+
if debug:
|
407 |
+
for i in range(world_size):
|
408 |
+
print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
|
409 |
+
|
410 |
+
wanted_params = len(param_shapes)
|
411 |
+
wanted_numel = sum(shape.numel() for shape in param_shapes.values())
|
412 |
+
# not asserting if there is a mismatch due to possible padding
|
413 |
+
avail_numel = fp32_flat_groups[0].numel() * world_size
|
414 |
+
print(f"Trainable params: Have {avail_numel} numels to process.")
|
415 |
+
print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
|
416 |
+
|
417 |
+
# params
|
418 |
+
# XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
|
419 |
+
# out-of-core computing solution
|
420 |
+
offset = 0
|
421 |
+
total_numel = 0
|
422 |
+
total_params = 0
|
423 |
+
for name, shape in param_shapes.items():
|
424 |
+
|
425 |
+
unpartitioned_numel = shape.numel()
|
426 |
+
total_numel += unpartitioned_numel
|
427 |
+
total_params += 1
|
428 |
+
|
429 |
+
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
|
430 |
+
|
431 |
+
if debug:
|
432 |
+
print(
|
433 |
+
f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
|
434 |
+
)
|
435 |
+
|
436 |
+
# XXX: memory usage doubles here
|
437 |
+
state_dict[name] = torch.cat(
|
438 |
+
tuple(fp32_flat_groups[i].narrow(0, offset, partitioned_numel) for i in range(world_size)),
|
439 |
+
0).narrow(0, 0, unpartitioned_numel).view(shape)
|
440 |
+
offset += partitioned_numel
|
441 |
+
|
442 |
+
offset *= world_size
|
443 |
+
|
444 |
+
# Sanity check
|
445 |
+
if offset != avail_numel:
|
446 |
+
raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
|
447 |
+
|
448 |
+
print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
|
449 |
+
|
450 |
+
|
451 |
+
def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
|
452 |
+
exclude_frozen_parameters):
|
453 |
+
state_dict = OrderedDict()
|
454 |
+
|
455 |
+
# buffers
|
456 |
+
buffers = zero_model_states[0].buffers
|
457 |
+
state_dict.update(buffers)
|
458 |
+
if debug:
|
459 |
+
print(f"added {len(buffers)} buffers")
|
460 |
+
|
461 |
+
if not exclude_frozen_parameters:
|
462 |
+
_zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
|
463 |
+
|
464 |
+
_zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
|
465 |
+
|
466 |
+
# recover shared parameters
|
467 |
+
for pair in zero_model_states[0].shared_params:
|
468 |
+
if pair[1] in state_dict:
|
469 |
+
state_dict[pair[0]] = state_dict[pair[1]]
|
470 |
+
|
471 |
+
return state_dict
|
472 |
+
|
473 |
+
|
474 |
+
def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag=None, exclude_frozen_parameters=False):
|
475 |
+
"""
|
476 |
+
Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with
|
477 |
+
``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example
|
478 |
+
via a model hub.
|
479 |
+
|
480 |
+
Args:
|
481 |
+
- ``checkpoint_dir``: path to the desired checkpoint folder
|
482 |
+
- ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in 'latest' file. e.g., ``global_step14``
|
483 |
+
- ``exclude_frozen_parameters``: exclude frozen parameters
|
484 |
+
|
485 |
+
Returns:
|
486 |
+
- pytorch ``state_dict``
|
487 |
+
|
488 |
+
Note: this approach may not work if your application doesn't have sufficient free CPU memory and
|
489 |
+
you may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with
|
490 |
+
the checkpoint.
|
491 |
+
|
492 |
+
A typical usage might be ::
|
493 |
+
|
494 |
+
from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
|
495 |
+
# do the training and checkpoint saving
|
496 |
+
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu
|
497 |
+
model = model.cpu() # move to cpu
|
498 |
+
model.load_state_dict(state_dict)
|
499 |
+
# submit to model hub or save the model to share with others
|
500 |
+
|
501 |
+
In this example the ``model`` will no longer be usable in the deepspeed context of the same
|
502 |
+
application. i.e. you will need to re-initialize the deepspeed engine, since
|
503 |
+
``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
|
504 |
+
|
505 |
+
If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
|
506 |
+
|
507 |
+
"""
|
508 |
+
if tag is None:
|
509 |
+
latest_path = os.path.join(checkpoint_dir, 'latest')
|
510 |
+
if os.path.isfile(latest_path):
|
511 |
+
with open(latest_path, 'r') as fd:
|
512 |
+
tag = fd.read().strip()
|
513 |
+
else:
|
514 |
+
raise ValueError(f"Unable to find 'latest' file at {latest_path}")
|
515 |
+
|
516 |
+
ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
|
517 |
+
|
518 |
+
if not os.path.isdir(ds_checkpoint_dir):
|
519 |
+
raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
|
520 |
+
|
521 |
+
return _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters)
|
522 |
+
|
523 |
+
|
524 |
+
def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir, output_file, tag=None, exclude_frozen_parameters=False):
|
525 |
+
"""
|
526 |
+
Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be
|
527 |
+
loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
|
528 |
+
|
529 |
+
Args:
|
530 |
+
- ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
|
531 |
+
- ``output_file``: path to the pytorch fp32 state_dict output file (e.g. path/pytorch_model.bin)
|
532 |
+
- ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
|
533 |
+
- ``exclude_frozen_parameters``: exclude frozen parameters
|
534 |
+
"""
|
535 |
+
|
536 |
+
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag, exclude_frozen_parameters)
|
537 |
+
print(f"Saving fp32 state dict to {output_file}")
|
538 |
+
torch.save(state_dict, output_file)
|
539 |
+
|
540 |
+
|
541 |
+
def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None):
|
542 |
+
"""
|
543 |
+
1. Put the provided model to cpu
|
544 |
+
2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict``
|
545 |
+
3. Load it into the provided model
|
546 |
+
|
547 |
+
Args:
|
548 |
+
- ``model``: the model object to update
|
549 |
+
- ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
|
550 |
+
- ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
|
551 |
+
|
552 |
+
Returns:
|
553 |
+
- ``model`: modified model
|
554 |
+
|
555 |
+
Make sure you have plenty of CPU memory available before you call this function. If you don't
|
556 |
+
have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it
|
557 |
+
conveniently placed for you in the checkpoint folder.
|
558 |
+
|
559 |
+
A typical usage might be ::
|
560 |
+
|
561 |
+
from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
|
562 |
+
model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir)
|
563 |
+
# submit to model hub or save the model to share with others
|
564 |
+
|
565 |
+
Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context
|
566 |
+
of the same application. i.e. you will need to re-initialize the deepspeed engine, since
|
567 |
+
``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
|
568 |
+
|
569 |
+
"""
|
570 |
+
logger.info(f"Extracting fp32 weights")
|
571 |
+
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
|
572 |
+
|
573 |
+
logger.info(f"Overwriting model with fp32 weights")
|
574 |
+
model = model.cpu()
|
575 |
+
model.load_state_dict(state_dict, strict=False)
|
576 |
+
|
577 |
+
return model
|
578 |
+
|
579 |
+
|
580 |
+
if __name__ == "__main__":
|
581 |
+
|
582 |
+
parser = argparse.ArgumentParser()
|
583 |
+
parser.add_argument("checkpoint_dir",
|
584 |
+
type=str,
|
585 |
+
help="path to the desired checkpoint folder, e.g., path/checkpoint-12")
|
586 |
+
parser.add_argument(
|
587 |
+
"output_file",
|
588 |
+
type=str,
|
589 |
+
help="path to the pytorch fp32 state_dict output file (e.g. path/checkpoint-12/pytorch_model.bin)")
|
590 |
+
parser.add_argument("-t",
|
591 |
+
"--tag",
|
592 |
+
type=str,
|
593 |
+
default=None,
|
594 |
+
help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1")
|
595 |
+
parser.add_argument("--exclude_frozen_parameters", action='store_true', help="exclude frozen parameters")
|
596 |
+
parser.add_argument("-d", "--debug", action='store_true', help="enable debug")
|
597 |
+
args = parser.parse_args()
|
598 |
+
|
599 |
+
debug = args.debug
|
600 |
+
|
601 |
+
convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir,
|
602 |
+
args.output_file,
|
603 |
+
tag=args.tag,
|
604 |
+
exclude_frozen_parameters=args.exclude_frozen_parameters)
|