Upload Qwen2MMForCausalLM
Browse files- README.md +199 -0
- config.json +112 -0
- configuration_qwen2mm.py +201 -0
- generation_config.json +9 -0
- model.safetensors +3 -0
- modeling_phi4mm.py +1877 -0
- processing_phi4mm.py +744 -0
- speech_conformer_encoder.py +0 -0
README.md
ADDED
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
library_name: transformers
|
3 |
+
tags: []
|
4 |
+
---
|
5 |
+
|
6 |
+
# Model Card for Model ID
|
7 |
+
|
8 |
+
<!-- Provide a quick summary of what the model is/does. -->
|
9 |
+
|
10 |
+
|
11 |
+
|
12 |
+
## Model Details
|
13 |
+
|
14 |
+
### Model Description
|
15 |
+
|
16 |
+
<!-- Provide a longer summary of what this model is. -->
|
17 |
+
|
18 |
+
This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
|
19 |
+
|
20 |
+
- **Developed by:** [More Information Needed]
|
21 |
+
- **Funded by [optional]:** [More Information Needed]
|
22 |
+
- **Shared by [optional]:** [More Information Needed]
|
23 |
+
- **Model type:** [More Information Needed]
|
24 |
+
- **Language(s) (NLP):** [More Information Needed]
|
25 |
+
- **License:** [More Information Needed]
|
26 |
+
- **Finetuned from model [optional]:** [More Information Needed]
|
27 |
+
|
28 |
+
### Model Sources [optional]
|
29 |
+
|
30 |
+
<!-- Provide the basic links for the model. -->
|
31 |
+
|
32 |
+
- **Repository:** [More Information Needed]
|
33 |
+
- **Paper [optional]:** [More Information Needed]
|
34 |
+
- **Demo [optional]:** [More Information Needed]
|
35 |
+
|
36 |
+
## Uses
|
37 |
+
|
38 |
+
<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
|
39 |
+
|
40 |
+
### Direct Use
|
41 |
+
|
42 |
+
<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
|
43 |
+
|
44 |
+
[More Information Needed]
|
45 |
+
|
46 |
+
### Downstream Use [optional]
|
47 |
+
|
48 |
+
<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
|
49 |
+
|
50 |
+
[More Information Needed]
|
51 |
+
|
52 |
+
### Out-of-Scope Use
|
53 |
+
|
54 |
+
<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
|
55 |
+
|
56 |
+
[More Information Needed]
|
57 |
+
|
58 |
+
## Bias, Risks, and Limitations
|
59 |
+
|
60 |
+
<!-- This section is meant to convey both technical and sociotechnical limitations. -->
|
61 |
+
|
62 |
+
[More Information Needed]
|
63 |
+
|
64 |
+
### Recommendations
|
65 |
+
|
66 |
+
<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
|
67 |
+
|
68 |
+
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
|
69 |
+
|
70 |
+
## How to Get Started with the Model
|
71 |
+
|
72 |
+
Use the code below to get started with the model.
|
73 |
+
|
74 |
+
[More Information Needed]
|
75 |
+
|
76 |
+
## Training Details
|
77 |
+
|
78 |
+
### Training Data
|
79 |
+
|
80 |
+
<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
|
81 |
+
|
82 |
+
[More Information Needed]
|
83 |
+
|
84 |
+
### Training Procedure
|
85 |
+
|
86 |
+
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
|
87 |
+
|
88 |
+
#### Preprocessing [optional]
|
89 |
+
|
90 |
+
[More Information Needed]
|
91 |
+
|
92 |
+
|
93 |
+
#### Training Hyperparameters
|
94 |
+
|
95 |
+
- **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
|
96 |
+
|
97 |
+
#### Speeds, Sizes, Times [optional]
|
98 |
+
|
99 |
+
<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
|
100 |
+
|
101 |
+
[More Information Needed]
|
102 |
+
|
103 |
+
## Evaluation
|
104 |
+
|
105 |
+
<!-- This section describes the evaluation protocols and provides the results. -->
|
106 |
+
|
107 |
+
### Testing Data, Factors & Metrics
|
108 |
+
|
109 |
+
#### Testing Data
|
110 |
+
|
111 |
+
<!-- This should link to a Dataset Card if possible. -->
|
112 |
+
|
113 |
+
[More Information Needed]
|
114 |
+
|
115 |
+
#### Factors
|
116 |
+
|
117 |
+
<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
|
118 |
+
|
119 |
+
[More Information Needed]
|
120 |
+
|
121 |
+
#### Metrics
|
122 |
+
|
123 |
+
<!-- These are the evaluation metrics being used, ideally with a description of why. -->
|
124 |
+
|
125 |
+
[More Information Needed]
|
126 |
+
|
127 |
+
### Results
|
128 |
+
|
129 |
+
[More Information Needed]
|
130 |
+
|
131 |
+
#### Summary
|
132 |
+
|
133 |
+
|
134 |
+
|
135 |
+
## Model Examination [optional]
|
136 |
+
|
137 |
+
<!-- Relevant interpretability work for the model goes here -->
|
138 |
+
|
139 |
+
[More Information Needed]
|
140 |
+
|
141 |
+
## Environmental Impact
|
142 |
+
|
143 |
+
<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
|
144 |
+
|
145 |
+
Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
|
146 |
+
|
147 |
+
- **Hardware Type:** [More Information Needed]
|
148 |
+
- **Hours used:** [More Information Needed]
|
149 |
+
- **Cloud Provider:** [More Information Needed]
|
150 |
+
- **Compute Region:** [More Information Needed]
|
151 |
+
- **Carbon Emitted:** [More Information Needed]
|
152 |
+
|
153 |
+
## Technical Specifications [optional]
|
154 |
+
|
155 |
+
### Model Architecture and Objective
|
156 |
+
|
157 |
+
[More Information Needed]
|
158 |
+
|
159 |
+
### Compute Infrastructure
|
160 |
+
|
161 |
+
[More Information Needed]
|
162 |
+
|
163 |
+
#### Hardware
|
164 |
+
|
165 |
+
[More Information Needed]
|
166 |
+
|
167 |
+
#### Software
|
168 |
+
|
169 |
+
[More Information Needed]
|
170 |
+
|
171 |
+
## Citation [optional]
|
172 |
+
|
173 |
+
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
|
174 |
+
|
175 |
+
**BibTeX:**
|
176 |
+
|
177 |
+
[More Information Needed]
|
178 |
+
|
179 |
+
**APA:**
|
180 |
+
|
181 |
+
[More Information Needed]
|
182 |
+
|
183 |
+
## Glossary [optional]
|
184 |
+
|
185 |
+
<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
|
186 |
+
|
187 |
+
[More Information Needed]
|
188 |
+
|
189 |
+
## More Information [optional]
|
190 |
+
|
191 |
+
[More Information Needed]
|
192 |
+
|
193 |
+
## Model Card Authors [optional]
|
194 |
+
|
195 |
+
[More Information Needed]
|
196 |
+
|
197 |
+
## Model Card Contact
|
198 |
+
|
199 |
+
[More Information Needed]
|
config.json
ADDED
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "/home/azureuser/phi4/qwen_works/Speech-to-Text-Training/MODELS/Qwen-Nahin-3-6/checkpoint-201000",
|
3 |
+
"architectures": [
|
4 |
+
"Qwen2MMForCausalLM"
|
5 |
+
],
|
6 |
+
"attention_bias": false,
|
7 |
+
"attention_dropout": 0.0,
|
8 |
+
"audio_processor": {
|
9 |
+
"config": {
|
10 |
+
"activation": "swish",
|
11 |
+
"activation_checkpointing": {
|
12 |
+
"interval": 1,
|
13 |
+
"module": "transformer",
|
14 |
+
"offload": false
|
15 |
+
},
|
16 |
+
"attention_dim": 1024,
|
17 |
+
"attention_heads": 16,
|
18 |
+
"batch_norm": false,
|
19 |
+
"bias_in_glu": true,
|
20 |
+
"causal": true,
|
21 |
+
"chunk_size": -1,
|
22 |
+
"cnn_layer_norm": true,
|
23 |
+
"conv_activation": "swish",
|
24 |
+
"conv_glu_type": "swish",
|
25 |
+
"depthwise_multiplier": 1,
|
26 |
+
"depthwise_seperable_out_channel": 1024,
|
27 |
+
"dropout_rate": 0.0,
|
28 |
+
"encoder_embedding_config": {
|
29 |
+
"input_size": 80
|
30 |
+
},
|
31 |
+
"ext_pw_kernel_size": 1,
|
32 |
+
"ext_pw_out_channel": 1024,
|
33 |
+
"input_layer": "nemo_conv",
|
34 |
+
"input_size": 80,
|
35 |
+
"kernel_size": 3,
|
36 |
+
"left_chunk": 18,
|
37 |
+
"linear_units": 1536,
|
38 |
+
"nemo_conv_settings": {
|
39 |
+
"conv_channels": 1024
|
40 |
+
},
|
41 |
+
"num_blocks": 24,
|
42 |
+
"relative_attention_bias_args": {
|
43 |
+
"t5_bias_max_distance": 500,
|
44 |
+
"type": "t5"
|
45 |
+
},
|
46 |
+
"time_reduction": 8
|
47 |
+
},
|
48 |
+
"name": "cascades"
|
49 |
+
},
|
50 |
+
"auto_map": {
|
51 |
+
"AutoConfig": "configuration_qwen2mm.Qwen2MMConfig",
|
52 |
+
"AutoModelForCausalLM": "modeling_phi4mm.Qwen2MMForCausalLM",
|
53 |
+
"AutoTokenizer": "./"
|
54 |
+
},
|
55 |
+
"bos_token_id": 151644,
|
56 |
+
"embd_layer": {
|
57 |
+
"audio_embd_layer": {
|
58 |
+
"compression_rate": 8,
|
59 |
+
"downsample_rate": 1,
|
60 |
+
"embedding_cls": "audio",
|
61 |
+
"enable_gradient_checkpointing": true,
|
62 |
+
"projection_cls": "mlp",
|
63 |
+
"use_conv_downsample": false,
|
64 |
+
"use_qformer": false
|
65 |
+
},
|
66 |
+
"embedding_cls": "image_audio",
|
67 |
+
"image_embd_layer": {
|
68 |
+
"crop_size": 448,
|
69 |
+
"embedding_cls": "tune_image",
|
70 |
+
"enable_gradient_checkpointing": true,
|
71 |
+
"hd_transform_order": "sub_glb",
|
72 |
+
"image_token_compression_cls": "avg_pool_2d",
|
73 |
+
"projection_cls": "mlp",
|
74 |
+
"use_hd_transform": true,
|
75 |
+
"with_learnable_separator": true
|
76 |
+
}
|
77 |
+
},
|
78 |
+
"eos_token_id": 151645,
|
79 |
+
"hidden_act": "silu",
|
80 |
+
"hidden_size": 896,
|
81 |
+
"initializer_range": 0.02,
|
82 |
+
"intermediate_size": 4864,
|
83 |
+
"max_position_embeddings": 131072,
|
84 |
+
"max_window_layers": 24,
|
85 |
+
"model_type": "qwen2-mm",
|
86 |
+
"num_attention_heads": 14,
|
87 |
+
"num_hidden_layers": 24,
|
88 |
+
"num_key_value_heads": 2,
|
89 |
+
"pad_token_id": 151643,
|
90 |
+
"rms_norm_eps": 1e-06,
|
91 |
+
"rope_scaling": null,
|
92 |
+
"rope_theta": 1000000.0,
|
93 |
+
"sliding_window": null,
|
94 |
+
"speech_lora": {
|
95 |
+
"dp": 0.01,
|
96 |
+
"layer": "((layers.*self_attn\\.(qkv|o)_proj)|(layers.*mlp\\.(gate_up|down)_proj))",
|
97 |
+
"lora_alpha": 640,
|
98 |
+
"r": 320
|
99 |
+
},
|
100 |
+
"tie_word_embeddings": true,
|
101 |
+
"torch_dtype": "bfloat16",
|
102 |
+
"transformers_version": "4.48.3",
|
103 |
+
"use_cache": false,
|
104 |
+
"use_sliding_window": false,
|
105 |
+
"vision_lora": {
|
106 |
+
"dp": 0.0,
|
107 |
+
"layer": "layers.*((self_attn\\.(qkv_proj|o_proj))|(mlp\\.(gate_up|down)_proj))",
|
108 |
+
"lora_alpha": 512,
|
109 |
+
"r": 256
|
110 |
+
},
|
111 |
+
"vocab_size": 194498
|
112 |
+
}
|
configuration_qwen2mm.py
ADDED
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
"""Qwen2 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 Qwen2MMConfig(PretrainedConfig):
|
26 |
+
r"""
|
27 |
+
This is the configuration class to store the configuration of a [`Qwen2Model`]. It is used to instantiate a
|
28 |
+
Qwen2 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 |
+
Qwen2-7B-beta [Qwen/Qwen2-7B-beta](https://huggingface.co/Qwen/Qwen2-7B-beta).
|
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 Qwen2 model. Defines the number of different tokens that can be represented by the
|
39 |
+
`inputs_ids` passed when calling [`Qwen2Model`]
|
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 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
56 |
+
The non-linear activation function (function or string) in the decoder.
|
57 |
+
max_position_embeddings (`int`, *optional*, defaults to 32768):
|
58 |
+
The maximum sequence length that this model might ever be used with.
|
59 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
60 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
61 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
62 |
+
The epsilon used by the rms normalization layers.
|
63 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
64 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
65 |
+
relevant if `config.is_decoder=True`.
|
66 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
67 |
+
Whether the model's input and output word embeddings should be tied.
|
68 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
69 |
+
The base period of the RoPE embeddings.
|
70 |
+
rope_scaling (`Dict`, *optional*):
|
71 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
|
72 |
+
and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
|
73 |
+
accordingly.
|
74 |
+
Expected contents:
|
75 |
+
`rope_type` (`str`):
|
76 |
+
The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
|
77 |
+
'llama3'], with 'default' being the original RoPE implementation.
|
78 |
+
`factor` (`float`, *optional*):
|
79 |
+
Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
|
80 |
+
most scaling types, a `factor` of x will enable the model to handle sequences of length x *
|
81 |
+
original maximum pre-trained length.
|
82 |
+
`original_max_position_embeddings` (`int`, *optional*):
|
83 |
+
Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
|
84 |
+
pretraining.
|
85 |
+
`attention_factor` (`float`, *optional*):
|
86 |
+
Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
|
87 |
+
computation. If unspecified, it defaults to value recommended by the implementation, using the
|
88 |
+
`factor` field to infer the suggested value.
|
89 |
+
`beta_fast` (`float`, *optional*):
|
90 |
+
Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
|
91 |
+
ramp function. If unspecified, it defaults to 32.
|
92 |
+
`beta_slow` (`float`, *optional*):
|
93 |
+
Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
|
94 |
+
ramp function. If unspecified, it defaults to 1.
|
95 |
+
`short_factor` (`List[float]`, *optional*):
|
96 |
+
Only used with 'longrope'. The scaling factor to be applied to short contexts (<
|
97 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
98 |
+
size divided by the number of attention heads divided by 2
|
99 |
+
`long_factor` (`List[float]`, *optional*):
|
100 |
+
Only used with 'longrope'. The scaling factor to be applied to long contexts (<
|
101 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
102 |
+
size divided by the number of attention heads divided by 2
|
103 |
+
`low_freq_factor` (`float`, *optional*):
|
104 |
+
Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
|
105 |
+
`high_freq_factor` (`float`, *optional*):
|
106 |
+
Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
|
107 |
+
use_sliding_window (`bool`, *optional*, defaults to `False`):
|
108 |
+
Whether to use sliding window attention.
|
109 |
+
sliding_window (`int`, *optional*, defaults to 4096):
|
110 |
+
Sliding window attention (SWA) window size. If not specified, will default to `4096`.
|
111 |
+
max_window_layers (`int`, *optional*, defaults to 28):
|
112 |
+
The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
|
113 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
114 |
+
The dropout ratio for the attention probabilities.
|
115 |
+
|
116 |
+
```python
|
117 |
+
>>> from transformers import Qwen2Model, Qwen2Config
|
118 |
+
|
119 |
+
>>> # Initializing a Qwen2 style configuration
|
120 |
+
>>> configuration = Qwen2Config()
|
121 |
+
|
122 |
+
>>> # Initializing a model from the Qwen2-7B style configuration
|
123 |
+
>>> model = Qwen2Model(configuration)
|
124 |
+
|
125 |
+
>>> # Accessing the model configuration
|
126 |
+
>>> configuration = model.config
|
127 |
+
```"""
|
128 |
+
|
129 |
+
model_type = "qwen2-mm"
|
130 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
131 |
+
|
132 |
+
# Default tensor parallel plan for base model `Qwen2`
|
133 |
+
base_model_tp_plan = {
|
134 |
+
"layers.*.self_attn.q_proj": "colwise",
|
135 |
+
"layers.*.self_attn.k_proj": "colwise",
|
136 |
+
"layers.*.self_attn.v_proj": "colwise",
|
137 |
+
"layers.*.self_attn.o_proj": "rowwise",
|
138 |
+
"layers.*.mlp.gate_proj": "colwise",
|
139 |
+
"layers.*.mlp.up_proj": "colwise",
|
140 |
+
"layers.*.mlp.down_proj": "rowwise",
|
141 |
+
}
|
142 |
+
base_model_pp_plan = {
|
143 |
+
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
144 |
+
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
|
145 |
+
"norm": (["hidden_states"], ["hidden_states"]),
|
146 |
+
}
|
147 |
+
|
148 |
+
def __init__(
|
149 |
+
self,
|
150 |
+
vocab_size=151936,
|
151 |
+
hidden_size=4096,
|
152 |
+
intermediate_size=22016,
|
153 |
+
num_hidden_layers=32,
|
154 |
+
num_attention_heads=32,
|
155 |
+
num_key_value_heads=32,
|
156 |
+
hidden_act="silu",
|
157 |
+
max_position_embeddings=32768,
|
158 |
+
initializer_range=0.02,
|
159 |
+
rms_norm_eps=1e-6,
|
160 |
+
use_cache=True,
|
161 |
+
tie_word_embeddings=False,
|
162 |
+
rope_theta=10000.0,
|
163 |
+
rope_scaling=None,
|
164 |
+
use_sliding_window=False,
|
165 |
+
sliding_window=4096,
|
166 |
+
max_window_layers=28,
|
167 |
+
attention_dropout=0.0,
|
168 |
+
**kwargs,
|
169 |
+
):
|
170 |
+
self.vocab_size = vocab_size
|
171 |
+
self.max_position_embeddings = max_position_embeddings
|
172 |
+
self.hidden_size = hidden_size
|
173 |
+
self.intermediate_size = intermediate_size
|
174 |
+
self.num_hidden_layers = num_hidden_layers
|
175 |
+
self.num_attention_heads = num_attention_heads
|
176 |
+
self.use_sliding_window = use_sliding_window
|
177 |
+
self.sliding_window = sliding_window # we check `use_sliding_window` in the modeling code
|
178 |
+
self.max_window_layers = max_window_layers
|
179 |
+
|
180 |
+
# for backward compatibility
|
181 |
+
if num_key_value_heads is None:
|
182 |
+
num_key_value_heads = num_attention_heads
|
183 |
+
|
184 |
+
self.num_key_value_heads = num_key_value_heads
|
185 |
+
self.hidden_act = hidden_act
|
186 |
+
self.initializer_range = initializer_range
|
187 |
+
self.rms_norm_eps = rms_norm_eps
|
188 |
+
self.use_cache = use_cache
|
189 |
+
self.rope_theta = rope_theta
|
190 |
+
self.rope_scaling = rope_scaling
|
191 |
+
self.attention_dropout = attention_dropout
|
192 |
+
# Validate the correctness of rotary position embeddings parameters
|
193 |
+
# BC: if there is a 'type' field, move it to 'rope_type'.
|
194 |
+
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
195 |
+
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
196 |
+
rope_config_validation(self)
|
197 |
+
|
198 |
+
super().__init__(
|
199 |
+
tie_word_embeddings=tie_word_embeddings,
|
200 |
+
**kwargs,
|
201 |
+
)
|
generation_config.json
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"bos_token_id": 151644,
|
4 |
+
"eos_token_id": [
|
5 |
+
151645
|
6 |
+
],
|
7 |
+
"pad_token_id": 151643,
|
8 |
+
"transformers_version": "4.48.3"
|
9 |
+
}
|
model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6f642731b0bdfe6f3703ef4b208b6cdf17e0c47d2b2de1a99067ed633fca06ff
|
3 |
+
size 1950430024
|
modeling_phi4mm.py
ADDED
@@ -0,0 +1,1877 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2024 Microsoft 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 |
+
|
16 |
+
""" PyTorch Phi-4-MM model."""
|
17 |
+
import math
|
18 |
+
import warnings
|
19 |
+
from typing import List, Optional, Tuple, Union
|
20 |
+
|
21 |
+
import numpy as np
|
22 |
+
|
23 |
+
import torch
|
24 |
+
import torch.utils.checkpoint
|
25 |
+
from torch import nn
|
26 |
+
from torch.nn import CrossEntropyLoss
|
27 |
+
|
28 |
+
from transformers.activations import ACT2FN
|
29 |
+
from transformers.cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
|
30 |
+
from transformers.generation import GenerationMixin
|
31 |
+
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
32 |
+
from transformers.modeling_flash_attention_utils import _flash_attention_forward
|
33 |
+
from transformers.modeling_outputs import (
|
34 |
+
BaseModelOutputWithPast,
|
35 |
+
CausalLMOutputWithPast,
|
36 |
+
SequenceClassifierOutputWithPast,
|
37 |
+
TokenClassifierOutput,
|
38 |
+
)
|
39 |
+
from transformers.modeling_utils import PreTrainedModel
|
40 |
+
from transformers.utils import (
|
41 |
+
add_code_sample_docstrings,
|
42 |
+
add_start_docstrings,
|
43 |
+
add_start_docstrings_to_model_forward,
|
44 |
+
is_flash_attn_greater_or_equal_2_10,
|
45 |
+
logging,
|
46 |
+
replace_return_docstrings,
|
47 |
+
)
|
48 |
+
from transformers import AutoConfig, AutoModelForCausalLM, PretrainedConfig
|
49 |
+
|
50 |
+
# from .configuration_phi4mm import Phi4MMConfig
|
51 |
+
from .processing_phi4mm import InputMode
|
52 |
+
# from .vision_siglip_navit import get_siglip_vision_model
|
53 |
+
from .speech_conformer_encoder import ConformerEncoder
|
54 |
+
|
55 |
+
|
56 |
+
logger = logging.get_logger(__name__)
|
57 |
+
|
58 |
+
_CHECKPOINT_FOR_DOC = "TBA"
|
59 |
+
_CONFIG_FOR_DOC = "Qwen2MMConfig"
|
60 |
+
|
61 |
+
# Special token ids
|
62 |
+
_IMAGE_SPECIAL_TOKEN_ID = 1516444 # '<|endoftext10|>', or we can better name it (in `tokenizer_config.json`)
|
63 |
+
_AUDIO_SPECIAL_TOKEN_ID = 151644 # '<|endoftext11|>'
|
64 |
+
_COMPATIBLE_IMAGE_SPECIAL_TOKEN_ID_RANGE = [-9999, -1] # For backward compatibility
|
65 |
+
_COMPATIBLE_AUDIO_SPECIAL_TOKEN_ID_RANGE = [float('-inf'), -10000] # For backward compatibility
|
66 |
+
|
67 |
+
|
68 |
+
# class Phi4MMImageEmbedding(nn.Module):
|
69 |
+
# """Image embedding."""
|
70 |
+
|
71 |
+
# def __init__(self, config: PretrainedConfig, **kwargs) -> None:
|
72 |
+
# super().__init__()
|
73 |
+
|
74 |
+
# # n_embed or hidden_size
|
75 |
+
# hidden_size = config.n_embd if hasattr(config, 'n_embd') else config.hidden_size
|
76 |
+
# if hasattr(config, 'embd_pdrop') or hasattr(config, 'embed_pdrop'):
|
77 |
+
# embd_drop = config.embd_pdrop if hasattr(config, 'embd_pdrop') else config.embed_pdrop
|
78 |
+
# self.drop = nn.Dropout(embd_drop)
|
79 |
+
# else:
|
80 |
+
# self.drop = None
|
81 |
+
|
82 |
+
# logger.info(f"create image tower {config.img_processor}")
|
83 |
+
# enable_gradient_checkpointing = kwargs.get('enable_gradient_checkpointing', False)
|
84 |
+
|
85 |
+
# # Load SigLIP model
|
86 |
+
# self.img_processor = get_siglip_vision_model(
|
87 |
+
# _flash_attn_2_enabled=config._attn_implementation == 'flash_attention_2'
|
88 |
+
# )
|
89 |
+
|
90 |
+
# pe_weight = self.img_processor.embeddings.position_embedding.weight
|
91 |
+
# L, D = pe_weight.size()
|
92 |
+
# H = int(math.sqrt(L))
|
93 |
+
# assert H**2 == L
|
94 |
+
# if H % 2 != 0: #and kwargs.get('image_token_compression_cls', None) is None:
|
95 |
+
# self.img_processor_padding = nn.ReflectionPad2d((0, 1, 0, 1))
|
96 |
+
# H += 1
|
97 |
+
# image_dim_out = D
|
98 |
+
# # ((448/14)//2)**2
|
99 |
+
# self.num_img_tokens = (H//2)**2
|
100 |
+
# self.base_feat_height_target = H
|
101 |
+
|
102 |
+
# if enable_gradient_checkpointing:
|
103 |
+
# self.img_processor.encoder.gradient_checkpointing = True
|
104 |
+
|
105 |
+
# self.image_dim_out = image_dim_out
|
106 |
+
# self.img_sizes = None
|
107 |
+
# self.image_attention_mask = None
|
108 |
+
|
109 |
+
# # global_gn and sub_gn for hd transform, serves as line separator
|
110 |
+
# self.use_hd_transform = kwargs.get('use_hd_transform', False)
|
111 |
+
# self.with_learnable_separator = kwargs.get('with_learnable_separator', False)
|
112 |
+
# self.hd_transform_order = kwargs.get('hd_transform_order', 'glb_sub')
|
113 |
+
# self.freeze_img_processor = kwargs.get('freeze_img_processor', False)
|
114 |
+
# self.crop_size = kwargs.get('crop_size', 336)
|
115 |
+
# logger.info(f'freeze_img_processor = {self.freeze_img_processor}')
|
116 |
+
|
117 |
+
# # image token compression
|
118 |
+
# self.image_token_compression_cls = kwargs.get('image_token_compression_cls', None)
|
119 |
+
# if self.image_token_compression_cls == 'avg_pool_2d':
|
120 |
+
# self.image_token_compression = nn.AvgPool2d(kernel_size=2, stride=2)
|
121 |
+
# self.base_feat_height_reduction = 1
|
122 |
+
# self.base_feat_height_target = self.base_feat_height_target // 2
|
123 |
+
# elif self.image_token_compression_cls is None:
|
124 |
+
# self.image_token_compression = None
|
125 |
+
# self.base_feat_height_reduction = 2
|
126 |
+
# else:
|
127 |
+
# raise NotImplementedError(f'image_token_compression_cls = {self.image_token_compression_cls}, not implemented')
|
128 |
+
|
129 |
+
# # with_hd_transform and with_learnable_separator should have same value
|
130 |
+
# assert self.use_hd_transform == self.with_learnable_separator, 'use_hd_transform and with_learnable_separator should have same value'
|
131 |
+
# if self.with_learnable_separator:
|
132 |
+
# assert self.use_hd_transform, 'learnable separator is only for hd transform'
|
133 |
+
# # 1024 * 4, merge spatial to channel dimension
|
134 |
+
# self.glb_GN = nn.Parameter(torch.zeros([1, 1, self.image_dim_out * self.base_feat_height_reduction**2]))
|
135 |
+
# self.sub_GN = nn.Parameter(torch.zeros([1, 1, 1, self.image_dim_out * self.base_feat_height_reduction**2]))
|
136 |
+
# logger.info(f'learnable separator enabled for hd transform, hd_transform_order = {self.hd_transform_order}')
|
137 |
+
|
138 |
+
# projection_cls = kwargs.get('projection_cls', 'linear')
|
139 |
+
# if projection_cls == 'linear':
|
140 |
+
# self.img_projection = nn.Linear(image_dim_out, hidden_size)
|
141 |
+
# elif projection_cls == 'mlp' and self.use_hd_transform:
|
142 |
+
# dim_projection = hidden_size
|
143 |
+
# depth = 2
|
144 |
+
# layers = [nn.Linear(image_dim_out * self.base_feat_height_reduction**2, dim_projection)]
|
145 |
+
# for _ in range(1, depth):
|
146 |
+
# layers.extend([nn.GELU(),
|
147 |
+
# nn.Linear(dim_projection, dim_projection)])
|
148 |
+
# self.img_projection = nn.Sequential(*layers)
|
149 |
+
# elif projection_cls == 'mlp':
|
150 |
+
# # follow llava-v1.5's implementation
|
151 |
+
# # (do not use image_projection and image_proj_norm)
|
152 |
+
# dim_projection = hidden_size
|
153 |
+
# depth = 2
|
154 |
+
# layers = [nn.Linear(image_dim_out, dim_projection)]
|
155 |
+
# for _ in range(1, depth):
|
156 |
+
# layers.extend([nn.GELU(),
|
157 |
+
# nn.Linear(dim_projection, dim_projection)])
|
158 |
+
# self.img_projection = nn.Sequential(*layers)
|
159 |
+
# else:
|
160 |
+
# raise NotImplementedError(f'projection_cls = {projection_cls}, not implemented')
|
161 |
+
|
162 |
+
# self.vocab_size = config.vocab_size
|
163 |
+
# self.img_features = None
|
164 |
+
|
165 |
+
# if isinstance(config.img_processor, dict):
|
166 |
+
# self.layer_idx = config.img_processor.get('layer_idx', -2)
|
167 |
+
# self.type_feature = config.img_processor.get('type_feature', 'patch')
|
168 |
+
# else:
|
169 |
+
# self.layer_idx = -2
|
170 |
+
# self.type_feature = 'patch'
|
171 |
+
|
172 |
+
# def set_img_features(self, img_features: torch.FloatTensor) -> None:
|
173 |
+
# self.img_features = img_features
|
174 |
+
|
175 |
+
# def set_img_sizes(self, img_sizes: torch.LongTensor) -> None:
|
176 |
+
# self.img_sizes = img_sizes
|
177 |
+
|
178 |
+
# def set_img_attn_mask(self, image_attention_mask: torch.FloatTensor) -> None:
|
179 |
+
# self.image_attention_mask = image_attention_mask
|
180 |
+
|
181 |
+
# def get_img_features(self, img_embeds: torch.FloatTensor, attention_mask=None) -> torch.FloatTensor:
|
182 |
+
# LAYER_IDX = self.layer_idx
|
183 |
+
# TYPE_FEATURE = self.type_feature
|
184 |
+
|
185 |
+
# if self.freeze_img_processor:
|
186 |
+
# with torch.no_grad():
|
187 |
+
# if attention_mask is not None:
|
188 |
+
# img_processor_output = self.img_processor(img_embeds, output_hidden_states=True, patch_attention_mask=attention_mask)
|
189 |
+
# else:
|
190 |
+
# img_processor_output = self.img_processor(img_embeds, output_hidden_states=True)
|
191 |
+
# img_feature = img_processor_output.hidden_states[LAYER_IDX]
|
192 |
+
# else:
|
193 |
+
# if attention_mask is not None:
|
194 |
+
# img_processor_output = self.img_processor(img_embeds, output_hidden_states=True, patch_attention_mask=attention_mask)
|
195 |
+
# else:
|
196 |
+
# img_processor_output = self.img_processor(img_embeds, output_hidden_states=True)
|
197 |
+
# img_feature = img_processor_output.hidden_states[LAYER_IDX]
|
198 |
+
|
199 |
+
# if TYPE_FEATURE == "patch":
|
200 |
+
# patch_feature = img_feature
|
201 |
+
# if self.image_token_compression is not None:
|
202 |
+
# # reshape to 2D tensor
|
203 |
+
# width = int(math.sqrt(patch_feature.size(1)))
|
204 |
+
# patch_feature = patch_feature.view(-1, width, width, patch_feature.size(-1))
|
205 |
+
# # convert to NCHW
|
206 |
+
# patch_feature = patch_feature.permute(0, 3, 1, 2)
|
207 |
+
# if getattr(self, 'img_processor_padding', None) is not None:
|
208 |
+
# patch_feature = self.img_processor_padding(patch_feature)
|
209 |
+
# patch_feature = self.image_token_compression(patch_feature)
|
210 |
+
# # convert to NHWC
|
211 |
+
# patch_feature = patch_feature.permute(0, 2, 3, 1)
|
212 |
+
# patch_feature = patch_feature.view(-1, patch_feature.size(1) * patch_feature.size(2), patch_feature.size(-1))
|
213 |
+
# elif getattr(self, 'img_processor_padding', None) is not None:
|
214 |
+
# width = int(math.sqrt(patch_feature.size(1)))
|
215 |
+
# patch_feature = patch_feature.view(-1, width, width, patch_feature.size(-1))
|
216 |
+
# # convert to NCHW
|
217 |
+
# patch_feature = patch_feature.permute(0, 3, 1, 2)
|
218 |
+
# patch_feature = self.img_processor_padding(patch_feature)
|
219 |
+
# # convert to NHWC
|
220 |
+
# patch_feature = patch_feature.permute(0, 2, 3, 1)
|
221 |
+
# patch_feature = patch_feature.view(-1, patch_feature.size(1) * patch_feature.size(2), patch_feature.size(-1))
|
222 |
+
# return patch_feature
|
223 |
+
|
224 |
+
# if TYPE_FEATURE == "cls_patch":
|
225 |
+
# if self.image_token_compression is not None:
|
226 |
+
# # reshape to 2D tensor
|
227 |
+
# patch_feature = img_feature[:, 1:]
|
228 |
+
# cls_feature = img_feature[:, 0]
|
229 |
+
# width = math.sqrt(patch_feature.size(1))
|
230 |
+
# patch_feature = patch_feature.view(-1, width, width, patch_feature.size(-1))
|
231 |
+
# patch_feature = self.image_token_compression(patch_feature)
|
232 |
+
# patch_feature = patch_feature.view(-1, patch_feature.size(-2) * patch_feature.size(-1))
|
233 |
+
# img_feature = torch.cat([cls_feature, patch_feature], dim=1)
|
234 |
+
# return img_feature
|
235 |
+
|
236 |
+
# logger.info(f'processed img feature size = {img_feature.size()}')
|
237 |
+
# raise NotImplementedError
|
238 |
+
|
239 |
+
# def spatiotemporal_pool(self, x, num_img_tokens, batch_size=1, T=1):
|
240 |
+
|
241 |
+
# if self.image_pos_embed is not None:
|
242 |
+
# x = x.view(batch_size * T, -1, x.shape[-1])
|
243 |
+
# num_tokens = x.shape[-2]
|
244 |
+
# h, w = int(num_tokens ** 0.5), int(num_tokens ** 0.5)
|
245 |
+
# assert h * w == num_tokens, 'only support square feature maps for now'
|
246 |
+
# x = x.view(batch_size * T, h, w, x.shape[-1])
|
247 |
+
# pos_embed = self.image_pos_embed(x)
|
248 |
+
# x = x + pos_embed
|
249 |
+
# x = x.view(batch_size, T * h * w, x.shape[-1])
|
250 |
+
|
251 |
+
# if self.visual_temporal_embed is not None:
|
252 |
+
# visual_temporal_embed = self.visual_temporal_embed(x.view(batch_size, T, -1, x.shape[-1])[:, :, 0])
|
253 |
+
# x = x.view(batch_size, T, -1, x.shape[-1]) + visual_temporal_embed.view(1, T, 1, x.shape[-1])
|
254 |
+
|
255 |
+
# new_x = []
|
256 |
+
# # [bsz, T * H' * W', C] -> [bsz, T, C]
|
257 |
+
# spatial_avg_pool_x = x.view(batch_size, T, -1, x.shape[-1]).mean(dim=2)
|
258 |
+
# new_x.append(spatial_avg_pool_x)
|
259 |
+
|
260 |
+
# # [bsz, T * H' * W', C] -> [bsz, H'*W', C]
|
261 |
+
# temporal_avg_pool_x = x.view(batch_size, T, -1, x.shape[-1]).mean(dim=1)
|
262 |
+
# new_x.append(temporal_avg_pool_x)
|
263 |
+
|
264 |
+
# x = torch.cat(new_x, dim=1).view(-1, self.image_dim_out)
|
265 |
+
# num_img_tokens += T
|
266 |
+
# return x, num_img_tokens
|
267 |
+
|
268 |
+
# def forward(self, input_ids: torch.LongTensor, input_embeds: torch.FloatTensor, image_sizes=None, **kwargs) -> torch.FloatTensor:
|
269 |
+
|
270 |
+
# if isinstance(input_ids, tuple):
|
271 |
+
# # # pipeline parallel
|
272 |
+
# input_ids, input_embeds = input_ids
|
273 |
+
|
274 |
+
# img_embeds = input_embeds
|
275 |
+
# if image_sizes is None and 'image_sizes' in kwargs:
|
276 |
+
# image_sizes = kwargs['image_sizes']
|
277 |
+
# img_sizes = image_sizes
|
278 |
+
|
279 |
+
# if self.img_features is not None:
|
280 |
+
# img_embeds = self.img_features.clone()
|
281 |
+
# self.img_features = None
|
282 |
+
|
283 |
+
# if self.img_sizes is not None:
|
284 |
+
# img_sizes = self.img_sizes
|
285 |
+
|
286 |
+
# dtype = self.img_processor.embeddings.patch_embedding.weight.dtype
|
287 |
+
# if img_embeds is not None:
|
288 |
+
# # convert to bf16
|
289 |
+
# img_embeds = img_embeds.to(dtype)
|
290 |
+
|
291 |
+
# if self.image_attention_mask is not None:
|
292 |
+
# image_attention_mask = self.image_attention_mask.clone()
|
293 |
+
# self.image_attention_mask = None
|
294 |
+
# elif 'image_attention_mask' in kwargs:
|
295 |
+
# image_attention_mask = kwargs['image_attention_mask']
|
296 |
+
# else:
|
297 |
+
# image_attention_mask = None
|
298 |
+
# input_shape = input_ids.size()
|
299 |
+
# input_ids = input_ids.view(-1, input_shape[-1])
|
300 |
+
|
301 |
+
# with torch.no_grad():
|
302 |
+
# positions = torch.nonzero(input_ids == _IMAGE_SPECIAL_TOKEN_ID, as_tuple=False)
|
303 |
+
# positions_tuple = torch.nonzero(input_ids == _IMAGE_SPECIAL_TOKEN_ID, as_tuple=True)
|
304 |
+
|
305 |
+
# # logger.info(f'position size: {positions.size()} ...')
|
306 |
+
# fake_image_forward = False
|
307 |
+
# select = False
|
308 |
+
# hd_transform = False
|
309 |
+
|
310 |
+
# if isinstance(self.img_projection, nn.Sequential):
|
311 |
+
# target_device = self.img_projection[0].bias.device
|
312 |
+
# target_dtype = self.img_projection[0].bias.dtype
|
313 |
+
# else: # It's a single nn.Linear layer
|
314 |
+
# target_device = self.img_projection.bias.device
|
315 |
+
# target_dtype = self.img_projection.bias.dtype
|
316 |
+
|
317 |
+
# num_img_tokens = self.num_img_tokens
|
318 |
+
# if len(positions.tolist()) > 0:
|
319 |
+
# if self.use_hd_transform and img_sizes is not None and len(img_sizes):
|
320 |
+
# hd_transform = True
|
321 |
+
# assert img_embeds.ndim == 5, f'(branch 1) img_embeds size: {img_embeds.size()}, expect 5D tensor for hd transform'
|
322 |
+
# # img_embeds: (num_images, max_num_crops, 3, H, W)
|
323 |
+
# # img_sizes: (num_images, 2).view(1, -1)
|
324 |
+
|
325 |
+
# bs = img_embeds.shape[0]
|
326 |
+
# # Nx(HW)xC
|
327 |
+
# if image_attention_mask is not None and len(image_attention_mask) > 0:
|
328 |
+
# img_features = self.get_img_features(img_embeds.flatten(0, 1), attention_mask=image_attention_mask.type(torch.BoolTensor).flatten(0,1).to(target_device))
|
329 |
+
# else:
|
330 |
+
# img_features = self.get_img_features(img_embeds.flatten(0, 1))
|
331 |
+
|
332 |
+
# base_feat_height_target = self.base_feat_height_target
|
333 |
+
# base_resolution = self.crop_size
|
334 |
+
# base_feat_height_reduction = self.base_feat_height_reduction
|
335 |
+
|
336 |
+
# base_feat_height = base_feat_width = int(np.sqrt(img_features.shape[1]))
|
337 |
+
|
338 |
+
# assert base_feat_height == base_feat_height_target and base_feat_width == base_feat_height_target, f'base_feat_height: {base_feat_height}, base_feat_width: {base_feat_width}, expect {base_feat_height_target} features for hd transform'
|
339 |
+
|
340 |
+
# # bs x max_num_crops x (24x24) x C
|
341 |
+
# img_features = img_features.view(bs, -1, base_feat_height * base_feat_width, self.image_dim_out)
|
342 |
+
# C = self.image_dim_out
|
343 |
+
# H = base_feat_height
|
344 |
+
|
345 |
+
# output_imgs = []
|
346 |
+
# output_len = []
|
347 |
+
# # training is tensor, inference is list
|
348 |
+
# if isinstance(img_sizes, torch.Tensor):
|
349 |
+
# img_sizes = img_sizes.view(-1, 2)
|
350 |
+
# for _bs in range(bs):
|
351 |
+
# h, w = img_sizes[_bs]
|
352 |
+
# h = h // base_resolution
|
353 |
+
# w = w // base_resolution
|
354 |
+
# B_ = h * w
|
355 |
+
|
356 |
+
# # 1 x (24x24) x 1024
|
357 |
+
# global_img_feature = img_features[_bs, :1]
|
358 |
+
|
359 |
+
# # 1 x 12 x 12 x 4096
|
360 |
+
# glb_img = global_img_feature.reshape(1,H,H,C).reshape(1,H//base_feat_height_reduction,base_feat_height_reduction,H//base_feat_height_reduction,base_feat_height_reduction,C).contiguous().permute(0,1,3,2,4,5).reshape(1,H//base_feat_height_reduction,H//base_feat_height_reduction,base_feat_height_reduction*base_feat_height_reduction*C).contiguous()
|
361 |
+
# temp_glb_GN = self.sub_GN.repeat(1, H//base_feat_height_reduction, 1, 1)
|
362 |
+
|
363 |
+
# # 1 x 156 x 4096
|
364 |
+
# glb_img = torch.cat([glb_img, temp_glb_GN], dim=2).reshape(1,-1,base_feat_height_reduction*base_feat_height_reduction*C)
|
365 |
+
|
366 |
+
# # (max_num_crops-1) x (12x12) x C
|
367 |
+
# sub_img = img_features[_bs, 1:]
|
368 |
+
# # 16x574x1024
|
369 |
+
# # get rid of padding sub_img
|
370 |
+
# sub_img = sub_img[:B_]
|
371 |
+
|
372 |
+
# # (num_crops, 12, 2, 12, 2, 1024) -> (num_crops, 12, 12, 2, 2, 1024) -> (num_crops, 12*12, 4*1024)
|
373 |
+
# sub_img = sub_img.reshape(B_,H,H,C).reshape(B_,H//base_feat_height_reduction,base_feat_height_reduction,H//base_feat_height_reduction,base_feat_height_reduction,C).contiguous().permute(0,1,3,2,4,5).reshape(B_,-1,base_feat_height_reduction*base_feat_height_reduction*C).contiguous()
|
374 |
+
# sub_img = sub_img.reshape(1, h, w, base_feat_height // base_feat_height_reduction, base_feat_width // base_feat_height_reduction, -1).permute(0,1,3,2,4,5).reshape(1,h*base_feat_height//base_feat_height_reduction,w*base_feat_width//base_feat_height_reduction,base_feat_height_reduction*base_feat_height_reduction*C)
|
375 |
+
|
376 |
+
# if image_attention_mask is not None and len(image_attention_mask) > 0:
|
377 |
+
# reshaped_image_attention_mask = image_attention_mask[_bs,1:B_+1,0::2,0::2].reshape(1, h, w, base_feat_height // base_feat_height_reduction, base_feat_width // base_feat_height_reduction).permute(0,1,3,2,4).reshape(1,h*base_feat_height//base_feat_height_reduction,w*base_feat_width//base_feat_height_reduction)
|
378 |
+
# useful_height = int(reshaped_image_attention_mask[0,:,0].sum().item())
|
379 |
+
# useful_width = int(reshaped_image_attention_mask[0,0,:].sum().item())
|
380 |
+
# sub_img = sub_img[:,:useful_height, :useful_width]
|
381 |
+
# temp_sub_GN = self.sub_GN.repeat(1, useful_height, 1, 1)
|
382 |
+
# temp_len = int(image_attention_mask[_bs,:B_+1,0::2,0::2].sum().item()) + (useful_height+1) + base_feat_height//base_feat_height_reduction
|
383 |
+
# else:
|
384 |
+
# temp_sub_GN = self.sub_GN.repeat(1, h*base_feat_height//base_feat_height_reduction, 1, 1)
|
385 |
+
# temp_len = int((h*w+1)*self.num_img_tokens+ 1 + (h+1)*base_feat_height//base_feat_height_reduction)
|
386 |
+
|
387 |
+
# sub_img = torch.cat([sub_img, temp_sub_GN], dim=2).reshape(1,-1,base_feat_height_reduction*base_feat_height_reduction*C)
|
388 |
+
# # (1, num_img_tokens, 1024*4)
|
389 |
+
|
390 |
+
# # glb + sub
|
391 |
+
# if self.hd_transform_order == 'glb_sub':
|
392 |
+
# output_imgs.append(torch.cat([glb_img, self.glb_GN, sub_img], dim=1))
|
393 |
+
# elif self.hd_transform_order == 'sub_glb':
|
394 |
+
# output_imgs.append(torch.cat([sub_img, self.glb_GN, glb_img], dim=1))
|
395 |
+
# else:
|
396 |
+
# raise NotImplementedError(f'hd_transform_order = {self.hd_transform_order}, not implemented')
|
397 |
+
|
398 |
+
# #temp_len = int((h*w+1)*144 + 1 + (h+1)*12)
|
399 |
+
# assert temp_len == output_imgs[-1].shape[1], f'temp_len: {temp_len}, output_imgs[-1].shape[1]: {output_imgs[-1].shape[1]}'
|
400 |
+
# output_len.append(temp_len)
|
401 |
+
|
402 |
+
# num_img_tokens = output_len
|
403 |
+
# img_set_tensor = []
|
404 |
+
# for _output_img in output_imgs:
|
405 |
+
# img_feature_proj = self.img_projection(_output_img.to(target_device).to(target_dtype))
|
406 |
+
# img_set_tensor.append(img_feature_proj)
|
407 |
+
# #logger.info(f'img_embeds size: {img_embeds.size()}, image sizes: {img_sizes} loading time {datetime.now() - start_time}')
|
408 |
+
# #assert sum(num_img_tokens) == len(g_values), f'(branch 1) sum(num_img_tokens): {sum(num_img_tokens)}, g_values size: {len(g_values)}, g_values {g_values}'
|
409 |
+
|
410 |
+
# else:
|
411 |
+
# raise NotImplementedError
|
412 |
+
# select = True
|
413 |
+
# else:
|
414 |
+
# # # create a fake image tensor
|
415 |
+
# # # TODO: need define image size for different vision model
|
416 |
+
# if self.training:
|
417 |
+
# img_embeds = torch.zeros(1, 3, self.crop_size, self.crop_size, dtype=target_dtype, device=input_ids.device)
|
418 |
+
|
419 |
+
# tt = (
|
420 |
+
# self.get_img_features(img_embeds)
|
421 |
+
# .to(target_device)
|
422 |
+
# .to(target_dtype)
|
423 |
+
# .reshape(-1, 1024)
|
424 |
+
# )
|
425 |
+
# if self.use_hd_transform:
|
426 |
+
# img_set_tensor = self.img_projection(tt.reshape(-1, self.image_dim_out*self.base_feat_height_reduction**2) * self.glb_GN[0] * self.sub_GN[0, 0])
|
427 |
+
# else:
|
428 |
+
# img_set_tensor = self.img_projection(tt) # adapted visual features.
|
429 |
+
# fake_image_forward = True
|
430 |
+
|
431 |
+
# # we use the token embedding layer from the huggingface model, this is REQUIRED to make sure we are using the loaded weights.
|
432 |
+
# hidden_states = kwargs['wte'](input_ids)
|
433 |
+
|
434 |
+
# if select:
|
435 |
+
# if hd_transform:
|
436 |
+
# # new implementation without in-place operation
|
437 |
+
# # Ref: https://huggingface.co/microsoft/Phi-3.5-vision-instruct/blob/4a0d683eba9f1d0cbfb6151705d1ee73c25a80ca/modeling_phi3_v.py#L233
|
438 |
+
# # Ref: https://pytorch.org/docs/stable/generated/torch.Tensor.index_put.html
|
439 |
+
# # Ref: https://pytorch.org/docs/stable/generated/torch.Tensor.index_put_.html#torch.Tensor.index_put_
|
440 |
+
# # img_set_tensor: a list of tensors, each tensor has shape (1, N_tokens, C)
|
441 |
+
# assert all([_img_set_tensor.shape[0] == 1 for _img_set_tensor in img_set_tensor]), 'img_set_tensor should have shape (1, N_tokens, C)'
|
442 |
+
# # Shape: (merged_N_tokens, C)
|
443 |
+
# merged_img_set_tensor = torch.cat(img_set_tensor, dim=1).squeeze(0)
|
444 |
+
# merged_img_set_tensor = merged_img_set_tensor.to(hidden_states.dtype).to(hidden_states.device)
|
445 |
+
# # Temporarily disable autocast to avoid issue on bf16 tensors
|
446 |
+
# # Ref: https://github.com/pytorch/pytorch/issues/132715
|
447 |
+
# with torch.autocast(device_type=hidden_states.device.type, enabled=False):
|
448 |
+
# new_hidden_states = hidden_states.index_put(
|
449 |
+
# indices=positions_tuple,
|
450 |
+
# values=merged_img_set_tensor,
|
451 |
+
# accumulate=False
|
452 |
+
# )
|
453 |
+
# hidden_states = new_hidden_states
|
454 |
+
# else:
|
455 |
+
# raise NotImplementedError
|
456 |
+
|
457 |
+
# if fake_image_forward and self.training:
|
458 |
+
# hidden_states = hidden_states + (0 * img_set_tensor[0].to(hidden_states.dtype).to(hidden_states.device)).sum()
|
459 |
+
|
460 |
+
# if self.drop is not None:
|
461 |
+
# hidden_states = self.drop(hidden_states)
|
462 |
+
|
463 |
+
# return hidden_states
|
464 |
+
|
465 |
+
|
466 |
+
class Phi4MMAudioEmbedding(nn.Module):
|
467 |
+
"""Audio embedding."""
|
468 |
+
|
469 |
+
def __init__(self, config: PretrainedConfig, **kwargs) -> None:
|
470 |
+
super().__init__()
|
471 |
+
self.config = config
|
472 |
+
# n_embed or hidden_size for text LM
|
473 |
+
hidden_size = config.n_embd if hasattr(config, 'n_embd') else config.hidden_size
|
474 |
+
|
475 |
+
if hasattr(config, 'embd_pdrop') or hasattr(config, 'embed_pdrop'):
|
476 |
+
embd_drop = config.embd_pdrop if hasattr(config, 'embd_pdrop') else config.embed_pdrop
|
477 |
+
self.drop = nn.Dropout(embd_drop)
|
478 |
+
else:
|
479 |
+
self.drop = None
|
480 |
+
|
481 |
+
audio_dim_out = None # Set this variable according to the actual audio processor
|
482 |
+
logger.info(f"create audio processor {config.audio_processor}")
|
483 |
+
self.layer_idx = -2
|
484 |
+
|
485 |
+
if isinstance(config.audio_processor, dict) and config.audio_processor.get('name', None) == "cascades":
|
486 |
+
encoder_config = config.audio_processor.get("config", None)
|
487 |
+
assert encoder_config is not None
|
488 |
+
self.encoder = ConformerEncoder(**encoder_config)
|
489 |
+
|
490 |
+
# fake initialization, create encoder_embedding layer only so that
|
491 |
+
# in decoding, all parameters can be loaded in from_pretrained_function
|
492 |
+
# in training, we do post init after from_pretrained function to make sure the correct initialization
|
493 |
+
self.encoder.post_init({})
|
494 |
+
|
495 |
+
audio_dim_out = encoder_config["attention_dim"]
|
496 |
+
n_mels = encoder_config["input_size"]
|
497 |
+
else:
|
498 |
+
raise NotImplementedError
|
499 |
+
|
500 |
+
assert audio_dim_out is not None, "Remember to set values for audio_dim_out"
|
501 |
+
self.audio_dim_out = audio_dim_out
|
502 |
+
self.audio_dim_in = n_mels
|
503 |
+
|
504 |
+
self.freeze_audio_processor = kwargs.get('freeze_audio_processor', False)
|
505 |
+
logger.info(f'freeze_audio_processor = {self.freeze_audio_processor}')
|
506 |
+
|
507 |
+
self.downsample_rate = kwargs.get('downsample_rate', 1)
|
508 |
+
|
509 |
+
enable_gradient_checkpointing = kwargs.get('enable_gradient_checkpointing', False)
|
510 |
+
if enable_gradient_checkpointing:
|
511 |
+
self.encoder.gradient_checkpointing_enable()
|
512 |
+
logger.info(f'gradient checkpointing enabled for audio processor')
|
513 |
+
|
514 |
+
projection_cls = kwargs.get('projection_cls', 'linear')
|
515 |
+
if projection_cls == 'linear':
|
516 |
+
self.audio_projection = nn.Linear(audio_dim_out, hidden_size)
|
517 |
+
elif projection_cls == 'mlp':
|
518 |
+
# follow llava-v1.5's implementation
|
519 |
+
# (do not use image_projection and image_proj_norm)
|
520 |
+
dim_projection = hidden_size
|
521 |
+
depth = 2
|
522 |
+
self.linear_downsample_rate = self.downsample_rate
|
523 |
+
|
524 |
+
layers_for_speech = [nn.Linear(audio_dim_out * self.linear_downsample_rate, dim_projection)]
|
525 |
+
for _ in range(1, depth):
|
526 |
+
layers_for_speech.extend([nn.GELU(), nn.Linear(dim_projection, dim_projection)])
|
527 |
+
audio_projection_for_speech = nn.Sequential(*layers_for_speech)
|
528 |
+
|
529 |
+
layers_for_vision = [nn.Linear(audio_dim_out * self.linear_downsample_rate, dim_projection)]
|
530 |
+
for _ in range(1, depth):
|
531 |
+
layers_for_vision.extend([nn.GELU(), nn.Linear(dim_projection, dim_projection)])
|
532 |
+
# audio_projection_for_vision = nn.Sequential(*layers_for_vision)
|
533 |
+
|
534 |
+
self.audio_projection = nn.ModuleDict({
|
535 |
+
'speech': audio_projection_for_speech #,
|
536 |
+
# 'vision': audio_projection_for_vision
|
537 |
+
})
|
538 |
+
else:
|
539 |
+
raise NotImplementedError(f'projection_cls = {projection_cls}, not implemented')
|
540 |
+
|
541 |
+
self.vocab_size = config.vocab_size
|
542 |
+
self.input_embeds = None
|
543 |
+
self.audio_embed_sizes = None
|
544 |
+
|
545 |
+
def post_init(self, audio_config):
|
546 |
+
# execute after the from_pretrained() initialization of the phi4mm model
|
547 |
+
if audio_config.get('name', None) == "cascades":
|
548 |
+
init_model_config = audio_config.get("init_model", {})
|
549 |
+
self.encoder.post_init(init_model_config)
|
550 |
+
# remove the init model in config so it is not saved in the config.
|
551 |
+
# This might affect the model loading in resuming training and decoding.
|
552 |
+
if "init_model" in audio_config:
|
553 |
+
audio_config.pop("init_model")
|
554 |
+
|
555 |
+
def set_audio_embeds(self, input_embeds: torch.FloatTensor) -> None:
|
556 |
+
self.input_embeds = input_embeds
|
557 |
+
|
558 |
+
def set_audio_embed_sizes(self, audio_embed_sizes: torch.LongTensor) -> None:
|
559 |
+
self.audio_embed_sizes = audio_embed_sizes
|
560 |
+
|
561 |
+
def get_audio_features(self, input_embeds: torch.FloatTensor, audio_attention_mask: torch.Tensor, audio_projection_mode: str='speech'):
|
562 |
+
|
563 |
+
if self.freeze_audio_processor:
|
564 |
+
with torch.no_grad():
|
565 |
+
audio_features, masks = self.encoder(input_embeds, audio_attention_mask)
|
566 |
+
else:
|
567 |
+
audio_features, masks = self.encoder(input_embeds, audio_attention_mask)
|
568 |
+
|
569 |
+
if isinstance(self.audio_projection, nn.Sequential):
|
570 |
+
audio_set_tensor = self.audio_projection(audio_features)
|
571 |
+
elif isinstance(self.audio_projection, nn.ModuleDict):
|
572 |
+
audio_set_tensor = self.audio_projection[audio_projection_mode](audio_features)
|
573 |
+
else:
|
574 |
+
raise NotImplementedError
|
575 |
+
|
576 |
+
return audio_set_tensor
|
577 |
+
|
578 |
+
def forward(self, input_ids: torch.LongTensor, input_embeds: torch.FloatTensor, audio_embed_sizes=None, audio_attention_mask=None, audio_projection_mode='speech', **kwargs) -> torch.FloatTensor:
|
579 |
+
'''
|
580 |
+
arguments:
|
581 |
+
input_ids: input text ids (B, U)
|
582 |
+
input_embeds: audio features (B, T, D) B: num audios in a sequence
|
583 |
+
'''
|
584 |
+
|
585 |
+
if self.input_embeds is not None:
|
586 |
+
input_embeds = self.input_embeds.clone()
|
587 |
+
if self.audio_embed_sizes is not None:
|
588 |
+
audio_embed_sizes = self.audio_embed_sizes.clone()
|
589 |
+
|
590 |
+
input_shape = input_ids.size()
|
591 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
592 |
+
MAX_INPUT_ID = int(1e9)
|
593 |
+
|
594 |
+
with torch.no_grad():
|
595 |
+
positions = torch.nonzero(input_ids == _AUDIO_SPECIAL_TOKEN_ID, as_tuple=False)
|
596 |
+
positions_tuple = torch.nonzero(input_ids == _AUDIO_SPECIAL_TOKEN_ID, as_tuple=True)
|
597 |
+
|
598 |
+
if isinstance(self.audio_projection, nn.Sequential):
|
599 |
+
target_device = self.audio_projection[0].bias.device
|
600 |
+
target_dtype = self.audio_projection[0].bias.dtype
|
601 |
+
elif isinstance(self.audio_projection, nn.ModuleDict):
|
602 |
+
target_device = self.audio_projection[audio_projection_mode][0].bias.device
|
603 |
+
target_dtype = self.audio_projection[audio_projection_mode][0].bias.dtype
|
604 |
+
else: # It's a single nn.Linear layer
|
605 |
+
target_device = self.audio_projection.bias.device
|
606 |
+
target_dtype = self.audio_projection.bias.dtype
|
607 |
+
|
608 |
+
if input_embeds is not None:
|
609 |
+
input_embeds = input_embeds.to(target_device).to(target_dtype)
|
610 |
+
|
611 |
+
|
612 |
+
|
613 |
+
if len(positions.tolist()) > 0:
|
614 |
+
audio_set_tensor = self.get_audio_features(input_embeds, audio_attention_mask, audio_projection_mode)
|
615 |
+
else:
|
616 |
+
# # create an audio tensor
|
617 |
+
# To do: not sure if this is required for text only input
|
618 |
+
if self.training:
|
619 |
+
audio_embeds = torch.zeros(1, 500, self.audio_dim_in).to(target_device).to(target_dtype)
|
620 |
+
audio_attention_mask = audio_embeds.new_ones(audio_embeds.size()[:2]).long()
|
621 |
+
audio_set_tensor = self.get_audio_features(audio_embeds, audio_attention_mask, audio_projection_mode)
|
622 |
+
|
623 |
+
# print(kwargs['wte'])
|
624 |
+
# print(input_ids)
|
625 |
+
# print(kwargs['wte'](input_ids))
|
626 |
+
# print(audio_embed_sizes)
|
627 |
+
# print(len(positions.tolist()))
|
628 |
+
# print(audio_set_tensor)
|
629 |
+
# print(pppp)
|
630 |
+
|
631 |
+
hidden_states = kwargs['wte'](input_ids)
|
632 |
+
|
633 |
+
|
634 |
+
if len(positions.tolist()) > 0:
|
635 |
+
|
636 |
+
assert audio_embed_sizes.sum().item() == len(positions), \
|
637 |
+
f"please ensure the encoder outputs have the same length as defined in input_ids! \n audio_embed_sizes.sum().item(): {audio_embed_sizes.sum().item()} \n len(positions): {len(positions)} \n audio_embed_sizes: {audio_embed_sizes} \n positions: {positions} \n input_ids.shape \n {input_ids.shape}"
|
638 |
+
|
639 |
+
# new implementation without in-place operation
|
640 |
+
# Ref: https://huggingface.co/microsoft/Phi-3.5-vision-instruct/blob/4a0d683eba9f1d0cbfb6151705d1ee73c25a80ca/modeling_phi3_v.py#L233
|
641 |
+
# Ref: https://pytorch.org/docs/stable/generated/torch.Tensor.index_put.html
|
642 |
+
# Ref: https://pytorch.org/docs/stable/generated/torch.Tensor.index_put_.html#torch.Tensor.index_put_
|
643 |
+
# audio_set_tensor: shape (N_audios, N_padded_tokens, C)
|
644 |
+
# Shape: (merged_N_tokens, C)
|
645 |
+
|
646 |
+
|
647 |
+
|
648 |
+
merged_audio_set_tensor = torch.cat([
|
649 |
+
audio_set_tensor[i, :audio_embed_sizes[i], :]
|
650 |
+
for i in range(len(audio_embed_sizes))
|
651 |
+
], dim=0)
|
652 |
+
merged_audio_set_tensor = merged_audio_set_tensor.to(hidden_states.dtype).to(hidden_states.device)
|
653 |
+
# Temporarily disable autocast to avoid issue on bf16 tensors
|
654 |
+
# Ref: https://github.com/pytorch/pytorch/issues/132715
|
655 |
+
with torch.autocast(device_type=hidden_states.device.type, enabled=False):
|
656 |
+
new_hidden_states = hidden_states.index_put(
|
657 |
+
indices=positions_tuple,
|
658 |
+
values=merged_audio_set_tensor,
|
659 |
+
accumulate=False
|
660 |
+
)
|
661 |
+
hidden_states = new_hidden_states
|
662 |
+
else:
|
663 |
+
if self.training:
|
664 |
+
hidden_states = hidden_states + (0 * audio_set_tensor[:,0].to(hidden_states.dtype).to(hidden_states.device)).sum()
|
665 |
+
|
666 |
+
if self.drop is not None:
|
667 |
+
hidden_states = self.drop(hidden_states)
|
668 |
+
|
669 |
+
return hidden_states
|
670 |
+
|
671 |
+
|
672 |
+
|
673 |
+
class Phi4MMImageAudioEmbedding(nn.Module):
|
674 |
+
"""Image-audio embedding."""
|
675 |
+
|
676 |
+
def __init__(self, config: PretrainedConfig, **kwargs) -> None:
|
677 |
+
super().__init__()
|
678 |
+
|
679 |
+
self.vocab_size = config.vocab_size
|
680 |
+
|
681 |
+
# self.image_input_id = kwargs.get('image_input_id', -1)
|
682 |
+
self.audio_input_id = kwargs.get('audio_input_id', -10000)
|
683 |
+
# assert self.image_input_id != self.audio_input_id, 'image_input_id and audio_input_id should be different'
|
684 |
+
|
685 |
+
|
686 |
+
# self.image_embd_layer_kwargs = kwargs['image_embd_layer']
|
687 |
+
# self.image_embed = Phi4MMImageEmbedding(config, **self.image_embd_layer_kwargs)
|
688 |
+
self.audio_embd_layer_kwargs = kwargs['audio_embd_layer']
|
689 |
+
self.audio_embed = Phi4MMAudioEmbedding(config, **self.audio_embd_layer_kwargs)
|
690 |
+
|
691 |
+
# self.input_image_embeds = None
|
692 |
+
# self.image_sizes = None
|
693 |
+
# self.image_attention_mask = None
|
694 |
+
self.input_audio_embeds = None
|
695 |
+
self.audio_embed_sizes = None
|
696 |
+
|
697 |
+
def post_init(self, audio_config):
|
698 |
+
# post init for audio embedding
|
699 |
+
# ref: model.model.embed_tokens_extend.post_init(audio_config) in phyagi/getters/model.py
|
700 |
+
self.audio_embed.post_init(audio_config)
|
701 |
+
|
702 |
+
# def set_input_image_embeds(self, input_image_embeds: torch.FloatTensor) -> None:
|
703 |
+
# self.input_image_embeds = input_image_embeds
|
704 |
+
|
705 |
+
# def set_image_sizes(self, image_sizes: torch.LongTensor) -> None:
|
706 |
+
# self.image_sizes = image_sizes
|
707 |
+
|
708 |
+
# def set_img_attn_mask(self, image_attention_mask: torch.FloatTensor) -> None:
|
709 |
+
# self.image_attention_mask = image_attention_mask
|
710 |
+
|
711 |
+
def set_input_audio_embeds(self, input_audio_embeds: torch.FloatTensor) -> None:
|
712 |
+
self.input_audio_embeds = input_audio_embeds
|
713 |
+
|
714 |
+
def set_audio_embed_sizes(self, audio_embed_sizes: torch.LongTensor) -> None:
|
715 |
+
self.audio_embed_sizes = audio_embed_sizes
|
716 |
+
|
717 |
+
def forward(
|
718 |
+
self,
|
719 |
+
input_ids: torch.LongTensor,
|
720 |
+
input_embeds,
|
721 |
+
input_image_embeds: Optional[torch.FloatTensor]=None,
|
722 |
+
input_audio_embeds: Optional[torch.FloatTensor]=None,
|
723 |
+
image_sizes=None,
|
724 |
+
image_attention_mask=None,
|
725 |
+
audio_embed_sizes=None,
|
726 |
+
audio_attention_mask=None,
|
727 |
+
audio_projection_mode='speech',
|
728 |
+
wte=None,
|
729 |
+
) -> torch.FloatTensor:
|
730 |
+
|
731 |
+
MAX_INPUT_ID = int(1e9)
|
732 |
+
assert -MAX_INPUT_ID < self.audio_input_id #< self.image_input_id
|
733 |
+
|
734 |
+
# override image and audio embeddings and sizes from object itself
|
735 |
+
# this is for inference
|
736 |
+
# ref: phyagi/eval/utils/text_generation_vision_audio_pipeline.py
|
737 |
+
# if self.input_image_embeds is not None:
|
738 |
+
# assert input_image_embeds is None
|
739 |
+
# input_image_embeds = self.input_image_embeds.clone()
|
740 |
+
# # NOTE weijian: set input_image_embeds to None after first call in for eval stage
|
741 |
+
# # during evaluation, it will call model's forward() multiple times
|
742 |
+
# # the first time input_ids contains the prompt (including <|image_{}|>) and input_embeds exists
|
743 |
+
# # from the second time, the input_ids will only contain the generated text
|
744 |
+
# # thus, the input_image_embeds is no longer needed
|
745 |
+
# self.input_image_embeds = None
|
746 |
+
|
747 |
+
# if self.image_sizes is not None:
|
748 |
+
# assert image_sizes is None
|
749 |
+
# image_sizes = self.image_sizes
|
750 |
+
|
751 |
+
if self.input_audio_embeds is not None:
|
752 |
+
assert input_audio_embeds is None
|
753 |
+
input_audio_embeds = self.input_audio_embeds.clone()
|
754 |
+
self.input_audio_embeds = None
|
755 |
+
|
756 |
+
if self.audio_embed_sizes is not None:
|
757 |
+
assert audio_embed_sizes is None
|
758 |
+
audio_embed_sizes = self.audio_embed_sizes.clone()
|
759 |
+
|
760 |
+
# if self.image_attention_mask is not None:
|
761 |
+
# assert image_attention_mask is None
|
762 |
+
# image_attention_mask = self.image_attention_mask.clone()
|
763 |
+
# self.image_attention_mask = None
|
764 |
+
|
765 |
+
input_shape = input_ids.size()
|
766 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
767 |
+
|
768 |
+
# backward compatibility
|
769 |
+
with torch.no_grad():
|
770 |
+
new_input_ids = input_ids.clone()
|
771 |
+
# new_input_ids[(input_ids >= _COMPATIBLE_IMAGE_SPECIAL_TOKEN_ID_RANGE[0]) &
|
772 |
+
# (input_ids <= _COMPATIBLE_IMAGE_SPECIAL_TOKEN_ID_RANGE[1])] = _IMAGE_SPECIAL_TOKEN_ID
|
773 |
+
new_input_ids[(input_ids >= _COMPATIBLE_AUDIO_SPECIAL_TOKEN_ID_RANGE[0]) &
|
774 |
+
(input_ids <= _COMPATIBLE_AUDIO_SPECIAL_TOKEN_ID_RANGE[1])] = _AUDIO_SPECIAL_TOKEN_ID
|
775 |
+
input_ids = new_input_ids
|
776 |
+
|
777 |
+
# with torch.no_grad():
|
778 |
+
# image_position_mask = input_ids == _IMAGE_SPECIAL_TOKEN_ID
|
779 |
+
# non_image_position_mask = ~image_position_mask
|
780 |
+
|
781 |
+
assert input_embeds is None
|
782 |
+
# if self.training:
|
783 |
+
# assert input_image_embeds is not None or input_audio_embeds is not None
|
784 |
+
if self.training:
|
785 |
+
assert input_audio_embeds is not None
|
786 |
+
|
787 |
+
# if input_image_embeds is not None:
|
788 |
+
# image_hidden_states = self.image_embed(
|
789 |
+
# input_ids=input_ids,
|
790 |
+
# input_embeds=input_image_embeds,
|
791 |
+
# image_sizes=image_sizes,
|
792 |
+
# wte=wte,
|
793 |
+
# image_attention_mask=image_attention_mask
|
794 |
+
# )
|
795 |
+
|
796 |
+
|
797 |
+
if input_audio_embeds is not None:
|
798 |
+
audio_hidden_states = self.audio_embed(
|
799 |
+
input_ids=input_ids,
|
800 |
+
input_embeds=input_audio_embeds,
|
801 |
+
audio_embed_sizes=audio_embed_sizes,
|
802 |
+
audio_attention_mask=audio_attention_mask,
|
803 |
+
wte=wte,
|
804 |
+
audio_projection_mode=audio_projection_mode,
|
805 |
+
)
|
806 |
+
|
807 |
+
# merge image and audio hidden states
|
808 |
+
# NOTE weijian: for non-image-audio tokens, here we use audio hidden states
|
809 |
+
# actually, in the debug code above, the non-image-audio tokens from image_hidden_states and audio_hidden_states should be the same
|
810 |
+
# if input_image_embeds is not None and input_audio_embeds is not None:
|
811 |
+
# dtype = image_hidden_states.dtype
|
812 |
+
# hidden_states = image_hidden_states * image_position_mask.to(dtype).unsqueeze(-1) + audio_hidden_states * non_image_position_mask.to(dtype).unsqueeze(-1)
|
813 |
+
# elif input_image_embeds is not None:
|
814 |
+
# hidden_states = image_hidden_states
|
815 |
+
# elif input_audio_embeds is not None:
|
816 |
+
if input_audio_embeds is not None:
|
817 |
+
hidden_states = audio_hidden_states
|
818 |
+
else:
|
819 |
+
assert wte is not None
|
820 |
+
hidden_states = wte(input_ids)
|
821 |
+
|
822 |
+
return hidden_states
|
823 |
+
|
824 |
+
|
825 |
+
########################################################################################################################
|
826 |
+
|
827 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
828 |
+
# This file was automatically generated from src/transformers/models/qwen2/modular_qwen2.py.
|
829 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
830 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
831 |
+
# modular_qwen2.py file directly. One of our CI enforces this.
|
832 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
833 |
+
from typing import Callable, List, Optional, Tuple, Union
|
834 |
+
|
835 |
+
import torch
|
836 |
+
from torch import nn
|
837 |
+
|
838 |
+
from transformers.activations import ACT2FN
|
839 |
+
from transformers.cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
|
840 |
+
from transformers.generation import GenerationMixin
|
841 |
+
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
842 |
+
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
|
843 |
+
from transformers.modeling_outputs import (
|
844 |
+
BaseModelOutputWithPast,
|
845 |
+
CausalLMOutputWithPast,
|
846 |
+
QuestionAnsweringModelOutput,
|
847 |
+
SequenceClassifierOutputWithPast,
|
848 |
+
TokenClassifierOutput,
|
849 |
+
)
|
850 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
851 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
852 |
+
from transformers.processing_utils import Unpack
|
853 |
+
from transformers.utils import (
|
854 |
+
LossKwargs,
|
855 |
+
add_code_sample_docstrings,
|
856 |
+
add_start_docstrings,
|
857 |
+
add_start_docstrings_to_model_forward,
|
858 |
+
logging,
|
859 |
+
replace_return_docstrings,
|
860 |
+
)
|
861 |
+
from transformers.utils.deprecation import deprecate_kwarg
|
862 |
+
from .configuration_qwen2mm import Qwen2MMConfig
|
863 |
+
|
864 |
+
|
865 |
+
####################################################################
|
866 |
+
|
867 |
+
|
868 |
+
logger = logging.get_logger(__name__)
|
869 |
+
|
870 |
+
_CHECKPOINT_FOR_DOC = "meta-qwen2/Qwen2-2-7b-hf"
|
871 |
+
_CONFIG_FOR_DOC = "Qwen2MMConfig"
|
872 |
+
|
873 |
+
|
874 |
+
class Qwen2MLP(nn.Module):
|
875 |
+
def __init__(self, config):
|
876 |
+
super().__init__()
|
877 |
+
self.config = config
|
878 |
+
self.hidden_size = config.hidden_size
|
879 |
+
self.intermediate_size = config.intermediate_size
|
880 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
881 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
882 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
883 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
884 |
+
|
885 |
+
def forward(self, x):
|
886 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
887 |
+
return down_proj
|
888 |
+
|
889 |
+
|
890 |
+
def rotate_half(x):
|
891 |
+
"""Rotates half the hidden dims of the input."""
|
892 |
+
x1 = x[..., : x.shape[-1] // 2]
|
893 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
894 |
+
return torch.cat((-x2, x1), dim=-1)
|
895 |
+
|
896 |
+
|
897 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
898 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
899 |
+
|
900 |
+
Args:
|
901 |
+
q (`torch.Tensor`): The query tensor.
|
902 |
+
k (`torch.Tensor`): The key tensor.
|
903 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
904 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
905 |
+
position_ids (`torch.Tensor`, *optional*):
|
906 |
+
Deprecated and unused.
|
907 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
908 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
909 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
910 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
911 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
912 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
913 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
914 |
+
Returns:
|
915 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
916 |
+
"""
|
917 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
918 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
919 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
920 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
921 |
+
return q_embed, k_embed
|
922 |
+
|
923 |
+
|
924 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
925 |
+
"""
|
926 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
927 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
928 |
+
"""
|
929 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
930 |
+
if n_rep == 1:
|
931 |
+
return hidden_states
|
932 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
933 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
934 |
+
|
935 |
+
|
936 |
+
def eager_attention_forward(
|
937 |
+
module: nn.Module,
|
938 |
+
query: torch.Tensor,
|
939 |
+
key: torch.Tensor,
|
940 |
+
value: torch.Tensor,
|
941 |
+
attention_mask: Optional[torch.Tensor],
|
942 |
+
scaling: float,
|
943 |
+
dropout: float = 0.0,
|
944 |
+
**kwargs,
|
945 |
+
):
|
946 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
947 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
948 |
+
|
949 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
950 |
+
if attention_mask is not None:
|
951 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
952 |
+
attn_weights = attn_weights + causal_mask
|
953 |
+
|
954 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
955 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
956 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
957 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
958 |
+
|
959 |
+
return attn_output, attn_weights
|
960 |
+
|
961 |
+
|
962 |
+
class Qwen2Attention(nn.Module):
|
963 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
964 |
+
|
965 |
+
def __init__(self, config: Qwen2MMConfig, layer_idx: int):
|
966 |
+
super().__init__()
|
967 |
+
self.config = config
|
968 |
+
self.layer_idx = layer_idx
|
969 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
970 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
971 |
+
self.scaling = self.head_dim**-0.5
|
972 |
+
self.attention_dropout = config.attention_dropout
|
973 |
+
self.is_causal = True
|
974 |
+
self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)
|
975 |
+
self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
|
976 |
+
self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
|
977 |
+
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
|
978 |
+
|
979 |
+
def forward(
|
980 |
+
self,
|
981 |
+
hidden_states: torch.Tensor,
|
982 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
983 |
+
attention_mask: Optional[torch.Tensor],
|
984 |
+
past_key_value: Optional[Cache] = None,
|
985 |
+
cache_position: Optional[torch.LongTensor] = None,
|
986 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
987 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
988 |
+
input_shape = hidden_states.shape[:-1]
|
989 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
990 |
+
|
991 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
992 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
993 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
994 |
+
|
995 |
+
cos, sin = position_embeddings
|
996 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
997 |
+
|
998 |
+
if past_key_value is not None:
|
999 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
1000 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
1001 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
1002 |
+
|
1003 |
+
sliding_window = None
|
1004 |
+
if (
|
1005 |
+
self.config.use_sliding_window
|
1006 |
+
and getattr(self.config, "sliding_window", None) is not None
|
1007 |
+
and self.layer_idx >= self.config.max_window_layers
|
1008 |
+
):
|
1009 |
+
sliding_window = self.config.sliding_window
|
1010 |
+
|
1011 |
+
attention_interface: Callable = eager_attention_forward
|
1012 |
+
if self.config._attn_implementation != "eager":
|
1013 |
+
if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
|
1014 |
+
logger.warning_once(
|
1015 |
+
"`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
|
1016 |
+
'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
1017 |
+
)
|
1018 |
+
else:
|
1019 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
1020 |
+
|
1021 |
+
attn_output, attn_weights = attention_interface(
|
1022 |
+
self,
|
1023 |
+
query_states,
|
1024 |
+
key_states,
|
1025 |
+
value_states,
|
1026 |
+
attention_mask,
|
1027 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
1028 |
+
scaling=self.scaling,
|
1029 |
+
sliding_window=sliding_window, # main diff with Llama
|
1030 |
+
**kwargs,
|
1031 |
+
)
|
1032 |
+
|
1033 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
1034 |
+
attn_output = self.o_proj(attn_output)
|
1035 |
+
return attn_output, attn_weights
|
1036 |
+
|
1037 |
+
|
1038 |
+
class Qwen2RMSNorm(nn.Module):
|
1039 |
+
def __init__(self, hidden_size, eps=1e-6):
|
1040 |
+
"""
|
1041 |
+
Qwen2RMSNorm is equivalent to T5LayerNorm
|
1042 |
+
"""
|
1043 |
+
super().__init__()
|
1044 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
1045 |
+
self.variance_epsilon = eps
|
1046 |
+
|
1047 |
+
def forward(self, hidden_states):
|
1048 |
+
input_dtype = hidden_states.dtype
|
1049 |
+
hidden_states = hidden_states.to(torch.float32)
|
1050 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
1051 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
1052 |
+
return self.weight * hidden_states.to(input_dtype)
|
1053 |
+
|
1054 |
+
def extra_repr(self):
|
1055 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
1056 |
+
|
1057 |
+
|
1058 |
+
class Qwen2DecoderLayer(nn.Module):
|
1059 |
+
def __init__(self, config: Qwen2MMConfig, layer_idx: int):
|
1060 |
+
super().__init__()
|
1061 |
+
self.hidden_size = config.hidden_size
|
1062 |
+
self.self_attn = Qwen2Attention(config=config, layer_idx=layer_idx)
|
1063 |
+
self.mlp = Qwen2MLP(config)
|
1064 |
+
self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
1065 |
+
self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
1066 |
+
if config.sliding_window and config._attn_implementation != "flash_attention_2":
|
1067 |
+
logger.warning_once(
|
1068 |
+
f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
|
1069 |
+
"unexpected results may be encountered."
|
1070 |
+
)
|
1071 |
+
|
1072 |
+
def forward(
|
1073 |
+
self,
|
1074 |
+
hidden_states: torch.Tensor,
|
1075 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1076 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1077 |
+
past_key_value: Optional[Cache] = None,
|
1078 |
+
output_attentions: Optional[bool] = False,
|
1079 |
+
use_cache: Optional[bool] = False,
|
1080 |
+
cache_position: Optional[torch.LongTensor] = None,
|
1081 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
|
1082 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
1083 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
1084 |
+
residual = hidden_states
|
1085 |
+
|
1086 |
+
hidden_states = self.input_layernorm(hidden_states)
|
1087 |
+
|
1088 |
+
# Self Attention
|
1089 |
+
hidden_states, self_attn_weights = self.self_attn(
|
1090 |
+
hidden_states=hidden_states,
|
1091 |
+
attention_mask=attention_mask,
|
1092 |
+
position_ids=position_ids,
|
1093 |
+
past_key_value=past_key_value,
|
1094 |
+
output_attentions=output_attentions,
|
1095 |
+
use_cache=use_cache,
|
1096 |
+
cache_position=cache_position,
|
1097 |
+
position_embeddings=position_embeddings,
|
1098 |
+
**kwargs,
|
1099 |
+
)
|
1100 |
+
hidden_states = residual + hidden_states
|
1101 |
+
|
1102 |
+
# Fully Connected
|
1103 |
+
residual = hidden_states
|
1104 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
1105 |
+
hidden_states = self.mlp(hidden_states)
|
1106 |
+
hidden_states = residual + hidden_states
|
1107 |
+
|
1108 |
+
outputs = (hidden_states,)
|
1109 |
+
if output_attentions:
|
1110 |
+
outputs += (self_attn_weights,)
|
1111 |
+
|
1112 |
+
return outputs
|
1113 |
+
|
1114 |
+
|
1115 |
+
class Qwen2RotaryEmbedding(nn.Module):
|
1116 |
+
def __init__(self, config: Qwen2MMConfig, device=None):
|
1117 |
+
super().__init__()
|
1118 |
+
# BC: "rope_type" was originally "type"
|
1119 |
+
if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
|
1120 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
1121 |
+
else:
|
1122 |
+
self.rope_type = "default"
|
1123 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
1124 |
+
self.original_max_seq_len = config.max_position_embeddings
|
1125 |
+
|
1126 |
+
self.config = config
|
1127 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
1128 |
+
|
1129 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
1130 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
1131 |
+
self.original_inv_freq = self.inv_freq
|
1132 |
+
|
1133 |
+
def _dynamic_frequency_update(self, position_ids, device):
|
1134 |
+
"""
|
1135 |
+
dynamic RoPE layers should recompute `inv_freq` in the following situations:
|
1136 |
+
1 - growing beyond the cached sequence length (allow scaling)
|
1137 |
+
2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
|
1138 |
+
"""
|
1139 |
+
seq_len = torch.max(position_ids) + 1
|
1140 |
+
if seq_len > self.max_seq_len_cached: # growth
|
1141 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
|
1142 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
|
1143 |
+
self.max_seq_len_cached = seq_len
|
1144 |
+
|
1145 |
+
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
|
1146 |
+
# This .to() is needed if the model has been moved to a device after being initialized (because
|
1147 |
+
# the buffer is automatically moved, but not the original copy)
|
1148 |
+
self.original_inv_freq = self.original_inv_freq.to(device)
|
1149 |
+
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
1150 |
+
self.max_seq_len_cached = self.original_max_seq_len
|
1151 |
+
|
1152 |
+
@torch.no_grad()
|
1153 |
+
def forward(self, x, position_ids):
|
1154 |
+
if "dynamic" in self.rope_type:
|
1155 |
+
self._dynamic_frequency_update(position_ids, device=x.device)
|
1156 |
+
|
1157 |
+
# Core RoPE block
|
1158 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
1159 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
1160 |
+
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
|
1161 |
+
device_type = x.device.type
|
1162 |
+
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
1163 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
1164 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
1165 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
1166 |
+
cos = emb.cos()
|
1167 |
+
sin = emb.sin()
|
1168 |
+
|
1169 |
+
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
|
1170 |
+
cos = cos * self.attention_scaling
|
1171 |
+
sin = sin * self.attention_scaling
|
1172 |
+
|
1173 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
1174 |
+
|
1175 |
+
|
1176 |
+
QWEN2_START_DOCSTRING = r"""
|
1177 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
1178 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
1179 |
+
etc.)
|
1180 |
+
|
1181 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
1182 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
1183 |
+
and behavior.
|
1184 |
+
|
1185 |
+
Parameters:
|
1186 |
+
config ([`Qwen2MMConfig`]):
|
1187 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
1188 |
+
load the weights associated with the model, only the configuration. Check out the
|
1189 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
1190 |
+
"""
|
1191 |
+
|
1192 |
+
|
1193 |
+
@add_start_docstrings(
|
1194 |
+
"The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
|
1195 |
+
QWEN2_START_DOCSTRING,
|
1196 |
+
)
|
1197 |
+
class Qwen2PreTrainedModel(PreTrainedModel):
|
1198 |
+
config_class = Qwen2MMConfig
|
1199 |
+
base_model_prefix = "model"
|
1200 |
+
supports_gradient_checkpointing = True
|
1201 |
+
_no_split_modules = ["Qwen2DecoderLayer"]
|
1202 |
+
_skip_keys_device_placement = ["past_key_values"]
|
1203 |
+
_supports_flash_attn_2 = True
|
1204 |
+
_supports_sdpa = True
|
1205 |
+
_supports_flex_attn = True
|
1206 |
+
_supports_cache_class = True
|
1207 |
+
_supports_quantized_cache = True
|
1208 |
+
_supports_static_cache = True
|
1209 |
+
_supports_attention_backend = True
|
1210 |
+
|
1211 |
+
def _init_weights(self, module):
|
1212 |
+
std = self.config.initializer_range
|
1213 |
+
if isinstance(module, nn.Linear):
|
1214 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
1215 |
+
if module.bias is not None:
|
1216 |
+
module.bias.data.zero_()
|
1217 |
+
elif isinstance(module, nn.Embedding):
|
1218 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
1219 |
+
if module.padding_idx is not None:
|
1220 |
+
module.weight.data[module.padding_idx].zero_()
|
1221 |
+
|
1222 |
+
|
1223 |
+
QWEN2_INPUTS_DOCSTRING = r"""
|
1224 |
+
Args:
|
1225 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
1226 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
1227 |
+
it.
|
1228 |
+
|
1229 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
1230 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
1231 |
+
|
1232 |
+
[What are input IDs?](../glossary#input-ids)
|
1233 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1234 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
1235 |
+
|
1236 |
+
- 1 for tokens that are **not masked**,
|
1237 |
+
- 0 for tokens that are **masked**.
|
1238 |
+
|
1239 |
+
[What are attention masks?](../glossary#attention-mask)
|
1240 |
+
|
1241 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
1242 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
1243 |
+
|
1244 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
1245 |
+
`past_key_values`).
|
1246 |
+
|
1247 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
1248 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
1249 |
+
information on the default strategy.
|
1250 |
+
|
1251 |
+
- 1 indicates the head is **not masked**,
|
1252 |
+
- 0 indicates the head is **masked**.
|
1253 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1254 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
1255 |
+
config.n_positions - 1]`.
|
1256 |
+
|
1257 |
+
[What are position IDs?](../glossary#position-ids)
|
1258 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
1259 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
1260 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
1261 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
1262 |
+
|
1263 |
+
Two formats are allowed:
|
1264 |
+
- a [`~cache_utils.Cache`] instance, see our
|
1265 |
+
[kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
|
1266 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
1267 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
1268 |
+
cache format.
|
1269 |
+
|
1270 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
1271 |
+
legacy cache format will be returned.
|
1272 |
+
|
1273 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
1274 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
1275 |
+
of shape `(batch_size, sequence_length)`.
|
1276 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
1277 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
1278 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
1279 |
+
model's internal embedding lookup matrix.
|
1280 |
+
use_cache (`bool`, *optional*):
|
1281 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
1282 |
+
`past_key_values`).
|
1283 |
+
output_attentions (`bool`, *optional*):
|
1284 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
1285 |
+
tensors for more detail.
|
1286 |
+
output_hidden_states (`bool`, *optional*):
|
1287 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
1288 |
+
more detail.
|
1289 |
+
return_dict (`bool`, *optional*):
|
1290 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
1291 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
1292 |
+
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
|
1293 |
+
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
|
1294 |
+
the complete sequence length.
|
1295 |
+
"""
|
1296 |
+
|
1297 |
+
|
1298 |
+
@add_start_docstrings(
|
1299 |
+
"The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
|
1300 |
+
QWEN2_START_DOCSTRING,
|
1301 |
+
)
|
1302 |
+
class Qwen2MMModel(Qwen2PreTrainedModel):
|
1303 |
+
"""
|
1304 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
|
1305 |
+
|
1306 |
+
Args:
|
1307 |
+
config: Qwen2MMConfig
|
1308 |
+
"""
|
1309 |
+
|
1310 |
+
def __init__(self, config: Qwen2MMConfig):
|
1311 |
+
super().__init__(config)
|
1312 |
+
self.padding_idx = config.pad_token_id
|
1313 |
+
self.vocab_size = config.vocab_size
|
1314 |
+
|
1315 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
1316 |
+
|
1317 |
+
######QWEN#################
|
1318 |
+
self.embed_tokens_extend = None
|
1319 |
+
if isinstance(config.embd_layer, dict):
|
1320 |
+
embedding_config = {
|
1321 |
+
'embedding_cls': config.embd_layer['embedding_cls'],
|
1322 |
+
**config.embd_layer
|
1323 |
+
}
|
1324 |
+
self.embed_tokens_extend = Phi4MMImageAudioEmbedding(config, **embedding_config)
|
1325 |
+
self._attn_implementation = config._attn_implementation
|
1326 |
+
############################
|
1327 |
+
|
1328 |
+
self.layers = nn.ModuleList(
|
1329 |
+
[Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
1330 |
+
)
|
1331 |
+
self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
1332 |
+
self.rotary_emb = Qwen2RotaryEmbedding(config=config)
|
1333 |
+
self.gradient_checkpointing = False
|
1334 |
+
|
1335 |
+
# Initialize weights and apply final processing
|
1336 |
+
self.post_init()
|
1337 |
+
|
1338 |
+
def get_input_embeddings(self):
|
1339 |
+
return self.embed_tokens
|
1340 |
+
|
1341 |
+
def set_input_embeddings(self, value):
|
1342 |
+
self.embed_tokens = value
|
1343 |
+
|
1344 |
+
@add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
|
1345 |
+
def forward(
|
1346 |
+
# self,
|
1347 |
+
# input_ids: torch.LongTensor = None,
|
1348 |
+
# attention_mask: Optional[torch.Tensor] = None,
|
1349 |
+
# position_ids: Optional[torch.LongTensor] = None,
|
1350 |
+
# past_key_values: Optional[Cache] = None,
|
1351 |
+
# inputs_embeds: Optional[torch.FloatTensor] = None,
|
1352 |
+
# use_cache: Optional[bool] = None,
|
1353 |
+
# output_attentions: Optional[bool] = None,
|
1354 |
+
# output_hidden_states: Optional[bool] = None,
|
1355 |
+
# return_dict: Optional[bool] = None,
|
1356 |
+
# cache_position: Optional[torch.LongTensor] = None,
|
1357 |
+
########QWEN############
|
1358 |
+
self,
|
1359 |
+
input_ids: torch.LongTensor = None,
|
1360 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1361 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1362 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1363 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1364 |
+
input_image_embeds: Optional[torch.FloatTensor] = None,
|
1365 |
+
image_sizes: Optional[torch.LongTensor] = None,
|
1366 |
+
image_attention_mask=None,
|
1367 |
+
input_audio_embeds: Optional[torch.FloatTensor] = None,
|
1368 |
+
audio_embed_sizes=None,
|
1369 |
+
audio_attention_mask=None,
|
1370 |
+
audio_projection_mode=None,
|
1371 |
+
use_cache: Optional[bool] = None,
|
1372 |
+
output_attentions: Optional[bool] = None,
|
1373 |
+
output_hidden_states: Optional[bool] = None,
|
1374 |
+
return_dict: Optional[bool] = None,
|
1375 |
+
cache_position: Optional[torch.LongTensor] = None,
|
1376 |
+
##########################
|
1377 |
+
**flash_attn_kwargs: Unpack[FlashAttentionKwargs],
|
1378 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
1379 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1380 |
+
output_hidden_states = (
|
1381 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1382 |
+
)
|
1383 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
1384 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1385 |
+
|
1386 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
1387 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
1388 |
+
|
1389 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
1390 |
+
logger.warning_once(
|
1391 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
1392 |
+
)
|
1393 |
+
use_cache = False
|
1394 |
+
|
1395 |
+
# if inputs_embeds is None:
|
1396 |
+
# inputs_embeds = self.embed_tokens(input_ids)
|
1397 |
+
|
1398 |
+
############QWEN###########
|
1399 |
+
if inputs_embeds is None:
|
1400 |
+
inputs_embeds = self.embed_tokens_extend(
|
1401 |
+
input_ids=input_ids,
|
1402 |
+
input_embeds=inputs_embeds,
|
1403 |
+
input_image_embeds=input_image_embeds,
|
1404 |
+
input_audio_embeds=input_audio_embeds,
|
1405 |
+
image_sizes=image_sizes,
|
1406 |
+
image_attention_mask=image_attention_mask,
|
1407 |
+
audio_embed_sizes=audio_embed_sizes,
|
1408 |
+
audio_attention_mask=audio_attention_mask,
|
1409 |
+
audio_projection_mode=audio_projection_mode,
|
1410 |
+
wte=self.embed_tokens,
|
1411 |
+
)
|
1412 |
+
###########################
|
1413 |
+
if use_cache and past_key_values is None:
|
1414 |
+
past_key_values = DynamicCache()
|
1415 |
+
|
1416 |
+
if cache_position is None:
|
1417 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
1418 |
+
cache_position = torch.arange(
|
1419 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
1420 |
+
)
|
1421 |
+
|
1422 |
+
if position_ids is None:
|
1423 |
+
position_ids = cache_position.unsqueeze(0)
|
1424 |
+
|
1425 |
+
causal_mask = self._update_causal_mask(
|
1426 |
+
attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
|
1427 |
+
)
|
1428 |
+
|
1429 |
+
hidden_states = inputs_embeds
|
1430 |
+
|
1431 |
+
# create position embeddings to be shared across the decoder layers
|
1432 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
1433 |
+
|
1434 |
+
# decoder layers
|
1435 |
+
all_hidden_states = () if output_hidden_states else None
|
1436 |
+
all_self_attns = () if output_attentions else None
|
1437 |
+
|
1438 |
+
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
|
1439 |
+
if output_hidden_states:
|
1440 |
+
all_hidden_states += (hidden_states,)
|
1441 |
+
|
1442 |
+
if self.gradient_checkpointing and self.training:
|
1443 |
+
layer_outputs = self._gradient_checkpointing_func(
|
1444 |
+
decoder_layer.__call__,
|
1445 |
+
hidden_states,
|
1446 |
+
causal_mask,
|
1447 |
+
position_ids,
|
1448 |
+
past_key_values,
|
1449 |
+
output_attentions,
|
1450 |
+
use_cache,
|
1451 |
+
cache_position,
|
1452 |
+
position_embeddings,
|
1453 |
+
)
|
1454 |
+
else:
|
1455 |
+
layer_outputs = decoder_layer(
|
1456 |
+
hidden_states,
|
1457 |
+
attention_mask=causal_mask,
|
1458 |
+
position_ids=position_ids,
|
1459 |
+
past_key_value=past_key_values,
|
1460 |
+
output_attentions=output_attentions,
|
1461 |
+
use_cache=use_cache,
|
1462 |
+
cache_position=cache_position,
|
1463 |
+
position_embeddings=position_embeddings,
|
1464 |
+
**flash_attn_kwargs,
|
1465 |
+
)
|
1466 |
+
|
1467 |
+
hidden_states = layer_outputs[0]
|
1468 |
+
|
1469 |
+
if output_attentions:
|
1470 |
+
all_self_attns += (layer_outputs[1],)
|
1471 |
+
|
1472 |
+
hidden_states = self.norm(hidden_states)
|
1473 |
+
|
1474 |
+
# add hidden states from the last decoder layer
|
1475 |
+
if output_hidden_states:
|
1476 |
+
all_hidden_states += (hidden_states,)
|
1477 |
+
|
1478 |
+
output = BaseModelOutputWithPast(
|
1479 |
+
last_hidden_state=hidden_states,
|
1480 |
+
past_key_values=past_key_values if use_cache else None,
|
1481 |
+
hidden_states=all_hidden_states,
|
1482 |
+
attentions=all_self_attns,
|
1483 |
+
)
|
1484 |
+
return output if return_dict else output.to_tuple()
|
1485 |
+
|
1486 |
+
def _update_causal_mask(
|
1487 |
+
self,
|
1488 |
+
attention_mask: torch.Tensor,
|
1489 |
+
input_tensor: torch.Tensor,
|
1490 |
+
cache_position: torch.Tensor,
|
1491 |
+
past_key_values: Cache,
|
1492 |
+
output_attentions: bool,
|
1493 |
+
):
|
1494 |
+
if self.config._attn_implementation == "flash_attention_2":
|
1495 |
+
if attention_mask is not None and past_key_values is not None:
|
1496 |
+
is_padding_right = attention_mask[:, -1].sum().item() != input_tensor.size()[0]
|
1497 |
+
if is_padding_right:
|
1498 |
+
raise ValueError(
|
1499 |
+
"You are attempting to perform batched generation with padding_side='right'"
|
1500 |
+
" this may lead to unexpected behaviour for Flash Attention version of Qwen2. Make sure to "
|
1501 |
+
" call `tokenizer.padding_side = 'left'` before tokenizing the input. "
|
1502 |
+
)
|
1503 |
+
if attention_mask is not None and 0.0 in attention_mask:
|
1504 |
+
return attention_mask
|
1505 |
+
return None
|
1506 |
+
|
1507 |
+
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
|
1508 |
+
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
|
1509 |
+
# to infer the attention mask.
|
1510 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
1511 |
+
using_static_cache = isinstance(past_key_values, StaticCache)
|
1512 |
+
using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache)
|
1513 |
+
|
1514 |
+
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
|
1515 |
+
if (
|
1516 |
+
self.config._attn_implementation == "sdpa"
|
1517 |
+
and not (using_static_cache or using_sliding_window_cache)
|
1518 |
+
and not output_attentions
|
1519 |
+
):
|
1520 |
+
if AttentionMaskConverter._ignore_causal_mask_sdpa(
|
1521 |
+
attention_mask,
|
1522 |
+
inputs_embeds=input_tensor,
|
1523 |
+
past_key_values_length=past_seen_tokens,
|
1524 |
+
sliding_window=self.config.sliding_window,
|
1525 |
+
is_training=self.training,
|
1526 |
+
):
|
1527 |
+
return None
|
1528 |
+
|
1529 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
1530 |
+
min_dtype = torch.finfo(dtype).min
|
1531 |
+
sequence_length = input_tensor.shape[1]
|
1532 |
+
# SlidingWindowCache or StaticCache
|
1533 |
+
if using_sliding_window_cache or using_static_cache:
|
1534 |
+
target_length = past_key_values.get_max_cache_shape()
|
1535 |
+
# DynamicCache or no cache
|
1536 |
+
else:
|
1537 |
+
target_length = (
|
1538 |
+
attention_mask.shape[-1]
|
1539 |
+
if isinstance(attention_mask, torch.Tensor)
|
1540 |
+
else past_seen_tokens + sequence_length + 1
|
1541 |
+
)
|
1542 |
+
|
1543 |
+
# In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
|
1544 |
+
causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
|
1545 |
+
attention_mask,
|
1546 |
+
sequence_length=sequence_length,
|
1547 |
+
target_length=target_length,
|
1548 |
+
dtype=dtype,
|
1549 |
+
device=device,
|
1550 |
+
cache_position=cache_position,
|
1551 |
+
batch_size=input_tensor.shape[0],
|
1552 |
+
config=self.config,
|
1553 |
+
past_key_values=past_key_values,
|
1554 |
+
)
|
1555 |
+
|
1556 |
+
if (
|
1557 |
+
self.config._attn_implementation == "sdpa"
|
1558 |
+
and attention_mask is not None
|
1559 |
+
and attention_mask.device.type in ["cuda", "xpu"]
|
1560 |
+
and not output_attentions
|
1561 |
+
):
|
1562 |
+
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
|
1563 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
1564 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
1565 |
+
causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
|
1566 |
+
|
1567 |
+
return causal_mask
|
1568 |
+
|
1569 |
+
@staticmethod
|
1570 |
+
def _prepare_4d_causal_attention_mask_with_cache_position(
|
1571 |
+
attention_mask: torch.Tensor,
|
1572 |
+
sequence_length: int,
|
1573 |
+
target_length: int,
|
1574 |
+
dtype: torch.dtype,
|
1575 |
+
device: torch.device,
|
1576 |
+
cache_position: torch.Tensor,
|
1577 |
+
batch_size: int,
|
1578 |
+
config: Qwen2MMConfig,
|
1579 |
+
past_key_values: Cache,
|
1580 |
+
):
|
1581 |
+
"""
|
1582 |
+
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
1583 |
+
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
|
1584 |
+
|
1585 |
+
Args:
|
1586 |
+
attention_mask (`torch.Tensor`):
|
1587 |
+
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)`.
|
1588 |
+
sequence_length (`int`):
|
1589 |
+
The sequence length being processed.
|
1590 |
+
target_length (`int`):
|
1591 |
+
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.
|
1592 |
+
dtype (`torch.dtype`):
|
1593 |
+
The dtype to use for the 4D attention mask.
|
1594 |
+
device (`torch.device`):
|
1595 |
+
The device to plcae the 4D attention mask on.
|
1596 |
+
cache_position (`torch.Tensor`):
|
1597 |
+
Indices depicting the position of the input sequence tokens in the sequence.
|
1598 |
+
batch_size (`torch.Tensor`):
|
1599 |
+
Batch size.
|
1600 |
+
config (`Qwen2MMConfig`):
|
1601 |
+
The model's configuration class
|
1602 |
+
past_key_values (`Cache`):
|
1603 |
+
The cache class that is being used currently to generate
|
1604 |
+
"""
|
1605 |
+
if attention_mask is not None and attention_mask.dim() == 4:
|
1606 |
+
# In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
|
1607 |
+
causal_mask = attention_mask
|
1608 |
+
else:
|
1609 |
+
min_dtype = torch.finfo(dtype).min
|
1610 |
+
causal_mask = torch.full(
|
1611 |
+
(sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
|
1612 |
+
)
|
1613 |
+
diagonal_attend_mask = torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
|
1614 |
+
if config.sliding_window is not None:
|
1615 |
+
# if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also
|
1616 |
+
# the check is needed to verify is current checkpoint was trained with sliding window or not
|
1617 |
+
if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length:
|
1618 |
+
sliding_attend_mask = torch.arange(target_length, device=device) <= (
|
1619 |
+
cache_position.reshape(-1, 1) - config.sliding_window
|
1620 |
+
)
|
1621 |
+
diagonal_attend_mask.bitwise_or_(sliding_attend_mask)
|
1622 |
+
causal_mask *= diagonal_attend_mask
|
1623 |
+
causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
|
1624 |
+
if attention_mask is not None:
|
1625 |
+
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
|
1626 |
+
if attention_mask.shape[-1] > target_length:
|
1627 |
+
attention_mask = attention_mask[:, :target_length]
|
1628 |
+
mask_length = attention_mask.shape[-1]
|
1629 |
+
padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
|
1630 |
+
causal_mask.device
|
1631 |
+
)
|
1632 |
+
padding_mask = padding_mask == 0
|
1633 |
+
causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
|
1634 |
+
padding_mask, min_dtype
|
1635 |
+
)
|
1636 |
+
return causal_mask
|
1637 |
+
|
1638 |
+
|
1639 |
+
class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
|
1640 |
+
|
1641 |
+
|
1642 |
+
class Qwen2MMForCausalLM(Qwen2PreTrainedModel, GenerationMixin):
|
1643 |
+
_tied_weights_keys = ["lm_head.weight"]
|
1644 |
+
_tp_plan = {"lm_head": "colwise_rep"}
|
1645 |
+
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
1646 |
+
|
1647 |
+
def __init__(self, config):
|
1648 |
+
super().__init__(config)
|
1649 |
+
self.model = Qwen2MMModel(config)
|
1650 |
+
self.vocab_size = config.vocab_size
|
1651 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
1652 |
+
|
1653 |
+
# Initialize weights and apply final processing
|
1654 |
+
self.post_init()
|
1655 |
+
|
1656 |
+
def get_input_embeddings(self):
|
1657 |
+
return self.model.embed_tokens
|
1658 |
+
|
1659 |
+
def set_input_embeddings(self, value):
|
1660 |
+
self.model.embed_tokens = value
|
1661 |
+
|
1662 |
+
def get_output_embeddings(self):
|
1663 |
+
return self.lm_head
|
1664 |
+
|
1665 |
+
def set_output_embeddings(self, new_embeddings):
|
1666 |
+
self.lm_head = new_embeddings
|
1667 |
+
|
1668 |
+
def set_decoder(self, decoder):
|
1669 |
+
self.model = decoder
|
1670 |
+
|
1671 |
+
def get_decoder(self):
|
1672 |
+
return self.model
|
1673 |
+
|
1674 |
+
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
1675 |
+
@add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
|
1676 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
1677 |
+
def forward(
|
1678 |
+
# self,
|
1679 |
+
# input_ids: torch.LongTensor = None,
|
1680 |
+
# attention_mask: Optional[torch.Tensor] = None,
|
1681 |
+
# position_ids: Optional[torch.LongTensor] = None,
|
1682 |
+
# past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
1683 |
+
# inputs_embeds: Optional[torch.FloatTensor] = None,
|
1684 |
+
# labels: Optional[torch.LongTensor] = None,
|
1685 |
+
# use_cache: Optional[bool] = None,
|
1686 |
+
# output_attentions: Optional[bool] = None,
|
1687 |
+
# output_hidden_states: Optional[bool] = None,
|
1688 |
+
# return_dict: Optional[bool] = None,
|
1689 |
+
# cache_position: Optional[torch.LongTensor] = None,
|
1690 |
+
# logits_to_keep: Union[int, torch.Tensor] = 0,
|
1691 |
+
######QWEN###############
|
1692 |
+
self,
|
1693 |
+
input_ids: torch.LongTensor = None,
|
1694 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1695 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1696 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1697 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1698 |
+
input_image_embeds: Optional[torch.FloatTensor] = None,
|
1699 |
+
image_sizes: Optional[torch.LongTensor] = None,
|
1700 |
+
image_attention_mask=None,
|
1701 |
+
input_audio_embeds: Optional[torch.FloatTensor] = None,
|
1702 |
+
audio_embed_sizes=None,
|
1703 |
+
audio_attention_mask=None,
|
1704 |
+
input_mode=None,
|
1705 |
+
labels: Optional[torch.LongTensor] = None,
|
1706 |
+
use_cache: Optional[bool] = None,
|
1707 |
+
output_attentions: Optional[bool] = None,
|
1708 |
+
output_hidden_states: Optional[bool] = None,
|
1709 |
+
return_dict: Optional[bool] = None,
|
1710 |
+
cache_position: Optional[torch.LongTensor] = None,
|
1711 |
+
num_logits_to_keep: int = 0,
|
1712 |
+
####################################
|
1713 |
+
|
1714 |
+
**kwargs: Unpack[KwargsForCausalLM],
|
1715 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
1716 |
+
r"""
|
1717 |
+
Args:
|
1718 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1719 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
1720 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
1721 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
1722 |
+
|
1723 |
+
num_logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
1724 |
+
If an `int`, compute logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
|
1725 |
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
1726 |
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
1727 |
+
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
1728 |
+
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
1729 |
+
|
1730 |
+
Returns:
|
1731 |
+
|
1732 |
+
Example:
|
1733 |
+
|
1734 |
+
```python
|
1735 |
+
>>> from transformers import AutoTokenizer, Qwen2ForCausalLM
|
1736 |
+
|
1737 |
+
>>> model = Qwen2ForCausalLM.from_pretrained("meta-qwen2/Qwen2-2-7b-hf")
|
1738 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("meta-qwen2/Qwen2-2-7b-hf")
|
1739 |
+
|
1740 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
1741 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
1742 |
+
|
1743 |
+
>>> # Generate
|
1744 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
1745 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
1746 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
1747 |
+
```"""
|
1748 |
+
|
1749 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1750 |
+
output_hidden_states = (
|
1751 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1752 |
+
)
|
1753 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1754 |
+
|
1755 |
+
###########QWEN##########
|
1756 |
+
if isinstance(input_mode, torch.Tensor):
|
1757 |
+
# len(input_mode) == num_beams in beam search, and all elements of input_mode should have the same value
|
1758 |
+
input_mode = input_mode[0].item()
|
1759 |
+
input_mode = InputMode(input_mode)
|
1760 |
+
|
1761 |
+
if input_mode in [InputMode.VISION_SPEECH, InputMode.VISION]:
|
1762 |
+
# self.set_lora_adapter('vision')
|
1763 |
+
audio_projection_mode = 'vision'
|
1764 |
+
elif input_mode == InputMode.SPEECH:
|
1765 |
+
# self.set_lora_adapter('speech')
|
1766 |
+
audio_projection_mode = 'speech'
|
1767 |
+
elif input_mode == InputMode.LANGUAGE:
|
1768 |
+
# self.unset_lora_adapter()
|
1769 |
+
audio_projection_mode = 'speech'
|
1770 |
+
else:
|
1771 |
+
raise ValueError(f"Invalid input_mode: {input_mode}")
|
1772 |
+
|
1773 |
+
##################################
|
1774 |
+
|
1775 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
1776 |
+
outputs = self.model(
|
1777 |
+
input_ids=input_ids,
|
1778 |
+
attention_mask=attention_mask,
|
1779 |
+
position_ids=position_ids,
|
1780 |
+
past_key_values=past_key_values,
|
1781 |
+
inputs_embeds=inputs_embeds,
|
1782 |
+
input_image_embeds=input_image_embeds,
|
1783 |
+
image_sizes=image_sizes,
|
1784 |
+
image_attention_mask=image_attention_mask,
|
1785 |
+
input_audio_embeds=input_audio_embeds,
|
1786 |
+
audio_embed_sizes=audio_embed_sizes,
|
1787 |
+
audio_attention_mask=audio_attention_mask,
|
1788 |
+
audio_projection_mode=audio_projection_mode,
|
1789 |
+
use_cache=use_cache,
|
1790 |
+
output_attentions=output_attentions,
|
1791 |
+
output_hidden_states=output_hidden_states,
|
1792 |
+
return_dict=return_dict,
|
1793 |
+
**kwargs,
|
1794 |
+
)
|
1795 |
+
|
1796 |
+
hidden_states = outputs[0]
|
1797 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
1798 |
+
slice_indices = slice(-num_logits_to_keep, None) if isinstance(num_logits_to_keep, int) else num_logits_to_keep
|
1799 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
1800 |
+
|
1801 |
+
loss = None
|
1802 |
+
if labels is not None:
|
1803 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
1804 |
+
|
1805 |
+
if not return_dict:
|
1806 |
+
output = (logits,) + outputs[1:]
|
1807 |
+
return (loss,) + output if loss is not None else output
|
1808 |
+
|
1809 |
+
return CausalLMOutputWithPast(
|
1810 |
+
loss=loss,
|
1811 |
+
logits=logits,
|
1812 |
+
past_key_values=outputs.past_key_values,
|
1813 |
+
hidden_states=outputs.hidden_states,
|
1814 |
+
attentions=outputs.attentions,
|
1815 |
+
)
|
1816 |
+
|
1817 |
+
def prepare_inputs_for_generation(
|
1818 |
+
self,
|
1819 |
+
input_ids,
|
1820 |
+
past_key_values=None,
|
1821 |
+
attention_mask=None,
|
1822 |
+
inputs_embeds=None,
|
1823 |
+
input_image_embeds=None,
|
1824 |
+
image_sizes=None,
|
1825 |
+
image_attention_mask=None,
|
1826 |
+
input_audio_embeds=None,
|
1827 |
+
audio_embed_sizes=None,
|
1828 |
+
audio_attention_mask=None,
|
1829 |
+
input_mode=None,
|
1830 |
+
cache_position=None,
|
1831 |
+
position_ids=None,
|
1832 |
+
use_cache=True,
|
1833 |
+
num_logits_to_keep=None,
|
1834 |
+
**kwargs
|
1835 |
+
):
|
1836 |
+
# Overwritten -- this model may need to switch between short and long rope, invalidating the cache in the
|
1837 |
+
# process
|
1838 |
+
|
1839 |
+
# When the first time input length reached long and short factor switching point, enforce re-compute cache
|
1840 |
+
# It will cause downside of slower at this single token position, however, better than current failure.
|
1841 |
+
if (
|
1842 |
+
past_key_values
|
1843 |
+
and self.config.rope_scaling
|
1844 |
+
and input_ids.shape[1] >= self.config.original_max_position_embeddings + 1
|
1845 |
+
):
|
1846 |
+
past_length = cache_position[0]
|
1847 |
+
if past_length <= self.config.original_max_position_embeddings:
|
1848 |
+
past_key_values = None
|
1849 |
+
|
1850 |
+
model_inputs = super().prepare_inputs_for_generation(
|
1851 |
+
input_ids=input_ids,
|
1852 |
+
past_key_values=past_key_values,
|
1853 |
+
attention_mask=attention_mask,
|
1854 |
+
inputs_embeds=inputs_embeds,
|
1855 |
+
input_image_embeds=input_image_embeds,
|
1856 |
+
image_sizes=image_sizes,
|
1857 |
+
image_attention_mask=image_attention_mask,
|
1858 |
+
input_audio_embeds=input_audio_embeds,
|
1859 |
+
audio_embed_sizes=audio_embed_sizes,
|
1860 |
+
audio_attention_mask=audio_attention_mask,
|
1861 |
+
input_mode=input_mode,
|
1862 |
+
cache_position=cache_position,
|
1863 |
+
position_ids=position_ids,
|
1864 |
+
use_cache=use_cache,
|
1865 |
+
num_logits_to_keep=num_logits_to_keep,
|
1866 |
+
**kwargs,
|
1867 |
+
)
|
1868 |
+
return model_inputs
|
1869 |
+
|
1870 |
+
#######################################################################################################
|
1871 |
+
|
1872 |
+
|
1873 |
+
|
1874 |
+
AutoConfig.register("qwen2-mm", Qwen2MMConfig)
|
1875 |
+
AutoModelForCausalLM.register(Qwen2MMConfig, Qwen2MMForCausalLM)
|
1876 |
+
Qwen2MMConfig.register_for_auto_class()
|
1877 |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soft and the HuggingFace Inc. team. All rights reserved.
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
|
15 |
+
"""
|
16 |
+
Processor class for Phi4MM
|
17 |
+
"""
|
18 |
+
import re
|
19 |
+
from typing import List, Optional, Tuple, Union
|
20 |
+
import math
|
21 |
+
from enum import Enum
|
22 |
+
|
23 |
+
import numpy as np
|
24 |
+
import scipy
|
25 |
+
import torch
|
26 |
+
import torchvision
|
27 |
+
|
28 |
+
from transformers import AutoFeatureExtractor, AutoImageProcessor
|
29 |
+
from transformers.feature_extraction_sequence_utils import SequenceFeatureExtractor
|
30 |
+
from transformers.image_processing_utils import BaseImageProcessor, BatchFeature
|
31 |
+
from transformers.image_utils import (
|
32 |
+
ImageInput,
|
33 |
+
make_list_of_images,
|
34 |
+
valid_images,
|
35 |
+
)
|
36 |
+
from transformers.processing_utils import ProcessorMixin
|
37 |
+
from transformers.tokenization_utils_base import PaddingStrategy, TextInput, TruncationStrategy
|
38 |
+
from transformers.utils import TensorType, logging
|
39 |
+
from torch.nn.utils.rnn import pad_sequence
|
40 |
+
|
41 |
+
|
42 |
+
logger = logging.get_logger(__name__)
|
43 |
+
|
44 |
+
# Special tokens
|
45 |
+
_COMPATIBLE_IMAGE_SPECIAL_TOKEN_PATTERN = r'<\|im_start_im+\|>' # For backward compatibility
|
46 |
+
_COMPATIBLE_AUDIO_SPECIAL_TOKEN_PATTERN = r'<\|im_start+\|>' # For backward compatibility
|
47 |
+
_IMAGE_SPECIAL_TOKEN = '<|im_start_im|>'
|
48 |
+
_AUDIO_SPECIAL_TOKEN = '<|im_start|>'
|
49 |
+
_IMAGE_SPECIAL_TOKEN_ID = 1516444 # '<|endoftext10|>', or we can better name it (in `tokenizer_config.json`)
|
50 |
+
_AUDIO_SPECIAL_TOKEN_ID = 151644 # '<|endoftext11|>'
|
51 |
+
|
52 |
+
|
53 |
+
class InputMode(Enum):
|
54 |
+
LANGUAGE = 0
|
55 |
+
VISION = 1
|
56 |
+
SPEECH = 2
|
57 |
+
VISION_SPEECH = 3
|
58 |
+
|
59 |
+
|
60 |
+
class Phi4MMImageProcessor(BaseImageProcessor):
|
61 |
+
r"""
|
62 |
+
Constructs a Phi4MM image processor.
|
63 |
+
"""
|
64 |
+
model_input_names = ["input_image_embeds", "image_sizes", "image_attention_mask"]
|
65 |
+
|
66 |
+
def __init__(
|
67 |
+
self,
|
68 |
+
dynamic_hd,
|
69 |
+
**kwargs,
|
70 |
+
) -> None:
|
71 |
+
super().__init__(**kwargs)
|
72 |
+
self.dynamic_hd = dynamic_hd
|
73 |
+
|
74 |
+
def find_closest_aspect_ratio(self, aspect_ratio, target_ratios, width, height, image_size):
|
75 |
+
best_ratio_diff = float('inf')
|
76 |
+
best_ratio = (1, 1)
|
77 |
+
area = width * height
|
78 |
+
for ratio in target_ratios:
|
79 |
+
target_aspect_ratio = ratio[0] / ratio[1]
|
80 |
+
ratio_diff = abs(aspect_ratio - target_aspect_ratio)
|
81 |
+
if ratio_diff < best_ratio_diff:
|
82 |
+
best_ratio_diff = ratio_diff
|
83 |
+
best_ratio = ratio
|
84 |
+
elif ratio_diff == best_ratio_diff:
|
85 |
+
if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
|
86 |
+
best_ratio = ratio
|
87 |
+
return best_ratio
|
88 |
+
|
89 |
+
def dynamic_preprocess(self, image, min_num=1, max_num=12, image_size=384, mask_size=27, use_thumbnail=True):
|
90 |
+
orig_width, orig_height = image.size
|
91 |
+
|
92 |
+
w_crop_num = math.ceil(orig_width/float(image_size))
|
93 |
+
h_crop_num = math.ceil(orig_height/float(image_size))
|
94 |
+
if w_crop_num * h_crop_num > max_num:
|
95 |
+
|
96 |
+
aspect_ratio = orig_width / orig_height
|
97 |
+
|
98 |
+
# calculate the existing image aspect ratio
|
99 |
+
target_ratios = set(
|
100 |
+
(i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if
|
101 |
+
i * j <= max_num and i * j >= min_num)
|
102 |
+
target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
|
103 |
+
|
104 |
+
# find the closest aspect ratio to the target
|
105 |
+
target_aspect_ratio = self.find_closest_aspect_ratio(
|
106 |
+
aspect_ratio, target_ratios, orig_width, orig_height, image_size)
|
107 |
+
|
108 |
+
# calculate the target width and height
|
109 |
+
target_width = image_size * target_aspect_ratio[0]
|
110 |
+
target_height = image_size * target_aspect_ratio[1]
|
111 |
+
else:
|
112 |
+
target_width = image_size * w_crop_num
|
113 |
+
target_height = image_size * h_crop_num
|
114 |
+
target_aspect_ratio = (w_crop_num, h_crop_num)
|
115 |
+
|
116 |
+
# Calculate the ratio
|
117 |
+
ratio_width = target_width / orig_width
|
118 |
+
ratio_height = target_height / orig_height
|
119 |
+
if ratio_width < ratio_height:
|
120 |
+
new_size = (target_width, int(orig_height * ratio_width))
|
121 |
+
padding_width = 0
|
122 |
+
padding_height = target_height - int(orig_height * ratio_width)
|
123 |
+
else:
|
124 |
+
new_size = (int(orig_width * ratio_height), target_height)
|
125 |
+
padding_width = target_width - int(orig_width * ratio_height)
|
126 |
+
padding_height = 0
|
127 |
+
|
128 |
+
attention_mask = torch.ones((int(mask_size*target_aspect_ratio[1]), int(mask_size*target_aspect_ratio[0])))
|
129 |
+
if padding_width >= 14:
|
130 |
+
attention_mask[:, -math.floor(padding_width/14):] = 0
|
131 |
+
if padding_height >= 14:
|
132 |
+
attention_mask[-math.floor(padding_height/14):,:] = 0
|
133 |
+
assert attention_mask.sum() > 0
|
134 |
+
|
135 |
+
if min(new_size[1], target_height) < 10 or min(new_size[0], target_width) < 10:
|
136 |
+
raise ValueError(f'the aspect ratio is very extreme {new_size}')
|
137 |
+
|
138 |
+
image = torchvision.transforms.functional.resize(image, [new_size[1], new_size[0]],)
|
139 |
+
|
140 |
+
resized_img = torchvision.transforms.functional.pad(image, [0, 0, padding_width, padding_height], fill=[255,255,255])
|
141 |
+
|
142 |
+
return resized_img, attention_mask
|
143 |
+
|
144 |
+
def pad_to_max_num_crops(self, images, max_crops=5):
|
145 |
+
"""
|
146 |
+
images: B x 3 x H x W, B<=max_crops
|
147 |
+
"""
|
148 |
+
B, _, H, W = images.shape
|
149 |
+
if B < max_crops:
|
150 |
+
pad = torch.zeros(max_crops - B, 3, H, W, dtype=images.dtype, device=images.device)
|
151 |
+
images = torch.cat([images, pad], dim=0)
|
152 |
+
return images
|
153 |
+
|
154 |
+
def pad_mask_to_max_num_crops(self, masks, max_crops=5):
|
155 |
+
B, H, W = masks.shape
|
156 |
+
if B < max_crops:
|
157 |
+
pad = torch.ones(max_crops - B, H, W, dtype=masks.dtype, device=masks.device)
|
158 |
+
masks = torch.cat([masks, pad], dim=0)
|
159 |
+
return masks
|
160 |
+
|
161 |
+
def preprocess(
|
162 |
+
self,
|
163 |
+
images: ImageInput,
|
164 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
165 |
+
):
|
166 |
+
"""
|
167 |
+
Args:
|
168 |
+
images (`ImageInput`):
|
169 |
+
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
170 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
171 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
172 |
+
The type of tensors to return. Can be one of:
|
173 |
+
- Unset: Return a list of `np.ndarray`.
|
174 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
175 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
176 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
177 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
178 |
+
"""
|
179 |
+
images = make_list_of_images(images)
|
180 |
+
|
181 |
+
if not valid_images(images):
|
182 |
+
raise ValueError(
|
183 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
184 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
185 |
+
)
|
186 |
+
|
187 |
+
# Basic settings.
|
188 |
+
img_processor = torchvision.transforms.Compose([
|
189 |
+
torchvision.transforms.ToTensor(),
|
190 |
+
torchvision.transforms.Normalize(
|
191 |
+
(0.5, 0.5, 0.5),
|
192 |
+
(0.5, 0.5, 0.5)
|
193 |
+
),
|
194 |
+
])
|
195 |
+
dyhd_base_resolution = 448
|
196 |
+
|
197 |
+
# Dynamic HD
|
198 |
+
base_resolution = dyhd_base_resolution
|
199 |
+
images = [image.convert('RGB') for image in images]
|
200 |
+
# cover 384 and 448 resolution
|
201 |
+
mask_resolution = base_resolution // 14
|
202 |
+
elems, image_attention_masks = [], []
|
203 |
+
for im in images:
|
204 |
+
elem, attention_mask = self.dynamic_preprocess(im, max_num=self.dynamic_hd, image_size=base_resolution, mask_size=mask_resolution)
|
205 |
+
elems.append(elem)
|
206 |
+
image_attention_masks.append(attention_mask)
|
207 |
+
hd_images = [img_processor(im) for im in elems]
|
208 |
+
global_image = [torch.nn.functional.interpolate(im.unsqueeze(0).float(), size=(base_resolution, base_resolution), mode='bicubic',).to(im.dtype) for im in hd_images]
|
209 |
+
shapes = [[im.size(1), im.size(2)] for im in hd_images]
|
210 |
+
mask_shapes = [[mask.size(0), mask.size(1)] for mask in image_attention_masks]
|
211 |
+
global_attention_mask = [torch.ones((1, mask_resolution, mask_resolution)) for _ in hd_images]
|
212 |
+
hd_images_reshape = [im.reshape(1, 3,
|
213 |
+
h//base_resolution,
|
214 |
+
base_resolution,
|
215 |
+
w//base_resolution,
|
216 |
+
base_resolution
|
217 |
+
).permute(0,2,4,1,3,5).reshape(-1, 3, base_resolution, base_resolution).contiguous() for im, (h, w) in zip(hd_images, shapes)]
|
218 |
+
attention_masks_reshape = [mask.reshape(1,
|
219 |
+
h//mask_resolution,
|
220 |
+
mask_resolution,
|
221 |
+
w//mask_resolution,
|
222 |
+
mask_resolution
|
223 |
+
).permute(0,1,3,2,4).reshape(-1, mask_resolution, mask_resolution).contiguous() for mask, (h, w) in zip(image_attention_masks, mask_shapes)]
|
224 |
+
downsample_attention_masks = [mask[:,0::2,0::2].reshape(1,
|
225 |
+
h//mask_resolution,
|
226 |
+
w//mask_resolution,
|
227 |
+
mask_resolution//2+mask_resolution%2,
|
228 |
+
mask_resolution//2+mask_resolution%2
|
229 |
+
).permute(0,1,3,2,4) for mask, (h,w) in zip(attention_masks_reshape, mask_shapes)]
|
230 |
+
downsample_attention_masks = [mask.reshape(mask.size(1)*mask.size(2), mask.size(3)*mask.size(4))for mask in downsample_attention_masks]
|
231 |
+
num_img_tokens = [256 + 1 + int(mask.sum().item()) + int(mask[:,0].sum().item()) + 16 for mask in downsample_attention_masks]
|
232 |
+
|
233 |
+
hd_images_reshape = [torch.cat([_global_image] + [_im], dim=0) for _global_image, _im in zip(global_image, hd_images_reshape)]
|
234 |
+
hd_masks_reshape = [torch.cat([_global_mask] + [_mask], dim=0) for _global_mask, _mask in zip(global_attention_mask, attention_masks_reshape)]
|
235 |
+
max_crops = max([img.size(0) for img in hd_images_reshape])
|
236 |
+
image_transformed = [self.pad_to_max_num_crops(im, max_crops) for im in hd_images_reshape]
|
237 |
+
image_transformed = torch.stack(image_transformed, dim=0)
|
238 |
+
mask_transformed = [self.pad_mask_to_max_num_crops(mask, max_crops) for mask in hd_masks_reshape]
|
239 |
+
mask_transformed = torch.stack(mask_transformed, dim=0)
|
240 |
+
|
241 |
+
returned_input_image_embeds = image_transformed
|
242 |
+
returned_image_sizes = torch.tensor(shapes, dtype=torch.long)
|
243 |
+
returned_image_attention_mask = mask_transformed
|
244 |
+
returned_num_img_tokens = num_img_tokens
|
245 |
+
|
246 |
+
data = {
|
247 |
+
"input_image_embeds": returned_input_image_embeds,
|
248 |
+
"image_sizes": returned_image_sizes,
|
249 |
+
"image_attention_mask": returned_image_attention_mask,
|
250 |
+
"num_img_tokens": returned_num_img_tokens,
|
251 |
+
}
|
252 |
+
|
253 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
254 |
+
|
255 |
+
|
256 |
+
AudioInput = Tuple[Union[np.ndarray, torch.Tensor], int]
|
257 |
+
AudioInputs = List[AudioInput]
|
258 |
+
|
259 |
+
|
260 |
+
def speechlib_mel(sample_rate, n_fft, n_mels, fmin=None, fmax=None):
|
261 |
+
"""Create a Mel filter-bank the same as SpeechLib FbankFC.
|
262 |
+
|
263 |
+
Args:
|
264 |
+
sample_rate (int): Sample rate in Hz. number > 0 [scalar]
|
265 |
+
n_fft (int): FFT size. int > 0 [scalar]
|
266 |
+
n_mel (int): Mel filter size. int > 0 [scalar]
|
267 |
+
fmin (float): lowest frequency (in Hz). If None use 0.0.
|
268 |
+
float >= 0 [scalar]
|
269 |
+
fmax: highest frequency (in Hz). If None use sample_rate / 2.
|
270 |
+
float >= 0 [scalar]
|
271 |
+
|
272 |
+
Returns
|
273 |
+
out (numpy.ndarray): Mel transform matrix
|
274 |
+
[shape=(n_mels, 1 + n_fft/2)]
|
275 |
+
"""
|
276 |
+
|
277 |
+
bank_width = int(n_fft // 2 + 1)
|
278 |
+
if fmax is None:
|
279 |
+
fmax = sample_rate / 2
|
280 |
+
if fmin is None:
|
281 |
+
fmin = 0
|
282 |
+
assert fmin >= 0, "fmin cannot be negtive"
|
283 |
+
assert fmin < fmax <= sample_rate / 2, "fmax must be between (fmin, samplerate / 2]"
|
284 |
+
|
285 |
+
def mel(f):
|
286 |
+
return 1127.0 * np.log(1.0 + f / 700.0)
|
287 |
+
|
288 |
+
def bin2mel(fft_bin):
|
289 |
+
return 1127.0 * np.log(1.0 + fft_bin * sample_rate / (n_fft * 700.0))
|
290 |
+
|
291 |
+
def f2bin(f):
|
292 |
+
return int((f * n_fft / sample_rate) + 0.5)
|
293 |
+
|
294 |
+
# Spec 1: FFT bin range [f2bin(fmin) + 1, f2bin(fmax) - 1]
|
295 |
+
klo = f2bin(fmin) + 1
|
296 |
+
khi = f2bin(fmax)
|
297 |
+
|
298 |
+
khi = max(khi, klo)
|
299 |
+
|
300 |
+
# Spec 2: SpeechLib uses trianges in Mel space
|
301 |
+
mlo = mel(fmin)
|
302 |
+
mhi = mel(fmax)
|
303 |
+
m_centers = np.linspace(mlo, mhi, n_mels + 2)
|
304 |
+
ms = (mhi - mlo) / (n_mels + 1)
|
305 |
+
|
306 |
+
matrix = np.zeros((n_mels, bank_width), dtype=np.float32)
|
307 |
+
for m in range(0, n_mels):
|
308 |
+
left = m_centers[m]
|
309 |
+
center = m_centers[m + 1]
|
310 |
+
right = m_centers[m + 2]
|
311 |
+
for fft_bin in range(klo, khi):
|
312 |
+
mbin = bin2mel(fft_bin)
|
313 |
+
if left < mbin < right:
|
314 |
+
matrix[m, fft_bin] = 1.0 - abs(center - mbin) / ms
|
315 |
+
|
316 |
+
return matrix
|
317 |
+
|
318 |
+
|
319 |
+
class Phi4MMAudioFeatureExtractor(SequenceFeatureExtractor):
|
320 |
+
model_input_names = ["input_audio_embeds", "audio_embed_sizes", "audio_attention_mask"]
|
321 |
+
|
322 |
+
def __init__(self, audio_compression_rate, audio_downsample_rate, audio_feat_stride, **kwargs):
|
323 |
+
feature_size = 80
|
324 |
+
sampling_rate = 16000
|
325 |
+
padding_value = 0.0
|
326 |
+
super().__init__(feature_size, sampling_rate, padding_value, **kwargs)
|
327 |
+
|
328 |
+
self.compression_rate = audio_compression_rate
|
329 |
+
self.qformer_compression_rate = audio_downsample_rate
|
330 |
+
self.feat_stride = audio_feat_stride
|
331 |
+
|
332 |
+
self._eightk_method = "fillzero"
|
333 |
+
self._mel = speechlib_mel(16000, 512, 80, fmin=None, fmax=7690).T
|
334 |
+
|
335 |
+
self._hamming400 = np.hamming(400) # for 16k audio
|
336 |
+
self._hamming200 = np.hamming(200) # for 8k audio
|
337 |
+
|
338 |
+
def duration_to_frames(self, duration):
|
339 |
+
"""duration in s, estimated frames"""
|
340 |
+
frame_rate = 10
|
341 |
+
|
342 |
+
num_frames = duration * 1000 // frame_rate
|
343 |
+
return num_frames
|
344 |
+
|
345 |
+
def __call__(
|
346 |
+
self,
|
347 |
+
audios: List[AudioInput],
|
348 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
349 |
+
):
|
350 |
+
# Ref: https://github.com/huggingface/transformers/blob/v4.47.0/src/transformers/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.py#L161
|
351 |
+
returned_input_audio_embeds = []
|
352 |
+
returned_audio_embed_sizes = []
|
353 |
+
audio_frames_list = []
|
354 |
+
|
355 |
+
for audio_data, sample_rate in audios:
|
356 |
+
audio_embeds = self._extract_features(audio_data, sample_rate)
|
357 |
+
audio_frames = len(audio_embeds) * self.feat_stride
|
358 |
+
audio_embed_size = self._compute_audio_embed_size(audio_frames)
|
359 |
+
|
360 |
+
returned_input_audio_embeds.append(torch.tensor(audio_embeds))
|
361 |
+
returned_audio_embed_sizes.append(torch.tensor(audio_embed_size).long())
|
362 |
+
audio_frames_list.append(audio_frames)
|
363 |
+
|
364 |
+
returned_input_audio_embeds = pad_sequence(
|
365 |
+
returned_input_audio_embeds, batch_first=True
|
366 |
+
)
|
367 |
+
returned_audio_embed_sizes = torch.stack(returned_audio_embed_sizes, dim=0)
|
368 |
+
audio_frames = torch.tensor(audio_frames_list)
|
369 |
+
returned_audio_attention_mask = torch.arange(0, audio_frames.max()).unsqueeze(0) < audio_frames.unsqueeze(1) if len(audios) > 1 else None
|
370 |
+
|
371 |
+
data = {
|
372 |
+
"input_audio_embeds": returned_input_audio_embeds,
|
373 |
+
"audio_embed_sizes": returned_audio_embed_sizes,
|
374 |
+
}
|
375 |
+
if returned_audio_attention_mask is not None:
|
376 |
+
data["audio_attention_mask"] = returned_audio_attention_mask
|
377 |
+
|
378 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
379 |
+
|
380 |
+
def _extract_spectrogram(self, wav, fs):
|
381 |
+
"""Extract spectrogram features from waveform.
|
382 |
+
Args:
|
383 |
+
wav (1D array): waveform of the input
|
384 |
+
fs (int): sampling rate of the waveform, 16000 or 8000.
|
385 |
+
If fs=8000, the waveform will be resampled to 16000Hz.
|
386 |
+
Output:
|
387 |
+
log_fbank (2D array): a TxD matrix of log Mel filterbank features.
|
388 |
+
D=80, and T is the number of frames.
|
389 |
+
"""
|
390 |
+
if wav.ndim > 1:
|
391 |
+
wav = np.squeeze(wav)
|
392 |
+
|
393 |
+
# by default, we extract the mean if stereo
|
394 |
+
if len(wav.shape) == 2:
|
395 |
+
wav = wav.mean(1)
|
396 |
+
|
397 |
+
# Resample to 16000 or 8000 if needed
|
398 |
+
if fs > 16000:
|
399 |
+
wav = scipy.signal.resample_poly(wav, 1, fs // 16000)
|
400 |
+
fs = 16000
|
401 |
+
elif 8000 < fs < 16000:
|
402 |
+
wav = scipy.signal.resample_poly(wav, 1, fs // 8000)
|
403 |
+
fs = 8000
|
404 |
+
elif fs < 8000:
|
405 |
+
raise RuntimeError(f"Unsupported sample rate {fs}")
|
406 |
+
|
407 |
+
if fs == 8000:
|
408 |
+
if self._eightk_method == "resample":
|
409 |
+
# Input audio is 8 kHz. Convert to 16 kHz before feature
|
410 |
+
# extraction
|
411 |
+
wav = scipy.signal.resample_poly(wav, 2, 1)
|
412 |
+
fs = 16000
|
413 |
+
# Do nothing here for fillzero method
|
414 |
+
elif fs != 16000:
|
415 |
+
# Input audio is not a supported sample rate.
|
416 |
+
raise RuntimeError(f"Input data using an unsupported sample rate: {fs}")
|
417 |
+
|
418 |
+
preemphasis = 0.97
|
419 |
+
|
420 |
+
if fs == 8000:
|
421 |
+
n_fft = 256
|
422 |
+
win_length = 200
|
423 |
+
hop_length = 80
|
424 |
+
fft_window = self._hamming200
|
425 |
+
elif fs == 16000:
|
426 |
+
n_fft = 512
|
427 |
+
win_length = 400
|
428 |
+
hop_length = 160
|
429 |
+
fft_window = self._hamming400
|
430 |
+
|
431 |
+
# Spec 1: SpeechLib cut remaining sample insufficient for a hop
|
432 |
+
n_batch = (wav.shape[0] - win_length) // hop_length + 1
|
433 |
+
# Here we don't use stride_tricks since the input array may not satisfy
|
434 |
+
# memory layout requirement and we need writeable output
|
435 |
+
# Here we only use list of views before copy to desination
|
436 |
+
# so it is more efficient than broadcasting
|
437 |
+
y_frames = np.array(
|
438 |
+
[wav[_stride : _stride + win_length] for _stride in range(0, hop_length * n_batch, hop_length)],
|
439 |
+
dtype=np.float32,
|
440 |
+
)
|
441 |
+
|
442 |
+
# Spec 2: SpeechLib applies preemphasis within each batch
|
443 |
+
y_frames_prev = np.roll(y_frames, 1, axis=1)
|
444 |
+
y_frames_prev[:, 0] = y_frames_prev[:, 1]
|
445 |
+
y_frames = (y_frames - preemphasis * y_frames_prev) * 32768
|
446 |
+
|
447 |
+
S = np.fft.rfft(fft_window * y_frames, n=n_fft, axis=1).astype(np.complex64)
|
448 |
+
|
449 |
+
if fs == 8000:
|
450 |
+
# Need to pad the output to look like 16 kHz data but with zeros in
|
451 |
+
# the 4 to 8 kHz bins.
|
452 |
+
frames, bins = S.shape
|
453 |
+
padarray = np.zeros((frames, bins))
|
454 |
+
S = np.concatenate((S[:, 0:-1], padarray), axis=1) # Nyquist bin gets set to zero
|
455 |
+
|
456 |
+
spec = np.abs(S).astype(np.float32)
|
457 |
+
return spec
|
458 |
+
|
459 |
+
def _extract_features(self, wav, fs):
|
460 |
+
"""Extract log filterbank features from waveform.
|
461 |
+
Args:
|
462 |
+
wav (1D array): waveform of the input
|
463 |
+
fs (int): sampling rate of the waveform, 16000 or 8000.
|
464 |
+
If fs=8000, the waveform will be resampled to 16000Hz.
|
465 |
+
Output:
|
466 |
+
log_fbank (2D array): a TxD matrix of log Mel filterbank features.
|
467 |
+
D=80, and T is the number of frames.
|
468 |
+
"""
|
469 |
+
spec = self._extract_spectrogram(wav, fs)
|
470 |
+
spec_power = spec**2
|
471 |
+
|
472 |
+
fbank_power = np.clip(spec_power.dot(self._mel), 1.0, None)
|
473 |
+
log_fbank = np.log(fbank_power).astype(np.float32)
|
474 |
+
|
475 |
+
return log_fbank
|
476 |
+
|
477 |
+
def _compute_audio_embed_size(self, audio_frames):
|
478 |
+
integer = audio_frames // self.compression_rate
|
479 |
+
remainder = audio_frames % self.compression_rate
|
480 |
+
|
481 |
+
result = integer if remainder == 0 else integer + 1
|
482 |
+
|
483 |
+
integer = result // self.qformer_compression_rate
|
484 |
+
remainder = result % self.qformer_compression_rate
|
485 |
+
result = integer if remainder == 0 else integer + 1 # qformer compression
|
486 |
+
|
487 |
+
return result
|
488 |
+
|
489 |
+
|
490 |
+
class Phi4MMProcessor(ProcessorMixin):
|
491 |
+
r"""
|
492 |
+
Constructs a Phi4MM processor which raps an image processor, a audio processor, and a GPT tokenizer into a single processor.
|
493 |
+
|
494 |
+
[`Phi4MMProcessor`] offers all the functionalities of [`Phi4MMImageProcessor`] and [`GPT2Tokenizer`]. See the
|
495 |
+
[`~Phi4MMProcessor.__call__`] and [`~Phi4MMProcessor.decode`] for more information.
|
496 |
+
|
497 |
+
Args:
|
498 |
+
image_processor ([`Phi4MMImageProcessor`], *optional*):
|
499 |
+
The image processor is a required input.
|
500 |
+
tokenizer ([`GPT2Tokenizer`], *optional*):
|
501 |
+
The tokenizer is a required input.
|
502 |
+
"""
|
503 |
+
|
504 |
+
attributes = ["image_processor", "audio_processor", "tokenizer"]
|
505 |
+
tokenizer_class = "Qwen2Tokenizer"
|
506 |
+
image_processor_class = "AutoImageProcessor" # Phi4MMImageProcessor will be registered later
|
507 |
+
audio_processor_class = "AutoFeatureExtractor" # Phi4MMAudioFeatureExtractor will be registered later
|
508 |
+
|
509 |
+
def __init__(self, image_processor, audio_processor, tokenizer):
|
510 |
+
self.image_processor = image_processor
|
511 |
+
self.audio_processor = audio_processor
|
512 |
+
self.tokenizer = tokenizer
|
513 |
+
|
514 |
+
def __call__(
|
515 |
+
self,
|
516 |
+
text: Union[TextInput, List[TextInput]],
|
517 |
+
images: Optional[ImageInput] = None,
|
518 |
+
audios: Optional[AudioInputs] = None,
|
519 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
520 |
+
truncation: Optional[Union[bool, str, TruncationStrategy]] = None,
|
521 |
+
max_length=None,
|
522 |
+
return_tensors: Optional[Union[str, TensorType]] = TensorType.PYTORCH,
|
523 |
+
) -> BatchFeature:
|
524 |
+
"""
|
525 |
+
Main method to prepare for the model one or several sequences(s) and image(s). This method forards the `text`
|
526 |
+
and `kwargs` arguments to GPT2Tokenizer's [`~GPT2Tokenizer.__call__`] if `text` is not `None` to encode
|
527 |
+
the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
|
528 |
+
Phi4MMImageProcessor's [`~Phi4MMImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring
|
529 |
+
of the above two methods for more information.
|
530 |
+
|
531 |
+
Args:
|
532 |
+
text (`str`, `List[str]`, `List[List[str]]`):
|
533 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
534 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
535 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
536 |
+
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
|
537 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
538 |
+
tensor. Both channels-first and channels-last formats are supported.
|
539 |
+
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
|
540 |
+
Select a strategy to pad the returned sequences (according to the model's padding side and padding
|
541 |
+
index) among:
|
542 |
+
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
|
543 |
+
sequence if provided).
|
544 |
+
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
|
545 |
+
acceptable input length for the model if that argument is not provided.
|
546 |
+
- `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
|
547 |
+
lengths).
|
548 |
+
max_length (`int`, *optional*):
|
549 |
+
Maximum length of the returned list and optionally padding length (see above).
|
550 |
+
truncation (`bool`, *optional*):
|
551 |
+
Activates truncation to cut input sequences longer than `max_length` to `max_length`.
|
552 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
553 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
554 |
+
|
555 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
556 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
557 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
558 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
559 |
+
|
560 |
+
Returns:
|
561 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
562 |
+
|
563 |
+
- **input_ids** -- List of token ids to be fed to a model.
|
564 |
+
- **input_image_embeds** -- Pixel values to be fed to a model.
|
565 |
+
- **image_sizes** -- List of tuples specifying the size of each image in `input_image_embeds`.
|
566 |
+
- **image_attention_mask** -- List of attention masks for each image in `input_image_embeds`.
|
567 |
+
- **input_audio_embeds** -- Audio embeddings to be fed to a model.
|
568 |
+
- **audio_embed_sizes** -- List of integers specifying the size of each audio in `input_audio_embeds`.
|
569 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model.
|
570 |
+
"""
|
571 |
+
image_inputs = self.image_processor(images, return_tensors=return_tensors) if images is not None else {}
|
572 |
+
audio_inputs = self.audio_processor(audios, return_tensors=return_tensors) if audios is not None else {}
|
573 |
+
inputs = self._convert_images_audios_text_to_inputs(
|
574 |
+
image_inputs,
|
575 |
+
audio_inputs,
|
576 |
+
text,
|
577 |
+
padding=padding,
|
578 |
+
truncation=truncation,
|
579 |
+
max_length=max_length,
|
580 |
+
return_tensors=return_tensors,
|
581 |
+
)
|
582 |
+
|
583 |
+
# idenfity the input mode
|
584 |
+
if len(image_inputs) > 0 and len(audio_inputs) > 0:
|
585 |
+
input_mode = InputMode.VISION_SPEECH
|
586 |
+
elif len(image_inputs) > 0:
|
587 |
+
input_mode = InputMode.VISION
|
588 |
+
elif len(audio_inputs) > 0:
|
589 |
+
input_mode = InputMode.SPEECH
|
590 |
+
else:
|
591 |
+
input_mode = InputMode.LANGUAGE
|
592 |
+
inputs["input_mode"] = torch.tensor([input_mode.value], dtype=torch.long)
|
593 |
+
|
594 |
+
return inputs
|
595 |
+
|
596 |
+
@property
|
597 |
+
def special_image_token_id(self):
|
598 |
+
return self.tokenizer.convert_tokens_to_ids(self.special_image_token)
|
599 |
+
|
600 |
+
def get_special_image_token_id(self):
|
601 |
+
return self.tokenizer.convert_tokens_to_ids(self.special_image_token)
|
602 |
+
|
603 |
+
@property
|
604 |
+
def chat_template(self):
|
605 |
+
return self.tokenizer.chat_template
|
606 |
+
|
607 |
+
def _convert_images_audios_text_to_inputs(
|
608 |
+
self, images, audios, text, padding=False, truncation=None, max_length=None, return_tensors=None
|
609 |
+
):
|
610 |
+
# prepare image id to image input ids
|
611 |
+
if len(images) > 0:
|
612 |
+
input_image_embeds = images["input_image_embeds"]
|
613 |
+
image_sizes = images["image_sizes"]
|
614 |
+
image_attention_mask = images["image_attention_mask"]
|
615 |
+
num_img_tokens = images['num_img_tokens']
|
616 |
+
else:
|
617 |
+
input_image_embeds = torch.tensor([])
|
618 |
+
image_sizes = torch.tensor([])
|
619 |
+
image_attention_mask = torch.tensor([])
|
620 |
+
num_img_tokens = []
|
621 |
+
|
622 |
+
# prepare audio id to audio input ids
|
623 |
+
if len(audios) > 0:
|
624 |
+
input_audio_embeds = audios["input_audio_embeds"]
|
625 |
+
audio_embed_sizes = audios["audio_embed_sizes"]
|
626 |
+
audio_attention_mask = audios.get("audio_attention_mask", None)
|
627 |
+
else:
|
628 |
+
input_audio_embeds = torch.tensor([])
|
629 |
+
audio_embed_sizes = torch.tensor([])
|
630 |
+
audio_attention_mask = None
|
631 |
+
|
632 |
+
# Replace certain special tokens for compatibility
|
633 |
+
# Ref: https://stackoverflow.com/questions/11475885/python-replace-regex
|
634 |
+
if isinstance(text, str):
|
635 |
+
text = [text]
|
636 |
+
assert isinstance(text, list)
|
637 |
+
processed_text = [re.sub(_COMPATIBLE_IMAGE_SPECIAL_TOKEN_PATTERN, _IMAGE_SPECIAL_TOKEN, t) for t in text]
|
638 |
+
processed_text = [re.sub(_COMPATIBLE_AUDIO_SPECIAL_TOKEN_PATTERN, _AUDIO_SPECIAL_TOKEN, t) for t in processed_text]
|
639 |
+
|
640 |
+
input_ids_list = [self.tokenizer(t).input_ids for t in processed_text]
|
641 |
+
|
642 |
+
img_cnt, audio_cnt = 0, 0 # only needed for later assertion
|
643 |
+
image_token_count_iter = iter(num_img_tokens)
|
644 |
+
audio_embed_size_iter = iter(audio_embed_sizes.tolist())
|
645 |
+
new_input_ids_list = []
|
646 |
+
for input_ids in input_ids_list:
|
647 |
+
i = 0
|
648 |
+
while i < len(input_ids):
|
649 |
+
token_id = input_ids[i]
|
650 |
+
if token_id == _AUDIO_SPECIAL_TOKEN_ID:
|
651 |
+
token_count = next(audio_embed_size_iter)
|
652 |
+
audio_cnt += 1
|
653 |
+
elif token_id == _IMAGE_SPECIAL_TOKEN_ID:
|
654 |
+
token_count = next(image_token_count_iter)
|
655 |
+
img_cnt += 1
|
656 |
+
else:
|
657 |
+
i += 1
|
658 |
+
continue
|
659 |
+
tokens = [token_id] * token_count
|
660 |
+
input_ids = input_ids[:i] + tokens + input_ids[i + 1:]
|
661 |
+
i += token_count
|
662 |
+
input_ids = torch.tensor(input_ids, dtype=torch.long)
|
663 |
+
new_input_ids_list.append(input_ids)
|
664 |
+
lengths = torch.tensor([len(input_ids) for input_ids in new_input_ids_list])
|
665 |
+
max_len = lengths.max()
|
666 |
+
input_ids = input_ids.new_full((len(new_input_ids_list), max_len), self.tokenizer.pad_token_id)
|
667 |
+
# batched inference requires left padding
|
668 |
+
|
669 |
+
########QWEN##############
|
670 |
+
for i in range(len(new_input_ids_list)):
|
671 |
+
input_ids[i, max_len - len(new_input_ids_list[i]):] = new_input_ids_list[i]
|
672 |
+
|
673 |
+
# for i in range(len(new_input_ids_list)):
|
674 |
+
# input_ids[i, :len(new_input_ids_list[i])] = new_input_ids_list[i]
|
675 |
+
|
676 |
+
# If the below assertion fails, it might be that input pure-text
|
677 |
+
# messages contain image/audio special tokens literally
|
678 |
+
# (<|endoftext10|>, <|endoftext11|>).
|
679 |
+
assert (
|
680 |
+
img_cnt == len(num_img_tokens)
|
681 |
+
), (
|
682 |
+
f"Number of image tokens in prompt_token_ids ({img_cnt}) "
|
683 |
+
f"does not match number of images ({len(num_img_tokens)})"
|
684 |
+
)
|
685 |
+
assert (
|
686 |
+
audio_cnt == len(audio_embed_sizes)
|
687 |
+
), (
|
688 |
+
f"Number of audio tokens in prompt_token_ids ({audio_cnt}) "
|
689 |
+
f"does not match number of audios ({len(audio_embed_sizes)})"
|
690 |
+
)
|
691 |
+
|
692 |
+
# prepare attention mask
|
693 |
+
########QWEN##############
|
694 |
+
seq_range = torch.arange(max_len - 1, -1, -1)
|
695 |
+
# seq_range = torch.arange(0,max_len)
|
696 |
+
attention_mask = seq_range.unsqueeze(0) < lengths.unsqueeze(1)
|
697 |
+
|
698 |
+
# # prepare batch feature
|
699 |
+
# print(input_ids)
|
700 |
+
# print(attention_mask)
|
701 |
+
# print(pp)
|
702 |
+
|
703 |
+
data = {
|
704 |
+
"input_ids": input_ids,
|
705 |
+
"input_image_embeds": input_image_embeds,
|
706 |
+
"image_sizes": image_sizes,
|
707 |
+
"image_attention_mask": image_attention_mask,
|
708 |
+
"input_audio_embeds": input_audio_embeds,
|
709 |
+
"audio_embed_sizes": audio_embed_sizes,
|
710 |
+
"audio_attention_mask": audio_attention_mask,
|
711 |
+
"attention_mask": attention_mask,
|
712 |
+
}
|
713 |
+
|
714 |
+
return BatchFeature(
|
715 |
+
data=data
|
716 |
+
)
|
717 |
+
|
718 |
+
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Llama
|
719 |
+
def batch_decode(self, *args, **kwargs):
|
720 |
+
"""
|
721 |
+
This method forwards all its arguments to GPT2Tokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please
|
722 |
+
refer to the docstring of this method for more information.
|
723 |
+
"""
|
724 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
725 |
+
|
726 |
+
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Llama
|
727 |
+
def decode(self, *args, **kwargs):
|
728 |
+
"""
|
729 |
+
This method forwards all its arguments to GPT2Tokenizer's [`~PreTrainedTokenizer.decode`]. Please refer to
|
730 |
+
the docstring of this method for more information.
|
731 |
+
"""
|
732 |
+
return self.tokenizer.decode(*args, **kwargs)
|
733 |
+
|
734 |
+
@property
|
735 |
+
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names
|
736 |
+
def model_input_names(self):
|
737 |
+
tokenizer_input_names = self.tokenizer.model_input_names
|
738 |
+
image_processor_input_names = self.image_processor.model_input_names
|
739 |
+
audio_processor_input_names = self.audio_processor.model_input_names
|
740 |
+
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names + audio_processor_input_names))
|
741 |
+
|
742 |
+
|
743 |
+
AutoImageProcessor.register("Phi4MMImageProcessor", Phi4MMImageProcessor)
|
744 |
+
AutoFeatureExtractor.register("Phi4MMAudioFeatureExtractor", Phi4MMAudioFeatureExtractor)
|
speech_conformer_encoder.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|