chengs18 commited on
Commit
3a1fbb9
·
verified ·
1 Parent(s): d2e8ba2

Upload model files: SDAR-VL-Instruct-4B

Browse files
README.md ADDED
File without changes
added_tokens.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</think>": 151668,
3
+ "</tool_call>": 151658,
4
+ "</tool_response>": 151666,
5
+ "<think>": 151667,
6
+ "<tool_call>": 151657,
7
+ "<tool_response>": 151665,
8
+ "<|MASK|>": 151669,
9
+ "<|box_end|>": 151649,
10
+ "<|box_start|>": 151648,
11
+ "<|endoftext|>": 151643,
12
+ "<|file_sep|>": 151664,
13
+ "<|fim_middle|>": 151660,
14
+ "<|fim_pad|>": 151662,
15
+ "<|fim_prefix|>": 151659,
16
+ "<|fim_suffix|>": 151661,
17
+ "<|im_end|>": 151645,
18
+ "<|im_start|>": 151644,
19
+ "<|image_pad|>": 151655,
20
+ "<|object_ref_end|>": 151647,
21
+ "<|object_ref_start|>": 151646,
22
+ "<|quad_end|>": 151651,
23
+ "<|quad_start|>": 151650,
24
+ "<|repo_name|>": 151663,
25
+ "<|video_pad|>": 151656,
26
+ "<|vision_end|>": 151653,
27
+ "<|vision_pad|>": 151654,
28
+ "<|vision_start|>": 151652
29
+ }
all_results.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "epoch": 1.0,
3
+ "total_flos": 2.964601169621549e+20,
4
+ "train_loss": 0.849951366135661,
5
+ "train_runtime": 90359.1865,
6
+ "train_samples_per_second": 7.51,
7
+ "train_steps_per_second": 0.117
8
+ }
chat_template.jinja ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- set image_count = namespace(value=0) -%}
2
+ {%- set video_count = namespace(value=0) -%}
3
+ {%- for message in messages %}
4
+ {%- if loop.first and message['role'] != 'system' %}
5
+ {{- '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n' -}}
6
+ {%- endif %}
7
+ {{- '<|im_start|>' + message['role'] -}}
8
+ {%- if message['content'] is string -%}
9
+ {{- '\n\n' + message['content'] -}}
10
+ {%- else -%}
11
+ {{- '\n' -}}
12
+ {%- for content in message['content'] -%}
13
+ {%- if content['type'] == 'image' or 'image' in content or 'image_url' in content -%}
14
+ {%- set image_count.value = image_count.value + 1 -%}
15
+ {%- if add_vision_id %}{{ 'Picture ' }}{{ image_count.value }}{{ ': ' }}{% endif -%}
16
+ {{- '<|image_pad|>' -}}
17
+ {%- elif content['type'] == 'video' or 'video' in content -%}
18
+ {%- set video_count.value = video_count.value + 1 -%}
19
+ {%- if add_vision_id %}{{ 'Video ' }}{{ video_count.value }}{{ ': ' }}{% endif -%}
20
+ {{- '<|video_pad|>' -}}
21
+ {%- elif 'text' in content -%}
22
+ {{- content['text'] -}}
23
+ {%- endif -%}
24
+ {%- endfor %}
25
+ {%- endif -%}
26
+ {{- '\n<|im_end|>\n' -}}
27
+ {% endfor %}
28
+ {%- if add_generation_prompt -%}
29
+ {{- '<|im_start|>assistant\n' -}}
30
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "LlavaOnevisionForConditionalGeneration"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_llava_onevision.LlavaOnevisionConfig",
7
+ "AutoModel": "modeling_llava_onevision.LlavaOnevisionForConditionalGeneration",
8
+ "AutoModelForCausalLM": "modeling_llava_onevision.LlavaOnevisionForConditionalGeneration",
9
+ "AutoModelForImageTextToText": "modeling_llava_onevision.LlavaOnevisionForConditionalGeneration"
10
+ },
11
+ "hidden_size": 2560,
12
+ "ignore_index": -100,
13
+ "image_grid_pinpoints": [
14
+ [
15
+ 384,
16
+ 384
17
+ ],
18
+ [
19
+ 384,
20
+ 768
21
+ ],
22
+ [
23
+ 384,
24
+ 1152
25
+ ],
26
+ [
27
+ 384,
28
+ 1536
29
+ ],
30
+ [
31
+ 384,
32
+ 1920
33
+ ],
34
+ [
35
+ 384,
36
+ 2304
37
+ ],
38
+ [
39
+ 768,
40
+ 384
41
+ ],
42
+ [
43
+ 768,
44
+ 768
45
+ ],
46
+ [
47
+ 768,
48
+ 1152
49
+ ],
50
+ [
51
+ 768,
52
+ 1536
53
+ ],
54
+ [
55
+ 768,
56
+ 1920
57
+ ],
58
+ [
59
+ 768,
60
+ 2304
61
+ ],
62
+ [
63
+ 1152,
64
+ 384
65
+ ],
66
+ [
67
+ 1152,
68
+ 768
69
+ ],
70
+ [
71
+ 1152,
72
+ 1152
73
+ ],
74
+ [
75
+ 1152,
76
+ 1536
77
+ ],
78
+ [
79
+ 1152,
80
+ 1920
81
+ ],
82
+ [
83
+ 1152,
84
+ 2304
85
+ ],
86
+ [
87
+ 1536,
88
+ 384
89
+ ],
90
+ [
91
+ 1536,
92
+ 768
93
+ ],
94
+ [
95
+ 1536,
96
+ 1152
97
+ ],
98
+ [
99
+ 1536,
100
+ 1536
101
+ ],
102
+ [
103
+ 1536,
104
+ 1920
105
+ ],
106
+ [
107
+ 1536,
108
+ 2304
109
+ ],
110
+ [
111
+ 1920,
112
+ 384
113
+ ],
114
+ [
115
+ 1920,
116
+ 768
117
+ ],
118
+ [
119
+ 1920,
120
+ 1152
121
+ ],
122
+ [
123
+ 1920,
124
+ 1536
125
+ ],
126
+ [
127
+ 1920,
128
+ 1920
129
+ ],
130
+ [
131
+ 1920,
132
+ 2304
133
+ ],
134
+ [
135
+ 2304,
136
+ 384
137
+ ],
138
+ [
139
+ 2304,
140
+ 768
141
+ ],
142
+ [
143
+ 2304,
144
+ 1152
145
+ ],
146
+ [
147
+ 2304,
148
+ 1536
149
+ ],
150
+ [
151
+ 2304,
152
+ 1920
153
+ ],
154
+ [
155
+ 2304,
156
+ 2304
157
+ ]
158
+ ],
159
+ "image_token_index": 151655,
160
+ "model_type": "sdar_v",
161
+ "multimodal_projector_bias": true,
162
+ "projector_hidden_act": "gelu",
163
+ "text_config": {
164
+ "_name_or_path": "/mnt/shared-storage-user/chengshuang/projects/mdllm/llama_factory_sdar/saves/sdar_v_stage1/full/sft",
165
+ "architectures": [
166
+ "SDAR"
167
+ ],
168
+ "attention_bias": false,
169
+ "attention_dropout": 0.0,
170
+ "auto_map": {
171
+ "AutoConfig": "configuration_sdar.SDARConfig",
172
+ "AutoModel": "modeling_sdar.SDARModel",
173
+ "AutoModelForCausalLM": "modeling_sdar.SDARForCausalLM"
174
+ },
175
+ "block_size": 4,
176
+ "bos_token_id": 151643,
177
+ "debug": false,
178
+ "eos_token_id": 151643,
179
+ "ep_size": 1,
180
+ "fuse_cross_entropy": true,
181
+ "head_dim": 128,
182
+ "hidden_act": "silu",
183
+ "hidden_size": 2560,
184
+ "initializer_range": 0.02,
185
+ "intermediate_size": 9728,
186
+ "mask_token_id": 151669,
187
+ "max_position_embeddings": 32768,
188
+ "max_window_layers": 36,
189
+ "micro_forward": false,
190
+ "model_type": "sdar",
191
+ "num_attention_heads": 32,
192
+ "num_hidden_layers": 36,
193
+ "num_key_value_heads": 8,
194
+ "rms_norm_eps": 1e-06,
195
+ "rope_scaling": null,
196
+ "rope_theta": 1000000,
197
+ "skip_checkpoint": false,
198
+ "sliding_window": null,
199
+ "torch_dtype": "bfloat16",
200
+ "use_cache": false,
201
+ "use_deepep": false,
202
+ "use_sliding_window": false,
203
+ "vocab_size": 151936
204
+ },
205
+ "tie_word_embeddings": false,
206
+ "torch_dtype": "bfloat16",
207
+ "transformers_version": "4.52.4",
208
+ "use_cache": false,
209
+ "use_image_newline_parameter": true,
210
+ "video_token_index": 151656,
211
+ "vision_aspect_ratio": "anyres_max_9",
212
+ "vision_config": {
213
+ "attention_dropout": 0.0,
214
+ "hidden_act": "gelu_pytorch_tanh",
215
+ "hidden_size": 1152,
216
+ "image_size": 384,
217
+ "intermediate_size": 4304,
218
+ "layer_norm_eps": 1e-06,
219
+ "model_type": "siglip_vision_model",
220
+ "num_attention_heads": 16,
221
+ "num_channels": 3,
222
+ "num_hidden_layers": 27,
223
+ "patch_size": 14,
224
+ "torch_dtype": "bfloat16",
225
+ "vision_use_head": false
226
+ },
227
+ "vision_feature_layer": -1,
228
+ "vision_feature_select_strategy": "full"
229
+ }
configuration_llava_onevision.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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
+
16
+
17
+ from transformers.configuration_utils import PretrainedConfig
18
+ from transformers.utils import (
19
+ logging,
20
+ )
21
+ from transformers.models.auto import CONFIG_MAPPING, AutoConfig
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ class LlavaOnevisionConfig(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`LlavaOnevisionForConditionalGeneration`]. It is used to instantiate an
30
+ Llava-NeXT model according to the specified arguments, defining the model architecture. Instantiating a configuration
31
+ with the defaults will yield a similar configuration to that of the [llava-hf/llava-onevision-qwen2-7b-ov-hf](https://huggingface.co/llava-hf/llava-onevision-qwen2-7b-ov-hf)
32
+ model.
33
+
34
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
35
+ documentation from [`PretrainedConfig`] for more information.
36
+
37
+ Args:
38
+ vision_config (`Union[AutoConfig, dict]`, *optional*, defaults to `SiglipVisionConfig`):
39
+ The config object or dictionary of the vision backbone.
40
+ text_config (`Union[AutoConfig, dict]`, *optional*, defaults to `Qwen2Config`):
41
+ The config object or dictionary of the text backbone.
42
+ image_token_index (`int`, *optional*, defaults to 151646):
43
+ The image token index to encode the image prompt.
44
+ video_token_index (`int`, *optional*, defaults to 151647):
45
+ The video token index to encode the video prompt.
46
+ projector_hidden_act (`str`, *optional*, defaults to `"gelu"`):
47
+ The activation function used by the multimodal projector.
48
+ vision_feature_select_strategy (`str`, *optional*, defaults to `"full"`):
49
+ The feature selection strategy used to select the vision feature from the vision backbone.
50
+ Can be one of `"default"` or `"full"`. If `"default"`, the CLS token is removed from the vision features.
51
+ If `"full"`, the full vision features are used.
52
+ vision_feature_layer (`Union[int, List[int]]`, *optional*, defaults to -1):
53
+ The index of the layer to select the vision feature. If multiple indices are provided,
54
+ the vision feature of the corresponding indices will be concatenated to form the
55
+ vision features.
56
+ vision_aspect_ratio (`str`, *optional*, defaults to `"anyres_max_9"`):
57
+ Aspect ratio used when processong image features. The default value is "anyres_max_9".
58
+ image_grid_pinpoints (`List`, *optional*):
59
+ A list of possible resolutions to use for processing high resolution images. Each item in the list should be a tuple or list
60
+ of the form `(height, width)`.
61
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
62
+ Whether the model's input and output word embeddings should be tied.
63
+ multimodal_projector_bias (`bool`, *optional*, defaults to `True`):
64
+ Whether to use bias in the multimodal projector.
65
+
66
+ Example:
67
+
68
+ ```python
69
+ >>> from transformers import LlavaOnevisionForConditionalGeneration, LlavaOnevisionConfig, SiglipVisionConfig, Qwen2Config
70
+
71
+ >>> # Initializing a CLIP-vision config
72
+ >>> vision_config = SiglipVisionConfig()
73
+
74
+ >>> # Initializing a Llama config
75
+ >>> text_config = Qwen2Config()
76
+
77
+ >>> # Initializing a Llava-Next llava-hf/llava-onevision-qwen2-7b-ov-hf style configuration
78
+ >>> configuration = LlavaOnevisionConfig(vision_config, text_config)
79
+
80
+ >>> # Initializing a model from the llava-hf/llava-onevision-qwen2-7b-ov-hf style configuration
81
+ >>> model = LlavaOnevisionForConditionalGeneration(configuration)
82
+
83
+ >>> # Accessing the model configuration
84
+ >>> configuration = model.config
85
+ ```"""
86
+
87
+ model_type = "sdar_v"
88
+ attribute_map = {
89
+ "image_token_id": "image_token_index",
90
+ "video_token_id": "video_token_index",
91
+ }
92
+ sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig}
93
+
94
+ def __init__(
95
+ self,
96
+ vision_config=None,
97
+ text_config=None,
98
+ image_token_index=151646,
99
+ video_token_index=151647,
100
+ projector_hidden_act="gelu",
101
+ vision_feature_select_strategy="full",
102
+ vision_feature_layer=-1,
103
+ vision_aspect_ratio="anyres_max_9",
104
+ image_grid_pinpoints=None,
105
+ tie_word_embeddings=False,
106
+ multimodal_projector_bias=True,
107
+ **kwargs,
108
+ ):
109
+ self.image_token_index = image_token_index
110
+ self.video_token_index = video_token_index
111
+ self.projector_hidden_act = projector_hidden_act
112
+ self.multimodal_projector_bias = multimodal_projector_bias
113
+
114
+ if vision_feature_select_strategy not in ["default", "full"]:
115
+ raise ValueError(
116
+ "vision_feature_select_strategy should be one of 'default', 'full'."
117
+ f"Got: {vision_feature_select_strategy}"
118
+ )
119
+
120
+ self.vision_feature_select_strategy = vision_feature_select_strategy
121
+ self.vision_feature_layer = vision_feature_layer
122
+ self.vision_aspect_ratio = vision_aspect_ratio
123
+ image_grid_pinpoints = (
124
+ image_grid_pinpoints
125
+ if image_grid_pinpoints is not None
126
+ else [
127
+ [384, 384],
128
+ [384, 768],
129
+ [384, 1152],
130
+ [384, 1536],
131
+ [384, 1920],
132
+ [384, 2304],
133
+ [768, 384],
134
+ [768, 768],
135
+ [768, 1152],
136
+ [768, 1536],
137
+ [768, 1920],
138
+ [768, 2304],
139
+ [1152, 384],
140
+ [1152, 768],
141
+ [1152, 1152],
142
+ [1152, 1536],
143
+ [1152, 1920],
144
+ [1152, 2304],
145
+ [1536, 384],
146
+ [1536, 768],
147
+ [1536, 1152],
148
+ [1536, 1536],
149
+ [1536, 1920],
150
+ [1536, 2304],
151
+ [1920, 384],
152
+ [1920, 768],
153
+ [1920, 1152],
154
+ [1920, 1536],
155
+ [1920, 1920],
156
+ [1920, 2304],
157
+ [2304, 384],
158
+ [2304, 768],
159
+ [2304, 1152],
160
+ [2304, 1536],
161
+ [2304, 1920],
162
+ [2304, 2304],
163
+ ]
164
+ )
165
+ self.image_grid_pinpoints = image_grid_pinpoints
166
+
167
+ if isinstance(vision_config, dict):
168
+ vision_config["model_type"] = (
169
+ vision_config["model_type"] if "model_type" in vision_config else "siglip_vision_model"
170
+ )
171
+ vision_config = CONFIG_MAPPING[vision_config["model_type"]](**vision_config)
172
+ elif vision_config is None:
173
+ vision_config = CONFIG_MAPPING["siglip_vision_model"](
174
+ hidden_size=1152,
175
+ intermediate_size=4304,
176
+ patch_size=14,
177
+ image_size=384,
178
+ num_hidden_layers=26,
179
+ num_attention_heads=14,
180
+ vision_use_head=False,
181
+ )
182
+
183
+ self.vision_config = vision_config
184
+
185
+ if isinstance(text_config, dict):
186
+ text_config["model_type"] = text_config["model_type"] if "model_type" in text_config else "qwen2"
187
+ try:
188
+ text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config)
189
+ except:
190
+ from .configuration_sdar import SDARConfig
191
+ text_config = SDARConfig(**text_config)
192
+ elif text_config is None:
193
+ text_config = CONFIG_MAPPING["qwen2"]()
194
+
195
+ self.text_config = text_config
196
+
197
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
198
+
199
+
200
+ __all__ = ["LlavaOnevisionConfig"]
configuration_sdar.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and 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
+ """SDAR model configuration"""
16
+
17
+ from transformers.configuration_utils import PretrainedConfig
18
+ from transformers.modeling_rope_utils import rope_config_validation
19
+ from transformers.utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class SDARConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`SDARModel`]. It is used to instantiate a
28
+ SDAR model according to the specified arguments, defining the model architecture. Instantiating a configuration
29
+ with the defaults will yield a similar configuration to that of
30
+ SDAR-1.7B [DiffuOpen/SDAR-1.7B-Chat](https://huggingface.co/DiffuOpen/SDAR-1.7B-Chat/).
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+
36
+ Args:
37
+ vocab_size (`int`, *optional*, defaults to 151936):
38
+ Vocabulary size of the SDAR model. Defines the number of different tokens that can be represented by the
39
+ `inputs_ids` passed when calling [`SDARModel`]
40
+ hidden_size (`int`, *optional*, defaults to 4096):
41
+ Dimension of the hidden representations.
42
+ intermediate_size (`int`, *optional*, defaults to 22016):
43
+ Dimension of the MLP representations.
44
+ num_hidden_layers (`int`, *optional*, defaults to 32):
45
+ Number of hidden layers in the Transformer encoder.
46
+ num_attention_heads (`int`, *optional*, defaults to 32):
47
+ Number of attention heads for each attention layer in the Transformer encoder.
48
+ num_key_value_heads (`int`, *optional*, defaults to 32):
49
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
50
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
51
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
52
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
53
+ by meanpooling all the original heads within that group. For more details checkout [this
54
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
55
+ head_dim (`int`, *optional*, defaults to 128):
56
+ The attention head dimension.
57
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
58
+ The non-linear activation function (function or string) in the decoder.
59
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
60
+ The maximum sequence length that this model might ever be used with.
61
+ initializer_range (`float`, *optional*, defaults to 0.02):
62
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
63
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
64
+ The epsilon used by the rms normalization layers.
65
+ use_cache (`bool`, *optional*, defaults to `True`):
66
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
67
+ relevant if `config.is_decoder=True`.
68
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
69
+ Whether the model's input and output word embeddings should be tied.
70
+ rope_theta (`float`, *optional*, defaults to 10000.0):
71
+ The base period of the RoPE embeddings.
72
+ rope_scaling (`Dict`, *optional*):
73
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
74
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
75
+ accordingly.
76
+ Expected contents:
77
+ `rope_type` (`str`):
78
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
79
+ 'llama3'], with 'default' being the original RoPE implementation.
80
+ `factor` (`float`, *optional*):
81
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
82
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
83
+ original maximum pre-trained length.
84
+ `original_max_position_embeddings` (`int`, *optional*):
85
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
86
+ pretraining.
87
+ `attention_factor` (`float`, *optional*):
88
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
89
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
90
+ `factor` field to infer the suggested value.
91
+ `beta_fast` (`float`, *optional*):
92
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
93
+ ramp function. If unspecified, it defaults to 32.
94
+ `beta_slow` (`float`, *optional*):
95
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
96
+ ramp function. If unspecified, it defaults to 1.
97
+ `short_factor` (`List[float]`, *optional*):
98
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
99
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
100
+ size divided by the number of attention heads divided by 2
101
+ `long_factor` (`List[float]`, *optional*):
102
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
103
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
104
+ size divided by the number of attention heads divided by 2
105
+ `low_freq_factor` (`float`, *optional*):
106
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
107
+ `high_freq_factor` (`float`, *optional*):
108
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
109
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
110
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
111
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
112
+ Whether to use sliding window attention.
113
+ sliding_window (`int`, *optional*, defaults to 4096):
114
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
115
+ max_window_layers (`int`, *optional*, defaults to 28):
116
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
117
+ attention_dropout (`float`, *optional*, defaults to 0.0):
118
+ The dropout ratio for the attention probabilities.
119
+
120
+ ```python
121
+ >>> from transformers import SDARModel, SDARConfig
122
+
123
+ >>> # Initializing a SDAR style configuration
124
+ >>> configuration = SDARConfig()
125
+
126
+ >>> # Initializing a model from the SDAR-8B style configuration
127
+ >>> model = SDARModel(configuration)
128
+
129
+ >>> # Accessing the model configuration
130
+ >>> configuration = model.config
131
+ ```"""
132
+
133
+ model_type = "sdar"
134
+ keys_to_ignore_at_inference = ["past_key_values"]
135
+
136
+ # Default tensor parallel plan for base model `SDAR`
137
+ base_model_tp_plan = {
138
+ "layers.*.self_attn.q_proj": "colwise",
139
+ "layers.*.self_attn.k_proj": "colwise",
140
+ "layers.*.self_attn.v_proj": "colwise",
141
+ "layers.*.self_attn.o_proj": "rowwise",
142
+ "layers.*.mlp.gate_proj": "colwise",
143
+ "layers.*.mlp.up_proj": "colwise",
144
+ "layers.*.mlp.down_proj": "rowwise",
145
+ }
146
+ base_model_pp_plan = {
147
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
148
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
149
+ "norm": (["hidden_states"], ["hidden_states"]),
150
+ }
151
+
152
+ def __init__(
153
+ self,
154
+ vocab_size=151936,
155
+ hidden_size=4096,
156
+ intermediate_size=22016,
157
+ num_hidden_layers=32,
158
+ num_attention_heads=32,
159
+ num_key_value_heads=32,
160
+ head_dim=128,
161
+ hidden_act="silu",
162
+ max_position_embeddings=32768,
163
+ initializer_range=0.02,
164
+ rms_norm_eps=1e-6,
165
+ use_cache=True,
166
+ tie_word_embeddings=False,
167
+ rope_theta=10000.0,
168
+ rope_scaling=None,
169
+ attention_bias=False,
170
+ use_sliding_window=False,
171
+ sliding_window=4096,
172
+ max_window_layers=28,
173
+ attention_dropout=0.0,
174
+ **kwargs,
175
+ ):
176
+ self.vocab_size = vocab_size
177
+ self.max_position_embeddings = max_position_embeddings
178
+ self.hidden_size = hidden_size
179
+ self.intermediate_size = intermediate_size
180
+ self.num_hidden_layers = num_hidden_layers
181
+ self.num_attention_heads = num_attention_heads
182
+ self.use_sliding_window = use_sliding_window
183
+ self.sliding_window = sliding_window # we check `use_sliding_window` in the modeling code
184
+ self.max_window_layers = max_window_layers
185
+
186
+ # for backward compatibility
187
+ if num_key_value_heads is None:
188
+ num_key_value_heads = num_attention_heads
189
+
190
+ self.num_key_value_heads = num_key_value_heads
191
+ self.head_dim = head_dim
192
+ self.hidden_act = hidden_act
193
+ self.initializer_range = initializer_range
194
+ self.rms_norm_eps = rms_norm_eps
195
+ self.use_cache = use_cache
196
+ self.rope_theta = rope_theta
197
+ self.rope_scaling = rope_scaling
198
+ self.attention_bias = attention_bias
199
+ self.attention_dropout = attention_dropout
200
+ # Validate the correctness of rotary position embeddings parameters
201
+ # BC: if there is a 'type' field, move it to 'rope_type'.
202
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
203
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
204
+ rope_config_validation(self)
205
+
206
+ super().__init__(
207
+ tie_word_embeddings=tie_word_embeddings,
208
+ **kwargs,
209
+ )
210
+
211
+
212
+ __all__ = ["SDARConfig"]
fused_linear_diffusion_cross_entropy.py ADDED
@@ -0,0 +1,682 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # Code adapted from
4
+ # https://github.com/fla-org/flash-linear-attention/blob/main/fla/modules/fused_linear_cross_entropy.py
5
+ # Implementation of element-wise division of cross entropy loss
6
+
7
+
8
+ # Code adapted from
9
+ # https://github.com/linkedin/Liger-Kernel/blob/main/src/liger_kernel/ops/fused_linear_cross_entropy.py
10
+
11
+ from functools import partial
12
+ from typing import Optional, Tuple
13
+
14
+ import torch
15
+ import torch.nn as nn
16
+ import torch.nn.functional as F
17
+ import triton
18
+ import triton.language as tl
19
+ from torch.distributed import DeviceMesh
20
+ from torch.distributed.tensor import DTensor, Replicate, Shard, distribute_module
21
+ from torch.distributed.tensor.parallel import ParallelStyle
22
+
23
+ # The hard limit of TRITON_MAX_TENSOR_NUMEL is 1048576
24
+ # https://github.com/triton-lang/triton/blob/ba42a5c68fd0505f8c42f4202d53be0f8d9a5fe0/python/triton/language/core.py#L19
25
+ # However, setting limit as 65536 as in LayerNorm tutorial is faster because of less register spilling
26
+ # The optimal maximum block size depends on your hardware, your kernel, and your dtype
27
+ MAX_FUSED_SIZE = 65536 // 2
28
+
29
+
30
+ @triton.heuristics({
31
+ 'HAS_SCALE': lambda args: args['scale'] is not None
32
+ })
33
+ @triton.autotune(
34
+ configs=[
35
+ triton.Config({}, num_warps=num_warps)
36
+ for num_warps in [1, 2, 4, 8, 16, 32]
37
+ ],
38
+ key=['D']
39
+ )
40
+ @triton.jit
41
+ def logsumexp_fwd_kernel(
42
+ x,
43
+ z,
44
+ scale,
45
+ D: tl.constexpr,
46
+ B: tl.constexpr,
47
+ HAS_SCALE: tl.constexpr
48
+ ):
49
+ i_n, i_d = tl.program_id(0).to(tl.int64), tl.program_id(1).to(tl.int64)
50
+ o_d = i_d * B + tl.arange(0, B)
51
+ m_d = o_d < D
52
+
53
+ b_x = tl.load(x + i_n * D + o_d, mask=m_d, other=-float('inf'))
54
+ if HAS_SCALE:
55
+ b_x = b_x * scale
56
+ b_m = tl.max(b_x, 0)
57
+ b_z = tl.log(tl.sum(tl.exp(b_x - b_m), 0)) + b_m
58
+ tl.store(z + i_n * tl.cdiv(D, B) + i_d, b_z)
59
+
60
+
61
+ def logsumexp_fwd(
62
+ x,
63
+ scale: Optional[float] = None,
64
+ dtype: Optional[torch.dtype] = None
65
+ ):
66
+ r"""
67
+ Compute the logsumexp of the input tensor over the last dimension.
68
+
69
+ Args:
70
+ x (Tensor):
71
+ The input tensor of any shape.
72
+ scale (Optional[float]):
73
+ The scale applied to the input tensor. Default: `None`.
74
+ dtype (Optional[torch.dtype]):
75
+ The data type of the output tensor. Default: `None`.
76
+ Returns:
77
+ Tensor: The logsumexp of the input tensor.
78
+ """
79
+
80
+ shape = x.shape
81
+ x = x.view(-1, shape[-1])
82
+ N, D = x.shape
83
+ B = min(triton.next_power_of_2(D), 64 * 1024)
84
+ ND = triton.cdiv(D, B)
85
+
86
+ z = x.new_empty(N, ND, dtype=torch.float)
87
+ logsumexp_fwd_kernel[(N, ND)](
88
+ x=x,
89
+ z=z,
90
+ scale=scale,
91
+ D=D,
92
+ B=B
93
+ )
94
+ z = z.logsumexp(-1).view(*shape[:-1])
95
+ if dtype is not None and dtype != torch.float:
96
+ z = z.to(dtype)
97
+ return z
98
+
99
+ @triton.jit
100
+ def cross_entropy_kernel(
101
+ logits,
102
+ lse,
103
+ target,
104
+ p_mask,
105
+ loss,
106
+ total,
107
+ ignore_index,
108
+ label_smoothing: tl.constexpr,
109
+ logit_scale: tl.constexpr,
110
+ reduction: tl.constexpr,
111
+ V: tl.constexpr,
112
+ BV: tl.constexpr
113
+ ):
114
+ """
115
+ This kernel computes both cross entropy loss and the gradient of the input.
116
+ We only consider hard label + mean reduction for now.
117
+ Please refer to https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html for the math.
118
+
119
+ Args:
120
+ logits:
121
+ Pointer to logits tensor.
122
+ lse:
123
+ Pointer to logsumexp tensor.
124
+ target: Pointer to target tensor.
125
+ loss:
126
+ Pointer to tensor to store the loss.
127
+ V (int):
128
+ The number of columns in the input tensor.
129
+ total (int):
130
+ The number of non-ignored classes.
131
+ ignore_index (int):
132
+ The index to ignore in the target.
133
+ label_smoothing (float):
134
+ The amount of smoothing when computing the loss, where 0.0 means no smoothing.
135
+ reduction (str):
136
+ The string for the reduction to apply
137
+ BV (int):
138
+ The block size for vocab.
139
+ """
140
+
141
+ # https://github.com/triton-lang/triton/issues/1058
142
+ # If B*T*V is too large, i_n * stride will overflow out of int32, so we convert to int64
143
+ i_n = tl.program_id(0).to(tl.int64)
144
+ NV = tl.cdiv(V, BV)
145
+
146
+ # 1. Load target first because if the target is ignore_index, we can return right away
147
+ b_y = tl.load(target + i_n)
148
+ # load p_mask
149
+ b_p_mask = tl.load(p_mask + i_n)
150
+
151
+ # 2. locate the start index
152
+ logits += i_n * V
153
+
154
+ if b_y == ignore_index:
155
+ # set all x as 0
156
+ for i in range(0, V, BV):
157
+ o_v = i + tl.arange(0, BV)
158
+ tl.store(logits + o_v, 0.0, mask=o_v < V)
159
+ return
160
+
161
+ # Online softmax: 2 loads + 1 store (compared with 3 loads + 1 store for the safe softmax)
162
+ # Refer to Algorithm 3 in the paper: https://arxiv.org/pdf/1805.02867
163
+
164
+ # 3. [Online softmax] first pass: compute logsumexp
165
+ # we did this in anouter kernel
166
+ b_l = tl.load(logits + b_y) * logit_scale
167
+ b_lse = tl.load(lse + i_n)
168
+
169
+ # 4. Calculate the loss
170
+ # loss = lse - logits_l
171
+ # celoss = -log(q_y) = -log(softmax(x_y))
172
+ b_loss = (b_lse - b_l) / b_p_mask # Diffusion Scaled '1/t'
173
+
174
+ # Label smoothing is a general case of normal cross entropy
175
+ # See the full derivation at https://github.com/linkedin/Liger-Kernel/pull/198#issue-2503665310
176
+ b_z = 0.0
177
+ eps = label_smoothing / V
178
+
179
+ # We need tl.debug_barrier() as mentioned in
180
+ # https://github.com/triton-lang/triton/blob/ba42a5c68fd0505f8c42f4202d53be0f8d9a5fe0/python/triton/ops/cross_entropy.py#L34
181
+ tl.debug_barrier()
182
+
183
+ # 5. [Online Softmax] Second pass: compute gradients
184
+ # For 'mean' reduction, gradients are normalized by number of non-ignored elements
185
+ # dx_y = (softmax(x_y) - 1) / N
186
+ # dx_i = softmax(x_i) / N, i != y
187
+ # For label smoothing:
188
+ # dx_i = (softmax(x_y) - label_smoothing / V) / N, i != y
189
+ # dx_y = (softmax(x_y) - label_smoothing / V - (1 - label_smoothing)) / N
190
+ # = dx_i - (1 - label_smoothing) / N
191
+ for iv in range(0, NV):
192
+ o_v = iv * BV + tl.arange(0, BV)
193
+ b_logits = tl.load(logits + o_v, mask=o_v < V, other=float('-inf')) * logit_scale
194
+ if label_smoothing > 0:
195
+ # scale X beforehand to avoid overflow
196
+ b_z += tl.sum(tl.where(o_v < V, -eps * b_logits, 0.0))
197
+ b_p = (tl.exp(b_logits - b_lse) - eps) * logit_scale
198
+ b_p /= b_p_mask # 修改
199
+ if reduction == "mean":
200
+ b_p = b_p / total
201
+ tl.store(logits + o_v, b_p, mask=o_v < V)
202
+
203
+ tl.debug_barrier()
204
+
205
+ # Orginal loss = H(q, p), with label smoothing regularization = H(q', p) and (label_smoothing / V) = eps
206
+ # H(q', p) = (1 - label_smoothing) * H(q, p) + label_smoothing * H(u, p)
207
+ # = (1 - label_smoothing) * H(q, p) + eps * sum(logsoftmax(x_i))
208
+ # By using m (global max of xi) and d (sum of e^(xi-m)), we can simplify as:
209
+ # = (1 - label_smoothing) * H(q, p) + (-sum(x_i * eps) + label_smoothing * (m + logd))
210
+ # Refer to H(q', p) in section 7 of the paper:
211
+ # https://arxiv.org/pdf/1512.00567
212
+ # pytorch:
213
+ # https://github.com/pytorch/pytorch/blob/2981534f54d49fa3a9755c9b0855e7929c2527f0/aten/src/ATen/native/LossNLL.cpp#L516
214
+ # See full derivation at https://github.com/linkedin/Liger-Kernel/pull/198#issuecomment-2333753087
215
+ if label_smoothing > 0:
216
+ b_loss = b_loss * (1 - label_smoothing) + (b_z + label_smoothing * b_lse)
217
+
218
+ # 6. Specially handle the i==y case where `dx_y = (softmax(x_y) - (1 - label_smoothing) / N`
219
+ b_l = tl.load(logits + b_y)
220
+
221
+ # Normalize the loss by the number of non-ignored elements if reduction is "mean"
222
+ if reduction == 'mean':
223
+ b_loss = b_loss / total
224
+ # b_l += (label_smoothing - 1) / total * logit_scale
225
+ # b_l has already been divided by b_p_mask and total
226
+ b_l += (label_smoothing - 1) / b_p_mask / total * logit_scale
227
+ else:
228
+ # b_l += (label_smoothing - 1) * logit_scale
229
+ b_l += (label_smoothing - 1) / b_p_mask * logit_scale
230
+
231
+ tl.store(loss + i_n, b_loss)
232
+ tl.store(logits + b_y, b_l)
233
+
234
+
235
+ @triton.jit
236
+ def elementwise_mul_kernel(
237
+ x,
238
+ g,
239
+ N: tl.constexpr,
240
+ B: tl.constexpr
241
+ ):
242
+ """
243
+ This function multiplies each element of the tensor pointed by x with the value pointed by g.
244
+ The multiplication is performed in-place on the tensor pointed by x.
245
+
246
+ Parameters:
247
+ x:
248
+ Pointer to the input tensor.
249
+ g:
250
+ Pointer to the gradient output value.
251
+ N (int):
252
+ The number of columns in the input tensor.
253
+ B (int):
254
+ The block size for Triton operations.
255
+ """
256
+
257
+ # Get the program ID and convert it to int64 to avoid overflow
258
+ i_x = tl.program_id(0).to(tl.int64)
259
+ o_x = i_x * B + tl.arange(0, B)
260
+
261
+ # Load the gradient output value
262
+ b_g = tl.load(g)
263
+ b_x = tl.load(x + o_x, mask=o_x < N)
264
+ tl.store(x + o_x, b_x * b_g, mask=o_x < N)
265
+
266
+
267
+ def fused_linear_cross_entropy_forward(
268
+ x: torch.Tensor,
269
+ target: torch.LongTensor,
270
+ weight: torch.Tensor,
271
+ bias: torch.Tensor = None,
272
+ p_mask: torch.Tensor = None,
273
+ ignore_index: int = -100,
274
+ label_smoothing: float = 0.0,
275
+ logit_scale: float = 1.0,
276
+ num_chunks: int = 8,
277
+ reduction: str = "mean"
278
+ ):
279
+ device = x.device
280
+ # inputs have shape: [N, H]
281
+ # materialized activations will have shape: [N, V]
282
+ # the increase in memory = [N, V]
283
+ # reduction can be achieved by partitioning the number of tokens N into smaller chunks.
284
+
285
+ # ideally, we would like to achieve the same memory consumption as [N, H],
286
+ # so the expected chunk size should be:
287
+ # NC = ceil(V / H)
288
+ # C = ceil(N / NC)
289
+ # for ex: N = 4096*4, V = 32000, H = 4096 ==> NC = 8, C = ceil(N / NC) = 2048
290
+ N, H, V = *x.shape, weight.shape[0]
291
+ BV = min(MAX_FUSED_SIZE, triton.next_power_of_2(V))
292
+ # TODO: in real cases, we may need to limit the number of chunks NC to
293
+ # ensure the precisions of accumulated gradients
294
+ NC = min(num_chunks, triton.cdiv(V, H))
295
+ C = triton.next_power_of_2(triton.cdiv(N, NC))
296
+ NC = triton.cdiv(N, C)
297
+
298
+ # [N, H]
299
+ dx = torch.zeros_like(x, device=device)
300
+ # [V, H]
301
+ dw = torch.zeros_like(weight, device=device, dtype=torch.float) if weight is not None else None
302
+ # [V]
303
+ db = torch.zeros_like(bias, device=device, dtype=torch.float) if bias is not None else None
304
+ # [N]
305
+ loss = torch.zeros(N, device=device, dtype=torch.float)
306
+
307
+ total = target.ne(ignore_index).sum().item()
308
+
309
+ for ic in range(NC):
310
+ start, end = ic * C, min((ic + 1) * C, N)
311
+ # [C, N]
312
+ c_x = x[start:end]
313
+ # when doing matmul, use the original precision
314
+ # [C, V]
315
+ c_logits = F.linear(c_x, weight, bias)
316
+ c_target = target[start:end]
317
+ c_p_mask = p_mask[start:end]
318
+ # [C]
319
+ # keep lse in fp32 to maintain precision
320
+ c_lse = logsumexp_fwd(c_logits, scale=logit_scale, dtype=torch.float)
321
+
322
+ # unreduced loss
323
+ c_loss = loss[start:end]
324
+
325
+ # Here we calculate the gradient of c_logits in place so we can save memory.
326
+ cross_entropy_kernel[(c_logits.shape[0],)](
327
+ logits=c_logits,
328
+ lse=c_lse,
329
+ target=c_target,
330
+ p_mask=c_p_mask,
331
+ loss=c_loss,
332
+ total=total,
333
+ ignore_index=ignore_index,
334
+ label_smoothing=label_smoothing,
335
+ logit_scale=logit_scale,
336
+ reduction=reduction,
337
+ V=V,
338
+ BV=BV,
339
+ num_warps=32
340
+ )
341
+
342
+ # gradient of logits is computed in-place by the above triton kernel and is of shape: C x V
343
+ # thus dx should be of shape: C x H
344
+ dx[start:end] = torch.mm(c_logits, weight)
345
+
346
+ # keep dw in fp32 to maintain precision
347
+ if weight is not None:
348
+ dw += c_logits.t() @ c_x
349
+
350
+ if bias is not None:
351
+ torch.add(input=db, other=c_logits.sum(0), out=db)
352
+
353
+ loss = loss.sum()
354
+ if dw is not None:
355
+ dw = dw.to(weight)
356
+ if db is not None:
357
+ db = db.to(bias)
358
+ return loss, dx, dw, db
359
+
360
+
361
+ def fused_linear_cross_entropy_backward(
362
+ do: torch.Tensor,
363
+ dx: torch.Tensor,
364
+ dw: torch.Tensor,
365
+ db: torch.Tensor
366
+ ):
367
+ # If cross entropy is the last layer, do is 1.0. Skip the mul to save time
368
+ if torch.ne(do, torch.tensor(1.0, device=do.device)):
369
+ # We use a Triton kernel instead of a PyTorch operation because modifying inputs in-place
370
+ # for gradient storage and backward multiple times causes anomalies with PyTorch but not with Triton.
371
+ N, H = dx.shape
372
+ B = min(MAX_FUSED_SIZE, triton.next_power_of_2(H))
373
+
374
+ elementwise_mul_kernel[(triton.cdiv(N * H, B),)](
375
+ x=dx,
376
+ g=do,
377
+ N=N*H,
378
+ B=B,
379
+ num_warps=32,
380
+ )
381
+
382
+ # handle dw
383
+ if dw is not None:
384
+ V, H = dw.shape
385
+ elementwise_mul_kernel[(triton.cdiv(V * H, B),)](
386
+ x=dw,
387
+ g=do,
388
+ N=V*H,
389
+ B=B,
390
+ num_warps=32,
391
+ )
392
+
393
+ if db is not None:
394
+ V = db.shape[0]
395
+ elementwise_mul_kernel[(triton.cdiv(V, B),)](
396
+ x=db,
397
+ g=do,
398
+ N=V,
399
+ B=B,
400
+ num_warps=32,
401
+ )
402
+ return dx, dw, db
403
+
404
+
405
+ class FusedLinearCrossEntropyFunction(torch.autograd.Function):
406
+
407
+ @staticmethod
408
+ def forward(
409
+ ctx,
410
+ x: torch.Tensor,
411
+ target: torch.LongTensor,
412
+ weight: torch.Tensor,
413
+ bias: torch.Tensor = None,
414
+ p_mask: torch.Tensor = None,
415
+ ignore_index: int = -100,
416
+ label_smoothing: float = 0.0,
417
+ logit_scale: float = 1.0,
418
+ num_chunks: int = 8,
419
+ reduction: str = "mean"
420
+ ):
421
+ """
422
+ Fusing the last linear layer with cross-entropy loss
423
+ Reference: https://github.com/mgmalek/efficient_cross_entropy
424
+
425
+ Handle the forward and backward pass of the final linear layer via cross-entropy loss by avoiding
426
+ the materialization of the large logits tensor. Since Cross Entropy Loss is the last layer, we can
427
+ compute the gradient at the forward pass. By doing so, we don't have to store the x and target
428
+ for the backward pass.
429
+
430
+ x (torch.Tensor): [batch_size * seq_len, hidden_size]
431
+ target (torch.LongTensor): [batch_size * seq_len]
432
+ where each value is in [0, vocab_size).
433
+ weight (torch.Tensor): [vocab_size, hidden_size]
434
+ where `vocab_size` is the number of classes.
435
+ bias (Optional[torch.Tensor]): [vocab_size]
436
+ where `vocab_size` is the number of classes.
437
+ p_mask(torch.Tensor): [batch_size * seq_len]
438
+ Its shape should be same as target.
439
+ ignore_index:
440
+ the index to ignore in the target.
441
+ label_smoothing:
442
+ the amount of smoothing when computing the loss, where 0.0 means no smoothing.
443
+ logit_scale: float = 1.0,
444
+ A scaling factor applied to the logits. Default: 1.0
445
+ num_chunks: int
446
+ The number of chunks to split the input tensor into for processing.
447
+ This can help optimize memory usage and computation speed.
448
+ Default: 8
449
+ reduction:
450
+ Specifies the reduction to apply to the output: 'mean' | 'sum'.
451
+ 'mean': the weighted mean of the output is taken,
452
+ 'sum': the output will be summed.
453
+ Default: 'mean'.
454
+ """
455
+ loss, dx, dw, db = fused_linear_cross_entropy_forward(
456
+ x,
457
+ target,
458
+ weight,
459
+ bias,
460
+ p_mask,
461
+ ignore_index,
462
+ label_smoothing,
463
+ logit_scale,
464
+ num_chunks,
465
+ reduction
466
+ )
467
+ # downcast to dtype and store for backward
468
+ ctx.save_for_backward(
469
+ dx.detach(),
470
+ dw.detach() if weight is not None else None,
471
+ db.detach() if bias is not None else None,
472
+ )
473
+ return loss
474
+
475
+ @staticmethod
476
+ def backward(ctx, do):
477
+ dx, dw, db = ctx.saved_tensors
478
+ dx, dw, db = fused_linear_cross_entropy_backward(do, dx, dw, db)
479
+ # 10 gradients should be returned, with `p_mask` having no grads
480
+ # Check the number of arguments in the `forward` method
481
+ return dx, None, dw, db, None, None, None, None, None, None
482
+
483
+
484
+ def fused_linear_cross_entropy_loss(
485
+ x: torch.Tensor,
486
+ target: torch.LongTensor,
487
+ weight: torch.Tensor,
488
+ bias: torch.Tensor = None,
489
+ p_mask: torch.Tensor = None,
490
+ ignore_index: int = -100,
491
+ label_smoothing: float = 0.0,
492
+ logit_scale: float = 1.0,
493
+ num_chunks: int = 8,
494
+ reduction: str = "mean"
495
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
496
+ """
497
+ Args:
498
+ x (torch.Tensor): [batch_size * seq_len, hidden_size]
499
+ target (torch.LongTensor): [batch_size * seq_len]
500
+ where each value is in [0, vocab_size).
501
+ weight (torch.Tensor): [vocab_size, hidden_size]
502
+ where `vocab_size` is the number of classes.
503
+ bias (Optional[torch.Tensor]): [vocab_size]
504
+ where `vocab_size` is the number of classes.
505
+ p_mask(torch.Tensor): [batch_size * seq_len]
506
+ Its shape should be same as target.
507
+ ignore_index: int.
508
+ If target == ignore_index, the loss is set to 0.0.
509
+ label_smoothing: float
510
+ logit_scale: float
511
+ A scaling factor applied to the logits. Default: 1.0
512
+ num_chunks: int
513
+ The number of chunks to split the input tensor into for processing.
514
+ This can help optimize memory usage and computation speed.
515
+ Default: 8
516
+ reduction:
517
+ Specifies the reduction to apply to the output: 'mean' | 'sum'.
518
+ 'mean': the weighted mean of the output is taken,
519
+ 'sum': the output will be summed.
520
+ Default: 'mean'.
521
+ Returns:
522
+ losses: [batch,], float
523
+ """
524
+ return FusedLinearCrossEntropyFunction.apply(
525
+ x,
526
+ target,
527
+ weight,
528
+ bias,
529
+ p_mask,
530
+ ignore_index,
531
+ label_smoothing,
532
+ logit_scale,
533
+ num_chunks,
534
+ reduction
535
+ )
536
+
537
+
538
+ class FusedLinearDiffusionCrossEntropyLoss(nn.Module):
539
+
540
+ def __init__(
541
+ self,
542
+ ignore_index: int = -100,
543
+ label_smoothing: float = 0.0,
544
+ logit_scale: float = 1.0,
545
+ num_chunks: int = 8,
546
+ reduction: str = "mean"
547
+ ):
548
+ """
549
+ Args:
550
+ ignore_index: int.
551
+ If target == ignore_index, the loss is set to 0.0.
552
+ label_smoothing: float
553
+ logit_scale: float
554
+ A scaling factor applied to the logits. Default: 1.0
555
+ num_chunks: int
556
+ The number of chunks to split the input tensor into for processing.
557
+ This can help optimize memory usage and computation speed.
558
+ Default: 8
559
+ reduction:
560
+ Specifies the reduction to apply to the output: 'mean' | 'sum'.
561
+ 'mean': the weighted mean of the output is taken,
562
+ 'sum': the output will be summed.
563
+ Default: 'mean'.
564
+ """
565
+ super().__init__()
566
+
567
+ assert reduction in ["mean", "sum"], f"reduction: {reduction} is not supported"
568
+
569
+ self.ignore_index = ignore_index
570
+ self.label_smoothing = label_smoothing
571
+ self.logit_scale = logit_scale
572
+ self.num_chunks = num_chunks
573
+ self.reduction = reduction
574
+
575
+ @torch.compiler.disable
576
+ def forward(
577
+ self,
578
+ x: torch.Tensor,
579
+ target: torch.LongTensor,
580
+ weight: torch.Tensor,
581
+ bias: Optional[torch.Tensor] = None,
582
+ p_mask: torch.Tensor = None
583
+ ):
584
+ """
585
+ Args:
586
+ x (torch.Tensor): [batch_size, seq_len, hidden_size]
587
+ target (torch.LongTensor): [batch_size, seq_len]
588
+ where each value is in [0, V).
589
+ weight (torch.Tensor): [vocab_size, hidden_size]
590
+ where `vocab_size` is the number of classes.
591
+ bias (Optional[torch.Tensor]): [vocab_size]
592
+ where `vocab_size` is the number of classes.
593
+ p_mask(torch.Tensor): [batch_size, seq_len]
594
+ Its shape is same as target.
595
+ Shape: (1, packed_length) when varlen attn is used.
596
+ Returns:
597
+ loss
598
+
599
+ TODO:
600
+ follow https://github.com/ML-GSAI/LLaDA/blob/main/GUIDELINES.md#pre-training
601
+ ```py
602
+ unreduced_loss /= p_mask
603
+ ```
604
+ Scale the values of `unreduced_loss at different positions
605
+ """
606
+ if p_mask is None:
607
+ p_mask = torch.ones_like(target, dtype=torch.float, device=x.device)
608
+
609
+ x = x.contiguous().view(-1, x.shape[-1])
610
+ target = target.contiguous().view(-1)
611
+ weight = weight.contiguous()
612
+ bias = bias.contiguous() if bias else None
613
+ p_mask = p_mask.contiguous().view(-1)
614
+ l, d = x.shape
615
+ assert l == target.shape[0] == p_mask.shape[0], f"{x.shape=}, {target.shape=}, {p_mask.shape=}"
616
+
617
+ loss = fused_linear_cross_entropy_loss(
618
+ x,
619
+ target,
620
+ weight=weight,
621
+ bias=bias,
622
+ p_mask=p_mask,
623
+ ignore_index=self.ignore_index,
624
+ label_smoothing=self.label_smoothing,
625
+ logit_scale=self.logit_scale,
626
+ num_chunks=self.num_chunks,
627
+ reduction=self.reduction
628
+ )
629
+ return loss
630
+
631
+
632
+ class LinearLossParallel(ParallelStyle):
633
+ def __init__(
634
+ self,
635
+ *,
636
+ sequence_dim: int = 1,
637
+ use_local_output: bool = False,
638
+ ):
639
+ super().__init__()
640
+
641
+ self.sequence_sharding = (Shard(sequence_dim),)
642
+ self.use_local_output = use_local_output
643
+
644
+ @staticmethod
645
+ def _prepare_input_fn(sequence_sharding, mod, inputs, device_mesh):
646
+ x, target, weight, bias = inputs
647
+
648
+ if not isinstance(x, DTensor):
649
+ # assume the input passed in already sharded on the sequence dim and create the DTensor
650
+ x = DTensor.from_local(x, device_mesh, sequence_sharding)
651
+ if x.placements != sequence_sharding:
652
+ x = x.redistribute(placements=sequence_sharding, async_op=True)
653
+ if not isinstance(target, DTensor):
654
+ target = DTensor.from_local(target, device_mesh, [Replicate()])
655
+ if target.placements != sequence_sharding:
656
+ target = target.redistribute(placements=sequence_sharding, async_op=True)
657
+
658
+ if not isinstance(weight, DTensor):
659
+ weight = DTensor.from_local(weight, device_mesh, [Replicate()])
660
+ if weight.placements != [Replicate()]:
661
+ # we replicate the weight/bias in FLCE
662
+ weight = weight.redistribute(placements=[Replicate()], async_op=True)
663
+
664
+ if bias is not None and not isinstance(bias, DTensor):
665
+ bias = DTensor.from_local(bias, device_mesh, [Replicate()])
666
+ if bias is not None and bias.placements != [Replicate()]:
667
+ bias = bias.redistribute(placements=[Replicate()], async_op=True)
668
+
669
+ return x.to_local(), target.to_local(), weight.to_local(), bias.to_local() if bias is not None else bias
670
+
671
+ @staticmethod
672
+ def _prepare_output_fn(use_local_output, mod, outputs, device_mesh):
673
+ return outputs.to_local() if use_local_output else outputs
674
+
675
+ def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
676
+ return distribute_module(
677
+ module,
678
+ device_mesh,
679
+ partition_fn=None,
680
+ input_fn=partial(self._prepare_input_fn, self.sequence_sharding),
681
+ output_fn=partial(self._prepare_output_fn, self.use_local_output)
682
+ )
generation_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "temperature": 0.6,
10
+ "top_k": 20,
11
+ "top_p": 0.95,
12
+ "transformers_version": "4.51.0"
13
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:39baf3cd60eafe330cb12fd1b486ce9e6f44cb76d857a0b93cc28522c02d1223
3
+ size 4955015232
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e5ddbfbe89faadb7fd02f7675703a01d5e61e492ba62d787acf1f21ba205f64e
3
+ size 4712941464
model.safetensors.index.json ADDED
@@ -0,0 +1,848 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 9667843808
4
+ },
5
+ "weight_map": {
6
+ "image_newline": "model-00001-of-00002.safetensors",
7
+ "language_model.lm_head.weight": "model-00002-of-00002.safetensors",
8
+ "language_model.model.embed_tokens.weight": "model-00001-of-00002.safetensors",
9
+ "language_model.model.layers.0.input_layernorm.weight": "model-00001-of-00002.safetensors",
10
+ "language_model.model.layers.0.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
11
+ "language_model.model.layers.0.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
12
+ "language_model.model.layers.0.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
13
+ "language_model.model.layers.0.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
14
+ "language_model.model.layers.0.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
15
+ "language_model.model.layers.0.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
16
+ "language_model.model.layers.0.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
17
+ "language_model.model.layers.0.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
18
+ "language_model.model.layers.0.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
19
+ "language_model.model.layers.0.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
20
+ "language_model.model.layers.1.input_layernorm.weight": "model-00001-of-00002.safetensors",
21
+ "language_model.model.layers.1.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
22
+ "language_model.model.layers.1.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
23
+ "language_model.model.layers.1.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
24
+ "language_model.model.layers.1.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
25
+ "language_model.model.layers.1.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
26
+ "language_model.model.layers.1.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
27
+ "language_model.model.layers.1.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
28
+ "language_model.model.layers.1.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
29
+ "language_model.model.layers.1.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
30
+ "language_model.model.layers.1.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
31
+ "language_model.model.layers.10.input_layernorm.weight": "model-00001-of-00002.safetensors",
32
+ "language_model.model.layers.10.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
33
+ "language_model.model.layers.10.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
34
+ "language_model.model.layers.10.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
35
+ "language_model.model.layers.10.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
36
+ "language_model.model.layers.10.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
37
+ "language_model.model.layers.10.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
38
+ "language_model.model.layers.10.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
39
+ "language_model.model.layers.10.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
40
+ "language_model.model.layers.10.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
41
+ "language_model.model.layers.10.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
42
+ "language_model.model.layers.11.input_layernorm.weight": "model-00001-of-00002.safetensors",
43
+ "language_model.model.layers.11.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
44
+ "language_model.model.layers.11.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
45
+ "language_model.model.layers.11.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
46
+ "language_model.model.layers.11.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
47
+ "language_model.model.layers.11.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
48
+ "language_model.model.layers.11.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
49
+ "language_model.model.layers.11.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
50
+ "language_model.model.layers.11.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
51
+ "language_model.model.layers.11.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
52
+ "language_model.model.layers.11.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
53
+ "language_model.model.layers.12.input_layernorm.weight": "model-00001-of-00002.safetensors",
54
+ "language_model.model.layers.12.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
55
+ "language_model.model.layers.12.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
56
+ "language_model.model.layers.12.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
57
+ "language_model.model.layers.12.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
58
+ "language_model.model.layers.12.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
59
+ "language_model.model.layers.12.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
60
+ "language_model.model.layers.12.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
61
+ "language_model.model.layers.12.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
62
+ "language_model.model.layers.12.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
63
+ "language_model.model.layers.12.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
64
+ "language_model.model.layers.13.input_layernorm.weight": "model-00001-of-00002.safetensors",
65
+ "language_model.model.layers.13.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
66
+ "language_model.model.layers.13.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
67
+ "language_model.model.layers.13.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
68
+ "language_model.model.layers.13.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
69
+ "language_model.model.layers.13.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
70
+ "language_model.model.layers.13.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
71
+ "language_model.model.layers.13.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
72
+ "language_model.model.layers.13.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
73
+ "language_model.model.layers.13.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
74
+ "language_model.model.layers.13.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
75
+ "language_model.model.layers.14.input_layernorm.weight": "model-00001-of-00002.safetensors",
76
+ "language_model.model.layers.14.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
77
+ "language_model.model.layers.14.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
78
+ "language_model.model.layers.14.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
79
+ "language_model.model.layers.14.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
80
+ "language_model.model.layers.14.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
81
+ "language_model.model.layers.14.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
82
+ "language_model.model.layers.14.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
83
+ "language_model.model.layers.14.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
84
+ "language_model.model.layers.14.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
85
+ "language_model.model.layers.14.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
86
+ "language_model.model.layers.15.input_layernorm.weight": "model-00001-of-00002.safetensors",
87
+ "language_model.model.layers.15.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
88
+ "language_model.model.layers.15.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
89
+ "language_model.model.layers.15.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
90
+ "language_model.model.layers.15.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
91
+ "language_model.model.layers.15.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
92
+ "language_model.model.layers.15.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
93
+ "language_model.model.layers.15.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
94
+ "language_model.model.layers.15.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
95
+ "language_model.model.layers.15.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
96
+ "language_model.model.layers.15.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
97
+ "language_model.model.layers.16.input_layernorm.weight": "model-00002-of-00002.safetensors",
98
+ "language_model.model.layers.16.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
99
+ "language_model.model.layers.16.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
100
+ "language_model.model.layers.16.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
101
+ "language_model.model.layers.16.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
102
+ "language_model.model.layers.16.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
103
+ "language_model.model.layers.16.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
104
+ "language_model.model.layers.16.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
105
+ "language_model.model.layers.16.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
106
+ "language_model.model.layers.16.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
107
+ "language_model.model.layers.16.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
108
+ "language_model.model.layers.17.input_layernorm.weight": "model-00002-of-00002.safetensors",
109
+ "language_model.model.layers.17.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
110
+ "language_model.model.layers.17.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
111
+ "language_model.model.layers.17.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
112
+ "language_model.model.layers.17.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
113
+ "language_model.model.layers.17.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
114
+ "language_model.model.layers.17.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
115
+ "language_model.model.layers.17.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
116
+ "language_model.model.layers.17.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
117
+ "language_model.model.layers.17.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
118
+ "language_model.model.layers.17.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
119
+ "language_model.model.layers.18.input_layernorm.weight": "model-00002-of-00002.safetensors",
120
+ "language_model.model.layers.18.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
121
+ "language_model.model.layers.18.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
122
+ "language_model.model.layers.18.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
123
+ "language_model.model.layers.18.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
124
+ "language_model.model.layers.18.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
125
+ "language_model.model.layers.18.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
126
+ "language_model.model.layers.18.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
127
+ "language_model.model.layers.18.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
128
+ "language_model.model.layers.18.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
129
+ "language_model.model.layers.18.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
130
+ "language_model.model.layers.19.input_layernorm.weight": "model-00002-of-00002.safetensors",
131
+ "language_model.model.layers.19.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
132
+ "language_model.model.layers.19.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
133
+ "language_model.model.layers.19.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
134
+ "language_model.model.layers.19.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
135
+ "language_model.model.layers.19.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
136
+ "language_model.model.layers.19.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
137
+ "language_model.model.layers.19.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
138
+ "language_model.model.layers.19.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
139
+ "language_model.model.layers.19.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
140
+ "language_model.model.layers.19.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
141
+ "language_model.model.layers.2.input_layernorm.weight": "model-00001-of-00002.safetensors",
142
+ "language_model.model.layers.2.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
143
+ "language_model.model.layers.2.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
144
+ "language_model.model.layers.2.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
145
+ "language_model.model.layers.2.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
146
+ "language_model.model.layers.2.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
147
+ "language_model.model.layers.2.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
148
+ "language_model.model.layers.2.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
149
+ "language_model.model.layers.2.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
150
+ "language_model.model.layers.2.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
151
+ "language_model.model.layers.2.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
152
+ "language_model.model.layers.20.input_layernorm.weight": "model-00002-of-00002.safetensors",
153
+ "language_model.model.layers.20.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
154
+ "language_model.model.layers.20.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
155
+ "language_model.model.layers.20.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
156
+ "language_model.model.layers.20.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
157
+ "language_model.model.layers.20.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
158
+ "language_model.model.layers.20.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
159
+ "language_model.model.layers.20.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
160
+ "language_model.model.layers.20.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
161
+ "language_model.model.layers.20.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
162
+ "language_model.model.layers.20.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
163
+ "language_model.model.layers.21.input_layernorm.weight": "model-00002-of-00002.safetensors",
164
+ "language_model.model.layers.21.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
165
+ "language_model.model.layers.21.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
166
+ "language_model.model.layers.21.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
167
+ "language_model.model.layers.21.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
168
+ "language_model.model.layers.21.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
169
+ "language_model.model.layers.21.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
170
+ "language_model.model.layers.21.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
171
+ "language_model.model.layers.21.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
172
+ "language_model.model.layers.21.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
173
+ "language_model.model.layers.21.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
174
+ "language_model.model.layers.22.input_layernorm.weight": "model-00002-of-00002.safetensors",
175
+ "language_model.model.layers.22.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
176
+ "language_model.model.layers.22.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
177
+ "language_model.model.layers.22.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
178
+ "language_model.model.layers.22.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
179
+ "language_model.model.layers.22.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
180
+ "language_model.model.layers.22.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
181
+ "language_model.model.layers.22.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
182
+ "language_model.model.layers.22.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
183
+ "language_model.model.layers.22.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
184
+ "language_model.model.layers.22.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
185
+ "language_model.model.layers.23.input_layernorm.weight": "model-00002-of-00002.safetensors",
186
+ "language_model.model.layers.23.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
187
+ "language_model.model.layers.23.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
188
+ "language_model.model.layers.23.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
189
+ "language_model.model.layers.23.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
190
+ "language_model.model.layers.23.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
191
+ "language_model.model.layers.23.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
192
+ "language_model.model.layers.23.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
193
+ "language_model.model.layers.23.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
194
+ "language_model.model.layers.23.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
195
+ "language_model.model.layers.23.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
196
+ "language_model.model.layers.24.input_layernorm.weight": "model-00002-of-00002.safetensors",
197
+ "language_model.model.layers.24.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
198
+ "language_model.model.layers.24.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
199
+ "language_model.model.layers.24.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
200
+ "language_model.model.layers.24.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
201
+ "language_model.model.layers.24.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
202
+ "language_model.model.layers.24.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
203
+ "language_model.model.layers.24.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
204
+ "language_model.model.layers.24.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
205
+ "language_model.model.layers.24.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
206
+ "language_model.model.layers.24.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
207
+ "language_model.model.layers.25.input_layernorm.weight": "model-00002-of-00002.safetensors",
208
+ "language_model.model.layers.25.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
209
+ "language_model.model.layers.25.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
210
+ "language_model.model.layers.25.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
211
+ "language_model.model.layers.25.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
212
+ "language_model.model.layers.25.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
213
+ "language_model.model.layers.25.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
214
+ "language_model.model.layers.25.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
215
+ "language_model.model.layers.25.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
216
+ "language_model.model.layers.25.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
217
+ "language_model.model.layers.25.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
218
+ "language_model.model.layers.26.input_layernorm.weight": "model-00002-of-00002.safetensors",
219
+ "language_model.model.layers.26.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
220
+ "language_model.model.layers.26.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
221
+ "language_model.model.layers.26.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
222
+ "language_model.model.layers.26.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
223
+ "language_model.model.layers.26.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
224
+ "language_model.model.layers.26.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
225
+ "language_model.model.layers.26.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
226
+ "language_model.model.layers.26.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
227
+ "language_model.model.layers.26.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
228
+ "language_model.model.layers.26.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
229
+ "language_model.model.layers.27.input_layernorm.weight": "model-00002-of-00002.safetensors",
230
+ "language_model.model.layers.27.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
231
+ "language_model.model.layers.27.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
232
+ "language_model.model.layers.27.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
233
+ "language_model.model.layers.27.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
234
+ "language_model.model.layers.27.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
235
+ "language_model.model.layers.27.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
236
+ "language_model.model.layers.27.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
237
+ "language_model.model.layers.27.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
238
+ "language_model.model.layers.27.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
239
+ "language_model.model.layers.27.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
240
+ "language_model.model.layers.28.input_layernorm.weight": "model-00002-of-00002.safetensors",
241
+ "language_model.model.layers.28.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
242
+ "language_model.model.layers.28.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
243
+ "language_model.model.layers.28.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
244
+ "language_model.model.layers.28.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
245
+ "language_model.model.layers.28.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
246
+ "language_model.model.layers.28.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
247
+ "language_model.model.layers.28.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
248
+ "language_model.model.layers.28.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
249
+ "language_model.model.layers.28.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
250
+ "language_model.model.layers.28.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
251
+ "language_model.model.layers.29.input_layernorm.weight": "model-00002-of-00002.safetensors",
252
+ "language_model.model.layers.29.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
253
+ "language_model.model.layers.29.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
254
+ "language_model.model.layers.29.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
255
+ "language_model.model.layers.29.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
256
+ "language_model.model.layers.29.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
257
+ "language_model.model.layers.29.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
258
+ "language_model.model.layers.29.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
259
+ "language_model.model.layers.29.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
260
+ "language_model.model.layers.29.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
261
+ "language_model.model.layers.29.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
262
+ "language_model.model.layers.3.input_layernorm.weight": "model-00001-of-00002.safetensors",
263
+ "language_model.model.layers.3.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
264
+ "language_model.model.layers.3.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
265
+ "language_model.model.layers.3.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
266
+ "language_model.model.layers.3.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
267
+ "language_model.model.layers.3.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
268
+ "language_model.model.layers.3.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
269
+ "language_model.model.layers.3.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
270
+ "language_model.model.layers.3.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
271
+ "language_model.model.layers.3.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
272
+ "language_model.model.layers.3.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
273
+ "language_model.model.layers.30.input_layernorm.weight": "model-00002-of-00002.safetensors",
274
+ "language_model.model.layers.30.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
275
+ "language_model.model.layers.30.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
276
+ "language_model.model.layers.30.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
277
+ "language_model.model.layers.30.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
278
+ "language_model.model.layers.30.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
279
+ "language_model.model.layers.30.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
280
+ "language_model.model.layers.30.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
281
+ "language_model.model.layers.30.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
282
+ "language_model.model.layers.30.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
283
+ "language_model.model.layers.30.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
284
+ "language_model.model.layers.31.input_layernorm.weight": "model-00002-of-00002.safetensors",
285
+ "language_model.model.layers.31.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
286
+ "language_model.model.layers.31.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
287
+ "language_model.model.layers.31.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
288
+ "language_model.model.layers.31.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
289
+ "language_model.model.layers.31.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
290
+ "language_model.model.layers.31.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
291
+ "language_model.model.layers.31.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
292
+ "language_model.model.layers.31.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
293
+ "language_model.model.layers.31.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
294
+ "language_model.model.layers.31.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
295
+ "language_model.model.layers.32.input_layernorm.weight": "model-00002-of-00002.safetensors",
296
+ "language_model.model.layers.32.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
297
+ "language_model.model.layers.32.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
298
+ "language_model.model.layers.32.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
299
+ "language_model.model.layers.32.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
300
+ "language_model.model.layers.32.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
301
+ "language_model.model.layers.32.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
302
+ "language_model.model.layers.32.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
303
+ "language_model.model.layers.32.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
304
+ "language_model.model.layers.32.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
305
+ "language_model.model.layers.32.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
306
+ "language_model.model.layers.33.input_layernorm.weight": "model-00002-of-00002.safetensors",
307
+ "language_model.model.layers.33.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
308
+ "language_model.model.layers.33.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
309
+ "language_model.model.layers.33.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
310
+ "language_model.model.layers.33.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
311
+ "language_model.model.layers.33.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
312
+ "language_model.model.layers.33.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
313
+ "language_model.model.layers.33.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
314
+ "language_model.model.layers.33.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
315
+ "language_model.model.layers.33.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
316
+ "language_model.model.layers.33.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
317
+ "language_model.model.layers.34.input_layernorm.weight": "model-00002-of-00002.safetensors",
318
+ "language_model.model.layers.34.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
319
+ "language_model.model.layers.34.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
320
+ "language_model.model.layers.34.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
321
+ "language_model.model.layers.34.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
322
+ "language_model.model.layers.34.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
323
+ "language_model.model.layers.34.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
324
+ "language_model.model.layers.34.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
325
+ "language_model.model.layers.34.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
326
+ "language_model.model.layers.34.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
327
+ "language_model.model.layers.34.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
328
+ "language_model.model.layers.35.input_layernorm.weight": "model-00002-of-00002.safetensors",
329
+ "language_model.model.layers.35.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
330
+ "language_model.model.layers.35.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
331
+ "language_model.model.layers.35.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
332
+ "language_model.model.layers.35.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
333
+ "language_model.model.layers.35.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
334
+ "language_model.model.layers.35.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
335
+ "language_model.model.layers.35.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
336
+ "language_model.model.layers.35.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
337
+ "language_model.model.layers.35.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
338
+ "language_model.model.layers.35.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
339
+ "language_model.model.layers.4.input_layernorm.weight": "model-00001-of-00002.safetensors",
340
+ "language_model.model.layers.4.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
341
+ "language_model.model.layers.4.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
342
+ "language_model.model.layers.4.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
343
+ "language_model.model.layers.4.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
344
+ "language_model.model.layers.4.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
345
+ "language_model.model.layers.4.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
346
+ "language_model.model.layers.4.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
347
+ "language_model.model.layers.4.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
348
+ "language_model.model.layers.4.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
349
+ "language_model.model.layers.4.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
350
+ "language_model.model.layers.5.input_layernorm.weight": "model-00001-of-00002.safetensors",
351
+ "language_model.model.layers.5.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
352
+ "language_model.model.layers.5.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
353
+ "language_model.model.layers.5.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
354
+ "language_model.model.layers.5.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
355
+ "language_model.model.layers.5.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
356
+ "language_model.model.layers.5.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
357
+ "language_model.model.layers.5.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
358
+ "language_model.model.layers.5.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
359
+ "language_model.model.layers.5.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
360
+ "language_model.model.layers.5.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
361
+ "language_model.model.layers.6.input_layernorm.weight": "model-00001-of-00002.safetensors",
362
+ "language_model.model.layers.6.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
363
+ "language_model.model.layers.6.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
364
+ "language_model.model.layers.6.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
365
+ "language_model.model.layers.6.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
366
+ "language_model.model.layers.6.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
367
+ "language_model.model.layers.6.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
368
+ "language_model.model.layers.6.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
369
+ "language_model.model.layers.6.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
370
+ "language_model.model.layers.6.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
371
+ "language_model.model.layers.6.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
372
+ "language_model.model.layers.7.input_layernorm.weight": "model-00001-of-00002.safetensors",
373
+ "language_model.model.layers.7.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
374
+ "language_model.model.layers.7.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
375
+ "language_model.model.layers.7.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
376
+ "language_model.model.layers.7.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
377
+ "language_model.model.layers.7.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
378
+ "language_model.model.layers.7.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
379
+ "language_model.model.layers.7.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
380
+ "language_model.model.layers.7.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
381
+ "language_model.model.layers.7.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
382
+ "language_model.model.layers.7.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
383
+ "language_model.model.layers.8.input_layernorm.weight": "model-00001-of-00002.safetensors",
384
+ "language_model.model.layers.8.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
385
+ "language_model.model.layers.8.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
386
+ "language_model.model.layers.8.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
387
+ "language_model.model.layers.8.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
388
+ "language_model.model.layers.8.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
389
+ "language_model.model.layers.8.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
390
+ "language_model.model.layers.8.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
391
+ "language_model.model.layers.8.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
392
+ "language_model.model.layers.8.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
393
+ "language_model.model.layers.8.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
394
+ "language_model.model.layers.9.input_layernorm.weight": "model-00001-of-00002.safetensors",
395
+ "language_model.model.layers.9.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
396
+ "language_model.model.layers.9.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
397
+ "language_model.model.layers.9.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
398
+ "language_model.model.layers.9.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
399
+ "language_model.model.layers.9.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
400
+ "language_model.model.layers.9.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
401
+ "language_model.model.layers.9.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
402
+ "language_model.model.layers.9.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
403
+ "language_model.model.layers.9.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
404
+ "language_model.model.layers.9.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
405
+ "language_model.model.norm.weight": "model-00002-of-00002.safetensors",
406
+ "multi_modal_projector.linear_1.bias": "model-00001-of-00002.safetensors",
407
+ "multi_modal_projector.linear_1.weight": "model-00001-of-00002.safetensors",
408
+ "multi_modal_projector.linear_2.bias": "model-00001-of-00002.safetensors",
409
+ "multi_modal_projector.linear_2.weight": "model-00001-of-00002.safetensors",
410
+ "vision_tower.vision_model.embeddings.patch_embedding.bias": "model-00001-of-00002.safetensors",
411
+ "vision_tower.vision_model.embeddings.patch_embedding.weight": "model-00001-of-00002.safetensors",
412
+ "vision_tower.vision_model.embeddings.position_embedding.weight": "model-00001-of-00002.safetensors",
413
+ "vision_tower.vision_model.encoder.layers.0.layer_norm1.bias": "model-00001-of-00002.safetensors",
414
+ "vision_tower.vision_model.encoder.layers.0.layer_norm1.weight": "model-00001-of-00002.safetensors",
415
+ "vision_tower.vision_model.encoder.layers.0.layer_norm2.bias": "model-00001-of-00002.safetensors",
416
+ "vision_tower.vision_model.encoder.layers.0.layer_norm2.weight": "model-00001-of-00002.safetensors",
417
+ "vision_tower.vision_model.encoder.layers.0.mlp.fc1.bias": "model-00001-of-00002.safetensors",
418
+ "vision_tower.vision_model.encoder.layers.0.mlp.fc1.weight": "model-00001-of-00002.safetensors",
419
+ "vision_tower.vision_model.encoder.layers.0.mlp.fc2.bias": "model-00001-of-00002.safetensors",
420
+ "vision_tower.vision_model.encoder.layers.0.mlp.fc2.weight": "model-00001-of-00002.safetensors",
421
+ "vision_tower.vision_model.encoder.layers.0.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
422
+ "vision_tower.vision_model.encoder.layers.0.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
423
+ "vision_tower.vision_model.encoder.layers.0.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
424
+ "vision_tower.vision_model.encoder.layers.0.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
425
+ "vision_tower.vision_model.encoder.layers.0.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
426
+ "vision_tower.vision_model.encoder.layers.0.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
427
+ "vision_tower.vision_model.encoder.layers.0.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
428
+ "vision_tower.vision_model.encoder.layers.0.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
429
+ "vision_tower.vision_model.encoder.layers.1.layer_norm1.bias": "model-00001-of-00002.safetensors",
430
+ "vision_tower.vision_model.encoder.layers.1.layer_norm1.weight": "model-00001-of-00002.safetensors",
431
+ "vision_tower.vision_model.encoder.layers.1.layer_norm2.bias": "model-00001-of-00002.safetensors",
432
+ "vision_tower.vision_model.encoder.layers.1.layer_norm2.weight": "model-00001-of-00002.safetensors",
433
+ "vision_tower.vision_model.encoder.layers.1.mlp.fc1.bias": "model-00001-of-00002.safetensors",
434
+ "vision_tower.vision_model.encoder.layers.1.mlp.fc1.weight": "model-00001-of-00002.safetensors",
435
+ "vision_tower.vision_model.encoder.layers.1.mlp.fc2.bias": "model-00001-of-00002.safetensors",
436
+ "vision_tower.vision_model.encoder.layers.1.mlp.fc2.weight": "model-00001-of-00002.safetensors",
437
+ "vision_tower.vision_model.encoder.layers.1.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
438
+ "vision_tower.vision_model.encoder.layers.1.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
439
+ "vision_tower.vision_model.encoder.layers.1.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
440
+ "vision_tower.vision_model.encoder.layers.1.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
441
+ "vision_tower.vision_model.encoder.layers.1.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
442
+ "vision_tower.vision_model.encoder.layers.1.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
443
+ "vision_tower.vision_model.encoder.layers.1.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
444
+ "vision_tower.vision_model.encoder.layers.1.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
445
+ "vision_tower.vision_model.encoder.layers.10.layer_norm1.bias": "model-00001-of-00002.safetensors",
446
+ "vision_tower.vision_model.encoder.layers.10.layer_norm1.weight": "model-00001-of-00002.safetensors",
447
+ "vision_tower.vision_model.encoder.layers.10.layer_norm2.bias": "model-00001-of-00002.safetensors",
448
+ "vision_tower.vision_model.encoder.layers.10.layer_norm2.weight": "model-00001-of-00002.safetensors",
449
+ "vision_tower.vision_model.encoder.layers.10.mlp.fc1.bias": "model-00001-of-00002.safetensors",
450
+ "vision_tower.vision_model.encoder.layers.10.mlp.fc1.weight": "model-00001-of-00002.safetensors",
451
+ "vision_tower.vision_model.encoder.layers.10.mlp.fc2.bias": "model-00001-of-00002.safetensors",
452
+ "vision_tower.vision_model.encoder.layers.10.mlp.fc2.weight": "model-00001-of-00002.safetensors",
453
+ "vision_tower.vision_model.encoder.layers.10.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
454
+ "vision_tower.vision_model.encoder.layers.10.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
455
+ "vision_tower.vision_model.encoder.layers.10.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
456
+ "vision_tower.vision_model.encoder.layers.10.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
457
+ "vision_tower.vision_model.encoder.layers.10.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
458
+ "vision_tower.vision_model.encoder.layers.10.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
459
+ "vision_tower.vision_model.encoder.layers.10.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
460
+ "vision_tower.vision_model.encoder.layers.10.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
461
+ "vision_tower.vision_model.encoder.layers.11.layer_norm1.bias": "model-00001-of-00002.safetensors",
462
+ "vision_tower.vision_model.encoder.layers.11.layer_norm1.weight": "model-00001-of-00002.safetensors",
463
+ "vision_tower.vision_model.encoder.layers.11.layer_norm2.bias": "model-00001-of-00002.safetensors",
464
+ "vision_tower.vision_model.encoder.layers.11.layer_norm2.weight": "model-00001-of-00002.safetensors",
465
+ "vision_tower.vision_model.encoder.layers.11.mlp.fc1.bias": "model-00001-of-00002.safetensors",
466
+ "vision_tower.vision_model.encoder.layers.11.mlp.fc1.weight": "model-00001-of-00002.safetensors",
467
+ "vision_tower.vision_model.encoder.layers.11.mlp.fc2.bias": "model-00001-of-00002.safetensors",
468
+ "vision_tower.vision_model.encoder.layers.11.mlp.fc2.weight": "model-00001-of-00002.safetensors",
469
+ "vision_tower.vision_model.encoder.layers.11.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
470
+ "vision_tower.vision_model.encoder.layers.11.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
471
+ "vision_tower.vision_model.encoder.layers.11.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
472
+ "vision_tower.vision_model.encoder.layers.11.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
473
+ "vision_tower.vision_model.encoder.layers.11.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
474
+ "vision_tower.vision_model.encoder.layers.11.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
475
+ "vision_tower.vision_model.encoder.layers.11.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
476
+ "vision_tower.vision_model.encoder.layers.11.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
477
+ "vision_tower.vision_model.encoder.layers.12.layer_norm1.bias": "model-00001-of-00002.safetensors",
478
+ "vision_tower.vision_model.encoder.layers.12.layer_norm1.weight": "model-00001-of-00002.safetensors",
479
+ "vision_tower.vision_model.encoder.layers.12.layer_norm2.bias": "model-00001-of-00002.safetensors",
480
+ "vision_tower.vision_model.encoder.layers.12.layer_norm2.weight": "model-00001-of-00002.safetensors",
481
+ "vision_tower.vision_model.encoder.layers.12.mlp.fc1.bias": "model-00001-of-00002.safetensors",
482
+ "vision_tower.vision_model.encoder.layers.12.mlp.fc1.weight": "model-00001-of-00002.safetensors",
483
+ "vision_tower.vision_model.encoder.layers.12.mlp.fc2.bias": "model-00001-of-00002.safetensors",
484
+ "vision_tower.vision_model.encoder.layers.12.mlp.fc2.weight": "model-00001-of-00002.safetensors",
485
+ "vision_tower.vision_model.encoder.layers.12.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
486
+ "vision_tower.vision_model.encoder.layers.12.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
487
+ "vision_tower.vision_model.encoder.layers.12.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
488
+ "vision_tower.vision_model.encoder.layers.12.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
489
+ "vision_tower.vision_model.encoder.layers.12.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
490
+ "vision_tower.vision_model.encoder.layers.12.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
491
+ "vision_tower.vision_model.encoder.layers.12.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
492
+ "vision_tower.vision_model.encoder.layers.12.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
493
+ "vision_tower.vision_model.encoder.layers.13.layer_norm1.bias": "model-00001-of-00002.safetensors",
494
+ "vision_tower.vision_model.encoder.layers.13.layer_norm1.weight": "model-00001-of-00002.safetensors",
495
+ "vision_tower.vision_model.encoder.layers.13.layer_norm2.bias": "model-00001-of-00002.safetensors",
496
+ "vision_tower.vision_model.encoder.layers.13.layer_norm2.weight": "model-00001-of-00002.safetensors",
497
+ "vision_tower.vision_model.encoder.layers.13.mlp.fc1.bias": "model-00001-of-00002.safetensors",
498
+ "vision_tower.vision_model.encoder.layers.13.mlp.fc1.weight": "model-00001-of-00002.safetensors",
499
+ "vision_tower.vision_model.encoder.layers.13.mlp.fc2.bias": "model-00001-of-00002.safetensors",
500
+ "vision_tower.vision_model.encoder.layers.13.mlp.fc2.weight": "model-00001-of-00002.safetensors",
501
+ "vision_tower.vision_model.encoder.layers.13.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
502
+ "vision_tower.vision_model.encoder.layers.13.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
503
+ "vision_tower.vision_model.encoder.layers.13.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
504
+ "vision_tower.vision_model.encoder.layers.13.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
505
+ "vision_tower.vision_model.encoder.layers.13.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
506
+ "vision_tower.vision_model.encoder.layers.13.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
507
+ "vision_tower.vision_model.encoder.layers.13.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
508
+ "vision_tower.vision_model.encoder.layers.13.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
509
+ "vision_tower.vision_model.encoder.layers.14.layer_norm1.bias": "model-00001-of-00002.safetensors",
510
+ "vision_tower.vision_model.encoder.layers.14.layer_norm1.weight": "model-00001-of-00002.safetensors",
511
+ "vision_tower.vision_model.encoder.layers.14.layer_norm2.bias": "model-00001-of-00002.safetensors",
512
+ "vision_tower.vision_model.encoder.layers.14.layer_norm2.weight": "model-00001-of-00002.safetensors",
513
+ "vision_tower.vision_model.encoder.layers.14.mlp.fc1.bias": "model-00001-of-00002.safetensors",
514
+ "vision_tower.vision_model.encoder.layers.14.mlp.fc1.weight": "model-00001-of-00002.safetensors",
515
+ "vision_tower.vision_model.encoder.layers.14.mlp.fc2.bias": "model-00001-of-00002.safetensors",
516
+ "vision_tower.vision_model.encoder.layers.14.mlp.fc2.weight": "model-00001-of-00002.safetensors",
517
+ "vision_tower.vision_model.encoder.layers.14.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
518
+ "vision_tower.vision_model.encoder.layers.14.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
519
+ "vision_tower.vision_model.encoder.layers.14.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
520
+ "vision_tower.vision_model.encoder.layers.14.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
521
+ "vision_tower.vision_model.encoder.layers.14.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
522
+ "vision_tower.vision_model.encoder.layers.14.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
523
+ "vision_tower.vision_model.encoder.layers.14.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
524
+ "vision_tower.vision_model.encoder.layers.14.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
525
+ "vision_tower.vision_model.encoder.layers.15.layer_norm1.bias": "model-00001-of-00002.safetensors",
526
+ "vision_tower.vision_model.encoder.layers.15.layer_norm1.weight": "model-00001-of-00002.safetensors",
527
+ "vision_tower.vision_model.encoder.layers.15.layer_norm2.bias": "model-00001-of-00002.safetensors",
528
+ "vision_tower.vision_model.encoder.layers.15.layer_norm2.weight": "model-00001-of-00002.safetensors",
529
+ "vision_tower.vision_model.encoder.layers.15.mlp.fc1.bias": "model-00001-of-00002.safetensors",
530
+ "vision_tower.vision_model.encoder.layers.15.mlp.fc1.weight": "model-00001-of-00002.safetensors",
531
+ "vision_tower.vision_model.encoder.layers.15.mlp.fc2.bias": "model-00001-of-00002.safetensors",
532
+ "vision_tower.vision_model.encoder.layers.15.mlp.fc2.weight": "model-00001-of-00002.safetensors",
533
+ "vision_tower.vision_model.encoder.layers.15.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
534
+ "vision_tower.vision_model.encoder.layers.15.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
535
+ "vision_tower.vision_model.encoder.layers.15.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
536
+ "vision_tower.vision_model.encoder.layers.15.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
537
+ "vision_tower.vision_model.encoder.layers.15.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
538
+ "vision_tower.vision_model.encoder.layers.15.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
539
+ "vision_tower.vision_model.encoder.layers.15.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
540
+ "vision_tower.vision_model.encoder.layers.15.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
541
+ "vision_tower.vision_model.encoder.layers.16.layer_norm1.bias": "model-00001-of-00002.safetensors",
542
+ "vision_tower.vision_model.encoder.layers.16.layer_norm1.weight": "model-00001-of-00002.safetensors",
543
+ "vision_tower.vision_model.encoder.layers.16.layer_norm2.bias": "model-00001-of-00002.safetensors",
544
+ "vision_tower.vision_model.encoder.layers.16.layer_norm2.weight": "model-00001-of-00002.safetensors",
545
+ "vision_tower.vision_model.encoder.layers.16.mlp.fc1.bias": "model-00001-of-00002.safetensors",
546
+ "vision_tower.vision_model.encoder.layers.16.mlp.fc1.weight": "model-00001-of-00002.safetensors",
547
+ "vision_tower.vision_model.encoder.layers.16.mlp.fc2.bias": "model-00001-of-00002.safetensors",
548
+ "vision_tower.vision_model.encoder.layers.16.mlp.fc2.weight": "model-00001-of-00002.safetensors",
549
+ "vision_tower.vision_model.encoder.layers.16.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
550
+ "vision_tower.vision_model.encoder.layers.16.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
551
+ "vision_tower.vision_model.encoder.layers.16.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
552
+ "vision_tower.vision_model.encoder.layers.16.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
553
+ "vision_tower.vision_model.encoder.layers.16.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
554
+ "vision_tower.vision_model.encoder.layers.16.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
555
+ "vision_tower.vision_model.encoder.layers.16.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
556
+ "vision_tower.vision_model.encoder.layers.16.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
557
+ "vision_tower.vision_model.encoder.layers.17.layer_norm1.bias": "model-00001-of-00002.safetensors",
558
+ "vision_tower.vision_model.encoder.layers.17.layer_norm1.weight": "model-00001-of-00002.safetensors",
559
+ "vision_tower.vision_model.encoder.layers.17.layer_norm2.bias": "model-00001-of-00002.safetensors",
560
+ "vision_tower.vision_model.encoder.layers.17.layer_norm2.weight": "model-00001-of-00002.safetensors",
561
+ "vision_tower.vision_model.encoder.layers.17.mlp.fc1.bias": "model-00001-of-00002.safetensors",
562
+ "vision_tower.vision_model.encoder.layers.17.mlp.fc1.weight": "model-00001-of-00002.safetensors",
563
+ "vision_tower.vision_model.encoder.layers.17.mlp.fc2.bias": "model-00001-of-00002.safetensors",
564
+ "vision_tower.vision_model.encoder.layers.17.mlp.fc2.weight": "model-00001-of-00002.safetensors",
565
+ "vision_tower.vision_model.encoder.layers.17.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
566
+ "vision_tower.vision_model.encoder.layers.17.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
567
+ "vision_tower.vision_model.encoder.layers.17.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
568
+ "vision_tower.vision_model.encoder.layers.17.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
569
+ "vision_tower.vision_model.encoder.layers.17.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
570
+ "vision_tower.vision_model.encoder.layers.17.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
571
+ "vision_tower.vision_model.encoder.layers.17.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
572
+ "vision_tower.vision_model.encoder.layers.17.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
573
+ "vision_tower.vision_model.encoder.layers.18.layer_norm1.bias": "model-00001-of-00002.safetensors",
574
+ "vision_tower.vision_model.encoder.layers.18.layer_norm1.weight": "model-00001-of-00002.safetensors",
575
+ "vision_tower.vision_model.encoder.layers.18.layer_norm2.bias": "model-00001-of-00002.safetensors",
576
+ "vision_tower.vision_model.encoder.layers.18.layer_norm2.weight": "model-00001-of-00002.safetensors",
577
+ "vision_tower.vision_model.encoder.layers.18.mlp.fc1.bias": "model-00001-of-00002.safetensors",
578
+ "vision_tower.vision_model.encoder.layers.18.mlp.fc1.weight": "model-00001-of-00002.safetensors",
579
+ "vision_tower.vision_model.encoder.layers.18.mlp.fc2.bias": "model-00001-of-00002.safetensors",
580
+ "vision_tower.vision_model.encoder.layers.18.mlp.fc2.weight": "model-00001-of-00002.safetensors",
581
+ "vision_tower.vision_model.encoder.layers.18.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
582
+ "vision_tower.vision_model.encoder.layers.18.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
583
+ "vision_tower.vision_model.encoder.layers.18.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
584
+ "vision_tower.vision_model.encoder.layers.18.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
585
+ "vision_tower.vision_model.encoder.layers.18.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
586
+ "vision_tower.vision_model.encoder.layers.18.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
587
+ "vision_tower.vision_model.encoder.layers.18.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
588
+ "vision_tower.vision_model.encoder.layers.18.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
589
+ "vision_tower.vision_model.encoder.layers.19.layer_norm1.bias": "model-00001-of-00002.safetensors",
590
+ "vision_tower.vision_model.encoder.layers.19.layer_norm1.weight": "model-00001-of-00002.safetensors",
591
+ "vision_tower.vision_model.encoder.layers.19.layer_norm2.bias": "model-00001-of-00002.safetensors",
592
+ "vision_tower.vision_model.encoder.layers.19.layer_norm2.weight": "model-00001-of-00002.safetensors",
593
+ "vision_tower.vision_model.encoder.layers.19.mlp.fc1.bias": "model-00001-of-00002.safetensors",
594
+ "vision_tower.vision_model.encoder.layers.19.mlp.fc1.weight": "model-00001-of-00002.safetensors",
595
+ "vision_tower.vision_model.encoder.layers.19.mlp.fc2.bias": "model-00001-of-00002.safetensors",
596
+ "vision_tower.vision_model.encoder.layers.19.mlp.fc2.weight": "model-00001-of-00002.safetensors",
597
+ "vision_tower.vision_model.encoder.layers.19.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
598
+ "vision_tower.vision_model.encoder.layers.19.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
599
+ "vision_tower.vision_model.encoder.layers.19.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
600
+ "vision_tower.vision_model.encoder.layers.19.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
601
+ "vision_tower.vision_model.encoder.layers.19.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
602
+ "vision_tower.vision_model.encoder.layers.19.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
603
+ "vision_tower.vision_model.encoder.layers.19.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
604
+ "vision_tower.vision_model.encoder.layers.19.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
605
+ "vision_tower.vision_model.encoder.layers.2.layer_norm1.bias": "model-00001-of-00002.safetensors",
606
+ "vision_tower.vision_model.encoder.layers.2.layer_norm1.weight": "model-00001-of-00002.safetensors",
607
+ "vision_tower.vision_model.encoder.layers.2.layer_norm2.bias": "model-00001-of-00002.safetensors",
608
+ "vision_tower.vision_model.encoder.layers.2.layer_norm2.weight": "model-00001-of-00002.safetensors",
609
+ "vision_tower.vision_model.encoder.layers.2.mlp.fc1.bias": "model-00001-of-00002.safetensors",
610
+ "vision_tower.vision_model.encoder.layers.2.mlp.fc1.weight": "model-00001-of-00002.safetensors",
611
+ "vision_tower.vision_model.encoder.layers.2.mlp.fc2.bias": "model-00001-of-00002.safetensors",
612
+ "vision_tower.vision_model.encoder.layers.2.mlp.fc2.weight": "model-00001-of-00002.safetensors",
613
+ "vision_tower.vision_model.encoder.layers.2.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
614
+ "vision_tower.vision_model.encoder.layers.2.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
615
+ "vision_tower.vision_model.encoder.layers.2.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
616
+ "vision_tower.vision_model.encoder.layers.2.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
617
+ "vision_tower.vision_model.encoder.layers.2.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
618
+ "vision_tower.vision_model.encoder.layers.2.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
619
+ "vision_tower.vision_model.encoder.layers.2.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
620
+ "vision_tower.vision_model.encoder.layers.2.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
621
+ "vision_tower.vision_model.encoder.layers.20.layer_norm1.bias": "model-00001-of-00002.safetensors",
622
+ "vision_tower.vision_model.encoder.layers.20.layer_norm1.weight": "model-00001-of-00002.safetensors",
623
+ "vision_tower.vision_model.encoder.layers.20.layer_norm2.bias": "model-00001-of-00002.safetensors",
624
+ "vision_tower.vision_model.encoder.layers.20.layer_norm2.weight": "model-00001-of-00002.safetensors",
625
+ "vision_tower.vision_model.encoder.layers.20.mlp.fc1.bias": "model-00001-of-00002.safetensors",
626
+ "vision_tower.vision_model.encoder.layers.20.mlp.fc1.weight": "model-00001-of-00002.safetensors",
627
+ "vision_tower.vision_model.encoder.layers.20.mlp.fc2.bias": "model-00001-of-00002.safetensors",
628
+ "vision_tower.vision_model.encoder.layers.20.mlp.fc2.weight": "model-00001-of-00002.safetensors",
629
+ "vision_tower.vision_model.encoder.layers.20.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
630
+ "vision_tower.vision_model.encoder.layers.20.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
631
+ "vision_tower.vision_model.encoder.layers.20.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
632
+ "vision_tower.vision_model.encoder.layers.20.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
633
+ "vision_tower.vision_model.encoder.layers.20.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
634
+ "vision_tower.vision_model.encoder.layers.20.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
635
+ "vision_tower.vision_model.encoder.layers.20.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
636
+ "vision_tower.vision_model.encoder.layers.20.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
637
+ "vision_tower.vision_model.encoder.layers.21.layer_norm1.bias": "model-00001-of-00002.safetensors",
638
+ "vision_tower.vision_model.encoder.layers.21.layer_norm1.weight": "model-00001-of-00002.safetensors",
639
+ "vision_tower.vision_model.encoder.layers.21.layer_norm2.bias": "model-00001-of-00002.safetensors",
640
+ "vision_tower.vision_model.encoder.layers.21.layer_norm2.weight": "model-00001-of-00002.safetensors",
641
+ "vision_tower.vision_model.encoder.layers.21.mlp.fc1.bias": "model-00001-of-00002.safetensors",
642
+ "vision_tower.vision_model.encoder.layers.21.mlp.fc1.weight": "model-00001-of-00002.safetensors",
643
+ "vision_tower.vision_model.encoder.layers.21.mlp.fc2.bias": "model-00001-of-00002.safetensors",
644
+ "vision_tower.vision_model.encoder.layers.21.mlp.fc2.weight": "model-00001-of-00002.safetensors",
645
+ "vision_tower.vision_model.encoder.layers.21.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
646
+ "vision_tower.vision_model.encoder.layers.21.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
647
+ "vision_tower.vision_model.encoder.layers.21.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
648
+ "vision_tower.vision_model.encoder.layers.21.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
649
+ "vision_tower.vision_model.encoder.layers.21.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
650
+ "vision_tower.vision_model.encoder.layers.21.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
651
+ "vision_tower.vision_model.encoder.layers.21.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
652
+ "vision_tower.vision_model.encoder.layers.21.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
653
+ "vision_tower.vision_model.encoder.layers.22.layer_norm1.bias": "model-00001-of-00002.safetensors",
654
+ "vision_tower.vision_model.encoder.layers.22.layer_norm1.weight": "model-00001-of-00002.safetensors",
655
+ "vision_tower.vision_model.encoder.layers.22.layer_norm2.bias": "model-00001-of-00002.safetensors",
656
+ "vision_tower.vision_model.encoder.layers.22.layer_norm2.weight": "model-00001-of-00002.safetensors",
657
+ "vision_tower.vision_model.encoder.layers.22.mlp.fc1.bias": "model-00001-of-00002.safetensors",
658
+ "vision_tower.vision_model.encoder.layers.22.mlp.fc1.weight": "model-00001-of-00002.safetensors",
659
+ "vision_tower.vision_model.encoder.layers.22.mlp.fc2.bias": "model-00001-of-00002.safetensors",
660
+ "vision_tower.vision_model.encoder.layers.22.mlp.fc2.weight": "model-00001-of-00002.safetensors",
661
+ "vision_tower.vision_model.encoder.layers.22.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
662
+ "vision_tower.vision_model.encoder.layers.22.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
663
+ "vision_tower.vision_model.encoder.layers.22.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
664
+ "vision_tower.vision_model.encoder.layers.22.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
665
+ "vision_tower.vision_model.encoder.layers.22.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
666
+ "vision_tower.vision_model.encoder.layers.22.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
667
+ "vision_tower.vision_model.encoder.layers.22.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
668
+ "vision_tower.vision_model.encoder.layers.22.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
669
+ "vision_tower.vision_model.encoder.layers.23.layer_norm1.bias": "model-00001-of-00002.safetensors",
670
+ "vision_tower.vision_model.encoder.layers.23.layer_norm1.weight": "model-00001-of-00002.safetensors",
671
+ "vision_tower.vision_model.encoder.layers.23.layer_norm2.bias": "model-00001-of-00002.safetensors",
672
+ "vision_tower.vision_model.encoder.layers.23.layer_norm2.weight": "model-00001-of-00002.safetensors",
673
+ "vision_tower.vision_model.encoder.layers.23.mlp.fc1.bias": "model-00001-of-00002.safetensors",
674
+ "vision_tower.vision_model.encoder.layers.23.mlp.fc1.weight": "model-00001-of-00002.safetensors",
675
+ "vision_tower.vision_model.encoder.layers.23.mlp.fc2.bias": "model-00001-of-00002.safetensors",
676
+ "vision_tower.vision_model.encoder.layers.23.mlp.fc2.weight": "model-00001-of-00002.safetensors",
677
+ "vision_tower.vision_model.encoder.layers.23.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
678
+ "vision_tower.vision_model.encoder.layers.23.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
679
+ "vision_tower.vision_model.encoder.layers.23.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
680
+ "vision_tower.vision_model.encoder.layers.23.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
681
+ "vision_tower.vision_model.encoder.layers.23.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
682
+ "vision_tower.vision_model.encoder.layers.23.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
683
+ "vision_tower.vision_model.encoder.layers.23.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
684
+ "vision_tower.vision_model.encoder.layers.23.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
685
+ "vision_tower.vision_model.encoder.layers.24.layer_norm1.bias": "model-00001-of-00002.safetensors",
686
+ "vision_tower.vision_model.encoder.layers.24.layer_norm1.weight": "model-00001-of-00002.safetensors",
687
+ "vision_tower.vision_model.encoder.layers.24.layer_norm2.bias": "model-00001-of-00002.safetensors",
688
+ "vision_tower.vision_model.encoder.layers.24.layer_norm2.weight": "model-00001-of-00002.safetensors",
689
+ "vision_tower.vision_model.encoder.layers.24.mlp.fc1.bias": "model-00001-of-00002.safetensors",
690
+ "vision_tower.vision_model.encoder.layers.24.mlp.fc1.weight": "model-00001-of-00002.safetensors",
691
+ "vision_tower.vision_model.encoder.layers.24.mlp.fc2.bias": "model-00001-of-00002.safetensors",
692
+ "vision_tower.vision_model.encoder.layers.24.mlp.fc2.weight": "model-00001-of-00002.safetensors",
693
+ "vision_tower.vision_model.encoder.layers.24.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
694
+ "vision_tower.vision_model.encoder.layers.24.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
695
+ "vision_tower.vision_model.encoder.layers.24.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
696
+ "vision_tower.vision_model.encoder.layers.24.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
697
+ "vision_tower.vision_model.encoder.layers.24.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
698
+ "vision_tower.vision_model.encoder.layers.24.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
699
+ "vision_tower.vision_model.encoder.layers.24.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
700
+ "vision_tower.vision_model.encoder.layers.24.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
701
+ "vision_tower.vision_model.encoder.layers.25.layer_norm1.bias": "model-00001-of-00002.safetensors",
702
+ "vision_tower.vision_model.encoder.layers.25.layer_norm1.weight": "model-00001-of-00002.safetensors",
703
+ "vision_tower.vision_model.encoder.layers.25.layer_norm2.bias": "model-00001-of-00002.safetensors",
704
+ "vision_tower.vision_model.encoder.layers.25.layer_norm2.weight": "model-00001-of-00002.safetensors",
705
+ "vision_tower.vision_model.encoder.layers.25.mlp.fc1.bias": "model-00001-of-00002.safetensors",
706
+ "vision_tower.vision_model.encoder.layers.25.mlp.fc1.weight": "model-00001-of-00002.safetensors",
707
+ "vision_tower.vision_model.encoder.layers.25.mlp.fc2.bias": "model-00001-of-00002.safetensors",
708
+ "vision_tower.vision_model.encoder.layers.25.mlp.fc2.weight": "model-00001-of-00002.safetensors",
709
+ "vision_tower.vision_model.encoder.layers.25.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
710
+ "vision_tower.vision_model.encoder.layers.25.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
711
+ "vision_tower.vision_model.encoder.layers.25.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
712
+ "vision_tower.vision_model.encoder.layers.25.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
713
+ "vision_tower.vision_model.encoder.layers.25.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
714
+ "vision_tower.vision_model.encoder.layers.25.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
715
+ "vision_tower.vision_model.encoder.layers.25.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
716
+ "vision_tower.vision_model.encoder.layers.25.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
717
+ "vision_tower.vision_model.encoder.layers.26.layer_norm1.bias": "model-00001-of-00002.safetensors",
718
+ "vision_tower.vision_model.encoder.layers.26.layer_norm1.weight": "model-00001-of-00002.safetensors",
719
+ "vision_tower.vision_model.encoder.layers.26.layer_norm2.bias": "model-00001-of-00002.safetensors",
720
+ "vision_tower.vision_model.encoder.layers.26.layer_norm2.weight": "model-00001-of-00002.safetensors",
721
+ "vision_tower.vision_model.encoder.layers.26.mlp.fc1.bias": "model-00001-of-00002.safetensors",
722
+ "vision_tower.vision_model.encoder.layers.26.mlp.fc1.weight": "model-00001-of-00002.safetensors",
723
+ "vision_tower.vision_model.encoder.layers.26.mlp.fc2.bias": "model-00001-of-00002.safetensors",
724
+ "vision_tower.vision_model.encoder.layers.26.mlp.fc2.weight": "model-00001-of-00002.safetensors",
725
+ "vision_tower.vision_model.encoder.layers.26.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
726
+ "vision_tower.vision_model.encoder.layers.26.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
727
+ "vision_tower.vision_model.encoder.layers.26.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
728
+ "vision_tower.vision_model.encoder.layers.26.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
729
+ "vision_tower.vision_model.encoder.layers.26.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
730
+ "vision_tower.vision_model.encoder.layers.26.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
731
+ "vision_tower.vision_model.encoder.layers.26.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
732
+ "vision_tower.vision_model.encoder.layers.26.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
733
+ "vision_tower.vision_model.encoder.layers.3.layer_norm1.bias": "model-00001-of-00002.safetensors",
734
+ "vision_tower.vision_model.encoder.layers.3.layer_norm1.weight": "model-00001-of-00002.safetensors",
735
+ "vision_tower.vision_model.encoder.layers.3.layer_norm2.bias": "model-00001-of-00002.safetensors",
736
+ "vision_tower.vision_model.encoder.layers.3.layer_norm2.weight": "model-00001-of-00002.safetensors",
737
+ "vision_tower.vision_model.encoder.layers.3.mlp.fc1.bias": "model-00001-of-00002.safetensors",
738
+ "vision_tower.vision_model.encoder.layers.3.mlp.fc1.weight": "model-00001-of-00002.safetensors",
739
+ "vision_tower.vision_model.encoder.layers.3.mlp.fc2.bias": "model-00001-of-00002.safetensors",
740
+ "vision_tower.vision_model.encoder.layers.3.mlp.fc2.weight": "model-00001-of-00002.safetensors",
741
+ "vision_tower.vision_model.encoder.layers.3.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
742
+ "vision_tower.vision_model.encoder.layers.3.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
743
+ "vision_tower.vision_model.encoder.layers.3.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
744
+ "vision_tower.vision_model.encoder.layers.3.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
745
+ "vision_tower.vision_model.encoder.layers.3.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
746
+ "vision_tower.vision_model.encoder.layers.3.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
747
+ "vision_tower.vision_model.encoder.layers.3.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
748
+ "vision_tower.vision_model.encoder.layers.3.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
749
+ "vision_tower.vision_model.encoder.layers.4.layer_norm1.bias": "model-00001-of-00002.safetensors",
750
+ "vision_tower.vision_model.encoder.layers.4.layer_norm1.weight": "model-00001-of-00002.safetensors",
751
+ "vision_tower.vision_model.encoder.layers.4.layer_norm2.bias": "model-00001-of-00002.safetensors",
752
+ "vision_tower.vision_model.encoder.layers.4.layer_norm2.weight": "model-00001-of-00002.safetensors",
753
+ "vision_tower.vision_model.encoder.layers.4.mlp.fc1.bias": "model-00001-of-00002.safetensors",
754
+ "vision_tower.vision_model.encoder.layers.4.mlp.fc1.weight": "model-00001-of-00002.safetensors",
755
+ "vision_tower.vision_model.encoder.layers.4.mlp.fc2.bias": "model-00001-of-00002.safetensors",
756
+ "vision_tower.vision_model.encoder.layers.4.mlp.fc2.weight": "model-00001-of-00002.safetensors",
757
+ "vision_tower.vision_model.encoder.layers.4.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
758
+ "vision_tower.vision_model.encoder.layers.4.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
759
+ "vision_tower.vision_model.encoder.layers.4.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
760
+ "vision_tower.vision_model.encoder.layers.4.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
761
+ "vision_tower.vision_model.encoder.layers.4.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
762
+ "vision_tower.vision_model.encoder.layers.4.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
763
+ "vision_tower.vision_model.encoder.layers.4.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
764
+ "vision_tower.vision_model.encoder.layers.4.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
765
+ "vision_tower.vision_model.encoder.layers.5.layer_norm1.bias": "model-00001-of-00002.safetensors",
766
+ "vision_tower.vision_model.encoder.layers.5.layer_norm1.weight": "model-00001-of-00002.safetensors",
767
+ "vision_tower.vision_model.encoder.layers.5.layer_norm2.bias": "model-00001-of-00002.safetensors",
768
+ "vision_tower.vision_model.encoder.layers.5.layer_norm2.weight": "model-00001-of-00002.safetensors",
769
+ "vision_tower.vision_model.encoder.layers.5.mlp.fc1.bias": "model-00001-of-00002.safetensors",
770
+ "vision_tower.vision_model.encoder.layers.5.mlp.fc1.weight": "model-00001-of-00002.safetensors",
771
+ "vision_tower.vision_model.encoder.layers.5.mlp.fc2.bias": "model-00001-of-00002.safetensors",
772
+ "vision_tower.vision_model.encoder.layers.5.mlp.fc2.weight": "model-00001-of-00002.safetensors",
773
+ "vision_tower.vision_model.encoder.layers.5.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
774
+ "vision_tower.vision_model.encoder.layers.5.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
775
+ "vision_tower.vision_model.encoder.layers.5.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
776
+ "vision_tower.vision_model.encoder.layers.5.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
777
+ "vision_tower.vision_model.encoder.layers.5.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
778
+ "vision_tower.vision_model.encoder.layers.5.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
779
+ "vision_tower.vision_model.encoder.layers.5.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
780
+ "vision_tower.vision_model.encoder.layers.5.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
781
+ "vision_tower.vision_model.encoder.layers.6.layer_norm1.bias": "model-00001-of-00002.safetensors",
782
+ "vision_tower.vision_model.encoder.layers.6.layer_norm1.weight": "model-00001-of-00002.safetensors",
783
+ "vision_tower.vision_model.encoder.layers.6.layer_norm2.bias": "model-00001-of-00002.safetensors",
784
+ "vision_tower.vision_model.encoder.layers.6.layer_norm2.weight": "model-00001-of-00002.safetensors",
785
+ "vision_tower.vision_model.encoder.layers.6.mlp.fc1.bias": "model-00001-of-00002.safetensors",
786
+ "vision_tower.vision_model.encoder.layers.6.mlp.fc1.weight": "model-00001-of-00002.safetensors",
787
+ "vision_tower.vision_model.encoder.layers.6.mlp.fc2.bias": "model-00001-of-00002.safetensors",
788
+ "vision_tower.vision_model.encoder.layers.6.mlp.fc2.weight": "model-00001-of-00002.safetensors",
789
+ "vision_tower.vision_model.encoder.layers.6.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
790
+ "vision_tower.vision_model.encoder.layers.6.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
791
+ "vision_tower.vision_model.encoder.layers.6.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
792
+ "vision_tower.vision_model.encoder.layers.6.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
793
+ "vision_tower.vision_model.encoder.layers.6.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
794
+ "vision_tower.vision_model.encoder.layers.6.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
795
+ "vision_tower.vision_model.encoder.layers.6.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
796
+ "vision_tower.vision_model.encoder.layers.6.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
797
+ "vision_tower.vision_model.encoder.layers.7.layer_norm1.bias": "model-00001-of-00002.safetensors",
798
+ "vision_tower.vision_model.encoder.layers.7.layer_norm1.weight": "model-00001-of-00002.safetensors",
799
+ "vision_tower.vision_model.encoder.layers.7.layer_norm2.bias": "model-00001-of-00002.safetensors",
800
+ "vision_tower.vision_model.encoder.layers.7.layer_norm2.weight": "model-00001-of-00002.safetensors",
801
+ "vision_tower.vision_model.encoder.layers.7.mlp.fc1.bias": "model-00001-of-00002.safetensors",
802
+ "vision_tower.vision_model.encoder.layers.7.mlp.fc1.weight": "model-00001-of-00002.safetensors",
803
+ "vision_tower.vision_model.encoder.layers.7.mlp.fc2.bias": "model-00001-of-00002.safetensors",
804
+ "vision_tower.vision_model.encoder.layers.7.mlp.fc2.weight": "model-00001-of-00002.safetensors",
805
+ "vision_tower.vision_model.encoder.layers.7.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
806
+ "vision_tower.vision_model.encoder.layers.7.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
807
+ "vision_tower.vision_model.encoder.layers.7.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
808
+ "vision_tower.vision_model.encoder.layers.7.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
809
+ "vision_tower.vision_model.encoder.layers.7.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
810
+ "vision_tower.vision_model.encoder.layers.7.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
811
+ "vision_tower.vision_model.encoder.layers.7.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
812
+ "vision_tower.vision_model.encoder.layers.7.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
813
+ "vision_tower.vision_model.encoder.layers.8.layer_norm1.bias": "model-00001-of-00002.safetensors",
814
+ "vision_tower.vision_model.encoder.layers.8.layer_norm1.weight": "model-00001-of-00002.safetensors",
815
+ "vision_tower.vision_model.encoder.layers.8.layer_norm2.bias": "model-00001-of-00002.safetensors",
816
+ "vision_tower.vision_model.encoder.layers.8.layer_norm2.weight": "model-00001-of-00002.safetensors",
817
+ "vision_tower.vision_model.encoder.layers.8.mlp.fc1.bias": "model-00001-of-00002.safetensors",
818
+ "vision_tower.vision_model.encoder.layers.8.mlp.fc1.weight": "model-00001-of-00002.safetensors",
819
+ "vision_tower.vision_model.encoder.layers.8.mlp.fc2.bias": "model-00001-of-00002.safetensors",
820
+ "vision_tower.vision_model.encoder.layers.8.mlp.fc2.weight": "model-00001-of-00002.safetensors",
821
+ "vision_tower.vision_model.encoder.layers.8.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
822
+ "vision_tower.vision_model.encoder.layers.8.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
823
+ "vision_tower.vision_model.encoder.layers.8.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
824
+ "vision_tower.vision_model.encoder.layers.8.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
825
+ "vision_tower.vision_model.encoder.layers.8.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
826
+ "vision_tower.vision_model.encoder.layers.8.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
827
+ "vision_tower.vision_model.encoder.layers.8.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
828
+ "vision_tower.vision_model.encoder.layers.8.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
829
+ "vision_tower.vision_model.encoder.layers.9.layer_norm1.bias": "model-00001-of-00002.safetensors",
830
+ "vision_tower.vision_model.encoder.layers.9.layer_norm1.weight": "model-00001-of-00002.safetensors",
831
+ "vision_tower.vision_model.encoder.layers.9.layer_norm2.bias": "model-00001-of-00002.safetensors",
832
+ "vision_tower.vision_model.encoder.layers.9.layer_norm2.weight": "model-00001-of-00002.safetensors",
833
+ "vision_tower.vision_model.encoder.layers.9.mlp.fc1.bias": "model-00001-of-00002.safetensors",
834
+ "vision_tower.vision_model.encoder.layers.9.mlp.fc1.weight": "model-00001-of-00002.safetensors",
835
+ "vision_tower.vision_model.encoder.layers.9.mlp.fc2.bias": "model-00001-of-00002.safetensors",
836
+ "vision_tower.vision_model.encoder.layers.9.mlp.fc2.weight": "model-00001-of-00002.safetensors",
837
+ "vision_tower.vision_model.encoder.layers.9.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
838
+ "vision_tower.vision_model.encoder.layers.9.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
839
+ "vision_tower.vision_model.encoder.layers.9.self_attn.out_proj.bias": "model-00001-of-00002.safetensors",
840
+ "vision_tower.vision_model.encoder.layers.9.self_attn.out_proj.weight": "model-00001-of-00002.safetensors",
841
+ "vision_tower.vision_model.encoder.layers.9.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
842
+ "vision_tower.vision_model.encoder.layers.9.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
843
+ "vision_tower.vision_model.encoder.layers.9.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
844
+ "vision_tower.vision_model.encoder.layers.9.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
845
+ "vision_tower.vision_model.post_layernorm.bias": "model-00001-of-00002.safetensors",
846
+ "vision_tower.vision_model.post_layernorm.weight": "model-00001-of-00002.safetensors"
847
+ }
848
+ }
modeling_llava_onevision.py ADDED
@@ -0,0 +1,1451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/llava_onevision/modular_llava_onevision.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_llava_onevision.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2024 the HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+ import math
23
+ from dataclasses import dataclass
24
+ from typing import List, Optional, Tuple, Union
25
+
26
+ import numpy as np
27
+ import torch
28
+ from torch import nn
29
+ import torch.distributed as dist
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.generation import GenerationMixin
33
+ from transformers.image_processing_utils import select_best_resolution
34
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
35
+ from transformers.modeling_outputs import BaseModelOutputWithPast, ModelOutput
36
+ from transformers.modeling_utils import PreTrainedModel
37
+ from transformers.processing_utils import Unpack
38
+ from transformers.utils import (
39
+ LossKwargs,
40
+ auto_docstring,
41
+ can_return_tuple,
42
+ is_torchdynamo_compiling,
43
+ logging,
44
+ )
45
+ from transformers.models.auto import AutoModel
46
+ from torch.nn.attention.flex_attention import create_block_mask
47
+ from .configuration_llava_onevision import LlavaOnevisionConfig
48
+ from .fused_linear_diffusion_cross_entropy import FusedLinearDiffusionCrossEntropyLoss
49
+
50
+ logger = logging.get_logger(__name__)
51
+
52
+
53
+ @dataclass
54
+ class LlavaOnevisionModelOutputWithPast(BaseModelOutputWithPast):
55
+ """
56
+ Base class for Llava outputs, with hidden states and attentions.
57
+
58
+ Args:
59
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
60
+ Sequence of hidden-states at the output of the last layer of the model.
61
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
62
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
63
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
64
+
65
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
66
+ `past_key_values` input) to speed up sequential decoding.
67
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
68
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
69
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
70
+
71
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
72
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
73
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
74
+ sequence_length)`.
75
+
76
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
77
+ heads.
78
+ image_hidden_states (`torch.FloatTensor`, *optional*):
79
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
80
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
81
+
82
+ video_hidden_states (`torch.FloatTensor`, *optional*):
83
+ A `torch.FloatTensor` of size `(batch_size * num_frames, num_videos, sequence_length, hidden_size)`.
84
+ video_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
85
+ """
86
+
87
+ image_hidden_states: Optional[torch.FloatTensor] = None
88
+
89
+ video_hidden_states: Optional[torch.FloatTensor] = None
90
+
91
+ logits_to_keep_half: Optional[torch.BoolTensor] = None
92
+
93
+ logits_to_keep: Optional[torch.BoolTensor] = None
94
+
95
+ p_mask: Optional[torch.FloatTensor] = None
96
+
97
+
98
+
99
+ @dataclass
100
+ class LlavaOnevisionCausalLMOutputWithPast(ModelOutput):
101
+ """
102
+ Base class for LlavaOnevision causal language model (or autoregressive) outputs.
103
+
104
+ Args:
105
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
106
+ Language modeling loss (for next-token prediction).
107
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
108
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
109
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
110
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
111
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
112
+
113
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
114
+ `past_key_values` input) to speed up sequential decoding.
115
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
116
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
117
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
118
+
119
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
120
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
121
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
122
+ sequence_length)`.
123
+
124
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
125
+ heads.
126
+ image_hidden_states (`torch.FloatTensor`, *optional*):
127
+ A `torch.FloatTensor` of size (batch_size * num_patches, num_images, sequence_length, hidden_size)`.
128
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
129
+
130
+ video_hidden_states (`torch.FloatTensor`, *optional*):
131
+ A `torch.FloatTensor` of size `(batch_size * num_frames, num_videos, sequence_length, hidden_size)`.
132
+ video_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
133
+ """
134
+
135
+ loss: Optional[torch.FloatTensor] = None
136
+ logits: Optional[torch.FloatTensor] = None
137
+ past_key_values: Optional[List[torch.FloatTensor]] = None
138
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
139
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
140
+ image_hidden_states: Optional[torch.FloatTensor] = None
141
+
142
+ video_hidden_states: Optional[torch.FloatTensor] = None
143
+
144
+
145
+ class LlavaOnevisionPooler(nn.Module):
146
+ def __init__(self, config):
147
+ super().__init__()
148
+
149
+ mode = config.spatial_pool_mode
150
+ stride = config.spatial_pool_stride
151
+ out_channels = getattr(config, "spatial_pool_out_channels", config.vision_config.hidden_size)
152
+ self.image_size = (config.vision_config.image_size // config.vision_config.patch_size) ** 2
153
+
154
+ if mode == "average":
155
+ self.pool = nn.AvgPool2d(kernel_size=stride, stride=stride)
156
+ elif mode == "max":
157
+ self.pool = nn.MaxPool2d(kernel_size=stride, stride=stride)
158
+ elif mode == "conv":
159
+ self.pool = nn.Conv2d(
160
+ in_channels=config.vision_config.hidden_size,
161
+ out_channels=out_channels,
162
+ kernel_size=stride,
163
+ stride=stride,
164
+ )
165
+ else:
166
+ raise ValueError(f"Unknown pooling mode: {mode}. Has to be one of [`average`, `max`, `conv`]")
167
+
168
+ def forward(self, image_features):
169
+ ori_width = int(math.sqrt(image_features.shape[1] * self.image_size // self.image_size))
170
+ ori_height = int(ori_width * self.image_size // self.image_size)
171
+
172
+ batch_size, _, dim = image_features.shape
173
+ image_features_spatial = image_features.view(batch_size, ori_height, ori_height, dim).permute(0, 3, 1, 2)
174
+ image_features_spatial_pool = self.pool(image_features_spatial)
175
+
176
+ return image_features_spatial_pool.flatten(2).transpose(1, 2).contiguous()
177
+
178
+
179
+ class LlavaOnevisionMultiModalProjector(nn.Module):
180
+ def __init__(self, config: LlavaOnevisionConfig):
181
+ super().__init__()
182
+ # We have hidden_size * the number of vision feature layers
183
+ num_feature_layers = 1 if isinstance(config.vision_feature_layer, int) else len(config.vision_feature_layer)
184
+ self.linear_1 = nn.Linear(
185
+ config.vision_config.hidden_size * num_feature_layers,
186
+ config.text_config.hidden_size,
187
+ bias=config.multimodal_projector_bias,
188
+ )
189
+ self.act = ACT2FN[config.projector_hidden_act]
190
+ self.linear_2 = nn.Linear(
191
+ config.text_config.hidden_size, config.text_config.hidden_size, bias=config.multimodal_projector_bias
192
+ )
193
+
194
+ def forward(self, image_features):
195
+ hidden_states = self.linear_1(image_features)
196
+ hidden_states = self.act(hidden_states)
197
+ hidden_states = self.linear_2(hidden_states)
198
+ return hidden_states
199
+
200
+
201
+ def get_anyres_image_grid_shape(image_size, grid_pinpoints, patch_size):
202
+ """
203
+ Calculate the shape of the image patch grid after the preprocessing for images of any resolution.
204
+
205
+ Args:
206
+ image_size (`tuple`):
207
+ The size of the input image in the format (width, height).
208
+ grid_pinpoints (`List`):
209
+ A list containing possible resolutions. Each item in the list should be a tuple or list
210
+ of the form `(height, width)`.
211
+ patch_size (`int`):
212
+ The size of each image patch.
213
+
214
+ Returns:
215
+ tuple: The shape of the image patch grid in the format (width, height).
216
+ """
217
+ if not isinstance(grid_pinpoints, list):
218
+ raise TypeError("grid_pinpoints should be a list of tuples or lists")
219
+
220
+ # ! VERY IMPORTANT if image_size is tensor, must convert to into tuple, otherwise it will cause wrong calculate
221
+ if not isinstance(image_size, (list, tuple)):
222
+ if not isinstance(image_size, (torch.Tensor, np.ndarray)):
223
+ raise TypeError(
224
+ f"image_size invalid type: {type(image_size)} not valid, should be either list, tuple, np.ndarray or tensor"
225
+ )
226
+ image_size = image_size.tolist()
227
+
228
+ height, width = select_best_resolution(image_size, grid_pinpoints)
229
+ return height // patch_size, width // patch_size
230
+
231
+
232
+ def image_size_to_num_patches(image_size, grid_pinpoints, patch_size: int):
233
+ """
234
+ Calculate the number of patches after the preprocessing for images of any resolution.
235
+
236
+ Args:
237
+ image_size (`torch.LongTensor` or `np.ndarray` or `Tuple[int, int]`):
238
+ The size of the input image in the format (height, width). ?
239
+ grid_pinpoints (`List`):
240
+ A list containing possible resolutions. Each item in the list should be a tuple or list
241
+ of the form `(height, width)`.
242
+ patch_size (`int`):
243
+ The size of each image patch.
244
+
245
+ Returns:
246
+ int: the number of patches
247
+ """
248
+ if not isinstance(grid_pinpoints, list):
249
+ raise TypeError("grid_pinpoints should be a list of tuples or lists")
250
+
251
+ # ! VERY IMPORTANT if image_size is tensor, must convert to into tuple, otherwise it will cause wrong calculate
252
+ if not isinstance(image_size, (list, tuple)):
253
+ if not isinstance(image_size, (torch.Tensor, np.ndarray)):
254
+ raise TypeError(f"image_size invalid type {type(image_size)} with value {image_size}")
255
+ image_size = image_size.tolist()
256
+
257
+ best_resolution = select_best_resolution(image_size, grid_pinpoints)
258
+ height, width = best_resolution
259
+ num_patches = 0
260
+ # consider change to ceil(height/patch_size)*ceil(width/patch_size) + 1
261
+ for i in range(0, height, patch_size):
262
+ for j in range(0, width, patch_size):
263
+ num_patches += 1
264
+ # add the base patch
265
+ num_patches += 1
266
+ return num_patches
267
+
268
+
269
+ def unpad_image(tensor, original_size):
270
+ """
271
+ Unpads a PyTorch tensor of a padded and resized image.
272
+
273
+ Args:
274
+ tensor (`torch.Tensor`):
275
+ The image tensor, assumed to be of shape (num_channels, height, width).
276
+ original_size (`tuple`):
277
+ The original size of the image (height, width).
278
+
279
+ Returns:
280
+ `torch.Tensor`: The unpadded image tensor.
281
+ """
282
+ if not isinstance(original_size, (list, tuple)):
283
+ if not isinstance(original_size, (torch.Tensor, np.ndarray)):
284
+ raise TypeError(
285
+ f"image_size invalid type: {type(original_size)} not valid, should be either list, tuple, np.ndarray or tensor"
286
+ )
287
+ original_size = original_size.tolist()
288
+ original_height, original_width = original_size
289
+ current_height, current_width = tensor.shape[1:]
290
+
291
+ original_aspect_ratio = original_width / original_height
292
+ current_aspect_ratio = current_width / current_height
293
+
294
+ if original_aspect_ratio > current_aspect_ratio:
295
+ scale_factor = current_width / original_width
296
+ new_height = int(round(original_height * scale_factor, 7))
297
+ padding = (current_height - new_height) // 2
298
+ unpadded_tensor = tensor[:, padding : current_height - padding, :]
299
+ else:
300
+ scale_factor = current_height / original_height
301
+ new_width = int(round(original_width * scale_factor, 7))
302
+ padding = (current_width - new_width) // 2
303
+ unpadded_tensor = tensor[:, :, padding : current_width - padding]
304
+
305
+ return unpadded_tensor
306
+
307
+
308
+ @auto_docstring
309
+ class LlavaOnevisionPreTrainedModel(PreTrainedModel):
310
+ config_class = LlavaOnevisionConfig
311
+ base_model_prefix = ""
312
+ supports_gradient_checkpointing = True
313
+ _no_split_modules = ["LlamaDecoderLayer"]
314
+ _skip_keys_device_placement = "past_key_values"
315
+ _supports_cache_class = True
316
+ _supports_flash_attn_2 = True
317
+ _supports_sdpa = True
318
+ _supports_quantized_cache = True
319
+ _supports_static_cache = True
320
+ _supports_attention_backend = True
321
+
322
+ def _init_weights(self, module):
323
+ std = getattr(self.config, "initializer_range", self.config.get_text_config().initializer_range)
324
+
325
+ if isinstance(module, nn.Linear):
326
+ module.weight.data.normal_(mean=0.0, std=std)
327
+ if module.bias is not None:
328
+ module.bias.data.zero_()
329
+ elif isinstance(module, LlavaOnevisionModel):
330
+ embed_std = 1 / math.sqrt(self.config.text_config.hidden_size)
331
+ module.image_newline.data.normal_(mean=0.0, std=embed_std)
332
+
333
+
334
+ def modify_padded_position_ids(position_ids: torch.Tensor) -> torch.Tensor:
335
+ """
336
+ 使用 PyTorch Tensor 操作修改 packed position_ids 中尾部 padding 的值。
337
+ 这个函数假设输入是一个 1D Tensor。
338
+ Args:
339
+ position_ids: 一维 PyTorch Tensor.
340
+ Returns:
341
+ 修改后的 position_ids Tensor.
342
+ """
343
+ seq_len = position_ids.size(0)
344
+ # 找到所有非零元素的索引
345
+ nonzero_indices = (position_ids != 0).nonzero().squeeze()
346
+
347
+ # 确定 padding 开始的位置
348
+ if nonzero_indices.numel() > 0:
349
+ # 如果存在非零元素,padding 从最后一个非零元素的下一个位置开始
350
+ last_nonzero_idx = nonzero_indices.max().item()
351
+ pad_start_idx = last_nonzero_idx + 1
352
+ else:
353
+ pad_start_idx = 0
354
+
355
+ # 如果有需要修改的 padding 部分
356
+ if pad_start_idx < seq_len:
357
+ pad_length = seq_len - pad_start_idx
358
+ new_pad_values = torch.arange(pad_length, device=position_ids.device, dtype=position_ids.dtype)
359
+ position_ids[pad_start_idx:] = new_pad_values
360
+
361
+ return position_ids
362
+
363
+
364
+ def modify_padded_position_ids_2d(position_ids: torch.LongTensor) -> torch.LongTensor:
365
+ """
366
+ 使用完全向量化的 PyTorch 操作修改一个 batch 的 packed position_ids。
367
+ 这个函数假设输入是一个 2D Tensor,形状为 (batch_size, sequence_length)。
368
+ 它会独立地处理 batch 中的每一行。
369
+
370
+ Args:
371
+ position_ids: 二维 PyTorch Tensor, shape (batch_size, sequence_length).
372
+
373
+ Returns:
374
+ 修改后的 position_ids Tensor, shape (batch_size, sequence_length).
375
+ """
376
+ if position_ids.dim() != 2:
377
+ raise ValueError(f"Input tensor must be 2D, but got {position_ids.dim()} dimensions.")
378
+
379
+ batch_size, seq_len = position_ids.shape
380
+ device = position_ids.device
381
+
382
+ col_indices = torch.arange(seq_len, device=device, dtype=position_ids.dtype).expand(batch_size, -1)
383
+ mask = (position_ids != 0)
384
+
385
+ masked_indices = col_indices * mask
386
+ last_nonzero_idx = torch.max(masked_indices, dim=1).values
387
+ has_nonzero = torch.any(mask, dim=1)
388
+ pad_start_idx = torch.where(has_nonzero, last_nonzero_idx + 1, torch.tensor(0, device=device, dtype=position_ids.dtype))
389
+
390
+ padding_mask = col_indices >= pad_start_idx.unsqueeze(1)
391
+ new_pad_values = col_indices - pad_start_idx.unsqueeze(1)
392
+ position_ids = torch.where(padding_mask, new_pad_values, position_ids)
393
+
394
+ return position_ids
395
+
396
+
397
+ def calculate_token_nums(position_ids: torch.Tensor):
398
+ """
399
+ 使用 PyTorch 高效计算一个批次中每个打包序列的长度。
400
+
401
+ Args:
402
+ position_ids (torch.Tensor): 一个 2D Tensor,形状为 (batch_size, sequence_length)。
403
+ 例如:tensor([[0,1,2,3,4,0,1,2,3,4,5,0,1,2,3,0,0,0]])
404
+ Returns:
405
+ list[list[int]]: 一个嵌套列表,包含每个批次项中各个序列的长度。
406
+ 例如:[[5, 6, 4, 1, 1, 1]]
407
+ """
408
+ # 检查输入是否为 2D Tensor
409
+ if position_ids.dim() != 2:
410
+ raise ValueError(f"输入必须是 2D Tensor,但得到了 {position_ids.dim()}D")
411
+
412
+ all_lengths = []
413
+
414
+ # 我们按批次逐行处理。因为每行的序列长度数量不同(ragged),
415
+ # 所以 Python 循环在批次维度上是最高效且最清晰的写法。
416
+ # 循环内部的操作是完全向量化的。
417
+ for pids_row in position_ids:
418
+ # 获取当前行的总长度
419
+ seq_len = pids_row.shape[0]
420
+
421
+ # 1. 找到所有值为 0 的元素的索引
422
+ # pids_row == 0 会返回一个布尔 Tensor: [True, False, ..., True, ...]
423
+ # torch.nonzero 会返回这些 True 值的索引
424
+ # .flatten() 将其从 (N, 1) 形状的 Tensor 变为 (N,) 形状
425
+ zero_indices = torch.nonzero(pids_row == 0).flatten()
426
+
427
+ # 2. 将序列的总长度作为一个额外的切分点添加到末尾
428
+ # 这对于计算最后一个序列的长度至关重要
429
+ # 注意:要确保新创建的 tensor 和原始 tensor 在同一个设备上 (cpu/cuda)
430
+ split_points = torch.cat([
431
+ zero_indices,
432
+ torch.tensor([seq_len], device=pids_row.device, dtype=zero_indices.dtype)
433
+ ])
434
+
435
+ # 3. 计算相邻切分点之间的差值,这就是我们想要的长度
436
+ # torch.diff([a, b, c, d]) 会返回 [b-a, c-b, d-c]
437
+ lengths = torch.diff(split_points)
438
+
439
+ all_lengths.append(lengths)
440
+
441
+ return all_lengths
442
+
443
+
444
+ # def forward_add_noise_packed(
445
+ # inputs_embeds: torch.Tensor,
446
+ # num_tokens: torch.Tensor,
447
+ # prompt_mask: torch.Tensor,
448
+ # mask_embed: torch.Tensor,
449
+ # eps: float = 1e-3,
450
+ # max_tries: int = 10,
451
+ # ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
452
+ # """
453
+ # 为单个打包(packed)序列的 embedding 添加噪声,该序列的形状带有 batch 维度。
454
+
455
+ # 函数为每个逻辑样本(在 inputs_embeds 中拼接)生成一个随机噪声率,
456
+ # 并随机将一部分 token 的 embedding 替换为 mask_embed。
457
+ # 这个过程会避开被 prompt_mask 标记的位置。
458
+
459
+ # Args:
460
+ # inputs_embeds (torch.Tensor): 输入的 embedding 张量,形状为 **(1, total_tokens, embed_dim)**。
461
+ # num_tokens (torch.Tensor): 1D 张量,记录了每个逻辑样本的长度。
462
+ # 例如 [len_sample1, len_sample2, ...]。
463
+ # prompt_mask (torch.Tensor): 布尔型张量,形状为 **(1, total_tokens)**,
464
+ # 值为 True 的位置表示是 prompt,不应添加噪声。
465
+ # mask_embed (torch.Tensor): 用于替换的 mask embedding,形状为 (embed_dim,) 或 (1, embed_dim)。
466
+ # eps (float): 微小值,用于防止噪声率 t 恰好为 0,确保 p_mask > 0。
467
+ # max_tries (int): 为确保至少一个非 prompt token 被 mask,尝试的最大次数。
468
+
469
+ # Returns:
470
+ # Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
471
+ # - noisy_embeds (torch.Tensor): 添加噪声后的 embedding 张量,形状为 (1, total_tokens, embed_dim)。
472
+ # - final_masked_indices (torch.Tensor): 布尔型张量,标记了哪些位置被实际 mask 了,形状为 (1, total_tokens)。
473
+ # - p_mask_per_sample (torch.Tensor): 每个逻辑样本实际使用的噪声率,形状为 (num_samples, )。
474
+ # """
475
+ # # 1. 验证和获取形状
476
+ # bsz, total_tokens, embed_dim = inputs_embeds.shape
477
+ # assert bsz == 1, f"此函数设计用于处理 bsz=1 的打包序列,但收到了 bsz={bsz}"
478
+
479
+ # num_samples = len(num_tokens)
480
+ # assert total_tokens == torch.sum(num_tokens), "num_tokens 之和与 inputs_embeds 的总长度不匹配"
481
+ # assert prompt_mask.shape == (bsz, total_tokens), f"prompt_mask 形状不匹配, 期望 {(bsz, total_tokens)}, 得到 {prompt_mask.shape}"
482
+ # assert mask_embed.dim() == 1 or mask_embed.shape[-1] == embed_dim, "mask_embed 形状不匹配"
483
+
484
+ # device = inputs_embeds.device
485
+
486
+ # # 调整 mask_embed 形状以便广播: (dim,) -> (1, 1, dim)
487
+ # mask_embed = mask_embed.view(1, 1, embed_dim)
488
+
489
+ # # --- 确定可以被 mask 的位置 ---
490
+ # eligible_for_masking = ~prompt_mask
491
+
492
+ # # 如果没有任何 token 可以被 mask,直接返回原始输入
493
+ # if not eligible_for_masking.any():
494
+ # return (
495
+ # inputs_embeds,
496
+ # torch.zeros_like(prompt_mask, dtype=torch.bool),
497
+ # torch.full((num_samples,), eps, device=device)
498
+ # )
499
+
500
+ # # 2. 生成噪声率和 mask,尝试几次以确保至少 mask 一个 token
501
+ # final_masked_indices = torch.zeros_like(prompt_mask, dtype=torch.bool)
502
+
503
+ # for _ in range(max_tries):
504
+ # # 为每个逻辑样本生成一个独立的随机噪声率 t in [0, 1]
505
+ # t = torch.rand(num_samples, device=device) # shape: (num_samples,)
506
+ # p_mask_per_sample = (1 - eps) * t + eps
507
+
508
+ # # 将每个样本的噪声率扩展到其所有 token 上
509
+ # p_mask_per_token_1d = torch.repeat_interleave(p_mask_per_sample, num_tokens) # shape: (total_tokens,)
510
+ # p_mask_per_token = p_mask_per_token_1d.unsqueeze(0) # shape: (1, total_tokens)
511
+
512
+ # # 生成随机数并根据 p_mask 创建初步的 mask
513
+ # masked_indices = torch.rand_like(p_mask_per_token) < p_mask_per_token # shape: (1, total_tokens)
514
+
515
+ # # 应用约束:只在允许的位置进行 mask
516
+ # final_masked_indices = masked_indices & eligible_for_masking
517
+
518
+ # if final_masked_indices.any():
519
+ # break
520
+
521
+ # # 3. 根据最终的 mask 生成带噪声的 embedding
522
+ # # final_masked_indices 是 (1, total_tokens),需要扩展到 (1, total_tokens, 1)
523
+ # # 以便和 (1, total_tokens, embed_dim) 的张量在 torch.where 中正确广播
524
+ # noisy_embeds = torch.where(
525
+ # final_masked_indices.unsqueeze(-1),
526
+ # mask_embed,
527
+ # inputs_embeds
528
+ # )
529
+
530
+ # return noisy_embeds, final_masked_indices, p_mask_per_token[final_masked_indices]
531
+
532
+ def forward_add_noise_packed(
533
+ inputs_embeds: torch.Tensor,
534
+ num_tokens_list: List[torch.Tensor],
535
+ prompt_mask: torch.Tensor,
536
+ mask_embed: torch.Tensor,
537
+ eps: float = 1e-3,
538
+ max_tries: int = 10,
539
+ ) -> Tuple[torch.Tensor, torch.Tensor, List[torch.Tensor]]:
540
+ """
541
+ 为一批打包(packed)序列的 embedding 添加噪声。
542
+
543
+ 函数为每个逻辑样本(在每个批次项内拼接)生成一个独立的随机噪声率,
544
+ 并随机将一部分 token 的 embedding 替换为 mask_embed。
545
+ 这个过程会避开被 prompt_mask 标记的位置。
546
+
547
+ Args:
548
+ inputs_embeds (torch.Tensor):
549
+ 输入的 embedding 张量,形状为 (bsz, total_tokens, embed_dim)。
550
+ num_tokens_list (List[torch.Tensor]):
551
+ 一个张量列表,长度为 bsz。列表中的每个张量记录了对应批次项中
552
+ 每个逻辑样本的长度。例如: [tensor([len1, len2]), tensor([len3, len4, len5])].
553
+ prompt_mask (torch.Tensor):
554
+ 布尔型张量,形状为 (bsz, total_tokens),值为 True 的位置表示是 prompt,
555
+ 不应添加噪声。
556
+ mask_embed (torch.Tensor):
557
+ 用于替换的 mask embedding,形状为 (embed_dim,) 或 (1, embed_dim)。
558
+ eps (float):
559
+ 微小值,用于防止噪声率 t 恰好为 0,确保 p_mask > 0。
560
+ max_tries (int):
561
+ 为确保至少一个非 prompt token 被 mask,对每个批次项尝试的最大次数。
562
+
563
+ Returns:
564
+ Tuple[torch.Tensor, torch.Tensor, List[torch.Tensor]]:
565
+ - noisy_embeds (torch.Tensor):
566
+ 添加噪声后的 embedding 张量,形状为 (bsz, total_tokens, embed_dim)。
567
+ - final_masked_indices (torch.Tensor):
568
+ 布尔型张量,标记了哪些位置被实际 mask 了,形状为 (bsz, total_tokens)。
569
+ - p_masks_list (List[torch.Tensor]):
570
+ 一个张量列表,长度为 bsz。每个张量包含了对应批次项中每个逻辑样本的
571
+ 实际噪声率。
572
+ """
573
+ # 1. 验证和获取形状
574
+ bsz, total_tokens, embed_dim = inputs_embeds.shape
575
+ device = inputs_embeds.device
576
+
577
+ # 检查输入的一致性
578
+ assert len(num_tokens_list) == bsz, f"num_tokens_list 的长度 ({len(num_tokens_list)}) 必须等于 bsz ({bsz})"
579
+ assert prompt_mask.shape == (bsz, total_tokens), f"prompt_mask 形状不匹配, 期望 {(bsz, total_tokens)}, 得到 {prompt_mask.shape}"
580
+
581
+ # 准备结果容器
582
+ noisy_embeds_list = []
583
+ final_masked_indices_list = []
584
+ p_masks_list = []
585
+
586
+ # 调整 mask_embed 形状以便广播: (dim,) -> (1, 1, dim)
587
+ mask_embed_view = mask_embed.view(1, 1, embed_dim)
588
+
589
+ # 2. 在批次维度上迭代
590
+ # 这是处理不同打包结构最直接有效的方法
591
+ for i in range(bsz):
592
+ # 提取当前批次项的数据
593
+ current_embeds = inputs_embeds[i:i+1] # shape: (1, total_tokens, embed_dim)
594
+ current_num_tokens = num_tokens_list[i]
595
+ current_prompt_mask = prompt_mask[i:i+1] # shape: (1, total_tokens)
596
+
597
+ num_samples_in_item = len(current_num_tokens)
598
+ assert total_tokens == torch.sum(current_num_tokens), \
599
+ f"批次项 {i} 的 num_tokens 之和与总长度不匹配"
600
+
601
+ eligible_for_masking = ~current_prompt_mask
602
+
603
+ # 如果没有任何 token 可以被 mask,直接使用原始输入
604
+ if not eligible_for_masking.any():
605
+ noisy_embeds_list.append(current_embeds)
606
+ final_masked_indices_list.append(torch.zeros_like(current_prompt_mask, dtype=torch.bool))
607
+ p_masks_list.append(torch.full((total_tokens,), eps, device=device))
608
+ continue
609
+
610
+ # --- 尝试生成 mask,确保至少 mask 一个 token ---
611
+ final_masked_indices_item = torch.zeros_like(current_prompt_mask, dtype=torch.bool)
612
+ p_mask_per_token = None
613
+ for _ in range(max_tries):
614
+ t = torch.rand(num_samples_in_item, device=device)
615
+ p_mask_per_sample = (1 - eps) * t + eps
616
+
617
+ p_mask_per_token_1d = torch.repeat_interleave(p_mask_per_sample, current_num_tokens)
618
+ p_mask_per_token = p_mask_per_token_1d.unsqueeze(0)
619
+
620
+ masked_indices = torch.rand_like(p_mask_per_token) < p_mask_per_token
621
+ final_masked_indices_item = masked_indices & eligible_for_masking
622
+
623
+ if final_masked_indices_item.any():
624
+ break
625
+
626
+ # --- 根据最终的 mask 生成带噪声的 embedding ---
627
+ noisy_embeds_item = torch.where(
628
+ final_masked_indices_item.unsqueeze(-1),
629
+ mask_embed_view,
630
+ current_embeds
631
+ )
632
+
633
+ # 保存这个批次项的结果
634
+ noisy_embeds_list.append(noisy_embeds_item)
635
+ final_masked_indices_list.append(final_masked_indices_item)
636
+
637
+ p_masks_list.append(p_mask_per_token)
638
+
639
+ # 3. 将列表中的结果堆叠成最终的批处理张量
640
+ final_noisy_embeds = torch.cat(noisy_embeds_list, dim=0)
641
+ final_masked_indices = torch.cat(final_masked_indices_list, dim=0)
642
+ p_mask = torch.cat(p_masks_list, dim=0)
643
+ return final_noisy_embeds, final_masked_indices, p_mask[final_masked_indices]
644
+
645
+
646
+ def block_diff_mask(b, h, q_idx, kv_idx, block_size=None, n=None):
647
+ """
648
+ Constructs the specialized block diffusion attention mask for training
649
+ composed of three masks:
650
+ - **Block Diagonal Mask (M_BD)**: Self-attention within noised blocks
651
+ - **Offset Block Causal Mask (M_OBC)**: Cross-attention for conditional context
652
+ - **Block Causal Mask (M_BC)**: Attention to update x0
653
+
654
+ Args:
655
+ b, h: Batch and head indices (ignored for mask logic).
656
+ q_idx, kv_idx: Query and Key indices.
657
+ seq_len: Total sequence length.
658
+ block_size: Defines the block structure.
659
+
660
+ Returns:
661
+ A boolean attention mask.
662
+ """
663
+
664
+ # Indicate whether token belongs to xt or x0
665
+ x0_flag_q = q_idx >= n
666
+ x0_flag_kv = kv_idx >= n
667
+
668
+ # Compute block indices
669
+ block_q = torch.where(
670
+ x0_flag_q == 1, (q_idx - n) // block_size, q_idx // block_size
671
+ )
672
+ block_kv = torch.where(
673
+ x0_flag_kv == 1, (kv_idx - n) // block_size, kv_idx // block_size
674
+ )
675
+
676
+ # **1. Block Diagonal Mask (M_BD) **
677
+ block_diagonal = (block_q == block_kv) & (x0_flag_q == x0_flag_kv)
678
+
679
+ # **2. Offset Block-Causal Mask (M_OBC) **
680
+ offset_block_causal = (block_q > block_kv) & (
681
+ x0_flag_kv == 1) & (x0_flag_q == 0)
682
+
683
+ # **3. Block-Causal Mask (M_BC) **
684
+ block_causal = (block_q >= block_kv) & (x0_flag_kv == 1) & (x0_flag_q == 1)
685
+
686
+ # **4. Combine Masks **
687
+ return block_diagonal | offset_block_causal | block_causal
688
+
689
+
690
+ def block_attn_mask(num_tokens, block_size, device):
691
+ masks = []
692
+ for i in range(len(num_tokens)):
693
+ cur_masks = []
694
+ for num in num_tokens[i]:
695
+ # 全部返回 n*n 而非 2n*2n
696
+ single_mask = block_diff_mask(
697
+ b=None,
698
+ h=None,
699
+ q_idx=torch.arange(num * 2, device=device)[:, None],
700
+ kv_idx=torch.arange(num * 2, device=device)[None, :],
701
+ block_size=block_size,
702
+ n=num,
703
+ )
704
+ cur_masks.append(single_mask)
705
+ masks.append(torch.block_diag(*cur_masks))
706
+ masks = torch.stack(masks, dim=0)
707
+ return masks
708
+
709
+
710
+ @auto_docstring(
711
+ custom_intro="""
712
+ The Llava-Next model which consists of a vision backbone and a language model without language modeling head.
713
+ """
714
+ )
715
+ class LlavaOnevisionModel(LlavaOnevisionPreTrainedModel):
716
+ _checkpoint_conversion_mapping = {"language_model.model": "language_model"}
717
+
718
+ def __init__(self, config):
719
+ super().__init__(config)
720
+ self.vision_tower = AutoModel.from_config(config.vision_config)
721
+
722
+ self.multi_modal_projector = LlavaOnevisionMultiModalProjector(config)
723
+ embed_std = 1 / math.sqrt(config.text_config.hidden_size)
724
+ self.image_newline = nn.Parameter(torch.randn(config.text_config.hidden_size, dtype=self.dtype) * embed_std)
725
+
726
+ self.vocab_size = config.text_config.vocab_size
727
+ if "auto_map" in config.text_config.to_dict():
728
+ logger.warning_once(
729
+ "The text_config of this model contains `auto_map` in its configuration. This might result in errors when using `from_pretrained` to load the model. Please make sure that the `auto_map` is correct."
730
+ )
731
+ config.text_config._name_or_path = config._name_or_path
732
+ self.language_model = AutoModel.from_config(config.text_config, trust_remote_code=True)
733
+ else:
734
+ self.language_model = AutoModel.from_config(config.text_config)
735
+
736
+ self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1
737
+ self.post_init()
738
+
739
+ def get_input_embeddings(self):
740
+ return self.language_model.get_input_embeddings()
741
+
742
+ def set_input_embeddings(self, value):
743
+ self.language_model.set_input_embeddings(value)
744
+
745
+ def pack_image_features(self, image_features, image_sizes, image_newline=None, vision_aspect_ratio="anyres_max_9"):
746
+ """
747
+ Reshape, unpad and then pack each image_feature into a single image_features tensor containing all visual vectors.
748
+
749
+ Args:
750
+ image_features (`List[torch.Tensor]` of length num_images, each of shape `(num_patches, image_length, embed_dim)`)
751
+ List of image feature tensor, each contains all the visual feature of all patches.
752
+ image_sizes (`torch.Tensor` of shape `(num_images, 2)`)
753
+ Actual image size of each images (H, W).
754
+ image_newline (`torch.Tensor` of shape `(embed_dim)`)
755
+ New line embedding vector.
756
+ vision_aspect_ratio (`str`, *optional*, "anyres_max_9"):
757
+ Aspect ratio used when processong image features. The default value is "anyres_max_9".
758
+ Returns:
759
+ image_features (`torch.Tensor` of shape `(all_feat_len, embed_dim)`)
760
+ feature_lens (`List[int]`)
761
+ token length of each image in image_features
762
+ """
763
+ new_image_features = []
764
+ feature_lens = []
765
+ for image_idx, image_feature in enumerate(image_features):
766
+ if image_feature.shape[0] > 1:
767
+ base_image_feature = image_feature[0]
768
+ image_feature = image_feature[1:]
769
+ height = width = self.config.vision_config.image_size // self.config.vision_config.patch_size
770
+ if height * width != base_image_feature.shape[0]:
771
+ raise ValueError("The number of patches is not consistent with the image size.")
772
+ num_patch_height, num_patch_width = get_anyres_image_grid_shape(
773
+ image_sizes[image_idx],
774
+ self.config.image_grid_pinpoints,
775
+ self.config.vision_config.image_size,
776
+ )
777
+ image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
778
+ image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
779
+ image_feature = image_feature.flatten(1, 2).flatten(2, 3)
780
+ image_feature = unpad_image(image_feature, image_sizes[image_idx])
781
+ max_num_patches = int(vision_aspect_ratio.strip("anyres_max_"))
782
+ channels, curr_height, curr_width = image_feature.shape
783
+ ratio = math.sqrt(curr_height * curr_width / (max_num_patches * height**2))
784
+ if ratio > 1.1:
785
+ image_feature = image_feature[None]
786
+ image_feature = nn.functional.interpolate(
787
+ image_feature, [int(curr_height // ratio), int(curr_width // ratio)], mode="bilinear"
788
+ )[0]
789
+ if image_newline is not None:
790
+ image_feature = torch.cat(
791
+ (
792
+ image_feature,
793
+ image_newline[:, None, None]
794
+ .expand(*image_feature.shape[:-1], 1)
795
+ .to(image_feature.device, image_feature.dtype),
796
+ ),
797
+ dim=-1,
798
+ )
799
+ image_feature = image_feature.flatten(1, 2).transpose(0, 1)
800
+ image_feature = torch.cat((base_image_feature, image_feature), dim=0)
801
+ else:
802
+ image_feature = image_feature[0]
803
+ if image_newline is not None:
804
+ image_feature = torch.cat((image_feature, image_newline[None].to(image_feature)), dim=0)
805
+ new_image_features.append(image_feature)
806
+ feature_lens.append(image_feature.size(0))
807
+ image_features = torch.cat(new_image_features, dim=0)
808
+ feature_lens = torch.tensor(feature_lens, dtype=torch.long, device=image_features.device)
809
+ return image_features, feature_lens
810
+
811
+ def get_image_features(
812
+ self,
813
+ pixel_values: torch.FloatTensor,
814
+ image_sizes: torch.Tensor,
815
+ vision_feature_layer: Optional[Union[int, List[int]]] = None,
816
+ vision_feature_select_strategy: Optional[str] = None,
817
+ ):
818
+ """
819
+ Obtains image last hidden states from the vision tower and apply multimodal projection.
820
+
821
+ Args:
822
+ pixel_values (`torch.FloatTensor]` of shape `(batch_size, num_patches, channels, height, width)`)
823
+ The tensors corresponding to the input images.
824
+ image_sizes (`torch.Tensor` of shape `(num_images, 2)`)
825
+ Actual image size of each images (H, W).
826
+ vision_feature_layer (`Union[int, List[int]]`, *optional*):
827
+ The index of the layer to select the vision feature. If multiple indices are provided,
828
+ the vision feature of the corresponding indices will be concatenated to form the
829
+ vision features.
830
+ vision_feature_select_strategy (`str`, *optional*):
831
+ The feature selection strategy used to select the vision feature from the vision backbone.
832
+ Can be one of `"default"` or `"full"`
833
+ Returns:
834
+ image_features (List[`torch.Tensor`]): List of image feature tensor, each contains all the visual feature of all patches
835
+ and are of shape `(num_patches, image_length, embed_dim)`).
836
+ """
837
+ vision_feature_layer = (
838
+ vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
839
+ )
840
+ vision_feature_select_strategy = (
841
+ vision_feature_select_strategy
842
+ if vision_feature_select_strategy is not None
843
+ else self.config.vision_feature_select_strategy
844
+ )
845
+
846
+ # ! infer image_num_patches from image_sizes
847
+ image_num_patches = [
848
+ image_size_to_num_patches(
849
+ image_size=imsize,
850
+ grid_pinpoints=self.config.image_grid_pinpoints,
851
+ patch_size=self.config.vision_config.image_size,
852
+ )
853
+ for imsize in image_sizes
854
+ ]
855
+ if pixel_values.dim() == 5:
856
+ # stacked if input is (batch_size, num_patches, num_channels, height, width)
857
+ _pixel_values_list = [pix_val[:num_patch] for pix_val, num_patch in zip(pixel_values, image_num_patches)]
858
+ pixel_values = torch.cat(_pixel_values_list, dim=0)
859
+ elif pixel_values.dim() != 4:
860
+ # otherwise has to be stacked from list of (num_patches, num_channels, height, width)
861
+ raise ValueError(f"pixel_values of shape {pixel_values.shape}, expect to be of 4 or 5 dimensions")
862
+
863
+ image_features = self.vision_tower(pixel_values, output_hidden_states=True)
864
+ # If we have one vision feature layer, return the corresponding hidden states,
865
+ # otherwise, select the hidden states of each feature layer and concatenate them
866
+ if isinstance(vision_feature_layer, int):
867
+ selected_image_feature = image_features.hidden_states[vision_feature_layer]
868
+ else:
869
+ hs_pool = [image_features.hidden_states[layer_idx] for layer_idx in vision_feature_layer]
870
+ selected_image_feature = torch.cat(hs_pool, dim=-1)
871
+
872
+ if vision_feature_select_strategy == "default":
873
+ selected_image_feature = selected_image_feature[:, 1:]
874
+ elif vision_feature_select_strategy == "full":
875
+ selected_image_feature = selected_image_feature
876
+ image_features = self.multi_modal_projector(selected_image_feature)
877
+ image_features = torch.split(image_features, image_num_patches, dim=0)
878
+ return image_features
879
+
880
+ def _get_mask_embedding(self):
881
+ device = self.get_input_embeddings().weight.device
882
+ mask_token_tensor = torch.tensor(self.config.text_config.mask_token_id, device=device)
883
+ return self.get_input_embeddings()(mask_token_tensor)
884
+
885
+ def prepare_for_bd_training(self, inputs_embeds, position_ids, prompt_mask):
886
+ bsz, seq_len, _ = inputs_embeds.shape
887
+ num_tokens = calculate_token_nums(position_ids) # List[torch.Tensor]
888
+ noisy_inputs_embeds, logits_to_keep_half, p_mask = forward_add_noise_packed(
889
+ inputs_embeds=inputs_embeds,
890
+ num_tokens_list=num_tokens,
891
+ prompt_mask=prompt_mask,
892
+ mask_embed=self._get_mask_embedding(),
893
+ )
894
+ router_noisy_part_list = []
895
+ for i in range(bsz):
896
+ cur_router_noisy_part = (torch.arange(num_tokens[i].shape[0] *2) % 2 == 0).to(inputs_embeds.device)
897
+ cur_router_noisy_part = cur_router_noisy_part.repeat_interleave(num_tokens[i].repeat_interleave(2))
898
+ router_noisy_part_list.append(cur_router_noisy_part)
899
+ router_noisy_part = torch.stack(router_noisy_part_list, dim=0)
900
+
901
+ # concated inputs_embeds: (bzs, seq_len x 2, dim)
902
+ concat_inputs_embeds = inputs_embeds.repeat(1, 2, 1)
903
+ # concated logits_to_keep: (bsz, seq_len x 2)
904
+ logits_to_keep = torch.zeros(
905
+ bsz, 2 * seq_len, dtype=torch.bool, device=inputs_embeds.device)
906
+ # concated position_ids: (bsz, seq_len x 2)
907
+ concat_position_ids = torch.zeros(
908
+ bsz, 2 * seq_len, dtype=position_ids.dtype, device=position_ids.device)
909
+ for i in range(bsz):
910
+ concat_inputs_embeds[i][router_noisy_part[i]] = noisy_inputs_embeds[i]
911
+ concat_inputs_embeds[i][~router_noisy_part[i]] = inputs_embeds[i]
912
+
913
+ logits_to_keep[i][router_noisy_part[i]] = logits_to_keep_half[i]
914
+
915
+ concat_position_ids[i][router_noisy_part[i]] = position_ids[i]
916
+ concat_position_ids[i][~router_noisy_part[i]] = position_ids[i]
917
+
918
+ # create flex_attention mask
919
+ attention_mask = block_attn_mask(num_tokens, self.config.text_config.block_size, inputs_embeds.device)
920
+ flex_attention_mask_3d = create_block_mask(
921
+ lambda b, h, q_idx, kv_idx: attention_mask[b, q_idx, kv_idx],
922
+ B=attention_mask.size(0), H=None,
923
+ Q_LEN=attention_mask.size(1), KV_LEN=attention_mask.size(2),
924
+ )
925
+
926
+ return concat_inputs_embeds, concat_position_ids, flex_attention_mask_3d, logits_to_keep_half, logits_to_keep, p_mask
927
+
928
+
929
+ @can_return_tuple
930
+ @auto_docstring
931
+ def forward(
932
+ self,
933
+ input_ids: torch.LongTensor = None,
934
+ pixel_values: torch.FloatTensor = None,
935
+ image_sizes: Optional[torch.LongTensor] = None,
936
+ pixel_values_videos: torch.FloatTensor = None,
937
+ image_sizes_videos: Optional[torch.LongTensor] = None,
938
+ attention_mask: Optional[torch.Tensor] = None,
939
+ prompt_mask: Optional[torch.Tensor] = None,
940
+ position_ids: Optional[torch.LongTensor] = None,
941
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
942
+ inputs_embeds: Optional[torch.FloatTensor] = None,
943
+ vision_feature_layer: Optional[Union[int, List[int]]] = None,
944
+ vision_feature_select_strategy: Optional[str] = None,
945
+ vision_aspect_ratio: Optional[str] = None,
946
+ use_cache: Optional[bool] = None,
947
+ output_attentions: Optional[bool] = None,
948
+ output_hidden_states: Optional[bool] = None,
949
+ return_dict: Optional[bool] = None,
950
+ cache_position: Optional[torch.LongTensor] = None,
951
+ **kwargs: Unpack[FlashAttentionKwargs],
952
+ ) -> Union[Tuple, LlavaOnevisionModelOutputWithPast]:
953
+ r"""
954
+ pixel_values_videos (`torch.FloatTensor` of shape `(batch_size, frames, num_channels, image_size, image_size)):
955
+ The tensors corresponding to the input videos. Pixel values can be obtained using
956
+ [`LlavaNextVideoProcessor`]. See [`LlavaNextVideoProcessor.__call__`] for details. [`LlavaProcessor`] uses
957
+ [`LlavaNextVideoProcessor`] for processing videos.
958
+ image_sizes_videos (`torch.LongTensor` of shape `(batch_size, frames, 2)`, *optional*):
959
+ The sizes of the videos in the batch, being (height, width) for each frame in the video.
960
+ vision_feature_select_strategy (`str`, *optional*, defaults to `"default"`):
961
+ The feature selection strategy used to select the vision feature from the vision backbone.
962
+ Can be one of `"default"` or `"full"`. If `"default"`, the CLS token is removed from the vision features.
963
+ If `"full"`, the full vision features are used.
964
+ vision_aspect_ratio (`str`, *optional*, defaults to `"anyres_max_9"`):
965
+ Aspect ratio used when processong image features. The default value is "anyres_max_9".
966
+ """
967
+
968
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
969
+ output_hidden_states = (
970
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
971
+ )
972
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
973
+ vision_feature_layer = (
974
+ vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
975
+ )
976
+ vision_feature_select_strategy = (
977
+ vision_feature_select_strategy
978
+ if vision_feature_select_strategy is not None
979
+ else self.config.vision_feature_select_strategy
980
+ )
981
+ vision_aspect_ratio = (
982
+ vision_aspect_ratio if vision_aspect_ratio is not None else self.config.vision_aspect_ratio
983
+ )
984
+
985
+ if (input_ids is None) ^ (inputs_embeds is not None):
986
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
987
+
988
+ if (pixel_values is not None or pixel_values_videos is not None) and inputs_embeds is not None:
989
+ raise ValueError(
990
+ "You cannot specify both `pixel_values`/`pixel_values_videos` and `inputs_embeds` at the same time, "
991
+ "and must specify either one"
992
+ )
993
+
994
+ if inputs_embeds is None:
995
+ inputs_embeds = self.get_input_embeddings()(input_ids)
996
+
997
+ # Images are processed with Anyres
998
+ if pixel_values is not None:
999
+ image_features = self.get_image_features(
1000
+ pixel_values,
1001
+ image_sizes,
1002
+ vision_feature_layer=vision_feature_layer,
1003
+ vision_feature_select_strategy=vision_feature_select_strategy,
1004
+ )
1005
+ image_features, feature_lens = self.pack_image_features(
1006
+ image_features,
1007
+ image_sizes,
1008
+ image_newline=self.image_newline,
1009
+ vision_aspect_ratio=vision_aspect_ratio,
1010
+ )
1011
+
1012
+ special_image_mask = (input_ids == self.config.image_token_id).unsqueeze(-1)
1013
+ special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
1014
+ if not is_torchdynamo_compiling() and inputs_embeds[special_image_mask].numel() != image_features.numel():
1015
+ n_image_tokens = (input_ids == self.config.image_token_id).sum()
1016
+ n_image_features = image_features.shape[0]
1017
+ raise ValueError(
1018
+ f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
1019
+ )
1020
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
1021
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
1022
+
1023
+ # Video are simply embedded and further pooled to decrease seq len
1024
+ if pixel_values_videos is not None:
1025
+ video_features = self.get_video_features(
1026
+ pixel_values_videos,
1027
+ vision_feature_layer=vision_feature_layer,
1028
+ vision_feature_select_strategy=vision_feature_select_strategy,
1029
+ )
1030
+ if isinstance(video_features, tuple):
1031
+ image_newline = self.image_newline[None, :].to(video_features[0].device)
1032
+ video_features = [torch.cat((single_video_feature, image_newline), dim=0) for single_video_feature in video_features]
1033
+ video_features = torch.cat(video_features, dim=0)
1034
+ else:
1035
+ image_newline = (
1036
+ self.image_newline[None, None, :].repeat(video_features.shape[0], 1, 1).to(video_features.device)
1037
+ )
1038
+ video_features = torch.cat((video_features, image_newline), dim=1)
1039
+ video_features = video_features.flatten(0, 1)
1040
+
1041
+ special_video_mask = (input_ids == self.config.video_token_id).unsqueeze(-1)
1042
+ special_video_mask = special_video_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
1043
+ if not is_torchdynamo_compiling() and inputs_embeds[special_video_mask].numel() != video_features.numel():
1044
+ n_video_tokens = (input_ids == self.config.video_token_id).sum()
1045
+ n_video_features = video_features.shape[0]
1046
+ raise ValueError(
1047
+ f"Video features and video tokens do not match: tokens: {n_video_tokens}, features {n_video_features}"
1048
+ )
1049
+ video_features = video_features.to(inputs_embeds.device, inputs_embeds.dtype)
1050
+ inputs_embeds = inputs_embeds.masked_scatter(special_video_mask, video_features)
1051
+
1052
+ if self.training:
1053
+ position_ids = modify_padded_position_ids_2d(position_ids)
1054
+ concat_inputs_embeds, concat_position_ids, flex_attention_mask_3d, logits_to_keep_half, logits_to_keep, p_mask = self.prepare_for_bd_training(inputs_embeds, position_ids, prompt_mask)
1055
+ outputs = self.language_model(
1056
+ attention_mask=flex_attention_mask_3d,
1057
+ position_ids=concat_position_ids,
1058
+ inputs_embeds=concat_inputs_embeds,
1059
+ output_attentions=output_attentions,
1060
+ output_hidden_states=output_hidden_states,
1061
+ return_dict=True,
1062
+ cache_position=cache_position,
1063
+ **kwargs,
1064
+ )
1065
+ else:
1066
+ # raise NotImplementedError("Currently only support training.")
1067
+ outputs = self.language_model(
1068
+ attention_mask=attention_mask,
1069
+ position_ids=position_ids,
1070
+ past_key_values=past_key_values,
1071
+ inputs_embeds=inputs_embeds,
1072
+ use_cache=use_cache,
1073
+ output_attentions=output_attentions,
1074
+ output_hidden_states=output_hidden_states,
1075
+ return_dict=True,
1076
+ cache_position=cache_position,
1077
+ **kwargs,
1078
+ )
1079
+
1080
+ return LlavaOnevisionModelOutputWithPast(
1081
+ last_hidden_state=outputs.last_hidden_state,
1082
+ logits_to_keep_half=logits_to_keep_half if self.training else None,
1083
+ logits_to_keep=logits_to_keep if self.training else None,
1084
+ p_mask=p_mask if self.training else None,
1085
+ past_key_values=outputs.past_key_values,
1086
+ hidden_states=outputs.hidden_states,
1087
+ attentions=outputs.attentions,
1088
+ image_hidden_states=image_features if pixel_values is not None else None,
1089
+ video_hidden_states=video_features if pixel_values_videos is not None else None,
1090
+ )
1091
+
1092
+ def get_video_features(
1093
+ self,
1094
+ pixel_values: torch.FloatTensor,
1095
+ vision_feature_layer: Union[int, List[int]],
1096
+ vision_feature_select_strategy: str,
1097
+ ):
1098
+ """
1099
+ Obtains video last hidden states from the vision tower, apply multimodal projection and pooling.
1100
+
1101
+ Args:
1102
+ pixel_values (`torch.FloatTensor]` of shape `(batch_size, num_frames, channels, height, width)`)
1103
+ The tensors corresponding to the input video.
1104
+ vision_feature_layer (`Union[int, List[int]], *optional*, defaults to -2`):
1105
+ The index of the layer to select the vision feature. If multiple indices are provided,
1106
+ the vision feature of the corresponding indices will be concatenated to form the
1107
+ vision features.
1108
+ vision_feature_select_strategy (`str`):
1109
+ The feature selection strategy used to select the vision feature from the vision backbone.
1110
+ Can be one of `"default"` or `"full"`
1111
+ Returns:
1112
+ video_features (List[`torch.Tensor`]): List of video feature tensor, each contains all the visual feature of all patches
1113
+ and are of shape `(num_videos, video_length, embed_dim)`).
1114
+ """
1115
+ has_variable_frames = isinstance(pixel_values, List)
1116
+ if has_variable_frames:
1117
+ frame_nums = [video.size(0) for video in pixel_values]
1118
+ pixel_values = torch.cat(pixel_values, dim=0) # Shape: (total_frames, C, H, W)
1119
+ else:
1120
+ # 每个视频帧数相同
1121
+ batch_size, frames, channels, height, width = pixel_values.shape
1122
+ pixel_values = pixel_values.view(batch_size * frames, channels, height, width)
1123
+ video_features = self.vision_tower(pixel_values, output_hidden_states=True)
1124
+ # If we have one vision feature layer, return the corresponding hidden states,
1125
+ # otherwise, select the hidden states of each feature layer and concatenate them
1126
+ if isinstance(vision_feature_layer, int):
1127
+ selected_video_feature = video_features.hidden_states[vision_feature_layer]
1128
+ else:
1129
+ hs_pool = [video_features.hidden_states[layer_idx] for layer_idx in vision_feature_layer]
1130
+ selected_video_feature = torch.cat(hs_pool, dim=-1)
1131
+
1132
+ if vision_feature_select_strategy == "default":
1133
+ selected_video_feature = selected_video_feature[:, 1:]
1134
+ elif vision_feature_select_strategy == "full":
1135
+ selected_video_feature = selected_video_feature
1136
+ video_features = self.multi_modal_projector(selected_video_feature)
1137
+
1138
+ video_features = self.apply_pooling(video_features)
1139
+
1140
+ if has_variable_frames:
1141
+ tokens_per_frame = video_features.shape[1]
1142
+ video_features = video_features.flatten(0, 1)
1143
+ video_tokens_lengths = [num_frames * tokens_per_frame for num_frames in frame_nums]
1144
+ video_features = torch.split(video_features, video_tokens_lengths, dim=0)
1145
+ else:
1146
+ video_features = video_features.reshape(batch_size, frames * video_features.shape[1], -1)
1147
+
1148
+ return video_features
1149
+
1150
+ def apply_pooling(self, image_features):
1151
+ height = width = self.config.vision_config.image_size // self.config.vision_config.patch_size
1152
+ batch_frames, seq_len, dim = image_features.shape
1153
+ image_features = image_features.view(batch_frames, height, width, -1)
1154
+ image_features = image_features.permute(0, 3, 1, 2).contiguous()
1155
+
1156
+ height, width = image_features.shape[2:]
1157
+ scaled_shape = [math.ceil(height / 2), math.ceil(width / 2)]
1158
+ image_features = nn.functional.interpolate(image_features, size=scaled_shape, mode="bilinear")
1159
+
1160
+ image_features = image_features.permute(0, 2, 3, 1)
1161
+ image_features = image_features.view(batch_frames, -1, dim)
1162
+ return image_features
1163
+
1164
+
1165
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
1166
+
1167
+
1168
+ @auto_docstring(
1169
+ custom_intro="""
1170
+ The LLAVA-NeXT model which consists of a vision backbone and a language model.
1171
+ """
1172
+ )
1173
+ class LlavaOnevisionForConditionalGeneration(LlavaOnevisionPreTrainedModel, GenerationMixin):
1174
+ _checkpoint_conversion_mapping = {
1175
+ "^language_model.model": "model.language_model",
1176
+ "^vision_tower": "model.vision_tower",
1177
+ "^multi_modal_projector": "model.multi_modal_projector",
1178
+ "^image_newline": "model.image_newline",
1179
+ "^language_model.lm_head": "lm_head",
1180
+ }
1181
+ _tied_weights_keys = ["lm_head.weight"]
1182
+
1183
+ def __init__(self, config: LlavaOnevisionConfig):
1184
+ super().__init__(config)
1185
+ self.model = LlavaOnevisionModel(config)
1186
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
1187
+ self.post_init()
1188
+
1189
+ def get_input_embeddings(self):
1190
+ return self.model.get_input_embeddings()
1191
+
1192
+ def set_input_embeddings(self, value):
1193
+ self.model.set_input_embeddings(value)
1194
+
1195
+ def get_output_embeddings(self) -> nn.Module:
1196
+ return self.lm_head
1197
+
1198
+ def set_output_embeddings(self, new_embeddings):
1199
+ self.lm_head = new_embeddings
1200
+
1201
+ # Make modules available throught conditional class for BC
1202
+ @property
1203
+ def language_model(self):
1204
+ return self.model.language_model
1205
+
1206
+ @property
1207
+ def vision_tower(self):
1208
+ return self.model.vision_tower
1209
+
1210
+ @property
1211
+ def multi_modal_projector(self):
1212
+ return self.model.multi_modal_projector
1213
+
1214
+ @can_return_tuple
1215
+ @auto_docstring
1216
+ def forward(
1217
+ self,
1218
+ input_ids: torch.LongTensor = None,
1219
+ pixel_values: torch.FloatTensor = None,
1220
+ image_sizes: Optional[torch.LongTensor] = None,
1221
+ pixel_values_videos: torch.FloatTensor = None,
1222
+ image_sizes_videos: Optional[torch.LongTensor] = None,
1223
+ attention_mask: Optional[torch.Tensor] = None,
1224
+ position_ids: Optional[torch.LongTensor] = None,
1225
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1226
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1227
+ vision_feature_layer: Optional[Union[int, List[int]]] = None,
1228
+ vision_feature_select_strategy: Optional[str] = None,
1229
+ vision_aspect_ratio: Optional[str] = None,
1230
+ labels: Optional[torch.LongTensor] = None,
1231
+ use_cache: Optional[bool] = None,
1232
+ output_attentions: Optional[bool] = None,
1233
+ output_hidden_states: Optional[bool] = None,
1234
+ return_dict: Optional[bool] = None,
1235
+ cache_position: Optional[torch.LongTensor] = None,
1236
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1237
+ **kwargs: Unpack[KwargsForCausalLM],
1238
+ ) -> Union[Tuple, LlavaOnevisionCausalLMOutputWithPast]:
1239
+ r"""
1240
+ pixel_values_videos (`torch.FloatTensor` of shape `(batch_size, frames, num_channels, image_size, image_size)):
1241
+ The tensors corresponding to the input videos. Pixel values can be obtained using
1242
+ [`LlavaNextVideoProcessor`]. See [`LlavaNextVideoProcessor.__call__`] for details. [`LlavaProcessor`] uses
1243
+ [`LlavaNextVideoProcessor`] for processing videos.
1244
+ image_sizes_videos (`torch.LongTensor` of shape `(batch_size, frames, 2)`, *optional*):
1245
+ The sizes of the videos in the batch, being (height, width) for each frame in the video.
1246
+ vision_feature_select_strategy (`str`, *optional*, defaults to `"default"`):
1247
+ The feature selection strategy used to select the vision feature from the vision backbone.
1248
+ Can be one of `"default"` or `"full"`. If `"default"`, the CLS token is removed from the vision features.
1249
+ If `"full"`, the full vision features are used.
1250
+ vision_aspect_ratio (`str`, *optional*, defaults to `"anyres_max_9"`):
1251
+ Aspect ratio used when processong image features. The default value is "anyres_max_9".
1252
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1253
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1254
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1255
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1256
+
1257
+ Example:
1258
+
1259
+ ```python
1260
+ >>> from PIL import Image
1261
+ >>> import requests
1262
+ >>> import torch
1263
+ >>> from transformers import LlavaOnevisionProcessor, LlavaOnevisionForConditionalGeneration
1264
+
1265
+ >>> model = LlavaOnevisionForConditionalGeneration.from_pretrained("llava-hf/llava-onevision-qwen2-7b-ov-hf", torch_dtype="float16", device_map="cuda:0")
1266
+ >>> processor = LlavaOnevisionProcessor.from_pretrained("llava-hf/llava-onevision-qwen2-7b-ov-hf")
1267
+
1268
+ >>> conversation = [
1269
+ ... {
1270
+ ... "role": "user",
1271
+ ... "content": [
1272
+ ... {"type": "text", "text": "What is shown in this image?"},
1273
+ ... {"type": "image"},
1274
+ ... ],
1275
+ ... },
1276
+ ... ]
1277
+ >>> prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
1278
+
1279
+ >>> image_file = "http://images.cocodataset.org/val2017/000000039769.jpg"
1280
+ >>> raw_image = Image.open(requests.get(image_file, stream=True).raw)
1281
+ >>> inputs = processor(text=prompt, images=raw_image, return_tensors='pt').to(0, torch.float16)
1282
+
1283
+ >>> output = model.generate(**inputs, max_new_tokens=20, do_sample=False)
1284
+ >>> processor.batch_decode(output, skip_special_tokens=True)[0]
1285
+ "user\n\nWhat is shown in this image?\nassistant\ncat"
1286
+ ```"""
1287
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1288
+ output_hidden_states = (
1289
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1290
+ )
1291
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1292
+ vision_feature_layer = (
1293
+ vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
1294
+ )
1295
+ vision_feature_select_strategy = (
1296
+ vision_feature_select_strategy
1297
+ if vision_feature_select_strategy is not None
1298
+ else self.config.vision_feature_select_strategy
1299
+ )
1300
+ vision_aspect_ratio = (
1301
+ vision_aspect_ratio if vision_aspect_ratio is not None else self.config.vision_aspect_ratio
1302
+ )
1303
+ prompt_mask = (labels == -100) if labels is not None else None
1304
+ outputs = self.model(
1305
+ input_ids=input_ids,
1306
+ pixel_values=pixel_values,
1307
+ pixel_values_videos=pixel_values_videos,
1308
+ image_sizes=image_sizes,
1309
+ image_sizes_videos=image_sizes_videos,
1310
+ vision_aspect_ratio=vision_aspect_ratio,
1311
+ vision_feature_layer=vision_feature_layer,
1312
+ vision_feature_select_strategy=vision_feature_select_strategy,
1313
+ attention_mask=attention_mask,
1314
+ prompt_mask=prompt_mask,
1315
+ position_ids=position_ids,
1316
+ past_key_values=past_key_values,
1317
+ inputs_embeds=inputs_embeds,
1318
+ use_cache=use_cache,
1319
+ output_attentions=output_attentions,
1320
+ output_hidden_states=output_hidden_states,
1321
+ return_dict=True,
1322
+ cache_position=cache_position,
1323
+ logits_to_keep=logits_to_keep,
1324
+ **kwargs,
1325
+ )
1326
+
1327
+ hidden_states = outputs[0]
1328
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1329
+
1330
+ loss = None
1331
+ if self.training:
1332
+ assert labels is not None, "Labels must be provided for training."
1333
+ hidden_states = hidden_states[outputs.logits_to_keep].contiguous()
1334
+ labels = labels[outputs.logits_to_keep_half].contiguous()
1335
+ loss_fct = FusedLinearDiffusionCrossEntropyLoss(reduction='sum')
1336
+ loss = loss_fct( # it will return (sum_loss, unreduced_loss)
1337
+ # conduct `view(-1, V)` inside the function
1338
+ x=hidden_states,
1339
+ target=labels,
1340
+ weight=self.lm_head.weight,
1341
+ bias=self.lm_head.bias,
1342
+ p_mask=outputs.p_mask,
1343
+ )
1344
+ loss = loss / labels.numel()
1345
+ logits = None
1346
+ else:
1347
+ logits = self.lm_head(hidden_states)
1348
+
1349
+ return LlavaOnevisionCausalLMOutputWithPast(
1350
+ loss=loss,
1351
+ logits=logits,
1352
+ past_key_values=outputs.past_key_values,
1353
+ hidden_states=outputs.hidden_states,
1354
+ attentions=outputs.attentions,
1355
+ image_hidden_states=outputs.image_hidden_states,
1356
+ video_hidden_states=outputs.video_hidden_states,
1357
+ )
1358
+
1359
+ def prepare_inputs_for_generation(
1360
+ self,
1361
+ input_ids,
1362
+ past_key_values=None,
1363
+ inputs_embeds=None,
1364
+ pixel_values=None,
1365
+ image_sizes=None,
1366
+ pixel_values_videos=None,
1367
+ image_sizes_videos=None,
1368
+ attention_mask=None,
1369
+ cache_position=None,
1370
+ logits_to_keep=None,
1371
+ **kwargs,
1372
+ ):
1373
+ # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
1374
+
1375
+ model_inputs = super().prepare_inputs_for_generation(
1376
+ input_ids,
1377
+ past_key_values=past_key_values,
1378
+ inputs_embeds=inputs_embeds,
1379
+ attention_mask=attention_mask,
1380
+ cache_position=cache_position,
1381
+ logits_to_keep=logits_to_keep,
1382
+ **kwargs,
1383
+ )
1384
+
1385
+ if cache_position[0] == 0:
1386
+ # If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore
1387
+ # Otherwise we need pixel values to be passed to model
1388
+ model_inputs["pixel_values"] = pixel_values
1389
+ model_inputs["image_sizes"] = image_sizes
1390
+ model_inputs["pixel_values_videos"] = pixel_values_videos
1391
+ model_inputs["image_sizes_videos"] = image_sizes_videos
1392
+
1393
+ return model_inputs
1394
+
1395
+ @staticmethod
1396
+ def _prepare_4d_causal_attention_mask_with_cache_position(
1397
+ attention_mask: torch.Tensor,
1398
+ sequence_length: int,
1399
+ target_length: int,
1400
+ dtype: torch.dtype,
1401
+ cache_position: torch.Tensor,
1402
+ batch_size: int,
1403
+ **kwargs,
1404
+ ):
1405
+ """
1406
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
1407
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
1408
+
1409
+ Args:
1410
+ attention_mask (`torch.Tensor`):
1411
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
1412
+ `(batch_size, 1, query_length, key_value_length)`.
1413
+ sequence_length (`int`):
1414
+ The sequence length being processed.
1415
+ target_length (`int`):
1416
+ The target length: when generating with static cache, the mask should be as long as the static cache,
1417
+ to account for the 0 padding, the part of the cache that is not filled yet.
1418
+ dtype (`torch.dtype`):
1419
+ The dtype to use for the 4D attention mask.
1420
+ cache_position (`torch.Tensor`):
1421
+ Indices depicting the position of the input sequence tokens in the sequence.
1422
+ batch_size (`torch.Tensor`):
1423
+ Batch size.
1424
+ """
1425
+ if attention_mask is not None and attention_mask.dim() == 4:
1426
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
1427
+ causal_mask = attention_mask
1428
+ else:
1429
+ min_dtype = torch.finfo(dtype).min
1430
+ causal_mask = torch.full(
1431
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
1432
+ )
1433
+ if sequence_length != 1:
1434
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1435
+ causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)
1436
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
1437
+ if attention_mask is not None:
1438
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1439
+ mask_length = attention_mask.shape[-1]
1440
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
1441
+ causal_mask.device
1442
+ )
1443
+ padding_mask = padding_mask == 0
1444
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1445
+ padding_mask, min_dtype
1446
+ )
1447
+
1448
+ return causal_mask
1449
+
1450
+
1451
+ __all__ = ["LlavaOnevisionModel", "LlavaOnevisionForConditionalGeneration", "LlavaOnevisionPreTrainedModel"]
modeling_sdar.py ADDED
@@ -0,0 +1,909 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is modified based on https://github.com/huggingface/transformers/blob/v4.52.4/src/transformers/models/qwen3/modeling_qwen3.py.
2
+ #
3
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
4
+ # This file was automatically generated from src/transformers/models/qwen3/modular_qwen3.py.
5
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
6
+ # the file from the modular. If any change should be done, please apply the change to the
7
+ # modular_qwen3.py file directly. One of our CI enforces this.
8
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
9
+ # coding=utf-8
10
+ # Copyright 2025 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
11
+ #
12
+ # Licensed under the Apache License, Version 2.0 (the "License");
13
+ # you may not use this file except in compliance with the License.
14
+ # You may obtain a copy of the License at
15
+ #
16
+ # http://www.apache.org/licenses/LICENSE-2.0
17
+ #
18
+ # Unless required by applicable law or agreed to in writing, software
19
+ # distributed under the License is distributed on an "AS IS" BASIS,
20
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
+ # See the License for the specific language governing permissions and
22
+ # limitations under the License.
23
+
24
+ from typing import Callable, Optional, Tuple, Union
25
+
26
+ import torch
27
+ from torch import nn
28
+ from einops import rearrange
29
+
30
+ from transformers.activations import ACT2FN
31
+ from transformers.cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
32
+ from transformers.generation import GenerationMixin
33
+ from transformers.integrations import use_kernel_forward_from_hub
34
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
35
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
36
+ from transformers.modeling_layers import GradientCheckpointingLayer
37
+ from transformers.modeling_outputs import (
38
+ BaseModelOutputWithPast,
39
+ CausalLMOutputWithPast,
40
+ QuestionAnsweringModelOutput,
41
+ SequenceClassifierOutputWithPast,
42
+ TokenClassifierOutput,
43
+ )
44
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
45
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
46
+ from transformers.processing_utils import Unpack
47
+ from transformers.utils import LossKwargs, auto_docstring, can_return_tuple, is_torch_flex_attn_available, logging
48
+ from .configuration_sdar import SDARConfig
49
+
50
+ from flash_attn.ops.triton.layer_norm import rms_norm_fn as flash_rms_norm
51
+
52
+ import torch.nn.functional as F
53
+ try:
54
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
55
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input
56
+ except:
57
+ pass
58
+
59
+ try:
60
+ from liger_kernel.ops.swiglu import LigerSiLUMulFunction # noqa: F401
61
+ liger_kernel_is_available = True
62
+ except ImportError:
63
+ liger_kernel_is_available = False
64
+
65
+
66
+
67
+ from torch.nn.attention.flex_attention import BlockMask, create_block_mask, flex_attention
68
+ from transformers.integrations.flex_attention import make_flex_block_causal_mask
69
+
70
+
71
+ @torch.compile(fullgraph=True, mode="max-autotune-no-cudagraphs")
72
+ def fused_flex_attention(query, key, value, attention_mask, **kwargs):
73
+ return flex_attention(query, key, value, block_mask=attention_mask, **kwargs)
74
+
75
+
76
+ logger = logging.get_logger(__name__)
77
+
78
+
79
+ @use_kernel_forward_from_hub("RMSNorm")
80
+ class SDARRMSNorm(nn.Module):
81
+ def __init__(self, hidden_size, eps=1e-6):
82
+ """
83
+ SDARRMSNorm is equivalent to T5LayerNorm
84
+ """
85
+ super().__init__()
86
+ self.weight = nn.Parameter(torch.ones(hidden_size))
87
+ self.variance_epsilon = eps
88
+
89
+ def forward(self, hidden_states):
90
+ return flash_rms_norm(
91
+ hidden_states, weight=self.weight, bias=None, eps=self.variance_epsilon)
92
+ '''
93
+ input_dtype = hidden_states.dtype
94
+ hidden_states = hidden_states.to(torch.float32)
95
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
96
+ hidden_states = hidden_states * \
97
+ torch.rsqrt(variance + self.variance_epsilon)
98
+ return self.weight * hidden_states.to(input_dtype)
99
+ '''
100
+
101
+ def extra_repr(self):
102
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
103
+
104
+
105
+ class SDARMLP(nn.Module):
106
+ def __init__(self, config):
107
+ super().__init__()
108
+ self.config = config
109
+ self.hidden_size = config.hidden_size
110
+ self.intermediate_size = config.intermediate_size
111
+ self.gate_proj = nn.Linear(
112
+ self.hidden_size, self.intermediate_size, bias=False)
113
+ self.up_proj = nn.Linear(
114
+ self.hidden_size, self.intermediate_size, bias=False)
115
+ self.down_proj = nn.Linear(
116
+ self.intermediate_size, self.hidden_size, bias=False)
117
+ self.act_fn = ACT2FN[config.hidden_act]
118
+
119
+ def forward(self, x):
120
+ if liger_kernel_is_available:
121
+ return self.down_proj(LigerSiLUMulFunction.apply(self.gate_proj(x), self.up_proj(x)))
122
+ else:
123
+ down_proj = self.down_proj(self.act_fn(
124
+ self.gate_proj(x)) * self.up_proj(x))
125
+ return down_proj
126
+
127
+
128
+ def rotate_half(x):
129
+ """Rotates half the hidden dims of the input."""
130
+ x1 = x[..., : x.shape[-1] // 2]
131
+ x2 = x[..., x.shape[-1] // 2:]
132
+ return torch.cat((-x2, x1), dim=-1)
133
+
134
+
135
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
136
+ """Applies Rotary Position Embedding to the query and key tensors.
137
+
138
+ Args:
139
+ q (`torch.Tensor`): The query tensor.
140
+ k (`torch.Tensor`): The key tensor.
141
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
142
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
143
+ position_ids (`torch.Tensor`, *optional*):
144
+ Deprecated and unused.
145
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
146
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
147
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
148
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
149
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
150
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
151
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
152
+ Returns:
153
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
154
+ """
155
+ cos = cos.unsqueeze(unsqueeze_dim)
156
+ sin = sin.unsqueeze(unsqueeze_dim)
157
+ q_embed = (q * cos) + (rotate_half(q) * sin)
158
+ k_embed = (k * cos) + (rotate_half(k) * sin)
159
+ return q_embed, k_embed
160
+
161
+
162
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
163
+ """
164
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
165
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
166
+ """
167
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
168
+ if n_rep == 1:
169
+ return hidden_states
170
+ hidden_states = hidden_states[:, :, None, :, :].expand(
171
+ batch, num_key_value_heads, n_rep, slen, head_dim)
172
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
173
+
174
+
175
+ def eager_attention_forward(
176
+ module: nn.Module,
177
+ query: torch.Tensor,
178
+ key: torch.Tensor,
179
+ value: torch.Tensor,
180
+ attention_mask: Optional[torch.Tensor],
181
+ scaling: float,
182
+ dropout: float = 0.0,
183
+ **kwargs,
184
+ ):
185
+ key_states = repeat_kv(key, module.num_key_value_groups)
186
+ value_states = repeat_kv(value, module.num_key_value_groups)
187
+
188
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
189
+ if attention_mask is not None:
190
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
191
+ attn_weights = attn_weights + causal_mask
192
+
193
+ attn_weights = nn.functional.softmax(
194
+ attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
195
+ attn_weights = nn.functional.dropout(
196
+ attn_weights, p=dropout, training=module.training)
197
+ attn_output = torch.matmul(attn_weights, value_states)
198
+ attn_output = attn_output.transpose(1, 2).contiguous()
199
+
200
+ return attn_output, attn_weights
201
+
202
+
203
+ class SDARAttention(nn.Module):
204
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
205
+
206
+ def __init__(self, config: SDARConfig, layer_idx: int):
207
+ super().__init__()
208
+ self.config = config
209
+ self.layer_idx = layer_idx
210
+ self.head_dim = getattr(
211
+ config, "head_dim", config.hidden_size // config.num_attention_heads)
212
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
213
+ self.scaling = self.head_dim**-0.5
214
+ self.attention_dropout = config.attention_dropout
215
+ self.is_causal = True
216
+
217
+ self.hidden_size = config.hidden_size
218
+ self.num_attention_heads = config.num_attention_heads
219
+ self.num_key_value_heads = config.num_key_value_heads
220
+
221
+ self.q_proj = nn.Linear(
222
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
223
+ )
224
+ self.k_proj = nn.Linear(
225
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
226
+ )
227
+ self.v_proj = nn.Linear(
228
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
229
+ )
230
+ self.o_proj = nn.Linear(
231
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
232
+ )
233
+ # unlike olmo, only on the head dim!
234
+ self.q_norm = SDARRMSNorm(self.head_dim, eps=config.rms_norm_eps)
235
+ # thus post q_norm does not need reshape
236
+ self.k_norm = SDARRMSNorm(self.head_dim, eps=config.rms_norm_eps)
237
+ self.sliding_window = config.sliding_window
238
+ if not (
239
+ self.config.use_sliding_window
240
+ and getattr(self.config, "sliding_window", None) is not None
241
+ and self.layer_idx >= self.config.max_window_layers
242
+ ):
243
+ self.sliding_window = None
244
+
245
+ def forward(
246
+ self,
247
+ hidden_states: torch.Tensor,
248
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
249
+ attention_mask: Optional[torch.Tensor],
250
+ past_key_value: Optional[Cache] = None,
251
+ cache_position: Optional[torch.LongTensor] = None,
252
+ **kwargs: Unpack[FlashAttentionKwargs],
253
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
254
+ input_shape = hidden_states.shape[:-1]
255
+ bsz, q_len = input_shape
256
+ hidden_shape = (*input_shape, -1, self.head_dim)
257
+
258
+ query_states = self.q_norm(self.q_proj(
259
+ hidden_states).view(hidden_shape)).transpose(1, 2)
260
+ key_states = self.k_norm(self.k_proj(
261
+ hidden_states).view(hidden_shape)).transpose(1, 2)
262
+ value_states = self.v_proj(hidden_states).view(
263
+ hidden_shape).transpose(1, 2)
264
+
265
+ cos, sin = position_embeddings
266
+ query_states, key_states = apply_rotary_pos_emb(
267
+ query_states, key_states, cos, sin)
268
+
269
+ if past_key_value is not None and kwargs.get("store_kv", False):
270
+ key_states, value_states = past_key_value.update(
271
+ key_states, value_states, self.layer_idx)
272
+ elif past_key_value is not None and not kwargs.get("store_kv", False) and len(past_key_value) > self.layer_idx:
273
+ past_key_states, past_value_states = past_key_value[self.layer_idx]
274
+ key_states = torch.cat(
275
+ [past_key_states, key_states], dim=-2)
276
+ value_states = torch.cat(
277
+ [past_value_states, value_states], dim=-2)
278
+
279
+ if self.training:
280
+ attn_output, attn_weights = fused_flex_attention(
281
+ query=query_states,
282
+ key=key_states,
283
+ value=value_states,
284
+ attention_mask=attention_mask,
285
+ enable_gqa=True,
286
+ scale=self.scaling,
287
+ return_lse=True
288
+ )
289
+ attn_weights = attn_weights.to(
290
+ value_states.dtype) if attn_weights is not None else None
291
+ attn_output = rearrange(attn_output, 'b h l d -> b l (h d)')
292
+ else:
293
+ attention_mask = attention_mask.bool() if attention_mask is not None else None
294
+ attn_weights = None
295
+ if torch.all(attention_mask): # decoding
296
+ query_states = query_states.transpose(1, 2)
297
+ key_states = key_states.transpose(1, 2)
298
+ value_states = value_states.transpose(1, 2)
299
+ attn_output = flash_attn_func(
300
+ query_states,
301
+ key_states,
302
+ value_states,
303
+ causal=False,
304
+ softmax_scale=self.scaling)
305
+ attn_output = rearrange(attn_output, 'b l h d -> b l (h d)')
306
+ else: # prefilling
307
+ # attn_output = F.scaled_dot_product_attention(
308
+ # query=query_states,
309
+ # key=key_states,
310
+ # value=value_states,
311
+ # attn_mask=attention_mask,
312
+ # is_causal=False,
313
+ # scale=self.scaling,
314
+ # enable_gqa=True)
315
+ # attn_output = rearrange(attn_output, 'b h l d -> b l (h d)')
316
+
317
+ query_chunk_size = 4096 # 可根据显存调整的超参数
318
+ q_len = query_states.size(2)
319
+ output_chunks = []
320
+ # 沿着序列长度 q_len 对 query 和 mask 进行分块
321
+ for i in range(0, q_len, query_chunk_size):
322
+ # 获取当前 query chunk
323
+ query_chunk = query_states[:, :, i:i + query_chunk_size, :]
324
+
325
+ # 获取对应的 attention mask chunk
326
+ # 注意,mask 的 slicing 维度要和 query 对应
327
+ attention_mask_chunk = attention_mask[:, i:i + query_chunk_size, :]
328
+ # 使用分块后的 query 和 mask 进行计算
329
+ # key 和 value 保持不变,始终是完整的
330
+ attn_output_chunk = F.scaled_dot_product_attention(
331
+ query=query_chunk,
332
+ key=key_states,
333
+ value=value_states,
334
+ attn_mask=attention_mask_chunk,
335
+ is_causal=False,
336
+ scale=self.scaling,
337
+ enable_gqa=True # 如果使用GQA,保持这个参数
338
+ )
339
+ output_chunks.append(attn_output_chunk)
340
+ # 将所有 chunk 的结果沿着序列长度维度拼接起来
341
+ attn_output = torch.cat(output_chunks, dim=2) # dim=2 是序列长度维度
342
+ attn_output = rearrange(attn_output, 'b h l d -> b l (h d)')
343
+
344
+ attn_output = self.o_proj(attn_output)
345
+
346
+ return attn_output, attn_weights
347
+
348
+
349
+ class SDARDecoderLayer(GradientCheckpointingLayer):
350
+ def __init__(self, config: SDARConfig, layer_idx: int):
351
+ super().__init__()
352
+ self.hidden_size = config.hidden_size
353
+ self.self_attn = SDARAttention(config=config, layer_idx=layer_idx)
354
+ self.mlp = SDARMLP(config)
355
+ self.input_layernorm = SDARRMSNorm(
356
+ config.hidden_size, eps=config.rms_norm_eps)
357
+ self.post_attention_layernorm = SDARRMSNorm(
358
+ config.hidden_size, eps=config.rms_norm_eps)
359
+ if (
360
+ config.sliding_window and config._attn_implementation != "flash_attention_2"
361
+ ): # diff with Llama is this warning
362
+ logger.warning_once(
363
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
364
+ "unexpected results may be encountered."
365
+ )
366
+
367
+ def forward(
368
+ self,
369
+ hidden_states: torch.Tensor,
370
+ attention_mask: Optional[torch.Tensor] = None,
371
+ position_ids: Optional[torch.LongTensor] = None,
372
+ past_key_value: Optional[Cache] = None,
373
+ output_attentions: Optional[bool] = False,
374
+ use_cache: Optional[bool] = False,
375
+ store_kv: Optional[bool] = False,
376
+ cache_position: Optional[torch.LongTensor] = None,
377
+ # necessary, but kept here for BC
378
+ position_embeddings: Optional[Tuple[torch.Tensor,
379
+ torch.Tensor]] = None,
380
+ **kwargs: Unpack[FlashAttentionKwargs],
381
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
382
+ residual = hidden_states
383
+ hidden_states = self.input_layernorm(hidden_states)
384
+
385
+ # Self Attention
386
+ hidden_states, self_attn_weights = self.self_attn(
387
+ hidden_states=hidden_states,
388
+ attention_mask=attention_mask,
389
+ position_ids=position_ids,
390
+ past_key_value=past_key_value,
391
+ output_attentions=output_attentions,
392
+ use_cache=use_cache,
393
+ store_kv=store_kv,
394
+ cache_position=cache_position,
395
+ position_embeddings=position_embeddings,
396
+ **kwargs,
397
+ )
398
+ hidden_states = residual + hidden_states
399
+
400
+ # Fully Connected
401
+ residual = hidden_states
402
+ hidden_states = self.post_attention_layernorm(hidden_states)
403
+ hidden_states = self.mlp(hidden_states)
404
+ hidden_states = residual + hidden_states
405
+
406
+ outputs = (hidden_states,)
407
+ if output_attentions:
408
+ outputs += (self_attn_weights,)
409
+
410
+ return outputs
411
+
412
+
413
+ @auto_docstring
414
+ class SDARPreTrainedModel(PreTrainedModel):
415
+ config_class = SDARConfig
416
+ base_model_prefix = "model"
417
+ supports_gradient_checkpointing = True
418
+ _no_split_modules = ["SDARDecoderLayer"]
419
+ _skip_keys_device_placement = ["past_key_values"]
420
+ _supports_flash_attn_2 = True
421
+ _supports_sdpa = True
422
+ _supports_flex_attn = True
423
+ _supports_cache_class = True
424
+ _supports_quantized_cache = True
425
+ _supports_static_cache = True
426
+ _supports_attention_backend = True
427
+
428
+ def _init_weights(self, module):
429
+ std = self.config.initializer_range
430
+ if isinstance(module, nn.Linear):
431
+ module.weight.data.normal_(mean=0.0, std=std)
432
+ if module.bias is not None:
433
+ module.bias.data.zero_()
434
+ elif isinstance(module, nn.Embedding):
435
+ module.weight.data.normal_(mean=0.0, std=std)
436
+ if module.padding_idx is not None:
437
+ module.weight.data[module.padding_idx].zero_()
438
+ elif isinstance(module, SDARRMSNorm):
439
+ module.weight.data.fill_(1.0)
440
+
441
+
442
+ class SDARRotaryEmbedding(nn.Module):
443
+ def __init__(self, config: SDARConfig, device=None):
444
+ super().__init__()
445
+ # BC: "rope_type" was originally "type"
446
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
447
+ self.rope_type = config.rope_scaling.get(
448
+ "rope_type", config.rope_scaling.get("type"))
449
+ else:
450
+ self.rope_type = "default"
451
+ self.max_seq_len_cached = config.max_position_embeddings
452
+ self.original_max_seq_len = config.max_position_embeddings
453
+
454
+ self.config = config
455
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
456
+
457
+ inv_freq, self.attention_scaling = self.rope_init_fn(
458
+ self.config, device)
459
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
460
+ self.original_inv_freq = self.inv_freq
461
+
462
+ @torch.no_grad()
463
+ # power user: used with advanced RoPE types (e.g. dynamic rope)
464
+ @dynamic_rope_update
465
+ def forward(self, x, position_ids):
466
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(
467
+ position_ids.shape[0], -1, 1).to(x.device)
468
+ position_ids_expanded = position_ids[:, None, :].float()
469
+
470
+ device_type = x.device.type if isinstance(
471
+ x.device.type, str) and x.device.type != "mps" else "cpu"
472
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
473
+ freqs = (inv_freq_expanded.float() @
474
+ position_ids_expanded.float()).transpose(1, 2)
475
+ emb = torch.cat((freqs, freqs), dim=-1)
476
+ cos = emb.cos() * self.attention_scaling
477
+ sin = emb.sin() * self.attention_scaling
478
+
479
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
480
+
481
+
482
+ @auto_docstring
483
+ class SDARModel(SDARPreTrainedModel):
484
+ def __init__(self, config: SDARConfig):
485
+ super().__init__(config)
486
+ self.padding_idx = config.pad_token_id
487
+ self.vocab_size = config.vocab_size
488
+
489
+ self.embed_tokens = nn.Embedding(
490
+ config.vocab_size, config.hidden_size, self.padding_idx)
491
+ self.layers = nn.ModuleList(
492
+ [SDARDecoderLayer(config, layer_idx)
493
+ for layer_idx in range(config.num_hidden_layers)]
494
+ )
495
+ self.norm = SDARRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
496
+ self.rotary_emb = SDARRotaryEmbedding(config=config)
497
+ self.gradient_checkpointing = False
498
+
499
+ # Initialize weights and apply final processing
500
+ self.post_init()
501
+
502
+ def get_input_embeddings(self):
503
+ return self.embed_tokens
504
+
505
+ def set_input_embeddings(self, value):
506
+ self.embed_tokens = value
507
+
508
+ @can_return_tuple
509
+ @auto_docstring
510
+ def forward(
511
+ self,
512
+ input_ids: Optional[torch.LongTensor] = None,
513
+ attention_mask: Optional[torch.Tensor] = None,
514
+ position_ids: Optional[torch.LongTensor] = None,
515
+ past_key_values: Optional[Cache] = None,
516
+ inputs_embeds: Optional[torch.FloatTensor] = None,
517
+ use_cache: Optional[bool] = None,
518
+ store_kv: Optional[bool] = None,
519
+ output_attentions: Optional[bool] = None,
520
+ output_hidden_states: Optional[bool] = None,
521
+ cache_position: Optional[torch.LongTensor] = None,
522
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
523
+ ) -> BaseModelOutputWithPast:
524
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
525
+ output_hidden_states = (
526
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
527
+ )
528
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
529
+
530
+ if (input_ids is None) ^ (inputs_embeds is not None):
531
+ raise ValueError(
532
+ "You must specify exactly one of input_ids or inputs_embeds")
533
+
534
+ if self.gradient_checkpointing and self.training and use_cache:
535
+ logger.warning_once(
536
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
537
+ )
538
+ use_cache = False
539
+
540
+ # TODO (joao): remove this exception in v4.56 -- it exists for users that try to pass a legacy cache
541
+ if not isinstance(past_key_values, (type(None), Cache)):
542
+ raise ValueError(
543
+ "The `past_key_values` should be either a `Cache` object or `None`.")
544
+
545
+ if inputs_embeds is None:
546
+ inputs_embeds = self.embed_tokens(input_ids)
547
+
548
+ if use_cache and past_key_values is None:
549
+ past_key_values = DynamicCache()
550
+
551
+ if cache_position is None:
552
+ past_seen_tokens = past_key_values.get_seq_length(
553
+ ) if past_key_values is not None else 0
554
+ cache_position = torch.arange(
555
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
556
+ )
557
+
558
+ if position_ids is None:
559
+ position_ids = cache_position.unsqueeze(0)
560
+
561
+ # causal_mask = self._update_causal_mask(
562
+ # attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
563
+ # )
564
+
565
+ hidden_states = inputs_embeds
566
+
567
+ # create position embeddings to be shared across the decoder layers
568
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
569
+
570
+ # decoder layers
571
+ all_hidden_states = () if output_hidden_states else None
572
+ all_self_attns = () if output_attentions else None
573
+
574
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
575
+ if output_hidden_states:
576
+ all_hidden_states += (hidden_states,)
577
+
578
+ layer_outputs = decoder_layer(
579
+ hidden_states,
580
+ attention_mask=attention_mask,
581
+ position_ids=position_ids,
582
+ past_key_value=past_key_values,
583
+ output_attentions=output_attentions,
584
+ use_cache=use_cache,
585
+ store_kv=store_kv,
586
+ cache_position=cache_position,
587
+ position_embeddings=position_embeddings,
588
+ **flash_attn_kwargs,
589
+ )
590
+
591
+ hidden_states = layer_outputs[0]
592
+
593
+ if output_attentions:
594
+ all_self_attns += (layer_outputs[1],)
595
+
596
+ hidden_states = self.norm(hidden_states)
597
+
598
+ # add hidden states from the last decoder layer
599
+ if output_hidden_states:
600
+ all_hidden_states += (hidden_states,)
601
+
602
+ return BaseModelOutputWithPast(
603
+ last_hidden_state=hidden_states,
604
+ past_key_values=past_key_values if use_cache else None,
605
+ hidden_states=all_hidden_states,
606
+ attentions=all_self_attns,
607
+ )
608
+
609
+ def _update_causal_mask(
610
+ self,
611
+ attention_mask: Union[torch.Tensor, "BlockMask"],
612
+ input_tensor: torch.Tensor,
613
+ cache_position: torch.Tensor,
614
+ past_key_values: Cache,
615
+ output_attentions: bool = False,
616
+ ):
617
+ if self.config._attn_implementation == "flash_attention_2":
618
+ if attention_mask is not None and past_key_values is not None:
619
+ is_padding_right = attention_mask[:, -
620
+ 1].sum().item() != input_tensor.size()[0]
621
+ if is_padding_right:
622
+ raise ValueError(
623
+ "You are attempting to perform batched generation with padding_side='right'"
624
+ " this may lead to unexpected behaviour for Flash Attention version of Qwen3. Make sure to "
625
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
626
+ )
627
+ if attention_mask is not None and 0.0 in attention_mask:
628
+ return attention_mask
629
+ return None
630
+ if self.config._attn_implementation == "flex_attention":
631
+ if isinstance(attention_mask, torch.Tensor):
632
+ seq_len_q, seq_len_kv = attention_mask.shape
633
+ assert seq_len_q == seq_len_kv, f"got {attention_mask.shape=}"
634
+ attention_mask = create_block_mask(
635
+ # 2d bool tensor, shape: [2*seqlen, 2*seqlen]
636
+ lambda b, h, q_idx, kv_idx: attention_mask[q_idx, kv_idx],
637
+ B=None, H=None, Q_LEN=seq_len_q, KV_LEN=seq_len_kv,
638
+ )
639
+ else:
640
+ # Here we pass in flex mask computed externally
641
+ assert isinstance(attention_mask, BlockMask)
642
+ return attention_mask
643
+
644
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
645
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
646
+ # to infer the attention mask.
647
+ past_seen_tokens = past_key_values.get_seq_length(
648
+ ) if past_key_values is not None else 0
649
+ using_static_cache = isinstance(past_key_values, StaticCache)
650
+ using_sliding_window_cache = isinstance(
651
+ past_key_values, SlidingWindowCache)
652
+
653
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
654
+ if (
655
+ self.config._attn_implementation == "sdpa"
656
+ and not (using_static_cache or using_sliding_window_cache)
657
+ and not output_attentions
658
+ ):
659
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
660
+ attention_mask,
661
+ inputs_embeds=input_tensor,
662
+ past_key_values_length=past_seen_tokens,
663
+ sliding_window=self.config.sliding_window,
664
+ is_training=self.training,
665
+ ):
666
+ return None
667
+
668
+ dtype = input_tensor.dtype
669
+ min_dtype = torch.finfo(dtype).min
670
+ sequence_length = input_tensor.shape[1]
671
+ # SlidingWindowCache or StaticCache
672
+ if using_sliding_window_cache or using_static_cache:
673
+ target_length = past_key_values.get_max_cache_shape()
674
+ # DynamicCache or no cache
675
+ else:
676
+ target_length = (
677
+ attention_mask.shape[-1]
678
+ if isinstance(attention_mask, torch.Tensor)
679
+ else past_seen_tokens + sequence_length + 1
680
+ )
681
+
682
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
683
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
684
+ attention_mask,
685
+ sequence_length=sequence_length,
686
+ target_length=target_length,
687
+ dtype=dtype,
688
+ cache_position=cache_position,
689
+ batch_size=input_tensor.shape[0],
690
+ config=self.config,
691
+ past_key_values=past_key_values,
692
+ )
693
+
694
+ if (
695
+ self.config._attn_implementation == "sdpa"
696
+ and attention_mask is not None
697
+ and attention_mask.device.type in ["cuda", "xpu", "npu"]
698
+ and not output_attentions
699
+ ):
700
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
701
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
702
+ # Details: https://github.com/pytorch/pytorch/issues/110213
703
+ causal_mask = AttentionMaskConverter._unmask_unattended(
704
+ causal_mask, min_dtype)
705
+
706
+ return causal_mask
707
+
708
+ @staticmethod
709
+ def _prepare_4d_causal_attention_mask_with_cache_position(
710
+ attention_mask: torch.Tensor,
711
+ sequence_length: int,
712
+ target_length: int,
713
+ dtype: torch.dtype,
714
+ cache_position: torch.Tensor,
715
+ batch_size: int,
716
+ config: SDARConfig,
717
+ past_key_values: Cache,
718
+ ):
719
+ """
720
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
721
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
722
+
723
+ Args:
724
+ attention_mask (`torch.Tensor`):
725
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
726
+ sequence_length (`int`):
727
+ The sequence length being processed.
728
+ target_length (`int`):
729
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
730
+ dtype (`torch.dtype`):
731
+ The dtype to use for the 4D attention mask.
732
+ cache_position (`torch.Tensor`):
733
+ Indices depicting the position of the input sequence tokens in the sequence.
734
+ batch_size (`torch.Tensor`):
735
+ Batch size.
736
+ config (`SDARConfig`):
737
+ The model's configuration class
738
+ past_key_values (`Cache`):
739
+ The cache class that is being used currently to generate
740
+ """
741
+ if attention_mask is not None and attention_mask.dim() == 4:
742
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
743
+ causal_mask = attention_mask
744
+ else:
745
+ min_dtype = torch.finfo(dtype).min
746
+ causal_mask = torch.full(
747
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
748
+ )
749
+ diagonal_attend_mask = torch.arange(target_length, device=cache_position.device) > cache_position.reshape(
750
+ -1, 1
751
+ )
752
+ text_config = config.get_text_config()
753
+ if getattr(text_config, "use_sliding_window", True) and text_config.sliding_window is not None:
754
+ # if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also
755
+ # the check is needed to verify is current checkpoint was trained with sliding window or not
756
+ if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length:
757
+ sliding_attend_mask = torch.arange(target_length, device=cache_position.device) <= (
758
+ cache_position.reshape(-1, 1) -
759
+ text_config.sliding_window
760
+ )
761
+ diagonal_attend_mask.bitwise_or_(sliding_attend_mask)
762
+ causal_mask *= diagonal_attend_mask
763
+ causal_mask = causal_mask[None, None,
764
+ :, :].expand(batch_size, 1, -1, -1)
765
+ if attention_mask is not None:
766
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
767
+ if attention_mask.shape[-1] > target_length:
768
+ attention_mask = attention_mask[:, :target_length]
769
+ mask_length = attention_mask.shape[-1]
770
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
771
+ causal_mask.device
772
+ )
773
+ padding_mask = padding_mask == 0
774
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
775
+ padding_mask, min_dtype
776
+ )
777
+ return causal_mask
778
+
779
+
780
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs):
781
+ ...
782
+
783
+
784
+ @auto_docstring
785
+ class SDARForCausalLM(SDARPreTrainedModel, GenerationMixin):
786
+ _tied_weights_keys = ["lm_head.weight"]
787
+ _tp_plan = {"lm_head": "colwise_rep"}
788
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
789
+
790
+ def __init__(self, config):
791
+ super().__init__(config)
792
+ self.model = SDARModel(config)
793
+ self.vocab_size = config.vocab_size
794
+ self.lm_head = nn.Linear(
795
+ config.hidden_size, config.vocab_size, bias=False)
796
+
797
+ # Initialize weights and apply final processing
798
+ self.post_init()
799
+
800
+ def get_input_embeddings(self):
801
+ return self.model.embed_tokens
802
+
803
+ def set_input_embeddings(self, value):
804
+ self.model.embed_tokens = value
805
+
806
+ def get_output_embeddings(self):
807
+ return self.lm_head
808
+
809
+ def set_output_embeddings(self, new_embeddings):
810
+ self.lm_head = new_embeddings
811
+
812
+ def set_decoder(self, decoder):
813
+ self.model = decoder
814
+
815
+ def get_decoder(self):
816
+ return self.model
817
+
818
+ @can_return_tuple
819
+ @auto_docstring
820
+ def forward(
821
+ self,
822
+ input_ids: Optional[torch.LongTensor] = None,
823
+ attention_mask: Optional[torch.Tensor] = None,
824
+ position_ids: Optional[torch.LongTensor] = None,
825
+ past_key_values: Optional[Cache] = None,
826
+ inputs_embeds: Optional[torch.FloatTensor] = None,
827
+ labels: Optional[torch.LongTensor] = None,
828
+ use_cache: Optional[bool] = None,
829
+ output_attentions: Optional[bool] = None,
830
+ output_hidden_states: Optional[bool] = None,
831
+ cache_position: Optional[torch.LongTensor] = None,
832
+ logits_to_keep: Union[int, torch.Tensor] = 0,
833
+ **kwargs: Unpack[KwargsForCausalLM],
834
+ ) -> CausalLMOutputWithPast:
835
+ r"""
836
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
837
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
838
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
839
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
840
+
841
+ Example:
842
+
843
+ ```python
844
+ >>> from transformers import AutoTokenizer, SDARForCausalLM
845
+
846
+ >>> model = SDARForCausalLM.from_pretrained("DiffuOpen/SDAR-1.7B-Chat")
847
+ >>> tokenizer = AutoTokenizer.from_pretrained("DiffuOpen/SDAR-1.7B-Chat")
848
+
849
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
850
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
851
+
852
+ >>> # Generate
853
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
854
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
855
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
856
+ ```"""
857
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
858
+ output_hidden_states = (
859
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
860
+ )
861
+
862
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
863
+ outputs: BaseModelOutputWithPast = self.model(
864
+ input_ids=input_ids,
865
+ attention_mask=attention_mask,
866
+ position_ids=position_ids,
867
+ past_key_values=past_key_values,
868
+ inputs_embeds=inputs_embeds,
869
+ use_cache=use_cache,
870
+ output_attentions=output_attentions,
871
+ output_hidden_states=output_hidden_states,
872
+ cache_position=cache_position,
873
+ **kwargs,
874
+ )
875
+
876
+ hidden_states = outputs.last_hidden_state
877
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
878
+ slice_indices = slice(-logits_to_keep,
879
+ None) if isinstance(logits_to_keep, int) else logits_to_keep
880
+ hidden_states = hidden_states[:, slice_indices, :].contiguous()
881
+ fuse_linear_and_cross_entropy = self.config.fuse_cross_entropy and self.training
882
+ if fuse_linear_and_cross_entropy:
883
+ # When using fused_linear_ce_loss, we do not compute the whole logits on HBM
884
+ logits = None
885
+ else:
886
+ logits = self.lm_head(hidden_states)
887
+
888
+ loss = None
889
+ if labels is not None:
890
+ # FusedLinearCrossEntropyLoss will be implemented by monkey patch when training
891
+ # We don't use it when inferencing
892
+ loss_fct = nn.CrossEntropyLoss() # nn.CE
893
+ loss = loss_fct(
894
+ logits.view(-1, self.config.vocab_size), labels.view(-1))
895
+
896
+ return CausalLMOutputWithPast(
897
+ loss=loss,
898
+ logits=logits,
899
+ past_key_values=outputs.past_key_values,
900
+ hidden_states=outputs.hidden_states,
901
+ attentions=outputs.attentions,
902
+ )
903
+
904
+
905
+ __all__ = [
906
+ "SDARForCausalLM",
907
+ "SDARModel",
908
+ "SDARPreTrainedModel",
909
+ ]
preprocessor_config.json ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "crop_size": null,
3
+ "data_format": "channels_first",
4
+ "default_to_square": false,
5
+ "device": null,
6
+ "do_center_crop": null,
7
+ "do_convert_rgb": true,
8
+ "do_normalize": true,
9
+ "do_pad": true,
10
+ "do_rescale": true,
11
+ "do_resize": true,
12
+ "image_grid_pinpoints": [
13
+ [
14
+ 384,
15
+ 384
16
+ ],
17
+ [
18
+ 384,
19
+ 768
20
+ ],
21
+ [
22
+ 384,
23
+ 1152
24
+ ],
25
+ [
26
+ 384,
27
+ 1536
28
+ ],
29
+ [
30
+ 384,
31
+ 1920
32
+ ],
33
+ [
34
+ 384,
35
+ 2304
36
+ ],
37
+ [
38
+ 768,
39
+ 384
40
+ ],
41
+ [
42
+ 768,
43
+ 768
44
+ ],
45
+ [
46
+ 768,
47
+ 1152
48
+ ],
49
+ [
50
+ 768,
51
+ 1536
52
+ ],
53
+ [
54
+ 768,
55
+ 1920
56
+ ],
57
+ [
58
+ 768,
59
+ 2304
60
+ ],
61
+ [
62
+ 1152,
63
+ 384
64
+ ],
65
+ [
66
+ 1152,
67
+ 768
68
+ ],
69
+ [
70
+ 1152,
71
+ 1152
72
+ ],
73
+ [
74
+ 1152,
75
+ 1536
76
+ ],
77
+ [
78
+ 1152,
79
+ 1920
80
+ ],
81
+ [
82
+ 1152,
83
+ 2304
84
+ ],
85
+ [
86
+ 1536,
87
+ 384
88
+ ],
89
+ [
90
+ 1536,
91
+ 768
92
+ ],
93
+ [
94
+ 1536,
95
+ 1152
96
+ ],
97
+ [
98
+ 1536,
99
+ 1536
100
+ ],
101
+ [
102
+ 1536,
103
+ 1920
104
+ ],
105
+ [
106
+ 1536,
107
+ 2304
108
+ ],
109
+ [
110
+ 1920,
111
+ 384
112
+ ],
113
+ [
114
+ 1920,
115
+ 768
116
+ ],
117
+ [
118
+ 1920,
119
+ 1152
120
+ ],
121
+ [
122
+ 1920,
123
+ 1536
124
+ ],
125
+ [
126
+ 1920,
127
+ 1920
128
+ ],
129
+ [
130
+ 1920,
131
+ 2304
132
+ ],
133
+ [
134
+ 2304,
135
+ 384
136
+ ],
137
+ [
138
+ 2304,
139
+ 768
140
+ ],
141
+ [
142
+ 2304,
143
+ 1152
144
+ ],
145
+ [
146
+ 2304,
147
+ 1536
148
+ ],
149
+ [
150
+ 2304,
151
+ 1920
152
+ ],
153
+ [
154
+ 2304,
155
+ 2304
156
+ ]
157
+ ],
158
+ "image_mean": [
159
+ 0.5,
160
+ 0.5,
161
+ 0.5
162
+ ],
163
+ "image_processor_type": "LlavaOnevisionImageProcessorFast",
164
+ "image_std": [
165
+ 0.5,
166
+ 0.5,
167
+ 0.5
168
+ ],
169
+ "input_data_format": null,
170
+ "processor_class": "LlavaOnevisionProcessor",
171
+ "resample": 3,
172
+ "rescale_factor": 0.00392156862745098,
173
+ "return_tensors": null,
174
+ "size": {
175
+ "height": 384,
176
+ "width": 384
177
+ }
178
+ }
processor_config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "image_token": "<|image_pad|>",
3
+ "num_image_tokens": 729,
4
+ "processor_class": "LlavaOnevisionProcessor",
5
+ "video_token": "<|video_pad|>",
6
+ "vision_aspect_ratio": "anyres_max_9",
7
+ "vision_feature_select_strategy": "full"
8
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "<|MASK|>"
17
+ ],
18
+ "eos_token": {
19
+ "content": "<|im_end|>",
20
+ "lstrip": false,
21
+ "normalized": false,
22
+ "rstrip": false,
23
+ "single_word": false
24
+ },
25
+ "mask_token": {
26
+ "content": "<|MASK|>",
27
+ "lstrip": false,
28
+ "normalized": false,
29
+ "rstrip": false,
30
+ "single_word": false
31
+ },
32
+ "pad_token": {
33
+ "content": "<|endoftext|>",
34
+ "lstrip": false,
35
+ "normalized": false,
36
+ "rstrip": false,
37
+ "single_word": false
38
+ }
39
+ }
tokenization_qwen2.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and 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
+ """Tokenization classes for Qwen2."""
16
+
17
+ import json
18
+ import os
19
+ import unicodedata
20
+ from functools import lru_cache
21
+ from typing import Optional, Tuple
22
+
23
+ import regex as re
24
+
25
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
26
+ from transformers.utils import logging
27
+
28
+
29
+ logger = logging.get_logger(__name__)
30
+
31
+ VOCAB_FILES_NAMES = {
32
+ "vocab_file": "vocab.json",
33
+ "merges_file": "merges.txt",
34
+ }
35
+
36
+
37
+ MAX_MODEL_INPUT_SIZES = {"qwen/qwen-tokenizer": 32768}
38
+
39
+ PRETOKENIZE_REGEX = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
40
+
41
+
42
+ @lru_cache()
43
+ # Copied from transformers.models.gpt2.tokenization_gpt2.bytes_to_unicode
44
+ def bytes_to_unicode():
45
+ """
46
+ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
47
+ characters the bpe code barfs on.
48
+
49
+ The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
50
+ if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
51
+ decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
52
+ tables between utf-8 bytes and unicode strings.
53
+ """
54
+ bs = (
55
+ list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
56
+ )
57
+ cs = bs[:]
58
+ n = 0
59
+ for b in range(2**8):
60
+ if b not in bs:
61
+ bs.append(b)
62
+ cs.append(2**8 + n)
63
+ n += 1
64
+ cs = [chr(n) for n in cs]
65
+ return dict(zip(bs, cs))
66
+
67
+
68
+ # Copied from transformers.models.gpt2.tokenization_gpt2.get_pairs
69
+ def get_pairs(word):
70
+ """
71
+ Return set of symbol pairs in a word.
72
+
73
+ Word is represented as tuple of symbols (symbols being variable-length strings).
74
+ """
75
+ pairs = set()
76
+ prev_char = word[0]
77
+ for char in word[1:]:
78
+ pairs.add((prev_char, char))
79
+ prev_char = char
80
+ return pairs
81
+
82
+
83
+ class Qwen2Tokenizer(PreTrainedTokenizer):
84
+ """
85
+ Construct a Qwen2 tokenizer. Based on byte-level Byte-Pair-Encoding.
86
+
87
+ Same with GPT2Tokenizer, this tokenizer has been trained to treat spaces like parts of the tokens so a word will
88
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
89
+
90
+ ```python
91
+ >>> from transformers import Qwen2Tokenizer
92
+
93
+ >>> tokenizer = Qwen2Tokenizer.from_pretrained("Qwen/Qwen-tokenizer")
94
+ >>> tokenizer("Hello world")["input_ids"]
95
+ [9707, 1879]
96
+
97
+ >>> tokenizer(" Hello world")["input_ids"]
98
+ [21927, 1879]
99
+ ```
100
+ This is expected.
101
+
102
+ You should not use GPT2Tokenizer instead, because of the different pretokenization rules.
103
+
104
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
105
+ this superclass for more information regarding those methods.
106
+
107
+ Args:
108
+ vocab_file (`str`):
109
+ Path to the vocabulary file.
110
+ merges_file (`str`):
111
+ Path to the merges file.
112
+ errors (`str`, *optional*, defaults to `"replace"`):
113
+ Paradigm to follow when decoding bytes to UTF-8. See
114
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
115
+ unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
116
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
117
+ token instead.
118
+ bos_token (`str`, *optional*):
119
+ The beginning of sequence token. Not applicable for this tokenizer.
120
+ eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
121
+ The end of sequence token.
122
+ pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
123
+ The token used for padding, for example when batching sequences of different lengths.
124
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
125
+ Whether or not the model should cleanup the spaces that were added when splitting the input text during the
126
+ tokenization process. Not applicable to this tokenizer, since tokenization does not add spaces.
127
+ split_special_tokens (`bool`, *optional*, defaults to `False`):
128
+ Whether or not the special tokens should be split during the tokenization process. The default behavior is
129
+ to not split special tokens. This means that if `<|endoftext|>` is the `eos_token`, then `tokenizer.tokenize("<|endoftext|>") =
130
+ ['<|endoftext|>`]. Otherwise, if `split_special_tokens=True`, then `tokenizer.tokenize("<|endoftext|>")` will be give `['<',
131
+ '|', 'endo', 'ft', 'ext', '|', '>']`. This argument is only supported for `slow` tokenizers for the moment.
132
+ """
133
+
134
+ vocab_files_names = VOCAB_FILES_NAMES
135
+ model_input_names = ["input_ids", "attention_mask"]
136
+
137
+ def __init__(
138
+ self,
139
+ vocab_file,
140
+ merges_file,
141
+ errors="replace",
142
+ unk_token="<|endoftext|>",
143
+ bos_token=None,
144
+ eos_token="<|endoftext|>",
145
+ pad_token="<|endoftext|>",
146
+ clean_up_tokenization_spaces=False,
147
+ split_special_tokens=False,
148
+ **kwargs,
149
+ ):
150
+ # Qwen vocab does not contain control tokens; added tokens need to be special
151
+ bos_token = (
152
+ AddedToken(bos_token, lstrip=False, rstrip=False, special=True, normalized=False)
153
+ if isinstance(bos_token, str)
154
+ else bos_token
155
+ )
156
+ eos_token = (
157
+ AddedToken(eos_token, lstrip=False, rstrip=False, special=True, normalized=False)
158
+ if isinstance(eos_token, str)
159
+ else eos_token
160
+ )
161
+ unk_token = (
162
+ AddedToken(unk_token, lstrip=False, rstrip=False, special=True, normalized=False)
163
+ if isinstance(unk_token, str)
164
+ else unk_token
165
+ )
166
+ pad_token = (
167
+ AddedToken(pad_token, lstrip=False, rstrip=False, special=True, normalized=False)
168
+ if isinstance(pad_token, str)
169
+ else pad_token
170
+ )
171
+
172
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
173
+ self.encoder = json.load(vocab_handle)
174
+ self.decoder = {v: k for k, v in self.encoder.items()}
175
+ self.errors = errors # how to handle errors in decoding
176
+ self.byte_encoder = bytes_to_unicode()
177
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
178
+ bpe_merges = []
179
+ with open(merges_file, encoding="utf-8") as merges_handle:
180
+ for i, line in enumerate(merges_handle):
181
+ line = line.strip()
182
+ if (i == 0 and line.startswith("#version:")) or not line:
183
+ continue
184
+ bpe_merges.append(tuple(line.split()))
185
+ self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
186
+ # NOTE: the cache can grow without bound and will get really large for long running processes
187
+ # (esp. for texts of language that do not use space between word, e.g. Chinese); technically
188
+ # not a memory leak but appears as one.
189
+ # GPT2Tokenizer has the same problem, so let's be consistent.
190
+ self.cache = {}
191
+
192
+ self.pat = re.compile(PRETOKENIZE_REGEX)
193
+
194
+ if kwargs.get("add_prefix_space", False):
195
+ logger.warning_once(
196
+ f"{self.__class__.__name} does not support `add_prefix_space`, setting it to True has no effect."
197
+ )
198
+
199
+ super().__init__(
200
+ errors=errors,
201
+ bos_token=bos_token,
202
+ eos_token=eos_token,
203
+ pad_token=pad_token,
204
+ unk_token=unk_token,
205
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
206
+ split_special_tokens=split_special_tokens,
207
+ **kwargs,
208
+ )
209
+
210
+ @property
211
+ def vocab_size(self) -> int:
212
+ return len(self.encoder)
213
+
214
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.get_vocab
215
+ def get_vocab(self):
216
+ return dict(self.encoder, **self.added_tokens_encoder)
217
+
218
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.bpe
219
+ def bpe(self, token):
220
+ if token in self.cache:
221
+ return self.cache[token]
222
+ word = tuple(token)
223
+ pairs = get_pairs(word)
224
+
225
+ if not pairs:
226
+ return token
227
+
228
+ while True:
229
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
230
+ if bigram not in self.bpe_ranks:
231
+ break
232
+ first, second = bigram
233
+ new_word = []
234
+ i = 0
235
+ while i < len(word):
236
+ try:
237
+ j = word.index(first, i)
238
+ except ValueError:
239
+ new_word.extend(word[i:])
240
+ break
241
+ else:
242
+ new_word.extend(word[i:j])
243
+ i = j
244
+
245
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
246
+ new_word.append(first + second)
247
+ i += 2
248
+ else:
249
+ new_word.append(word[i])
250
+ i += 1
251
+ new_word = tuple(new_word)
252
+ word = new_word
253
+ if len(word) == 1:
254
+ break
255
+ else:
256
+ pairs = get_pairs(word)
257
+ word = " ".join(word)
258
+ self.cache[token] = word
259
+ return word
260
+
261
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._tokenize
262
+ def _tokenize(self, text):
263
+ """Tokenize a string."""
264
+ bpe_tokens = []
265
+ for token in re.findall(self.pat, text):
266
+ token = "".join(
267
+ self.byte_encoder[b] for b in token.encode("utf-8")
268
+ ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
269
+ bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
270
+ return bpe_tokens
271
+
272
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_token_to_id
273
+ def _convert_token_to_id(self, token):
274
+ """Converts a token (str) in an id using the vocab."""
275
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
276
+
277
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_id_to_token
278
+ def _convert_id_to_token(self, index):
279
+ """Converts an index (integer) in a token (str) using the vocab."""
280
+ return self.decoder.get(index)
281
+
282
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.convert_tokens_to_string
283
+ def convert_tokens_to_string(self, tokens):
284
+ """Converts a sequence of tokens (string) in a single string."""
285
+ text = "".join(tokens)
286
+ text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
287
+ return text
288
+
289
+ def decode(
290
+ self,
291
+ token_ids,
292
+ skip_special_tokens: bool = False,
293
+ clean_up_tokenization_spaces: Optional[bool] = False,
294
+ spaces_between_special_tokens: bool = False,
295
+ **kwargs,
296
+ ) -> str:
297
+ # `spaces_between_special_tokens` defaults to True for _decode in slow tokenizers
298
+ # and cannot be configured elsewhere, but it should default to False for Qwen2Tokenizer
299
+ return super().decode(
300
+ token_ids,
301
+ skip_special_tokens=skip_special_tokens,
302
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
303
+ spaces_between_special_tokens=spaces_between_special_tokens,
304
+ **kwargs,
305
+ )
306
+
307
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.save_vocabulary
308
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
309
+ if not os.path.isdir(save_directory):
310
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
311
+ return
312
+ vocab_file = os.path.join(
313
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
314
+ )
315
+ merge_file = os.path.join(
316
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
317
+ )
318
+
319
+ with open(vocab_file, "w", encoding="utf-8") as f:
320
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
321
+
322
+ index = 0
323
+ with open(merge_file, "w", encoding="utf-8") as writer:
324
+ writer.write("#version: 0.2\n")
325
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
326
+ if index != token_index:
327
+ logger.warning(
328
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
329
+ " Please check that the tokenizer is not corrupted!"
330
+ )
331
+ index = token_index
332
+ writer.write(" ".join(bpe_tokens) + "\n")
333
+ index += 1
334
+
335
+ return vocab_file, merge_file
336
+
337
+ def prepare_for_tokenization(self, text, **kwargs):
338
+ text = unicodedata.normalize("NFC", text)
339
+ return (text, kwargs)
340
+
341
+
342
+ __all__ = ["Qwen2Tokenizer"]
tokenizer_config.json ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": "<tool_response>",
183
+ "lstrip": false,
184
+ "normalized": false,
185
+ "rstrip": false,
186
+ "single_word": false,
187
+ "special": false
188
+ },
189
+ "151666": {
190
+ "content": "</tool_response>",
191
+ "lstrip": false,
192
+ "normalized": false,
193
+ "rstrip": false,
194
+ "single_word": false,
195
+ "special": false
196
+ },
197
+ "151667": {
198
+ "content": "<think>",
199
+ "lstrip": false,
200
+ "normalized": false,
201
+ "rstrip": false,
202
+ "single_word": false,
203
+ "special": false
204
+ },
205
+ "151668": {
206
+ "content": "</think>",
207
+ "lstrip": false,
208
+ "normalized": false,
209
+ "rstrip": false,
210
+ "single_word": false,
211
+ "special": false
212
+ },
213
+ "151669": {
214
+ "content": "<|MASK|>",
215
+ "lstrip": false,
216
+ "normalized": false,
217
+ "rstrip": false,
218
+ "single_word": false,
219
+ "special": true
220
+ }
221
+ },
222
+ "additional_special_tokens": [
223
+ "<|im_start|>",
224
+ "<|im_end|>",
225
+ "<|object_ref_start|>",
226
+ "<|object_ref_end|>",
227
+ "<|box_start|>",
228
+ "<|box_end|>",
229
+ "<|quad_start|>",
230
+ "<|quad_end|>",
231
+ "<|vision_start|>",
232
+ "<|vision_end|>",
233
+ "<|vision_pad|>",
234
+ "<|image_pad|>",
235
+ "<|video_pad|>",
236
+ "<|MASK|>"
237
+ ],
238
+ "auto_map": {
239
+ "AutoTokenizer": [
240
+ "tokenization_qwen2.Qwen2Tokenizer",
241
+ null
242
+ ]
243
+ },
244
+ "bos_token": null,
245
+ "clean_up_tokenization_spaces": false,
246
+ "eos_token": "<|im_end|>",
247
+ "errors": "replace",
248
+ "extra_special_tokens": {},
249
+ "mask_token": "<|MASK|>",
250
+ "model_max_length": 131072,
251
+ "pad_token": "<|endoftext|>",
252
+ "padding_side": "right",
253
+ "processor_class": "LlavaOnevisionProcessor",
254
+ "split_special_tokens": false,
255
+ "tokenizer_class": "Qwen2Tokenizer",
256
+ "unk_token": null
257
+ }
train_results.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "epoch": 1.0,
3
+ "total_flos": 2.964601169621549e+20,
4
+ "train_loss": 0.849951366135661,
5
+ "train_runtime": 90359.1865,
6
+ "train_samples_per_second": 7.51,
7
+ "train_steps_per_second": 0.117
8
+ }
video_preprocessor_config.json ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_valid_kwargs_names": [
3
+ "do_convert_rgb",
4
+ "do_resize",
5
+ "size",
6
+ "size_divisor",
7
+ "default_to_square",
8
+ "resample",
9
+ "do_rescale",
10
+ "rescale_factor",
11
+ "do_normalize",
12
+ "image_mean",
13
+ "image_std",
14
+ "do_pad",
15
+ "do_center_crop",
16
+ "crop_size",
17
+ "data_format",
18
+ "input_data_format",
19
+ "device"
20
+ ],
21
+ "crop_size": null,
22
+ "data_format": "channels_first",
23
+ "default_to_square": false,
24
+ "device": null,
25
+ "do_center_crop": null,
26
+ "do_convert_rgb": true,
27
+ "do_normalize": true,
28
+ "do_pad": true,
29
+ "do_rescale": true,
30
+ "do_resize": true,
31
+ "do_sample_frames": false,
32
+ "fps": null,
33
+ "image_mean": [
34
+ 0.5,
35
+ 0.5,
36
+ 0.5
37
+ ],
38
+ "image_std": [
39
+ 0.5,
40
+ 0.5,
41
+ 0.5
42
+ ],
43
+ "input_data_format": null,
44
+ "model_valid_processing_keys": [
45
+ "do_convert_rgb",
46
+ "do_resize",
47
+ "size",
48
+ "size_divisor",
49
+ "default_to_square",
50
+ "resample",
51
+ "do_rescale",
52
+ "rescale_factor",
53
+ "do_normalize",
54
+ "image_mean",
55
+ "image_std",
56
+ "do_pad",
57
+ "do_center_crop",
58
+ "crop_size",
59
+ "data_format",
60
+ "input_data_format",
61
+ "device"
62
+ ],
63
+ "num_frames": null,
64
+ "processor_class": "LlavaOnevisionProcessor",
65
+ "resample": 3,
66
+ "rescale_factor": 0.00392156862745098,
67
+ "size": {
68
+ "height": 384,
69
+ "width": 384
70
+ },
71
+ "size_divisor": null,
72
+ "video_metadata": null,
73
+ "video_processor_type": "LlavaOnevisionVideoProcessor"
74
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff