xiaohaoWillX commited on
Commit
4ab6037
·
verified ·
1 Parent(s): 544c3ec

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. README.md +63 -0
  2. __pycache__/misc.cpython-310.pyc +0 -0
  3. data/textvqa/textvqa_val_annotations.json +0 -0
  4. data/textvqa/textvqa_val_questions.json +0 -0
  5. data/textvqa_official/TextVQA_0.5.1_test.json +0 -0
  6. data/textvqa_official/TextVQA_0.5.1_val.json +0 -0
  7. internvl/model/internlm2/configuration_internlm2.py +150 -0
  8. internvl/model/internlm2/modeling_internlm2.py +1659 -0
  9. internvl/model/internlm2/tokenization_internlm2.py +235 -0
  10. internvl/model/internlm2/tokenization_internlm2_fast.py +211 -0
  11. internvl/model/internvl_chat/__init__.py +13 -0
  12. internvl/model/internvl_chat/configuration_intern_vit.py +119 -0
  13. internvl/model/internvl_chat/configuration_internvl_chat.py +106 -0
  14. internvl/model/internvl_chat/flash_attention.py +76 -0
  15. internvl/model/internvl_chat/modeling_intern_vit.py +362 -0
  16. internvl/model/internvl_chat/modeling_internvl_chat.py +506 -0
  17. internvl/model/llama/__init__.py +116 -0
  18. internvl/model/llama/configuration_llama.py +203 -0
  19. internvl/model/llama/convert_llama_weights_to_hf.py +479 -0
  20. internvl/model/llama/modeling_flax_llama.py +750 -0
  21. internvl/model/llama/modeling_llama.py +1838 -0
  22. internvl/model/llama/tokenization_llama.py +412 -0
  23. internvl/model/llama/tokenization_llama_fast.py +255 -0
  24. internvl/model/phi3/configuration_phi3.py +211 -0
  25. internvl/model/phi3/modeling_phi3.py +1601 -0
  26. internvl/model/qwen2/__init__.py +82 -0
  27. internvl/model/qwen2/configuration_qwen2.py +140 -0
  28. internvl/model/qwen2/modeling_qwen2.py +1517 -0
  29. internvl/model/qwen2/tokenization_qwen2.py +339 -0
  30. internvl/model/qwen2/tokenization_qwen2_fast.py +134 -0
  31. internvl/patch/__init__.py +13 -0
  32. internvl/patch/llama2_flash_attn_monkey_patch.py +237 -0
  33. internvl/patch/llama_flash_attn_monkey_patch.py +216 -0
  34. internvl/patch/pad_data_collator.py +100 -0
  35. internvl/patch/train_sampler_patch.py +119 -0
  36. misc.py +364 -0
  37. results_qwen35_guided_vqav2/run.log +0 -0
  38. results_qwen35_guided_vqav2_reasoning_on4096_off16_bg/run_260425024028/analysis_on_vs_off/both_correct.json +0 -0
  39. results_qwen35_guided_vqav2_reasoning_on4096_off16_bg/run_260425024028/analysis_on_vs_off/both_reason_correct.json +0 -0
  40. results_qwen35_guided_vqav2_reasoning_on4096_off16_bg/run_260425024028/analysis_on_vs_off/both_wrong.json +0 -0
  41. results_qwen35_guided_vqav2_reasoning_on4096_off16_bg/run_260425024028/analysis_on_vs_off/both_wrong_with_on_off_reasoning.json +0 -0
  42. results_qwen35_guided_vqav2_reasoning_on4096_off16_bg/run_260425024028/analysis_on_vs_off/off_reason_correct_on_reason_wrong.json +0 -0
  43. results_qwen35_guided_vqav2_reasoning_on4096_off16_bg/run_260425024028/qwen35_4b_thinking_on/PruneLayer_0.0416667_PruneRatio_0.05/console_260425024028.log +0 -0
  44. results_qwen35_guided_vqav2_smoke/qwen35_4b_thinking_off/PruneLayer_0.0416667_PruneRatio_0.05/vqav2_val_260423091708.json +1 -0
  45. run.py +113 -0
  46. setup_sgl_2b_env.sh +13 -0
  47. textvqa2B-26B.sh +26 -0
  48. textvqa2B-largeonly.sh +22 -0
  49. tools/extract_mlp.py +19 -0
  50. tools/extract_video_frames.py +121 -0
README.md ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <h1 align="center"> <p>SGL</p></h1>
2
+
3
+ <p align="center">
4
+ <picture>
5
+ <img width="20%" alt="SGL" src="./logo.png">
6
+ </picture>
7
+ </p>
8
+
9
+
10
+
11
+
12
+ The official implementation of "2025 CVPR A Stitch in Time Saves Nine: Small VLM is a Precise Guidance for accelerating Large VLMs".
13
+
14
+ > Wangbo Zhao<sup>1</sup>, Yizeng Han<sup>2</sup>, Jiasheng Tang<sup>2,3</sup>, Zhikai Li<sup>1</sup>, Yibing Song<sup>2,3</sup>, Kai Wang<sup>1</sup>, Zhangyang Wang<sup>4</sup>, Yang You<sup>1</sup>
15
+ >
16
+ > <sup>1</sup>[National University of Singapore](https://www.nus.edu.sg/), <sup>2</sup>[DAMO Academy, Alibaba Group](https://damo.alibaba.com/?language=zh), <sup>3</sup>Hupan Lab, <sup>4</sup>[The University of Texas at Austin](https://www.tsinghua.edu.cn/)
17
+ >
18
+ > [Paper](https://arxiv.org/abs/2412.03324)
19
+
20
+
21
+ ## Update
22
+ 2025.02.27 SGL has been accepted to CVPR 2025.
23
+
24
+ ## 💥 Overview
25
+ ![20241230195723](https://github.com/user-attachments/assets/e244efd4-4136-4402-856f-95e87e33d408)
26
+
27
+ (a) Small VLM-guided visual token pruning in a large VLM (SGP). We update a global attention map aggregated from all layer of a small VLM. This global attention map is used to rank visual tokens and guide the visual token pruning in a large VLM.
28
+
29
+ (b) Aggregation of attention maps in SGP. We aggregate the attention score of visual tokens received from prompt tokens and generated tokens across all heads and layers in the small LM. Higher scores indicate greater significance.
30
+
31
+ (c) Inference with Small VLM Early Exiting (SEE). When the early exiting decision score from the small VLM is sufficient, the larger VLM will not be invoked.
32
+
33
+ ## 🔨 Usage
34
+
35
+
36
+ 1. Please refer to the documentation of [InternVL](https://github.com/OpenGVLab/InternVL) to set up the environment and prepare the data for evaluation.
37
+
38
+ 2. We take 'bash textvqa2B-26B.sh' as an example, which takes InternVL2-2B as the small model to accelerate the large model InternVL2-26B.
39
+
40
+
41
+
42
+
43
+
44
+
45
+
46
+
47
+ ## 🤔 Citation
48
+ If you found our work useful, please consider citing us.
49
+ ```
50
+ @article{zhao2024stitch,
51
+ title={A Stitch in Time Saves Nine: Small VLM is a Precise Guidance for accelerating Large VLMs},
52
+ author={Zhao, Wangbo and Han, Yizeng and Tang, Jiasheng and Li, Zhikai and Song, Yibing and Wang, Kai and Wang, Zhangyang and You, Yang},
53
+ journal={arXiv preprint arXiv:2412.03324},
54
+ year={2024}
55
+ }
56
+ ```
57
+
58
+ ## 🙏 Acknowledgement
59
+ SGL is built with reference to the code of the following projects: [InternVL](https://github.com/OpenGVLab/InternVL), [FastV](https://github.com/pkunlp-icler/FastV), [QWen2-VL](https://github.com/QwenLM/Qwen2-VL), and [LLaVa-OneVision](https://llava-vl.github.io/blog/2024-08-05-llava-onevision/).
60
+
61
+ ## ☎️ Contact
62
+ 🔥🔥🔥 If you are interested in this work and hope to cooperate with us, please drop an email to wangbo.zhao96@gmail.com 🔥🔥🔥
63
+
__pycache__/misc.cpython-310.pyc ADDED
Binary file (11.4 kB). View file
 
data/textvqa/textvqa_val_annotations.json ADDED
The diff for this file is too large to render. See raw diff
 
data/textvqa/textvqa_val_questions.json ADDED
The diff for this file is too large to render. See raw diff
 
data/textvqa_official/TextVQA_0.5.1_test.json ADDED
The diff for this file is too large to render. See raw diff
 
data/textvqa_official/TextVQA_0.5.1_val.json ADDED
The diff for this file is too large to render. See raw diff
 
internvl/model/internlm2/configuration_internlm2.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on transformers/src/transformers/models/llama/configuration_llama.py
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ InternLM2 model configuration"""
17
+
18
+ from transformers.configuration_utils import PretrainedConfig
19
+ from transformers.utils import logging
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+ INTERNLM2_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
24
+
25
+
26
+ # Modified from transformers.model.llama.configuration_llama.LlamaConfig
27
+ class InternLM2Config(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`InternLM2Model`]. It is used to instantiate
30
+ an InternLM2 model according to the specified arguments, defining the model architecture. Instantiating a
31
+ configuration with the defaults will yield a similar configuration to that of the InternLM2-7B.
32
+
33
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
34
+ documentation from [`PretrainedConfig`] for more information.
35
+
36
+
37
+ Args:
38
+ vocab_size (`int`, *optional*, defaults to 32000):
39
+ Vocabulary size of the InternLM2 model. Defines the number of different tokens that can be represented by the
40
+ `inputs_ids` passed when calling [`InternLM2Model`]
41
+ hidden_size (`int`, *optional*, defaults to 4096):
42
+ Dimension of the hidden representations.
43
+ intermediate_size (`int`, *optional*, defaults to 11008):
44
+ Dimension of the MLP representations.
45
+ num_hidden_layers (`int`, *optional*, defaults to 32):
46
+ Number of hidden layers in the Transformer encoder.
47
+ num_attention_heads (`int`, *optional*, defaults to 32):
48
+ Number of attention heads for each attention layer in the Transformer encoder.
49
+ num_key_value_heads (`int`, *optional*):
50
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
51
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
52
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
53
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
54
+ by meanpooling all the original heads within that group. For more details checkout [this
55
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
56
+ `num_attention_heads`.
57
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
58
+ The non-linear activation function (function or string) in the decoder.
59
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
60
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
61
+ just in case (e.g., 512 or 1024 or 2048).
62
+ initializer_range (`float`, *optional*, defaults to 0.02):
63
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
64
+ rms_norm_eps (`float`, *optional*, defaults to 1e-12):
65
+ The epsilon used by the rms normalization layers.
66
+ use_cache (`bool`, *optional*, defaults to `True`):
67
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
68
+ relevant if `config.is_decoder=True`.
69
+ tie_word_embeddings(`bool`, *optional*, defaults to `False`):
70
+ Whether to tie weight embeddings
71
+ Example:
72
+
73
+ """
74
+ model_type = 'internlm2'
75
+ _auto_class = 'AutoConfig'
76
+
77
+ def __init__( # pylint: disable=W0102
78
+ self,
79
+ vocab_size=103168,
80
+ hidden_size=4096,
81
+ intermediate_size=11008,
82
+ num_hidden_layers=32,
83
+ num_attention_heads=32,
84
+ num_key_value_heads=None,
85
+ hidden_act='silu',
86
+ max_position_embeddings=2048,
87
+ initializer_range=0.02,
88
+ rms_norm_eps=1e-6,
89
+ use_cache=True,
90
+ pad_token_id=0,
91
+ bos_token_id=1,
92
+ eos_token_id=2,
93
+ tie_word_embeddings=False,
94
+ bias=True,
95
+ rope_theta=10000,
96
+ rope_scaling=None,
97
+ attn_implementation='eager',
98
+ **kwargs,
99
+ ):
100
+ self.vocab_size = vocab_size
101
+ self.max_position_embeddings = max_position_embeddings
102
+ self.hidden_size = hidden_size
103
+ self.intermediate_size = intermediate_size
104
+ self.num_hidden_layers = num_hidden_layers
105
+ self.num_attention_heads = num_attention_heads
106
+ self.bias = bias
107
+
108
+ if num_key_value_heads is None:
109
+ num_key_value_heads = num_attention_heads
110
+ self.num_key_value_heads = num_key_value_heads
111
+
112
+ self.hidden_act = hidden_act
113
+ self.initializer_range = initializer_range
114
+ self.rms_norm_eps = rms_norm_eps
115
+ self.use_cache = use_cache
116
+ self.rope_theta = rope_theta
117
+ self.rope_scaling = rope_scaling
118
+ self._rope_scaling_validation()
119
+
120
+ self.attn_implementation = attn_implementation
121
+ if self.attn_implementation is None:
122
+ self.attn_implementation = 'eager'
123
+ super().__init__(
124
+ pad_token_id=pad_token_id,
125
+ bos_token_id=bos_token_id,
126
+ eos_token_id=eos_token_id,
127
+ tie_word_embeddings=tie_word_embeddings,
128
+ **kwargs,
129
+ )
130
+
131
+ def _rope_scaling_validation(self):
132
+ """
133
+ Validate the `rope_scaling` configuration.
134
+ """
135
+ if self.rope_scaling is None:
136
+ return
137
+
138
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
139
+ raise ValueError(
140
+ '`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, '
141
+ f'got {self.rope_scaling}'
142
+ )
143
+ rope_scaling_type = self.rope_scaling.get('type', None)
144
+ rope_scaling_factor = self.rope_scaling.get('factor', None)
145
+ if rope_scaling_type is None or rope_scaling_type not in ['linear', 'dynamic']:
146
+ raise ValueError(
147
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
148
+ )
149
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor < 1.0:
150
+ raise ValueError(f"`rope_scaling`'s factor field must be a float >= 1, got {rope_scaling_factor}")
internvl/model/internlm2/modeling_internlm2.py ADDED
@@ -0,0 +1,1659 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on transformers/src/transformers/models/llama/modeling_llama.py
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ PyTorch InternLM2 model."""
17
+ import math
18
+ import queue
19
+ import threading
20
+ import warnings
21
+ from typing import List, Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.nn.functional as F
25
+ import torch.utils.checkpoint
26
+ from einops import rearrange
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+ from transformers.activations import ACT2FN
30
+ from transformers.modeling_outputs import (BaseModelOutputWithPast,
31
+ CausalLMOutputWithPast,
32
+ SequenceClassifierOutputWithPast)
33
+ from transformers.modeling_utils import PreTrainedModel
34
+ from transformers.utils import (add_start_docstrings,
35
+ add_start_docstrings_to_model_forward, logging,
36
+ replace_return_docstrings)
37
+
38
+ from transformers import LogitsProcessorList, StoppingCriteriaList, GenerationConfig
39
+ from transformers.generation.utils import GenerateNonBeamOutput, GenerateDecoderOnlyOutput
40
+
41
+ try:
42
+ from transformers.generation.streamers import BaseStreamer
43
+ except: # noqa # pylint: disable=bare-except
44
+ BaseStreamer = None
45
+
46
+ from .configuration_internlm2 import InternLM2Config
47
+
48
+ logger = logging.get_logger(__name__)
49
+
50
+ _CONFIG_FOR_DOC = 'InternLM2Config'
51
+
52
+ flash_attn_func, flash_attn_varlen_func = None, None
53
+ pad_input, index_first_axis, unpad_input = None, None, None
54
+ try:
55
+ from flash_attn import flash_attn_func as _flash_attn_func
56
+ from flash_attn import flash_attn_varlen_func as _flash_attn_varlen_func
57
+ from flash_attn.bert_padding import index_first_axis as _index_first_axis
58
+ from flash_attn.bert_padding import pad_input as _pad_input
59
+ from flash_attn.bert_padding import unpad_input as _unpad_input
60
+
61
+ flash_attn_func, flash_attn_varlen_func = _flash_attn_func, _flash_attn_varlen_func
62
+ pad_input, index_first_axis, unpad_input = _pad_input, _index_first_axis, _unpad_input
63
+ has_flash_attn = True
64
+ except:
65
+ has_flash_attn = False
66
+
67
+
68
+ def _import_flash_attn():
69
+ global flash_attn_func, flash_attn_varlen_func
70
+ global pad_input, index_first_axis, unpad_input
71
+ try:
72
+ from flash_attn import flash_attn_func as _flash_attn_func
73
+ from flash_attn import \
74
+ flash_attn_varlen_func as _flash_attn_varlen_func
75
+ from flash_attn.bert_padding import \
76
+ index_first_axis as _index_first_axis
77
+ from flash_attn.bert_padding import pad_input as _pad_input
78
+ from flash_attn.bert_padding import unpad_input as _unpad_input
79
+ flash_attn_func, flash_attn_varlen_func = _flash_attn_func, _flash_attn_varlen_func
80
+ pad_input, index_first_axis, unpad_input = _pad_input, _index_first_axis, _unpad_input
81
+ except ImportError:
82
+ raise ImportError('flash_attn is not installed.')
83
+
84
+
85
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
86
+ def _get_unpad_data(attention_mask):
87
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
88
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
89
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
90
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
91
+ return (
92
+ indices,
93
+ cu_seqlens,
94
+ max_seqlen_in_batch,
95
+ )
96
+
97
+
98
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
99
+ def _make_causal_mask(
100
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
101
+ ):
102
+ """
103
+ Make causal mask used for bi-directional self-attention.
104
+ """
105
+ bsz, tgt_len = input_ids_shape
106
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
107
+ mask_cond = torch.arange(mask.size(-1), device=device)
108
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
109
+ mask = mask.to(dtype)
110
+
111
+ if past_key_values_length > 0:
112
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
113
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
114
+
115
+
116
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
117
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
118
+ """
119
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
120
+ """
121
+ bsz, src_len = mask.size()
122
+ tgt_len = tgt_len if tgt_len is not None else src_len
123
+
124
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
125
+
126
+ inverted_mask = 1.0 - expanded_mask
127
+
128
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
129
+
130
+
131
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->InternLM2
132
+ class InternLM2RMSNorm(nn.Module):
133
+ def __init__(self, hidden_size, eps=1e-6):
134
+ """
135
+ InternLM2RMSNorm is equivalent to T5LayerNorm
136
+ """
137
+ super().__init__()
138
+ self.weight = nn.Parameter(torch.ones(hidden_size))
139
+ self.variance_epsilon = eps
140
+
141
+ def forward(self, hidden_states):
142
+ input_dtype = hidden_states.dtype
143
+ hidden_states = hidden_states.to(torch.float32)
144
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
145
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
146
+ return self.weight * hidden_states.to(input_dtype)
147
+
148
+
149
+ try:
150
+ from functools import partial
151
+
152
+ from apex.normalization import FusedRMSNorm
153
+ InternLM2RMSNorm = partial(FusedRMSNorm, eps=1e-6) # noqa
154
+ print('Discovered apex.normalization.FusedRMSNorm - will use it instead of InternLM2RMSNorm')
155
+ except ImportError:
156
+ # using the normal LlamaRMSNorm
157
+ pass
158
+ except Exception:
159
+ print('discovered apex but it failed to load, falling back to InternLM2RMSNorm')
160
+ pass
161
+
162
+
163
+ # Copied from transformers.model.llama.modeling_llama.LlamaRotaryEmbedding with Llama->InternLM2
164
+ class InternLM2RotaryEmbedding(nn.Module):
165
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
166
+ super().__init__()
167
+
168
+ self.dim = dim
169
+ self.max_position_embeddings = max_position_embeddings
170
+ self.base = base
171
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
172
+ self.register_buffer('inv_freq', inv_freq, persistent=False)
173
+
174
+ # Build here to make `torch.jit.trace` work.
175
+ self._set_cos_sin_cache(
176
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
177
+ )
178
+
179
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
180
+ self.max_seq_len_cached = seq_len
181
+ t = torch.arange(self.max_seq_len_cached, device=device).to(dtype=self.inv_freq.dtype)
182
+
183
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
184
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
185
+ emb = torch.cat((freqs, freqs), dim=-1)
186
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
187
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
188
+
189
+ def forward(self, x, seq_len=None):
190
+ # x: [bs, num_attention_heads, seq_len, head_size]
191
+ if seq_len > self.max_seq_len_cached:
192
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=torch.float32)
193
+
194
+ return (
195
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
196
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
197
+ )
198
+
199
+
200
+ # Copied from transformers.model.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->InternLM2
201
+ class InternLM2LinearScalingRotaryEmbedding(InternLM2RotaryEmbedding):
202
+ """InternLM2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
203
+
204
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
205
+ self.scaling_factor = scaling_factor
206
+ super().__init__(dim, max_position_embeddings, base, device)
207
+
208
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
209
+ self.max_seq_len_cached = seq_len
210
+ t = torch.arange(self.max_seq_len_cached, device=device).to(dtype=self.inv_freq.dtype)
211
+ t = t / self.scaling_factor
212
+
213
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
214
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
215
+ emb = torch.cat((freqs, freqs), dim=-1)
216
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
217
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
218
+
219
+
220
+ # Copied from transformers.model.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->InternLM2
221
+ class InternLM2DynamicNTKScalingRotaryEmbedding(InternLM2RotaryEmbedding):
222
+ """InternLM2RotaryEmbedding extended with Dynamic NTK scaling.
223
+ Credits to the Reddit users /u/bloc97 and /u/emozilla.
224
+ """
225
+
226
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
227
+ self.scaling_factor = scaling_factor
228
+ super().__init__(dim, max_position_embeddings, base, device)
229
+
230
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
231
+ self.max_seq_len_cached = seq_len
232
+
233
+ if seq_len > self.max_position_embeddings:
234
+ base = self.base * (
235
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
236
+ ) ** (self.dim / (self.dim - 2))
237
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
238
+ self.register_buffer('inv_freq', inv_freq, persistent=False)
239
+
240
+ t = torch.arange(self.max_seq_len_cached, device=device).to(dtype=self.inv_freq.dtype)
241
+
242
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
243
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
244
+ emb = torch.cat((freqs, freqs), dim=-1)
245
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
246
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
247
+
248
+
249
+ # Copied from transformers.model.llama.modeling_llama.rotate_half
250
+ def rotate_half(x):
251
+ """Rotates half the hidden dims of the input."""
252
+ x1 = x[..., : x.shape[-1] // 2]
253
+ x2 = x[..., x.shape[-1] // 2:]
254
+ return torch.cat((-x2, x1), dim=-1)
255
+
256
+
257
+ # Copied from transformers.model.llama.modeling_llama.apply_rotary_pos_emb
258
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
259
+ """Applies Rotary Position Embedding to the query and key tensors."""
260
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
261
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
262
+ q_embed = (q * cos) + (rotate_half(q) * sin)
263
+ k_embed = (k * cos) + (rotate_half(k) * sin)
264
+ return q_embed, k_embed
265
+
266
+
267
+ class InternLM2MLP(nn.Module):
268
+ def __init__(self, config):
269
+ super().__init__()
270
+ self.config = config
271
+ self.hidden_size = config.hidden_size
272
+ self.intermediate_size = config.intermediate_size
273
+ self.w1 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
274
+ self.w3 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
275
+ self.w2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
276
+ self.act_fn = ACT2FN[config.hidden_act]
277
+
278
+ def forward(self, x):
279
+ down_proj = self.w2(self.act_fn(self.w1(x)) * self.w3(x))
280
+
281
+ return down_proj
282
+
283
+
284
+ # Copied from transformers.model.llama.modeling_llama.repeat_kv
285
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
286
+ """
287
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
288
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
289
+ """
290
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
291
+ if n_rep == 1:
292
+ return hidden_states
293
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
294
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
295
+
296
+
297
+ # Modified from transformers.model.llama.modeling_llama.LlamaAttention
298
+ class InternLM2Attention(nn.Module):
299
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
300
+
301
+ def __init__(self, config: InternLM2Config):
302
+ super().__init__()
303
+ self.config = config
304
+ self.hidden_size = config.hidden_size
305
+ self.num_heads = config.num_attention_heads
306
+ self.head_dim = self.hidden_size // self.num_heads
307
+ self.num_key_value_heads = config.num_key_value_heads
308
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
309
+ self.max_position_embeddings = config.max_position_embeddings
310
+ self.is_causal = True
311
+
312
+ if (self.head_dim * self.num_heads) != self.hidden_size:
313
+ raise ValueError(
314
+ f'hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}'
315
+ f' and `num_heads`: {self.num_heads}).'
316
+ )
317
+
318
+ self.wqkv = nn.Linear(
319
+ self.hidden_size,
320
+ (self.num_heads + 2 * self.num_key_value_heads) * self.head_dim,
321
+ bias=config.bias,
322
+ )
323
+
324
+ self.wo = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.bias)
325
+ self._init_rope()
326
+
327
+ def _init_rope(self):
328
+ if self.config.rope_scaling is None:
329
+ self.rotary_emb = InternLM2RotaryEmbedding(
330
+ self.head_dim,
331
+ max_position_embeddings=self.max_position_embeddings,
332
+ base=self.config.rope_theta,
333
+ )
334
+ else:
335
+ scaling_type = self.config.rope_scaling['type']
336
+ scaling_factor = self.config.rope_scaling['factor']
337
+ if scaling_type == 'dynamic':
338
+ self.rotary_emb = InternLM2DynamicNTKScalingRotaryEmbedding(
339
+ self.head_dim,
340
+ max_position_embeddings=self.max_position_embeddings,
341
+ base=self.config.rope_theta,
342
+ scaling_factor=scaling_factor,
343
+ )
344
+ elif scaling_type == 'linear':
345
+ self.rotary_emb = InternLM2LinearScalingRotaryEmbedding(
346
+ self.head_dim,
347
+ max_position_embeddings=self.max_position_embeddings,
348
+ base=self.config.rope_theta,
349
+ scaling_factor=scaling_factor,
350
+ )
351
+ else:
352
+ raise ValueError("Currently we only support rotary embedding's type being 'dynamic' or 'linear'.")
353
+ return self.rotary_emb
354
+
355
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
356
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
357
+
358
+ def forward(
359
+ self,
360
+ hidden_states: torch.Tensor,
361
+ attention_mask: Optional[torch.Tensor] = None,
362
+ position_ids: Optional[torch.LongTensor] = None,
363
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
364
+ output_attentions: bool = False,
365
+ use_cache: bool = False,
366
+ **kwargs,
367
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
368
+ if 'padding_mask' in kwargs:
369
+ warnings.warn(
370
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. '
371
+ 'Please make sure use `attention_mask` instead.`'
372
+ )
373
+
374
+ bsz, q_len, _ = hidden_states.size()
375
+
376
+ qkv_states = self.wqkv(hidden_states)
377
+
378
+ qkv_states = rearrange(
379
+ qkv_states,
380
+ 'b q (h gs d) -> b q h gs d',
381
+ gs=2 + self.num_key_value_groups,
382
+ d=self.head_dim,
383
+ )
384
+
385
+ query_states = qkv_states[..., : self.num_key_value_groups, :]
386
+ query_states = rearrange(query_states, 'b q h gs d -> b q (h gs) d')
387
+ key_states = qkv_states[..., -2, :]
388
+ value_states = qkv_states[..., -1, :]
389
+
390
+ query_states = query_states.transpose(1, 2)
391
+ key_states = key_states.transpose(1, 2)
392
+ value_states = value_states.transpose(1, 2)
393
+
394
+ kv_seq_len = key_states.shape[-2]
395
+ if past_key_value is not None:
396
+ kv_seq_len += past_key_value[0].shape[-2]
397
+
398
+ prunded_sequence_length = kwargs["prunded_sequence_length"]
399
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len + prunded_sequence_length)
400
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
401
+
402
+ if past_key_value is not None:
403
+ # reuse k, v, self_attention
404
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
405
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
406
+
407
+ past_key_value = (key_states, value_states) if use_cache else None
408
+
409
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
410
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
411
+
412
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
413
+
414
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
415
+ raise ValueError(
416
+ f'Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is'
417
+ f' {attn_weights.size()}'
418
+ )
419
+
420
+ if attention_mask is not None:
421
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
422
+ raise ValueError(
423
+ f'Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}'
424
+ )
425
+ attn_weights = attn_weights + attention_mask
426
+
427
+ # upcast attention to fp32
428
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
429
+ attn_output = torch.matmul(attn_weights, value_states)
430
+
431
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
432
+ raise ValueError(
433
+ f'`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is'
434
+ f' {attn_output.size()}'
435
+ )
436
+
437
+ attn_output = attn_output.transpose(1, 2).contiguous()
438
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
439
+
440
+ attn_output = self.wo(attn_output)
441
+
442
+ if not output_attentions:
443
+ attn_weights = None
444
+
445
+ return attn_output, attn_weights, past_key_value
446
+
447
+
448
+ # Modified from transformers.model.llama.modeling_llama.InternLM2FlashAttention2
449
+ class InternLM2FlashAttention2(InternLM2Attention):
450
+ """
451
+ InternLM2 flash attention module. This module inherits from `InternLM2Attention` as the weights of the module stays
452
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
453
+ flash attention and deal with padding tokens in case the input contains any of them.
454
+ """
455
+
456
+ def forward(
457
+ self,
458
+ hidden_states: torch.Tensor,
459
+ attention_mask: Optional[torch.LongTensor] = None,
460
+ position_ids: Optional[torch.LongTensor] = None,
461
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
462
+ output_attentions: bool = False,
463
+ use_cache: bool = False,
464
+ **kwargs,
465
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
466
+
467
+
468
+ # InternLM2FlashAttention2 attention does not support output_attentions
469
+ if 'padding_mask' in kwargs:
470
+ warnings.warn(
471
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. '
472
+ 'Please make sure use `attention_mask` instead.`'
473
+ )
474
+
475
+ # overwrite attention_mask with padding_mask
476
+ attention_mask = kwargs.pop('padding_mask')
477
+
478
+ output_attentions = False
479
+
480
+ bsz, q_len, _ = hidden_states.size()
481
+
482
+ qkv_states = self.wqkv(hidden_states)
483
+
484
+ qkv_states = rearrange(
485
+ qkv_states,
486
+ 'b q (h gs d) -> b q h gs d',
487
+ gs=2 + self.num_key_value_groups,
488
+ d=self.head_dim,
489
+ )
490
+
491
+ query_states = qkv_states[..., : self.num_key_value_groups, :]
492
+ query_states = rearrange(query_states, 'b q h gs d -> b q (h gs) d')
493
+ key_states = qkv_states[..., -2, :]
494
+ value_states = qkv_states[..., -1, :]
495
+
496
+ query_states = query_states.transpose(1, 2)
497
+ key_states = key_states.transpose(1, 2)
498
+ value_states = value_states.transpose(1, 2)
499
+
500
+ kv_seq_len = key_states.shape[-2]
501
+ if past_key_value is not None:
502
+ kv_seq_len += past_key_value[0].shape[-2]
503
+
504
+ prunded_sequence_length = kwargs["prunded_sequence_length"]
505
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len + prunded_sequence_length)
506
+
507
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
508
+
509
+ if past_key_value is not None:
510
+ # reuse k, v, self_attention
511
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
512
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
513
+
514
+ past_key_value = (key_states, value_states) if use_cache else None
515
+
516
+ query_states = query_states.transpose(1, 2)
517
+ key_states = key_states.transpose(1, 2)
518
+ value_states = value_states.transpose(1, 2)
519
+
520
+ attn_output = self._flash_attention_forward(
521
+ query_states, key_states, value_states, attention_mask, q_len
522
+ )
523
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
524
+ attn_output = self.wo(attn_output)
525
+
526
+ if not output_attentions:
527
+ attn_weights = None
528
+
529
+ return attn_output, attn_weights, past_key_value
530
+
531
+ def _flash_attention_forward(
532
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
533
+ ):
534
+ """
535
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
536
+ first unpad the input, then computes the attention scores and pad the final attention scores.
537
+
538
+ Args:
539
+ query_states (`torch.Tensor`):
540
+ Input query states to be passed to Flash Attention API
541
+ key_states (`torch.Tensor`):
542
+ Input key states to be passed to Flash Attention API
543
+ value_states (`torch.Tensor`):
544
+ Input value states to be passed to Flash Attention API
545
+ attention_mask (`torch.Tensor`):
546
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
547
+ position of padding tokens and 1 for the position of non-padding tokens.
548
+ dropout (`int`, *optional*):
549
+ Attention dropout
550
+ softmax_scale (`float`, *optional*):
551
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
552
+ """
553
+ # Contains at least one padding token in the sequence
554
+ causal = self.is_causal and query_length != 1
555
+ if attention_mask is not None:
556
+ batch_size = query_states.shape[0]
557
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._unpad_input(
558
+ query_states, key_states, value_states, attention_mask, query_length
559
+ )
560
+
561
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
562
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
563
+
564
+ attn_output_unpad = flash_attn_varlen_func(
565
+ query_states,
566
+ key_states,
567
+ value_states,
568
+ cu_seqlens_q=cu_seqlens_q,
569
+ cu_seqlens_k=cu_seqlens_k,
570
+ max_seqlen_q=max_seqlen_in_batch_q,
571
+ max_seqlen_k=max_seqlen_in_batch_k,
572
+ dropout_p=dropout,
573
+ softmax_scale=softmax_scale,
574
+ causal=causal,
575
+ )
576
+
577
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
578
+ else:
579
+ attn_output = flash_attn_func(
580
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
581
+ )
582
+
583
+ return attn_output
584
+
585
+ def _unpad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
586
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
587
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
588
+
589
+ key_layer = index_first_axis(
590
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
591
+ )
592
+ value_layer = index_first_axis(
593
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
594
+ )
595
+
596
+ if query_length == kv_seq_len:
597
+ query_layer = index_first_axis(
598
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
599
+ )
600
+ cu_seqlens_q = cu_seqlens_k
601
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
602
+ indices_q = indices_k
603
+ elif query_length == 1:
604
+ max_seqlen_in_batch_q = 1
605
+ cu_seqlens_q = torch.arange(
606
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
607
+ ) # There is a memcpy here, that is very bad.
608
+ indices_q = cu_seqlens_q[:-1]
609
+ query_layer = query_layer.squeeze(1)
610
+ else:
611
+ # The -q_len: slice assumes left padding.
612
+ attention_mask = attention_mask[:, -query_length:]
613
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
614
+
615
+ return (
616
+ query_layer,
617
+ key_layer,
618
+ value_layer,
619
+ indices_q.to(torch.int64),
620
+ (cu_seqlens_q, cu_seqlens_k),
621
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
622
+ )
623
+
624
+
625
+ INTERNLM2_ATTENTION_CLASSES = {
626
+ 'eager': InternLM2Attention,
627
+ 'flash_attention_2': InternLM2FlashAttention2,
628
+ }
629
+
630
+
631
+ # Modified from transformers.model.llama.modeling_llama.LlamaDecoderLayer
632
+ class InternLM2DecoderLayer(nn.Module):
633
+ def __init__(self, config: InternLM2Config):
634
+ super().__init__()
635
+ self.hidden_size = config.hidden_size
636
+
637
+ self.attention = INTERNLM2_ATTENTION_CLASSES[config.attn_implementation](config=config)
638
+
639
+ self.feed_forward = InternLM2MLP(config)
640
+ self.attention_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
641
+ self.ffn_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
642
+
643
+ def forward(
644
+ self,
645
+ hidden_states: torch.Tensor,
646
+ attention_mask: Optional[torch.Tensor] = None,
647
+ position_ids: Optional[torch.LongTensor] = None,
648
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
649
+ output_attentions: Optional[bool] = False,
650
+ use_cache: Optional[bool] = False,
651
+ **kwargs,
652
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
653
+ """
654
+ Args:
655
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
656
+ attention_mask (`torch.FloatTensor`, *optional*):
657
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
658
+ query_sequence_length, key_sequence_length)` if default attention is used.
659
+ output_attentions (`bool`, *optional*):
660
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
661
+ returned tensors for more detail.
662
+ use_cache (`bool`, *optional*):
663
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
664
+ (see `past_key_values`).
665
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
666
+ """
667
+ if 'padding_mask' in kwargs:
668
+ warnings.warn(
669
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. '
670
+ 'Please make sure use `attention_mask` instead.`'
671
+ )
672
+
673
+ residual = hidden_states
674
+
675
+ hidden_states = self.attention_norm(hidden_states)
676
+
677
+ # Self Attention
678
+ hidden_states, self_attn_weights, present_key_value = self.attention(
679
+ hidden_states=hidden_states,
680
+ attention_mask=attention_mask,
681
+ position_ids=position_ids,
682
+ past_key_value=past_key_value,
683
+ output_attentions=output_attentions,
684
+ use_cache=use_cache,
685
+ **kwargs,
686
+ )
687
+ hidden_states = residual + hidden_states
688
+
689
+ # Fully Connected
690
+ residual = hidden_states
691
+ hidden_states = self.ffn_norm(hidden_states)
692
+ hidden_states = self.feed_forward(hidden_states)
693
+ hidden_states = residual + hidden_states
694
+
695
+ outputs = (hidden_states,)
696
+
697
+ if output_attentions:
698
+ outputs += (self_attn_weights,)
699
+
700
+ if use_cache:
701
+ outputs += (present_key_value,)
702
+
703
+ return outputs
704
+
705
+
706
+ InternLM2_START_DOCSTRING = r"""
707
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
708
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
709
+ etc.)
710
+
711
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
712
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
713
+ and behavior.
714
+
715
+ Parameters:
716
+ config ([`InternLM2Config`]):
717
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
718
+ load the weights associated with the model, only the configuration. Check out the
719
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
720
+ """
721
+
722
+
723
+ # Copied from transformers.models.llama.modeling_llama.LlamaPreTrainedModel with Llama->InternLM2
724
+ @add_start_docstrings(
725
+ 'The bare InternLM2 Model outputting raw hidden-states without any specific head on top.',
726
+ InternLM2_START_DOCSTRING,
727
+ )
728
+ class InternLM2PreTrainedModel(PreTrainedModel):
729
+ config_class = InternLM2Config
730
+ base_model_prefix = 'model'
731
+ supports_gradient_checkpointing = True
732
+ _no_split_modules = ['InternLM2DecoderLayer']
733
+ _skip_keys_device_placement = 'past_key_values'
734
+ _supports_flash_attn_2 = True
735
+
736
+ def _init_weights(self, module):
737
+ std = self.config.initializer_range
738
+ if isinstance(module, nn.Linear):
739
+ module.weight.data.normal_(mean=0.0, std=std)
740
+ if module.bias is not None:
741
+ module.bias.data.zero_()
742
+ elif isinstance(module, nn.Embedding):
743
+ module.weight.data.normal_(mean=0.0, std=std)
744
+ if module.padding_idx is not None:
745
+ module.weight.data[module.padding_idx].zero_()
746
+
747
+
748
+ InternLM2_INPUTS_DOCSTRING = r"""
749
+ Args:
750
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
751
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
752
+ it.
753
+
754
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
755
+ [`PreTrainedTokenizer.__call__`] for details.
756
+
757
+ [What are input IDs?](../glossary#input-ids)
758
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
759
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
760
+
761
+ - 1 for tokens that are **not masked**,
762
+ - 0 for tokens that are **masked**.
763
+
764
+ [What are attention masks?](../glossary#attention-mask)
765
+
766
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
767
+ [`PreTrainedTokenizer.__call__`] for details.
768
+
769
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
770
+ `past_key_values`).
771
+
772
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
773
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
774
+ information on the default strategy.
775
+
776
+ - 1 indicates the head is **not masked**,
777
+ - 0 indicates the head is **masked**.
778
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
779
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
780
+ config.n_positions - 1]`.
781
+
782
+ [What are position IDs?](../glossary#position-ids)
783
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or
784
+ when `config.use_cache=True`):
785
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
786
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
787
+ `(batch_size, num_heads, decoder_sequence_length, embed_size_per_head)`.
788
+
789
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
790
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
791
+
792
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
793
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
794
+ of shape `(batch_size, sequence_length)`.
795
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
796
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
797
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
798
+ model's internal embedding lookup matrix.
799
+ use_cache (`bool`, *optional*):
800
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
801
+ `past_key_values`).
802
+ output_attentions (`bool`, *optional*):
803
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
804
+ tensors for more detail.
805
+ output_hidden_states (`bool`, *optional*):
806
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
807
+ more detail.
808
+ return_dict (`bool`, *optional*):
809
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
810
+ """
811
+
812
+
813
+ # Modified from transformers.model.llama.modeling_llama.LlamaModel
814
+ @add_start_docstrings(
815
+ 'The bare InternLM2 Model outputting raw hidden-states without any specific head on top.',
816
+ InternLM2_START_DOCSTRING,
817
+ )
818
+ class InternLM2Model(InternLM2PreTrainedModel):
819
+ """
820
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`InternLM2DecoderLayer`]
821
+
822
+ Args:
823
+ config: InternLM2Config
824
+ """
825
+
826
+ _auto_class = 'AutoModel'
827
+
828
+ def __init__(self, config: InternLM2Config):
829
+ super().__init__(config)
830
+ self.padding_idx = config.pad_token_id
831
+ self.vocab_size = config.vocab_size
832
+ self.config = config
833
+ if not has_flash_attn:
834
+ self.config.attn_implementation = 'eager'
835
+ print('Warning: Flash attention is not available, using eager attention instead.')
836
+
837
+ self.tok_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
838
+
839
+ self.layers = nn.ModuleList([InternLM2DecoderLayer(config) for _ in range(config.num_hidden_layers)])
840
+ self.norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
841
+
842
+ self.gradient_checkpointing = False
843
+ # Initialize weights and apply final processing
844
+ self.post_init()
845
+
846
+ def get_input_embeddings(self):
847
+ return self.tok_embeddings
848
+
849
+ def set_input_embeddings(self, value):
850
+ self.tok_embeddings = value
851
+
852
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
853
+ # create causal mask
854
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
855
+ combined_attention_mask = None
856
+ if input_shape[-1] > 1:
857
+ combined_attention_mask = _make_causal_mask(
858
+ input_shape,
859
+ inputs_embeds.dtype,
860
+ device=inputs_embeds.device,
861
+ past_key_values_length=past_key_values_length,
862
+ )
863
+
864
+ if attention_mask is not None:
865
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
866
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
867
+ inputs_embeds.device
868
+ )
869
+ combined_attention_mask = (
870
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
871
+ )
872
+
873
+ return combined_attention_mask
874
+
875
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
876
+ def forward(
877
+ self,
878
+ input_ids: torch.LongTensor = None,
879
+ attention_mask: Optional[torch.Tensor] = None,
880
+ position_ids: Optional[torch.LongTensor] = None,
881
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
882
+ inputs_embeds: Optional[torch.FloatTensor] = None,
883
+ use_cache: Optional[bool] = None,
884
+ output_attentions: Optional[bool] = None,
885
+ output_hidden_states: Optional[bool] = None,
886
+ return_dict: Optional[bool] = None,
887
+ visual_token_index: Optional[torch.Tensor] = None,
888
+ large_model_prune_layer: Optional[float] = None,
889
+ large_model_prune_ratio: Optional[float] = None,
890
+ visual_token_importance: Optional[torch.Tensor] = None,
891
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
892
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
893
+ output_hidden_states = (
894
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
895
+ )
896
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
897
+
898
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
899
+
900
+ if self.config.attn_implementation == 'flash_attention_2':
901
+ _import_flash_attn()
902
+
903
+ # retrieve input_ids and inputs_embeds
904
+ if input_ids is not None and inputs_embeds is not None:
905
+ raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time')
906
+ elif input_ids is not None:
907
+ batch_size, seq_length = input_ids.shape[:2]
908
+ elif inputs_embeds is not None:
909
+ batch_size, seq_length = inputs_embeds.shape[:2]
910
+ else:
911
+ raise ValueError('You have to specify either input_ids or inputs_embeds')
912
+
913
+ seq_length_with_past = seq_length
914
+ past_key_values_length = 0
915
+ if past_key_values is not None:
916
+ past_key_values_length = past_key_values[0][0].shape[2]
917
+ seq_length_with_past = seq_length_with_past + past_key_values_length
918
+
919
+ if position_ids is None:
920
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
921
+ position_ids = torch.arange(
922
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
923
+ )
924
+ position_ids = position_ids.unsqueeze(0)
925
+
926
+ if inputs_embeds is None:
927
+ inputs_embeds = self.tok_embeddings(input_ids)
928
+
929
+ if self.config.attn_implementation == 'flash_attention_2':
930
+ # 2d mask is passed through the layers
931
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
932
+ else:
933
+ if attention_mask is None:
934
+ attention_mask = torch.ones(
935
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
936
+ )
937
+ attention_mask = self._prepare_decoder_attention_mask(
938
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
939
+ )
940
+
941
+ # embed positions
942
+ hidden_states = inputs_embeds
943
+
944
+ if self.gradient_checkpointing and self.training:
945
+ if use_cache:
946
+ logger.warning_once(
947
+ '`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...'
948
+ )
949
+ use_cache = False
950
+
951
+ # decoder layers
952
+ all_hidden_states = () if output_hidden_states else None
953
+ all_self_attns = () if output_attentions else None
954
+ next_decoder_cache = () if use_cache else None
955
+
956
+ if large_model_prune_layer is not None:
957
+ token_prune = True
958
+ K = int(len(self.layers) * large_model_prune_layer)
959
+ keep_ratio = large_model_prune_ratio
960
+ else:
961
+ token_prune = False
962
+
963
+
964
+ aggregated_viusal_token_attention = 0 if output_attentions else None
965
+ prunded_sequence_length = 0
966
+ for idx, decoder_layer in enumerate(self.layers):
967
+ if output_hidden_states:
968
+ all_hidden_states += (hidden_states,)
969
+
970
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
971
+
972
+ if self.gradient_checkpointing and self.training:
973
+
974
+ def create_custom_forward(module):
975
+ def custom_forward(*inputs):
976
+ # None for past_key_value
977
+ return module(*inputs, output_attentions, None)
978
+
979
+ return custom_forward
980
+
981
+ layer_outputs = torch.utils.checkpoint.checkpoint(
982
+ create_custom_forward(decoder_layer),
983
+ hidden_states,
984
+ attention_mask,
985
+ position_ids,
986
+ None,
987
+ )
988
+ else:
989
+
990
+ ##### 某一层 random pruning #########
991
+ if token_prune:
992
+ if hidden_states.shape[1] != 1:
993
+ if idx == K:
994
+ device = hidden_states.device
995
+ visual_token_length = visual_token_index[1] - visual_token_index[0] + 1
996
+ image_attention_score = visual_token_importance.unsqueeze(0)
997
+ top_attention_rank_index = image_attention_score.topk(int(visual_token_length * keep_ratio), dim=-1).indices[0] + int(visual_token_index[0])
998
+ keep_indexs = torch.cat((torch.arange(int(visual_token_index[0]), device=device), top_attention_rank_index.to(device), torch.arange(int(visual_token_index[1]+1), seq_length, device=device)))
999
+ keep_indexs = keep_indexs.sort().values
1000
+ hidden_states = hidden_states[:, keep_indexs,:]
1001
+ if attention_mask is not None:
1002
+ attention_mask = attention_mask[:,:,:hidden_states.shape[1], :hidden_states.shape[1]]
1003
+ position_ids = keep_indexs.unsqueeze(0)
1004
+ prunded_sequence_length = visual_token_length - int(visual_token_length * keep_ratio)
1005
+
1006
+
1007
+ else:
1008
+ if idx == K:
1009
+ visual_token_length = visual_token_index[1] - visual_token_index[0] + 1
1010
+ prunded_sequence_length = visual_token_length - int(visual_token_length * keep_ratio)
1011
+ if attention_mask is not None:
1012
+ attention_mask = attention_mask[:, :, :, prunded_sequence_length:]
1013
+
1014
+
1015
+
1016
+
1017
+ layer_outputs = decoder_layer(
1018
+ hidden_states,
1019
+ attention_mask=attention_mask,
1020
+ position_ids=position_ids,
1021
+ past_key_value=past_key_value,
1022
+ output_attentions=output_attentions,
1023
+ use_cache=use_cache,
1024
+ prunded_sequence_length=prunded_sequence_length
1025
+ )
1026
+
1027
+ hidden_states = layer_outputs[0]
1028
+
1029
+ if use_cache:
1030
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
1031
+
1032
+ if output_attentions:
1033
+ # all_self_attns += (layer_outputs[1],)
1034
+ if layer_outputs[1].shape[2] != 1:
1035
+ aggregated_viusal_token_attention = aggregated_viusal_token_attention + layer_outputs[1][:, :, visual_token_index[1]:, visual_token_index[0]:visual_token_index[1]+1].sum(dim=(0, 1, 2))
1036
+ else:
1037
+ aggregated_viusal_token_attention = aggregated_viusal_token_attention + layer_outputs[1][:, :, :, visual_token_index[0]:visual_token_index[1]+1].sum(dim=(0, 1, 2))
1038
+
1039
+ hidden_states = self.norm(hidden_states)
1040
+
1041
+ # add hidden states from the last decoder layer
1042
+ if output_hidden_states:
1043
+ all_hidden_states += (hidden_states,)
1044
+
1045
+ next_cache = next_decoder_cache if use_cache else None
1046
+ if not return_dict:
1047
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1048
+
1049
+
1050
+ out_dict = BaseModelOutputWithPast(
1051
+ last_hidden_state=hidden_states,
1052
+ past_key_values=next_cache,
1053
+ hidden_states=all_hidden_states,
1054
+ attentions=all_self_attns,
1055
+ )
1056
+ out_dict.aggregated_viusal_token_attention = aggregated_viusal_token_attention
1057
+
1058
+ return out_dict
1059
+
1060
+
1061
+ # Modified from transformers.model.llama.modeling_llama.LlamaForCausalLM
1062
+ class InternLM2ForCausalLM(InternLM2PreTrainedModel):
1063
+ _auto_class = 'AutoModelForCausalLM'
1064
+
1065
+ _tied_weights_keys = ['output.weight']
1066
+
1067
+ def __init__(self, config):
1068
+ super().__init__(config)
1069
+ self.model = InternLM2Model(config)
1070
+ self.vocab_size = config.vocab_size
1071
+ self.output = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1072
+
1073
+ # Initialize weights and apply final processing
1074
+ self.post_init()
1075
+
1076
+ def get_input_embeddings(self):
1077
+ return self.model.tok_embeddings
1078
+
1079
+ def set_input_embeddings(self, value):
1080
+ self.model.tok_embeddings = value
1081
+
1082
+ def get_output_embeddings(self):
1083
+ return self.output
1084
+
1085
+ def set_output_embeddings(self, new_embeddings):
1086
+ self.output = new_embeddings
1087
+
1088
+ def set_decoder(self, decoder):
1089
+ self.model = decoder
1090
+
1091
+ def get_decoder(self):
1092
+ return self.model
1093
+
1094
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
1095
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1096
+ def forward(
1097
+ self,
1098
+ input_ids: torch.LongTensor = None,
1099
+ attention_mask: Optional[torch.Tensor] = None,
1100
+ position_ids: Optional[torch.LongTensor] = None,
1101
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1102
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1103
+ labels: Optional[torch.LongTensor] = None,
1104
+ use_cache: Optional[bool] = None,
1105
+ output_attentions: Optional[bool] = None,
1106
+ output_hidden_states: Optional[bool] = None,
1107
+ return_dict: Optional[bool] = None,
1108
+ visual_token_index: Optional[torch.Tensor] = None,
1109
+ large_model_prune_layer: Optional[float] = None,
1110
+ large_model_prune_ratio: Optional[float] = None,
1111
+ visual_token_importance: Optional[torch.Tensor] = None
1112
+
1113
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1114
+ r"""
1115
+ Args:
1116
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1117
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1118
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1119
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1120
+
1121
+ Returns:
1122
+
1123
+ Example:
1124
+
1125
+ ```python
1126
+ >>> from transformers import AutoTokenizer, InternLM2ForCausalLM
1127
+
1128
+ >>> model = InternLM2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1129
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1130
+
1131
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1132
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1133
+
1134
+ >>> # Generate
1135
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1136
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1137
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1138
+ ```"""
1139
+
1140
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1141
+ output_hidden_states = (
1142
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1143
+ )
1144
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1145
+
1146
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1147
+ outputs = self.model(
1148
+ input_ids=input_ids,
1149
+ attention_mask=attention_mask,
1150
+ position_ids=position_ids,
1151
+ past_key_values=past_key_values,
1152
+ inputs_embeds=inputs_embeds,
1153
+ use_cache=use_cache,
1154
+ output_attentions=output_attentions,
1155
+ output_hidden_states=output_hidden_states,
1156
+ return_dict=return_dict,
1157
+ visual_token_index=visual_token_index,
1158
+ large_model_prune_layer=large_model_prune_layer,
1159
+ large_model_prune_ratio=large_model_prune_ratio,
1160
+ visual_token_importance=visual_token_importance
1161
+ )
1162
+
1163
+ hidden_states = outputs[0]
1164
+ logits = self.output(hidden_states)
1165
+ logits = logits.float()
1166
+
1167
+ loss = None
1168
+ if labels is not None:
1169
+ # Shift so that tokens < n predict n
1170
+ shift_logits = logits[..., :-1, :].contiguous()
1171
+ shift_labels = labels[..., 1:].contiguous()
1172
+ # Flatten the tokens
1173
+ loss_fct = CrossEntropyLoss()
1174
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1175
+ shift_labels = shift_labels.view(-1)
1176
+ # Enable model parallelism
1177
+ shift_labels = shift_labels.to(shift_logits.device)
1178
+ loss = loss_fct(shift_logits, shift_labels)
1179
+
1180
+ if not return_dict:
1181
+ output = (logits,) + outputs[1:]
1182
+ return (loss,) + output if loss is not None else output
1183
+
1184
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1185
+ output = CausalLMOutputWithPast(
1186
+ loss=loss,
1187
+ logits=logits,
1188
+ past_key_values=outputs.past_key_values,
1189
+ hidden_states=outputs.hidden_states,
1190
+ attentions=outputs.attentions,
1191
+ )
1192
+ output['aggregated_viusal_token_attention'] = outputs.aggregated_viusal_token_attention
1193
+ output['logits'] = output['logits'].to(device)
1194
+ return output
1195
+
1196
+
1197
+ def _sample(
1198
+ self,
1199
+ input_ids: torch.LongTensor,
1200
+ logits_processor: LogitsProcessorList,
1201
+ stopping_criteria: StoppingCriteriaList,
1202
+ generation_config: GenerationConfig,
1203
+ synced_gpus: bool,
1204
+ streamer: Optional["BaseStreamer"],
1205
+ logits_warper: Optional[LogitsProcessorList],
1206
+ **model_kwargs,
1207
+ ) -> Union[GenerateNonBeamOutput, torch.LongTensor]:
1208
+ # init values
1209
+ pad_token_id = generation_config._pad_token_tensor
1210
+ output_attentions = generation_config.output_attentions
1211
+ output_hidden_states = generation_config.output_hidden_states
1212
+ output_scores = generation_config.output_scores
1213
+ output_logits = generation_config.output_logits
1214
+ return_dict_in_generate = generation_config.return_dict_in_generate
1215
+ max_length = generation_config.max_length
1216
+ has_eos_stopping_criteria = any(hasattr(criteria, "eos_token_id") for criteria in stopping_criteria)
1217
+ do_sample = generation_config.do_sample
1218
+ if do_sample is True and not isinstance(logits_warper, LogitsProcessorList):
1219
+ raise ValueError(
1220
+ "`do_sample` is set to `True`, `logits_warper` must be a `LogitsProcessorList` instance (it is "
1221
+ f"{logits_warper})."
1222
+ )
1223
+
1224
+ # init attention / hidden states / scores tuples
1225
+ scores = () if (return_dict_in_generate and output_scores) else None
1226
+ raw_logits = () if (return_dict_in_generate and output_logits) else None
1227
+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
1228
+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None
1229
+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
1230
+
1231
+ # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
1232
+ if return_dict_in_generate and self.config.is_encoder_decoder:
1233
+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
1234
+ encoder_hidden_states = (
1235
+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
1236
+ )
1237
+
1238
+ # keep track of which sequences are already finished
1239
+ batch_size, cur_len = input_ids.shape
1240
+ this_peer_finished = False
1241
+ unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
1242
+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
1243
+
1244
+ aggregated_viusal_token_attention = 0 if output_attentions else None
1245
+ while self._has_unfinished_sequences(
1246
+ this_peer_finished, synced_gpus, device=input_ids.device, cur_len=cur_len, max_length=max_length
1247
+ ):
1248
+ # prepare model inputs
1249
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
1250
+
1251
+ # prepare variable output controls (note: some models won't accept all output controls)
1252
+ model_inputs.update({"output_attentions": output_attentions} if output_attentions else {})
1253
+ model_inputs.update({"output_hidden_states": output_hidden_states} if output_hidden_states else {})
1254
+
1255
+ # forward pass to get next token
1256
+ outputs = self(**model_inputs, return_dict=True)
1257
+ if output_attentions:
1258
+ aggregated_viusal_token_attention = aggregated_viusal_token_attention + outputs['aggregated_viusal_token_attention']
1259
+
1260
+ if synced_gpus and this_peer_finished:
1261
+ continue # don't waste resources running the code we don't need
1262
+
1263
+ # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration
1264
+ # (the clone itself is always small)
1265
+ next_token_logits = outputs.logits[:, -1, :].clone()
1266
+
1267
+ # pre-process distribution
1268
+ next_token_scores = logits_processor(input_ids, next_token_logits)
1269
+ if do_sample:
1270
+ next_token_scores = logits_warper(input_ids, next_token_scores)
1271
+
1272
+ # Store scores, attentions and hidden_states when required
1273
+ if return_dict_in_generate:
1274
+ if output_scores:
1275
+ scores += (next_token_scores,)
1276
+ if output_logits:
1277
+ raw_logits += (next_token_logits,)
1278
+ if output_attentions:
1279
+ decoder_attentions += (
1280
+ (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
1281
+ )
1282
+ if self.config.is_encoder_decoder:
1283
+ cross_attentions += (outputs.cross_attentions,)
1284
+
1285
+ if output_hidden_states:
1286
+ decoder_hidden_states += (
1287
+ (outputs.decoder_hidden_states,)
1288
+ if self.config.is_encoder_decoder
1289
+ else (outputs.hidden_states,)
1290
+ )
1291
+
1292
+ # token selection
1293
+ if do_sample:
1294
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
1295
+ # TODO (joao): this OP throws "skipping cudagraphs due to ['incompatible ops']", find solution
1296
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
1297
+ else:
1298
+ next_tokens = torch.argmax(next_token_scores, dim=-1)
1299
+
1300
+ # finished sentences should have their next token be a padding token
1301
+ if has_eos_stopping_criteria:
1302
+ next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)
1303
+
1304
+ # update generated ids, model inputs, and length for next step
1305
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
1306
+ if streamer is not None:
1307
+ streamer.put(next_tokens.cpu())
1308
+ model_kwargs = self._update_model_kwargs_for_generation(
1309
+ outputs,
1310
+ model_kwargs,
1311
+ is_encoder_decoder=self.config.is_encoder_decoder,
1312
+ )
1313
+
1314
+ unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)
1315
+ this_peer_finished = unfinished_sequences.max() == 0
1316
+ cur_len += 1
1317
+
1318
+ # This is needed to properly delete outputs.logits which may be very large for first iteration
1319
+ # Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration
1320
+ del outputs
1321
+
1322
+ if streamer is not None:
1323
+ streamer.end()
1324
+
1325
+ if return_dict_in_generate:
1326
+ if self.config.is_encoder_decoder:
1327
+ return GenerateEncoderDecoderOutput(
1328
+ sequences=input_ids,
1329
+ scores=scores,
1330
+ logits=raw_logits,
1331
+ encoder_attentions=encoder_attentions,
1332
+ encoder_hidden_states=encoder_hidden_states,
1333
+ decoder_attentions=decoder_attentions,
1334
+ cross_attentions=cross_attentions,
1335
+ decoder_hidden_states=decoder_hidden_states,
1336
+ past_key_values=model_kwargs.get("past_key_values"),
1337
+ )
1338
+ else:
1339
+ out_dict = GenerateDecoderOnlyOutput(
1340
+ sequences=input_ids,
1341
+ scores=scores,
1342
+ logits=raw_logits,
1343
+ attentions=decoder_attentions,
1344
+ hidden_states=decoder_hidden_states,
1345
+ past_key_values=model_kwargs.get("past_key_values"),
1346
+ )
1347
+ out_dict["aggregated_viusal_token_attention"] = aggregated_viusal_token_attention
1348
+ return out_dict
1349
+ else:
1350
+ return input_ids
1351
+
1352
+ def prepare_inputs_for_generation(
1353
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1354
+ ):
1355
+ if past_key_values is not None:
1356
+ past_length = past_key_values[0][0].shape[2]
1357
+
1358
+ # Some generation methods already pass only the last input ID
1359
+ if input_ids.shape[1] > past_length:
1360
+ remove_prefix_length = past_length
1361
+ else:
1362
+ # Default to old behavior: keep only final ID
1363
+ remove_prefix_length = input_ids.shape[1] - 1
1364
+
1365
+ input_ids = input_ids[:, remove_prefix_length:]
1366
+
1367
+ position_ids = kwargs.get('position_ids', None)
1368
+ if attention_mask is not None and position_ids is None:
1369
+ # create position_ids on the fly for batch generation
1370
+ position_ids = attention_mask.long().cumsum(-1) - 1
1371
+ position_ids.masked_fill_(attention_mask == 0, 1)
1372
+ if past_key_values:
1373
+ position_ids = position_ids[:, -input_ids.shape[1]:]
1374
+
1375
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1376
+ if inputs_embeds is not None and past_key_values is None:
1377
+ model_inputs = {'inputs_embeds': inputs_embeds}
1378
+ else:
1379
+ model_inputs = {'input_ids': input_ids}
1380
+
1381
+ model_inputs.update(
1382
+ {
1383
+ 'position_ids': position_ids,
1384
+ 'past_key_values': past_key_values,
1385
+ 'use_cache': kwargs.get('use_cache'),
1386
+ 'attention_mask': attention_mask,
1387
+ 'visual_token_index': kwargs.get('visual_token_index'),
1388
+ 'large_model_prune_layer': kwargs.get('large_model_prune_layer'),
1389
+ 'large_model_prune_ratio': kwargs.get('large_model_prune_ratio'),
1390
+ 'visual_token_importance': kwargs.get('visual_token_importance')
1391
+ }
1392
+ )
1393
+ return model_inputs
1394
+
1395
+ @staticmethod
1396
+ def _reorder_cache(past_key_values, beam_idx):
1397
+ reordered_past = ()
1398
+ for layer_past in past_key_values:
1399
+ reordered_past += (
1400
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1401
+ )
1402
+ return reordered_past
1403
+
1404
+ def build_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = [], meta_instruction=''):
1405
+ if tokenizer.add_bos_token:
1406
+ prompt = ''
1407
+ else:
1408
+ prompt = tokenizer.bos_token
1409
+ if meta_instruction:
1410
+ prompt += f"""<|im_start|>system\n{meta_instruction}<|im_end|>\n"""
1411
+ for record in history:
1412
+ prompt += f"""<|im_start|>user\n{record[0]}<|im_end|>\n<|im_start|>assistant\n{record[1]}<|im_end|>\n"""
1413
+ prompt += f"""<|im_start|>user\n{query}<|im_end|>\n<|im_start|>assistant\n"""
1414
+ return tokenizer([prompt], return_tensors='pt')
1415
+
1416
+ @torch.no_grad()
1417
+ def chat(
1418
+ self,
1419
+ tokenizer,
1420
+ query: str,
1421
+ history: List[Tuple[str, str]] = [],
1422
+ streamer: Optional[BaseStreamer] = None,
1423
+ max_new_tokens: int = 1024,
1424
+ do_sample: bool = True,
1425
+ temperature: float = 0.8,
1426
+ top_p: float = 0.8,
1427
+ meta_instruction: str = 'You are an AI assistant whose name is InternLM (书生·浦语).\n'
1428
+ '- InternLM (书生·浦语) is a conversational language model that is developed by Shanghai AI Laboratory (上海人工智能实验室). It is designed to be helpful, honest, and harmless.\n'
1429
+ '- InternLM (书生·浦语) can understand and communicate fluently in the language chosen by the user such as English and 中文.',
1430
+ **kwargs,
1431
+ ):
1432
+ inputs = self.build_inputs(tokenizer, query, history, meta_instruction)
1433
+ inputs = {k: v.to(self.device) for k, v in inputs.items() if torch.is_tensor(v)}
1434
+ # also add end-of-assistant token in eos token id to avoid unnecessary generation
1435
+ eos_token_id = [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids(['<|im_end|>'])[0]]
1436
+ outputs = self.generate(
1437
+ **inputs,
1438
+ streamer=streamer,
1439
+ max_new_tokens=max_new_tokens,
1440
+ do_sample=do_sample,
1441
+ temperature=temperature,
1442
+ top_p=top_p,
1443
+ eos_token_id=eos_token_id,
1444
+ **kwargs,
1445
+ )
1446
+ outputs = outputs[0].cpu().tolist()[len(inputs['input_ids'][0]):]
1447
+ response = tokenizer.decode(outputs, skip_special_tokens=True)
1448
+ response = response.split('<|im_end|>')[0]
1449
+ history = history + [(query, response)]
1450
+ return response, history
1451
+
1452
+ @torch.no_grad()
1453
+ def stream_chat(
1454
+ self,
1455
+ tokenizer,
1456
+ query: str,
1457
+ history: List[Tuple[str, str]] = [],
1458
+ max_new_tokens: int = 1024,
1459
+ do_sample: bool = True,
1460
+ temperature: float = 0.8,
1461
+ top_p: float = 0.8,
1462
+ **kwargs,
1463
+ ):
1464
+ """
1465
+ Return a generator in format: (response, history)
1466
+ Eg.
1467
+ ('你好,有什么可以帮助您的吗', [('你好', '你好,有什么可以帮助您的吗')])
1468
+ ('你好,有什么可以帮助您的吗?', [('你好', '你好,有什么可以帮助您的吗?')])
1469
+ """
1470
+ if BaseStreamer is None:
1471
+ raise ModuleNotFoundError(
1472
+ 'The version of `transformers` is too low. Please make sure '
1473
+ 'that you have installed `transformers>=4.28.0`.'
1474
+ )
1475
+
1476
+ response_queue = queue.Queue(maxsize=20)
1477
+
1478
+ class ChatStreamer(BaseStreamer):
1479
+ def __init__(self, tokenizer) -> None:
1480
+ super().__init__()
1481
+ self.tokenizer = tokenizer
1482
+ self.queue = response_queue
1483
+ self.query = query
1484
+ self.history = history
1485
+ self.response = ''
1486
+ self.cache = []
1487
+ self.received_inputs = False
1488
+ self.queue.put((self.response, history + [(self.query, self.response)]))
1489
+
1490
+ def put(self, value):
1491
+ if len(value.shape) > 1 and value.shape[0] > 1:
1492
+ raise ValueError('ChatStreamer only supports batch size 1')
1493
+ elif len(value.shape) > 1:
1494
+ value = value[0]
1495
+
1496
+ if not self.received_inputs:
1497
+ # The first received value is input_ids, ignore here
1498
+ self.received_inputs = True
1499
+ return
1500
+
1501
+ self.cache.extend(value.tolist())
1502
+ token = self.tokenizer.decode(self.cache, skip_special_tokens=True)
1503
+ if token.strip() != '<|im_end|>':
1504
+ self.response = self.response + token
1505
+ history = self.history + [(self.query, self.response)]
1506
+ self.queue.put((self.response, history))
1507
+ self.cache = []
1508
+ else:
1509
+ self.end()
1510
+
1511
+ def end(self):
1512
+ self.queue.put(None)
1513
+
1514
+ def stream_producer():
1515
+ return self.chat(
1516
+ tokenizer=tokenizer,
1517
+ query=query,
1518
+ streamer=ChatStreamer(tokenizer=tokenizer),
1519
+ history=history,
1520
+ max_new_tokens=max_new_tokens,
1521
+ do_sample=do_sample,
1522
+ temperature=temperature,
1523
+ top_p=top_p,
1524
+ **kwargs,
1525
+ )
1526
+
1527
+ def consumer():
1528
+ producer = threading.Thread(target=stream_producer)
1529
+ producer.start()
1530
+ while True:
1531
+ res = response_queue.get()
1532
+ if res is None:
1533
+ return
1534
+ yield res
1535
+
1536
+ return consumer()
1537
+
1538
+
1539
+ # Copied from transformers.model.llama.modeling_llama.LlamaForSequenceClassification with Llama->InternLM2
1540
+ @add_start_docstrings(
1541
+ """
1542
+ The InternLM2 Model transformer with a sequence classification head on top (linear layer).
1543
+
1544
+ [`InternLM2ForSequenceClassification`] uses the last token in order to do the classification,
1545
+ as other causal models (e.g. GPT-2) do.
1546
+
1547
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1548
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1549
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1550
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1551
+ each row of the batch).
1552
+ """,
1553
+ InternLM2_START_DOCSTRING,
1554
+ )
1555
+ class InternLM2ForSequenceClassification(InternLM2PreTrainedModel):
1556
+ def __init__(self, config):
1557
+ super().__init__(config)
1558
+ self.num_labels = config.num_labels
1559
+ self.model = InternLM2Model(config)
1560
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1561
+
1562
+ # Initialize weights and apply final processing
1563
+ self.post_init()
1564
+
1565
+ def get_input_embeddings(self):
1566
+ return self.model.tok_embeddings
1567
+
1568
+ def set_input_embeddings(self, value):
1569
+ self.model.tok_embeddings = value
1570
+
1571
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
1572
+ def forward(
1573
+ self,
1574
+ input_ids: torch.LongTensor = None,
1575
+ attention_mask: Optional[torch.Tensor] = None,
1576
+ position_ids: Optional[torch.LongTensor] = None,
1577
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1578
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1579
+ labels: Optional[torch.LongTensor] = None,
1580
+ use_cache: Optional[bool] = None,
1581
+ output_attentions: Optional[bool] = None,
1582
+ output_hidden_states: Optional[bool] = None,
1583
+ return_dict: Optional[bool] = None,
1584
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1585
+ r"""
1586
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1587
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1588
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1589
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1590
+ """
1591
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1592
+
1593
+ transformer_outputs = self.model(
1594
+ input_ids,
1595
+ attention_mask=attention_mask,
1596
+ position_ids=position_ids,
1597
+ past_key_values=past_key_values,
1598
+ inputs_embeds=inputs_embeds,
1599
+ use_cache=use_cache,
1600
+ output_attentions=output_attentions,
1601
+ output_hidden_states=output_hidden_states,
1602
+ return_dict=return_dict,
1603
+ )
1604
+ hidden_states = transformer_outputs[0]
1605
+ logits = self.score(hidden_states)
1606
+
1607
+ if input_ids is not None:
1608
+ batch_size = input_ids.shape[0]
1609
+ else:
1610
+ batch_size = inputs_embeds.shape[0]
1611
+
1612
+ if self.config.pad_token_id is None and batch_size != 1:
1613
+ raise ValueError('Cannot handle batch sizes > 1 if no padding token is defined.')
1614
+ if self.config.pad_token_id is None:
1615
+ sequence_lengths = -1
1616
+ else:
1617
+ if input_ids is not None:
1618
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
1619
+ logits.device
1620
+ )
1621
+ else:
1622
+ sequence_lengths = -1
1623
+
1624
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1625
+
1626
+ loss = None
1627
+ if labels is not None:
1628
+ labels = labels.to(logits.device)
1629
+ if self.config.problem_type is None:
1630
+ if self.num_labels == 1:
1631
+ self.config.problem_type = 'regression'
1632
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1633
+ self.config.problem_type = 'single_label_classification'
1634
+ else:
1635
+ self.config.problem_type = 'multi_label_classification'
1636
+
1637
+ if self.config.problem_type == 'regression':
1638
+ loss_fct = MSELoss()
1639
+ if self.num_labels == 1:
1640
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1641
+ else:
1642
+ loss = loss_fct(pooled_logits, labels)
1643
+ elif self.config.problem_type == 'single_label_classification':
1644
+ loss_fct = CrossEntropyLoss()
1645
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1646
+ elif self.config.problem_type == 'multi_label_classification':
1647
+ loss_fct = BCEWithLogitsLoss()
1648
+ loss = loss_fct(pooled_logits, labels)
1649
+ if not return_dict:
1650
+ output = (pooled_logits,) + transformer_outputs[1:]
1651
+ return ((loss,) + output) if loss is not None else output
1652
+
1653
+ return SequenceClassifierOutputWithPast(
1654
+ loss=loss,
1655
+ logits=pooled_logits,
1656
+ past_key_values=transformer_outputs.past_key_values,
1657
+ hidden_states=transformer_outputs.hidden_states,
1658
+ attentions=transformer_outputs.attentions,
1659
+ )
internvl/model/internlm2/tokenization_internlm2.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on transformers/src/transformers/models/llama/tokenization_llama.py
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ """Tokenization classes for InternLM."""
18
+ import os
19
+ from shutil import copyfile
20
+ from typing import Any, Dict, List, Optional, Tuple
21
+
22
+ import sentencepiece as spm
23
+ from transformers.tokenization_utils import PreTrainedTokenizer
24
+ from transformers.utils import logging
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ VOCAB_FILES_NAMES = {'vocab_file': './tokenizer.model'}
29
+
30
+ PRETRAINED_VOCAB_FILES_MAP = {}
31
+
32
+
33
+ # Modified from transformers.model.llama.tokenization_llama.LlamaTokenizer
34
+ class InternLM2Tokenizer(PreTrainedTokenizer):
35
+ """
36
+ Construct a InternLM2 tokenizer. Based on byte-level Byte-Pair-Encoding.
37
+
38
+ Args:
39
+ vocab_file (`str`):
40
+ Path to the vocabulary file.
41
+ """
42
+
43
+ vocab_files_names = VOCAB_FILES_NAMES
44
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
45
+ model_input_names = ['input_ids', 'attention_mask']
46
+ _auto_class = 'AutoTokenizer'
47
+
48
+ def __init__(
49
+ self,
50
+ vocab_file,
51
+ unk_token='<unk>',
52
+ bos_token='<s>',
53
+ eos_token='</s>',
54
+ pad_token='</s>',
55
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
56
+ add_bos_token=True,
57
+ add_eos_token=False,
58
+ decode_with_prefix_space=False,
59
+ clean_up_tokenization_spaces=False,
60
+ **kwargs,
61
+ ):
62
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
63
+ self.vocab_file = vocab_file
64
+ self.add_bos_token = add_bos_token
65
+ self.add_eos_token = add_eos_token
66
+ self.decode_with_prefix_space = decode_with_prefix_space
67
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
68
+ self.sp_model.Load(vocab_file)
69
+ self._no_prefix_space_tokens = None
70
+ super().__init__(
71
+ bos_token=bos_token,
72
+ eos_token=eos_token,
73
+ unk_token=unk_token,
74
+ pad_token=pad_token,
75
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
76
+ **kwargs,
77
+ )
78
+
79
+ @property
80
+ def no_prefix_space_tokens(self):
81
+ if self._no_prefix_space_tokens is None:
82
+ vocab = self.convert_ids_to_tokens(list(range(self.vocab_size)))
83
+ self._no_prefix_space_tokens = {i for i, tok in enumerate(vocab) if not tok.startswith('▁')}
84
+ return self._no_prefix_space_tokens
85
+
86
+ @property
87
+ def vocab_size(self):
88
+ """Returns vocab size"""
89
+ return self.sp_model.get_piece_size()
90
+
91
+ @property
92
+ def bos_token_id(self) -> Optional[int]:
93
+ return self.sp_model.bos_id()
94
+
95
+ @property
96
+ def eos_token_id(self) -> Optional[int]:
97
+ return self.sp_model.eos_id()
98
+
99
+ def get_vocab(self):
100
+ """Returns vocab as a dict"""
101
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
102
+ vocab.update(self.added_tokens_encoder)
103
+ return vocab
104
+
105
+ def _tokenize(self, text):
106
+ """Returns a tokenized string."""
107
+ return self.sp_model.encode(text, out_type=str)
108
+
109
+ def _convert_token_to_id(self, token):
110
+ """Converts a token (str) in an id using the vocab."""
111
+ return self.sp_model.piece_to_id(token)
112
+
113
+ def _convert_id_to_token(self, index):
114
+ """Converts an index (integer) in a token (str) using the vocab."""
115
+ token = self.sp_model.IdToPiece(index)
116
+ return token
117
+
118
+ def _maybe_add_prefix_space(self, tokens, decoded):
119
+ if tokens and tokens[0] not in self.no_prefix_space_tokens:
120
+ return ' ' + decoded
121
+ else:
122
+ return decoded
123
+
124
+ def convert_tokens_to_string(self, tokens):
125
+ """Converts a sequence of tokens (string) in a single string."""
126
+ current_sub_tokens = []
127
+ out_string = ''
128
+ prev_is_special = False
129
+ for token in tokens:
130
+ # make sure that special tokens are not decoded using sentencepiece model
131
+ if token in self.all_special_tokens:
132
+ if not prev_is_special:
133
+ out_string += ' '
134
+ out_string += self.sp_model.decode(current_sub_tokens) + token
135
+ prev_is_special = True
136
+ current_sub_tokens = []
137
+ else:
138
+ current_sub_tokens.append(token)
139
+ prev_is_special = False
140
+ out_string += self.sp_model.decode(current_sub_tokens)
141
+ out_string = self.clean_up_tokenization(out_string)
142
+ out_string = self._maybe_add_prefix_space(tokens=tokens, decoded=out_string)
143
+ return out_string[1:]
144
+
145
+ def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
146
+ """
147
+ Save the vocabulary and special tokens file to a directory.
148
+
149
+ Args:
150
+ save_directory (`str`):
151
+ The directory in which to save the vocabulary.
152
+
153
+ Returns:
154
+ `Tuple(str)`: Paths to the files saved.
155
+ """
156
+ if not os.path.isdir(save_directory):
157
+ logger.error(f'Vocabulary path ({save_directory}) should be a directory')
158
+ return
159
+ out_vocab_file = os.path.join(
160
+ save_directory, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']
161
+ )
162
+
163
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
164
+ copyfile(self.vocab_file, out_vocab_file)
165
+ elif not os.path.isfile(self.vocab_file):
166
+ with open(out_vocab_file, 'wb') as fi:
167
+ content_spiece_model = self.sp_model.serialized_model_proto()
168
+ fi.write(content_spiece_model)
169
+
170
+ return (out_vocab_file,)
171
+
172
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
173
+ if self.add_bos_token:
174
+ bos_token_ids = [self.bos_token_id]
175
+ else:
176
+ bos_token_ids = []
177
+
178
+ output = bos_token_ids + token_ids_0
179
+
180
+ if token_ids_1 is not None:
181
+ output = output + token_ids_1
182
+
183
+ if self.add_eos_token:
184
+ output = output + [self.eos_token_id]
185
+
186
+ return output
187
+
188
+ def get_special_tokens_mask(
189
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
190
+ ) -> List[int]:
191
+ """
192
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
193
+ special tokens using the tokenizer `prepare_for_model` method.
194
+
195
+ Args:
196
+ token_ids_0 (`List[int]`):
197
+ List of IDs.
198
+ token_ids_1 (`List[int]`, *optional*):
199
+ Optional second list of IDs for sequence pairs.
200
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
201
+ Whether or not the token list is already formatted with special tokens for the model.
202
+
203
+ Returns:
204
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
205
+ """
206
+ if already_has_special_tokens:
207
+ return super().get_special_tokens_mask(
208
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
209
+ )
210
+
211
+ if token_ids_1 is None:
212
+ return [1] + ([0] * len(token_ids_0)) + [1]
213
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
214
+
215
+ def create_token_type_ids_from_sequences(
216
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
217
+ ) -> List[int]:
218
+ """
219
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. T5 does not make
220
+ use of token type ids, therefore a list of zeros is returned.
221
+
222
+ Args:
223
+ token_ids_0 (`List[int]`):
224
+ List of IDs.
225
+ token_ids_1 (`List[int]`, *optional*):
226
+ Optional second list of IDs for sequence pairs.
227
+
228
+ Returns:
229
+ `List[int]`: List of zeros.
230
+ """
231
+ eos = [self.eos_token_id]
232
+
233
+ if token_ids_1 is None:
234
+ return len(token_ids_0 + eos) * [0]
235
+ return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
internvl/model/internlm2/tokenization_internlm2_fast.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on transformers/src/transformers/models/llama/tokenization_llama_fast.py
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ """Tokenization Fast class for InternLM."""
18
+ import os
19
+ from shutil import copyfile
20
+ from typing import Any, Dict, Optional, Tuple
21
+
22
+ from tokenizers import Tokenizer, decoders, normalizers, processors
23
+ from tokenizers.models import BPE
24
+ from transformers.convert_slow_tokenizer import (SLOW_TO_FAST_CONVERTERS,
25
+ SentencePieceExtractor,
26
+ SpmConverter)
27
+ from transformers.tokenization_utils_fast import PreTrainedTokenizerFast
28
+ from transformers.utils import logging
29
+
30
+ from .tokenization_internlm2 import InternLM2Tokenizer
31
+
32
+ logger = logging.get_logger(__name__)
33
+
34
+ VOCAB_FILES_NAMES = {'vocab_file': './tokenizer.model'}
35
+
36
+
37
+ # Modified from transformers.convert_slow_tokenizer.LlamaConverter
38
+ class InternLM2Converter(SpmConverter):
39
+ handle_byte_fallback = True
40
+
41
+ def vocab(self, proto):
42
+ vocab = [
43
+ ('<unk>', 0.0),
44
+ ('<s>', 0.0),
45
+ ('</s>', 0.0),
46
+ ]
47
+ vocab += [(piece.piece, piece.score) for piece in proto.pieces[3:]]
48
+ return vocab
49
+
50
+ def unk_id(self, proto):
51
+ unk_id = 0
52
+ return unk_id
53
+
54
+ def decoder(self, replacement, add_prefix_space):
55
+ return decoders.Sequence(
56
+ [
57
+ decoders.Replace('▁', ' '),
58
+ decoders.ByteFallback(),
59
+ decoders.Fuse(),
60
+ decoders.Strip(content=' ', left=1),
61
+ ]
62
+ )
63
+
64
+ def tokenizer(self, proto):
65
+ model_type = proto.trainer_spec.model_type
66
+ vocab_scores = self.vocab(proto)
67
+ # special tokens
68
+ added_tokens = self.original_tokenizer.added_tokens_decoder
69
+ for i in range(len(vocab_scores)):
70
+ piece, score = vocab_scores[i]
71
+ if i in added_tokens:
72
+ vocab_scores[i] = (added_tokens[i].content, score)
73
+ if model_type == 1:
74
+ raise RuntimeError('InternLM2 is supposed to be a BPE model!')
75
+
76
+ elif model_type == 2:
77
+ _, merges = SentencePieceExtractor(self.original_tokenizer.vocab_file).extract(vocab_scores)
78
+ bpe_vocab = {word: i for i, (word, _score) in enumerate(vocab_scores)}
79
+ tokenizer = Tokenizer(
80
+ BPE(bpe_vocab, merges, unk_token=proto.trainer_spec.unk_piece, fuse_unk=True, byte_fallback=True)
81
+ )
82
+ tokenizer.add_special_tokens(
83
+ [ added_token for index, added_token in added_tokens.items()]
84
+ )
85
+ else:
86
+ raise Exception(
87
+ "You're trying to run a `Unigram` model but you're file was trained with a different algorithm"
88
+ )
89
+
90
+ return tokenizer
91
+
92
+ def normalizer(self, proto):
93
+ normalizers_list = []
94
+ if proto.normalizer_spec.add_dummy_prefix:
95
+ normalizers_list.append(normalizers.Prepend(prepend='▁'))
96
+ normalizers_list.append(normalizers.Replace(pattern=' ', content='▁'))
97
+ return normalizers.Sequence(normalizers_list)
98
+
99
+ def pre_tokenizer(self, replacement, add_prefix_space):
100
+ return None
101
+
102
+
103
+ SLOW_TO_FAST_CONVERTERS['InternLM2Tokenizer'] = InternLM2Converter
104
+
105
+
106
+ # Modified from transformers.model.llama.tokenization_llama_fast.LlamaTokenizerFast -> InternLM2TokenizerFast
107
+ class InternLM2TokenizerFast(PreTrainedTokenizerFast):
108
+ vocab_files_names = VOCAB_FILES_NAMES
109
+ slow_tokenizer_class = InternLM2Tokenizer
110
+ padding_side = 'left'
111
+ model_input_names = ['input_ids', 'attention_mask']
112
+ _auto_class = 'AutoTokenizer'
113
+
114
+ def __init__(
115
+ self,
116
+ vocab_file,
117
+ unk_token='<unk>',
118
+ bos_token='<s>',
119
+ eos_token='</s>',
120
+ pad_token='</s>',
121
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
122
+ add_bos_token=True,
123
+ add_eos_token=False,
124
+ decode_with_prefix_space=False,
125
+ clean_up_tokenization_spaces=False,
126
+ **kwargs,
127
+ ):
128
+ super().__init__(
129
+ vocab_file=vocab_file,
130
+ unk_token=unk_token,
131
+ bos_token=bos_token,
132
+ eos_token=eos_token,
133
+ pad_token=pad_token,
134
+ sp_model_kwargs=sp_model_kwargs,
135
+ add_bos_token=add_bos_token,
136
+ add_eos_token=add_eos_token,
137
+ decode_with_prefix_space=decode_with_prefix_space,
138
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
139
+ **kwargs,
140
+ )
141
+ self._add_bos_token = add_bos_token
142
+ self._add_eos_token = add_eos_token
143
+ self.update_post_processor()
144
+ self.vocab_file = vocab_file
145
+
146
+ @property
147
+ def can_save_slow_tokenizer(self) -> bool:
148
+ return os.path.isfile(self.vocab_file) if self.vocab_file else False
149
+
150
+ def update_post_processor(self):
151
+ """
152
+ Updates the underlying post processor with the current `bos_token` and `eos_token`.
153
+ """
154
+ bos = self.bos_token
155
+ bos_token_id = self.bos_token_id
156
+ if bos is None and self.add_bos_token:
157
+ raise ValueError('add_bos_token = True but bos_token = None')
158
+
159
+ eos = self.eos_token
160
+ eos_token_id = self.eos_token_id
161
+ if eos is None and self.add_eos_token:
162
+ raise ValueError('add_eos_token = True but eos_token = None')
163
+
164
+ single = f"{(bos+':0 ') if self.add_bos_token else ''}$A:0{(' '+eos+':0') if self.add_eos_token else ''}"
165
+ pair = f"{single}{(' '+bos+':1') if self.add_bos_token else ''} $B:1{(' '+eos+':1') if self.add_eos_token else ''}"
166
+
167
+ special_tokens = []
168
+ if self.add_bos_token:
169
+ special_tokens.append((bos, bos_token_id))
170
+ if self.add_eos_token:
171
+ special_tokens.append((eos, eos_token_id))
172
+ self._tokenizer.post_processor = processors.TemplateProcessing(
173
+ single=single, pair=pair, special_tokens=special_tokens
174
+ )
175
+
176
+ @property
177
+ def add_eos_token(self):
178
+ return self._add_eos_token
179
+
180
+ @property
181
+ def add_bos_token(self):
182
+ return self._add_bos_token
183
+
184
+ @add_eos_token.setter
185
+ def add_eos_token(self, value):
186
+ self._add_eos_token = value
187
+ self.update_post_processor()
188
+
189
+ @add_bos_token.setter
190
+ def add_bos_token(self, value):
191
+ self._add_bos_token = value
192
+ self.update_post_processor()
193
+
194
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
195
+ if not self.can_save_slow_tokenizer:
196
+ raise ValueError(
197
+ 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow '
198
+ 'tokenizer.'
199
+ )
200
+
201
+ if not os.path.isdir(save_directory):
202
+ logger.error(f'Vocabulary path ({save_directory}) should be a directory')
203
+ return
204
+ out_vocab_file = os.path.join(
205
+ save_directory, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']
206
+ )
207
+
208
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
209
+ copyfile(self.vocab_file, out_vocab_file)
210
+
211
+ return (out_vocab_file,)
internvl/model/internvl_chat/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+
7
+ from .configuration_intern_vit import InternVisionConfig
8
+ from .configuration_internvl_chat import InternVLChatConfig
9
+ from .modeling_intern_vit import InternVisionModel
10
+ from .modeling_internvl_chat import InternVLChatModel
11
+
12
+ __all__ = ['InternVisionConfig', 'InternVisionModel',
13
+ 'InternVLChatConfig', 'InternVLChatModel']
internvl/model/internvl_chat/configuration_intern_vit.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+ import os
7
+ from typing import Union
8
+
9
+ from transformers.configuration_utils import PretrainedConfig
10
+ from transformers.utils import logging
11
+
12
+ logger = logging.get_logger(__name__)
13
+
14
+
15
+ class InternVisionConfig(PretrainedConfig):
16
+ r"""
17
+ This is the configuration class to store the configuration of a [`InternVisionModel`]. It is used to
18
+ instantiate a vision encoder according to the specified arguments, defining the model architecture.
19
+
20
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
21
+ documentation from [`PretrainedConfig`] for more information.
22
+
23
+ Args:
24
+ num_channels (`int`, *optional*, defaults to 3):
25
+ Number of color channels in the input images (e.g., 3 for RGB).
26
+ patch_size (`int`, *optional*, defaults to 14):
27
+ The size (resolution) of each patch.
28
+ image_size (`int`, *optional*, defaults to 224):
29
+ The size (resolution) of each image.
30
+ qkv_bias (`bool`, *optional*, defaults to `False`):
31
+ Whether to add a bias to the queries and values in the self-attention layers.
32
+ hidden_size (`int`, *optional*, defaults to 3200):
33
+ Dimensionality of the encoder layers and the pooler layer.
34
+ num_attention_heads (`int`, *optional*, defaults to 25):
35
+ Number of attention heads for each attention layer in the Transformer encoder.
36
+ intermediate_size (`int`, *optional*, defaults to 12800):
37
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
38
+ qk_normalization (`bool`, *optional*, defaults to `True`):
39
+ Whether to normalize the queries and keys in the self-attention layers.
40
+ num_hidden_layers (`int`, *optional*, defaults to 48):
41
+ Number of hidden layers in the Transformer encoder.
42
+ use_flash_attn (`bool`, *optional*, defaults to `True`):
43
+ Whether to use flash attention mechanism.
44
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
45
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
46
+ `"relu"`, `"selu"` and `"gelu_new"` ``"gelu"` are supported.
47
+ layer_norm_eps (`float`, *optional*, defaults to 1e-6):
48
+ The epsilon used by the layer normalization layers.
49
+ dropout (`float`, *optional*, defaults to 0.0):
50
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
51
+ drop_path_rate (`float`, *optional*, defaults to 0.0):
52
+ Dropout rate for stochastic depth.
53
+ attention_dropout (`float`, *optional*, defaults to 0.0):
54
+ The dropout ratio for the attention probabilities.
55
+ initializer_range (`float`, *optional*, defaults to 0.02):
56
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
57
+ initializer_factor (`float`, *optional*, defaults to 0.1):
58
+ A factor for layer scale.
59
+ """
60
+
61
+ model_type = 'intern_vit_6b'
62
+
63
+ def __init__(
64
+ self,
65
+ num_channels=3,
66
+ patch_size=14,
67
+ image_size=224,
68
+ qkv_bias=False,
69
+ hidden_size=3200,
70
+ num_attention_heads=25,
71
+ intermediate_size=12800,
72
+ qk_normalization=True,
73
+ num_hidden_layers=48,
74
+ use_flash_attn=True,
75
+ hidden_act='gelu',
76
+ norm_type='rms_norm',
77
+ layer_norm_eps=1e-6,
78
+ dropout=0.0,
79
+ drop_path_rate=0.0,
80
+ attention_dropout=0.0,
81
+ initializer_range=0.02,
82
+ initializer_factor=0.1,
83
+ **kwargs,
84
+ ):
85
+ super().__init__(**kwargs)
86
+
87
+ self.hidden_size = hidden_size
88
+ self.intermediate_size = intermediate_size
89
+ self.dropout = dropout
90
+ self.drop_path_rate = drop_path_rate
91
+ self.num_hidden_layers = num_hidden_layers
92
+ self.num_attention_heads = num_attention_heads
93
+ self.num_channels = num_channels
94
+ self.patch_size = patch_size
95
+ self.image_size = image_size
96
+ self.initializer_range = initializer_range
97
+ self.initializer_factor = initializer_factor
98
+ self.attention_dropout = attention_dropout
99
+ self.layer_norm_eps = layer_norm_eps
100
+ self.hidden_act = hidden_act
101
+ self.norm_type = norm_type
102
+ self.qkv_bias = qkv_bias
103
+ self.qk_normalization = qk_normalization
104
+ self.use_flash_attn = use_flash_attn
105
+
106
+ @classmethod
107
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> 'PretrainedConfig':
108
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
109
+
110
+ if 'vision_config' in config_dict:
111
+ config_dict = config_dict['vision_config']
112
+
113
+ if 'model_type' in config_dict and hasattr(cls, 'model_type') and config_dict['model_type'] != cls.model_type:
114
+ logger.warning(
115
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
116
+ f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'
117
+ )
118
+
119
+ return cls.from_dict(config_dict, **kwargs)
internvl/model/internvl_chat/configuration_internvl_chat.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+
7
+ import copy
8
+
9
+ from internvl.model.internlm2.configuration_internlm2 import InternLM2Config
10
+ from internvl.model.phi3.configuration_phi3 import Phi3Config
11
+ from internvl.model.llama.configuration_llama import LlamaConfig
12
+ from transformers import AutoConfig, Qwen2Config
13
+
14
+ from transformers.configuration_utils import PretrainedConfig
15
+ from transformers.utils import logging
16
+
17
+ from .configuration_intern_vit import InternVisionConfig
18
+
19
+ logger = logging.get_logger(__name__)
20
+
21
+
22
+ class InternVLChatConfig(PretrainedConfig):
23
+ model_type = 'internvl_chat'
24
+ is_composition = True
25
+
26
+ def __init__(
27
+ self,
28
+ vision_config=None,
29
+ llm_config=None,
30
+ use_backbone_lora=0,
31
+ use_llm_lora=0,
32
+ pad2square=False,
33
+ select_layer=-1,
34
+ force_image_size=None,
35
+ downsample_ratio=0.5,
36
+ template=None,
37
+ dynamic_image_size=False,
38
+ use_thumbnail=False,
39
+ ps_version='v1',
40
+ min_dynamic_patch=1,
41
+ max_dynamic_patch=6,
42
+ **kwargs):
43
+ super().__init__(**kwargs)
44
+
45
+ if vision_config is None:
46
+ vision_config = {}
47
+ logger.info('vision_config is None. Initializing the InternVisionConfig with default values.')
48
+
49
+ if llm_config is None:
50
+ llm_config = {}
51
+ logger.info('llm_config is None. Initializing the LlamaConfig config with default values (`LlamaConfig`).')
52
+
53
+ self.vision_config = InternVisionConfig(**vision_config)
54
+ if llm_config['architectures'][0] == 'LlamaForCausalLM':
55
+ self.llm_config = LlamaConfig(**llm_config)
56
+ elif llm_config['architectures'][0] == 'InternLM2ForCausalLM':
57
+ self.llm_config = InternLM2Config(**llm_config)
58
+ elif llm_config['architectures'][0] == 'Phi3ForCausalLM':
59
+ self.llm_config = Phi3Config(**llm_config)
60
+ elif llm_config['architectures'][0] == 'Qwen2ForCausalLM':
61
+ self.llm_config = Qwen2Config(**llm_config)
62
+ else:
63
+ raise ValueError('Unsupported architecture: {}'.format(llm_config['architectures'][0]))
64
+ self.use_backbone_lora = use_backbone_lora
65
+ self.use_llm_lora = use_llm_lora
66
+ self.pad2square = pad2square
67
+ self.select_layer = select_layer
68
+ self.force_image_size = force_image_size
69
+ self.downsample_ratio = downsample_ratio
70
+ self.template = template
71
+ self.dynamic_image_size = dynamic_image_size
72
+ self.use_thumbnail = use_thumbnail
73
+ self.ps_version = ps_version # pixel shuffle version
74
+ self.min_dynamic_patch = min_dynamic_patch
75
+ self.max_dynamic_patch = max_dynamic_patch
76
+
77
+ logger.info(f'vision_select_layer: {self.select_layer}')
78
+ logger.info(f'ps_version: {self.ps_version}')
79
+ logger.info(f'min_dynamic_patch: {self.min_dynamic_patch}')
80
+ logger.info(f'max_dynamic_patch: {self.max_dynamic_patch}')
81
+
82
+ def to_dict(self):
83
+ """
84
+ Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
85
+
86
+ Returns:
87
+ `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
88
+ """
89
+ output = copy.deepcopy(self.__dict__)
90
+ output['vision_config'] = self.vision_config.to_dict()
91
+ output['llm_config'] = self.llm_config.to_dict()
92
+ output['model_type'] = self.__class__.model_type
93
+ output['use_backbone_lora'] = self.use_backbone_lora
94
+ output['use_llm_lora'] = self.use_llm_lora
95
+ output['pad2square'] = self.pad2square
96
+ output['select_layer'] = self.select_layer
97
+ output['force_image_size'] = self.force_image_size
98
+ output['downsample_ratio'] = self.downsample_ratio
99
+ output['template'] = self.template
100
+ output['dynamic_image_size'] = self.dynamic_image_size
101
+ output['use_thumbnail'] = self.use_thumbnail
102
+ output['ps_version'] = self.ps_version
103
+ output['min_dynamic_patch'] = self.min_dynamic_patch
104
+ output['max_dynamic_patch'] = self.max_dynamic_patch
105
+
106
+ return output
internvl/model/internvl_chat/flash_attention.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # https://github.com/Dao-AILab/flash-attention/blob/v0.2.8/flash_attn/flash_attention.py
2
+ import torch
3
+ import torch.nn as nn
4
+ from einops import rearrange
5
+
6
+ try: # v1
7
+ from flash_attn.flash_attn_interface import \
8
+ flash_attn_unpadded_qkvpacked_func
9
+ except: # v2
10
+ from flash_attn.flash_attn_interface import flash_attn_varlen_qkvpacked_func as flash_attn_unpadded_qkvpacked_func
11
+
12
+ from flash_attn.bert_padding import pad_input, unpad_input
13
+
14
+
15
+ class FlashAttention(nn.Module):
16
+ """Implement the scaled dot product attention with softmax.
17
+ Arguments
18
+ ---------
19
+ softmax_scale: The temperature to use for the softmax attention.
20
+ (default: 1/sqrt(d_keys) where d_keys is computed at
21
+ runtime)
22
+ attention_dropout: The dropout rate to apply to the attention
23
+ (default: 0.0)
24
+ """
25
+
26
+ def __init__(self, softmax_scale=None, attention_dropout=0.0, device=None, dtype=None):
27
+ super().__init__()
28
+ self.softmax_scale = softmax_scale
29
+ self.dropout_p = attention_dropout
30
+
31
+ def forward(self, qkv, key_padding_mask=None, causal=False, cu_seqlens=None,
32
+ max_s=None, need_weights=False):
33
+ """Implements the multihead softmax attention.
34
+ Arguments
35
+ ---------
36
+ qkv: The tensor containing the query, key, and value. (B, S, 3, H, D) if key_padding_mask is None
37
+ if unpadded: (nnz, 3, h, d)
38
+ key_padding_mask: a bool tensor of shape (B, S)
39
+ """
40
+ assert not need_weights
41
+ assert qkv.dtype in [torch.float16, torch.bfloat16]
42
+ assert qkv.is_cuda
43
+
44
+ if cu_seqlens is None:
45
+ batch_size = qkv.shape[0]
46
+ seqlen = qkv.shape[1]
47
+ if key_padding_mask is None:
48
+ qkv = rearrange(qkv, 'b s ... -> (b s) ...')
49
+ max_s = seqlen
50
+ cu_seqlens = torch.arange(0, (batch_size + 1) * seqlen, step=seqlen, dtype=torch.int32,
51
+ device=qkv.device)
52
+ output = flash_attn_unpadded_qkvpacked_func(
53
+ qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
54
+ softmax_scale=self.softmax_scale, causal=causal
55
+ )
56
+ output = rearrange(output, '(b s) ... -> b s ...', b=batch_size)
57
+ else:
58
+ nheads = qkv.shape[-2]
59
+ x = rearrange(qkv, 'b s three h d -> b s (three h d)')
60
+ x_unpad, indices, cu_seqlens, max_s = unpad_input(x, key_padding_mask)
61
+ x_unpad = rearrange(x_unpad, 'nnz (three h d) -> nnz three h d', three=3, h=nheads)
62
+ output_unpad = flash_attn_unpadded_qkvpacked_func(
63
+ x_unpad, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
64
+ softmax_scale=self.softmax_scale, causal=causal
65
+ )
66
+ output = rearrange(pad_input(rearrange(output_unpad, 'nnz h d -> nnz (h d)'),
67
+ indices, batch_size, seqlen),
68
+ 'b s (h d) -> b s h d', h=nheads)
69
+ else:
70
+ assert max_s is not None
71
+ output = flash_attn_unpadded_qkvpacked_func(
72
+ qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
73
+ softmax_scale=self.softmax_scale, causal=causal
74
+ )
75
+
76
+ return output, None
internvl/model/internvl_chat/modeling_intern_vit.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+ from typing import Optional, Tuple, Union
7
+
8
+ import torch
9
+ import torch.nn.functional as F
10
+ import torch.utils.checkpoint
11
+ from einops import rearrange
12
+ from timm.models.layers import DropPath
13
+ from torch import nn
14
+ from transformers.activations import ACT2FN
15
+ from transformers.modeling_outputs import (BaseModelOutput,
16
+ BaseModelOutputWithPooling)
17
+ from transformers.modeling_utils import PreTrainedModel
18
+ from transformers.utils import logging
19
+
20
+ from .configuration_intern_vit import InternVisionConfig
21
+
22
+ try:
23
+ from .flash_attention import FlashAttention
24
+ has_flash_attn = True
25
+ except:
26
+ print('FlashAttention is not installed.')
27
+ has_flash_attn = False
28
+
29
+ logger = logging.get_logger(__name__)
30
+
31
+
32
+ class InternRMSNorm(nn.Module):
33
+ def __init__(self, hidden_size, eps=1e-6):
34
+ super().__init__()
35
+ self.weight = nn.Parameter(torch.ones(hidden_size))
36
+ self.variance_epsilon = eps
37
+
38
+ def forward(self, hidden_states):
39
+ input_dtype = hidden_states.dtype
40
+ hidden_states = hidden_states.to(torch.float32)
41
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
42
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
43
+ return self.weight * hidden_states.to(input_dtype)
44
+
45
+
46
+ try:
47
+ from apex.normalization import FusedRMSNorm
48
+
49
+ InternRMSNorm = FusedRMSNorm # noqa
50
+
51
+ logger.info('Discovered apex.normalization.FusedRMSNorm - will use it instead of InternRMSNorm')
52
+ except ImportError:
53
+ # using the normal InternRMSNorm
54
+ pass
55
+ except Exception:
56
+ logger.warning('discovered apex but it failed to load, falling back to InternRMSNorm')
57
+ pass
58
+
59
+
60
+ NORM2FN = {
61
+ 'rms_norm': InternRMSNorm,
62
+ 'layer_norm': nn.LayerNorm,
63
+ }
64
+
65
+
66
+ class InternVisionEmbeddings(nn.Module):
67
+ def __init__(self, config: InternVisionConfig):
68
+ super().__init__()
69
+ self.config = config
70
+ self.embed_dim = config.hidden_size
71
+ self.image_size = config.image_size
72
+ self.patch_size = config.patch_size
73
+
74
+ self.class_embedding = nn.Parameter(
75
+ torch.randn(1, 1, self.embed_dim),
76
+ )
77
+
78
+ self.patch_embedding = nn.Conv2d(
79
+ in_channels=3, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size
80
+ )
81
+
82
+ self.num_patches = (self.image_size // self.patch_size) ** 2
83
+ self.num_positions = self.num_patches + 1
84
+
85
+ self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim))
86
+
87
+ def _get_pos_embed(self, pos_embed, H, W):
88
+ target_dtype = pos_embed.dtype
89
+ pos_embed = pos_embed.float().reshape(
90
+ 1, self.image_size // self.patch_size, self.image_size // self.patch_size, -1).permute(0, 3, 1, 2)
91
+ pos_embed = F.interpolate(pos_embed, size=(H, W), mode='bicubic', align_corners=False). \
92
+ reshape(1, -1, H * W).permute(0, 2, 1).to(target_dtype)
93
+ return pos_embed
94
+
95
+ def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
96
+ target_dtype = self.patch_embedding.weight.dtype
97
+ patch_embeds = self.patch_embedding(pixel_values) # shape = [*, channel, width, height]
98
+ batch_size, _, height, width = patch_embeds.shape
99
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
100
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1).to(target_dtype)
101
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
102
+ position_embedding = torch.cat([
103
+ self.position_embedding[:, :1, :],
104
+ self._get_pos_embed(self.position_embedding[:, 1:, :], height, width)
105
+ ], dim=1)
106
+ embeddings = embeddings + position_embedding.to(target_dtype)
107
+ return embeddings
108
+
109
+
110
+ class InternAttention(nn.Module):
111
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
112
+
113
+ def __init__(self, config: InternVisionConfig):
114
+ super().__init__()
115
+ self.config = config
116
+ self.embed_dim = config.hidden_size
117
+ self.num_heads = config.num_attention_heads
118
+ self.use_flash_attn = config.use_flash_attn and has_flash_attn
119
+ if config.use_flash_attn and not has_flash_attn:
120
+ print('Warning: Flash Attention is not available, use_flash_attn is set to False.')
121
+ self.head_dim = self.embed_dim // self.num_heads
122
+ if self.head_dim * self.num_heads != self.embed_dim:
123
+ raise ValueError(
124
+ f'embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:'
125
+ f' {self.num_heads}).'
126
+ )
127
+
128
+ self.scale = self.head_dim ** -0.5
129
+ self.qkv = nn.Linear(self.embed_dim, 3 * self.embed_dim, bias=config.qkv_bias)
130
+ self.attn_drop = nn.Dropout(config.attention_dropout)
131
+ self.proj_drop = nn.Dropout(config.dropout)
132
+
133
+ self.qk_normalization = config.qk_normalization
134
+
135
+ if self.qk_normalization:
136
+ self.q_norm = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
137
+ self.k_norm = InternRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
138
+
139
+ if self.use_flash_attn:
140
+ self.inner_attn = FlashAttention(attention_dropout=config.attention_dropout)
141
+ self.proj = nn.Linear(self.embed_dim, self.embed_dim)
142
+
143
+ def _naive_attn(self, x):
144
+ B, N, C = x.shape
145
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
146
+ q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple)
147
+
148
+ if self.qk_normalization:
149
+ B_, H_, N_, D_ = q.shape
150
+ q = self.q_norm(q.transpose(1, 2).flatten(-2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
151
+ k = self.k_norm(k.transpose(1, 2).flatten(-2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
152
+
153
+ attn = ((q * self.scale) @ k.transpose(-2, -1))
154
+ attn = attn.softmax(dim=-1)
155
+ attn = self.attn_drop(attn)
156
+
157
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
158
+ x = self.proj(x)
159
+ x = self.proj_drop(x)
160
+ return x
161
+
162
+ def _flash_attn(self, x, key_padding_mask=None, need_weights=False):
163
+ qkv = self.qkv(x)
164
+ qkv = rearrange(qkv, 'b s (three h d) -> b s three h d', three=3, h=self.num_heads)
165
+
166
+ if self.qk_normalization:
167
+ q, k, v = qkv.unbind(2)
168
+ q = self.q_norm(q.flatten(-2, -1)).view(q.shape)
169
+ k = self.k_norm(k.flatten(-2, -1)).view(k.shape)
170
+ qkv = torch.stack([q, k, v], dim=2)
171
+
172
+ context, _ = self.inner_attn(
173
+ qkv, key_padding_mask=key_padding_mask, need_weights=need_weights, causal=False
174
+ )
175
+ outs = self.proj(rearrange(context, 'b s h d -> b s (h d)'))
176
+ outs = self.proj_drop(outs)
177
+ return outs
178
+
179
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
180
+ x = self._naive_attn(hidden_states) if not self.use_flash_attn else self._flash_attn(hidden_states)
181
+ return x
182
+
183
+
184
+ class InternMLP(nn.Module):
185
+ def __init__(self, config: InternVisionConfig):
186
+ super().__init__()
187
+ self.config = config
188
+ self.act = ACT2FN[config.hidden_act]
189
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
190
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
191
+
192
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
193
+ hidden_states = self.fc1(hidden_states)
194
+ hidden_states = self.act(hidden_states)
195
+ hidden_states = self.fc2(hidden_states)
196
+ return hidden_states
197
+
198
+
199
+ class InternVisionEncoderLayer(nn.Module):
200
+ def __init__(self, config: InternVisionConfig, drop_path_rate: float):
201
+ super().__init__()
202
+ self.embed_dim = config.hidden_size
203
+ self.intermediate_size = config.intermediate_size
204
+ self.norm_type = config.norm_type
205
+
206
+ self.attn = InternAttention(config)
207
+ self.mlp = InternMLP(config)
208
+ self.norm1 = NORM2FN[self.norm_type](self.embed_dim, eps=config.layer_norm_eps)
209
+ self.norm2 = NORM2FN[self.norm_type](self.embed_dim, eps=config.layer_norm_eps)
210
+
211
+ self.ls1 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
212
+ self.ls2 = nn.Parameter(config.initializer_factor * torch.ones(self.embed_dim))
213
+ self.drop_path1 = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
214
+ self.drop_path2 = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
215
+
216
+ def forward(
217
+ self,
218
+ hidden_states: torch.Tensor,
219
+ ) -> Tuple[torch.FloatTensor, Optional[torch.FloatTensor], Optional[Tuple[torch.FloatTensor]]]:
220
+ """
221
+ Args:
222
+ hidden_states (`Tuple[torch.FloatTensor, Optional[torch.FloatTensor]]`): input to the layer of shape `(batch, seq_len, embed_dim)`
223
+ """
224
+ hidden_states = hidden_states + self.drop_path1(self.attn(self.norm1(hidden_states)) * self.ls1)
225
+
226
+ hidden_states = hidden_states + self.drop_path2(self.mlp(self.norm2(hidden_states)) * self.ls2)
227
+
228
+ return hidden_states
229
+
230
+
231
+ class InternVisionEncoder(nn.Module):
232
+ """
233
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
234
+ [`InternEncoderLayer`].
235
+
236
+ Args:
237
+ config (`InternConfig`):
238
+ The corresponding vision configuration for the `InternEncoder`.
239
+ """
240
+
241
+ def __init__(self, config: InternVisionConfig):
242
+ super().__init__()
243
+ self.config = config
244
+ # stochastic depth decay rule
245
+ dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, config.num_hidden_layers)]
246
+ self.layers = nn.ModuleList([
247
+ InternVisionEncoderLayer(config, dpr[idx]) for idx in range(config.num_hidden_layers)])
248
+ self.gradient_checkpointing = True
249
+
250
+ def forward(
251
+ self,
252
+ inputs_embeds,
253
+ output_hidden_states: Optional[bool] = None,
254
+ return_dict: Optional[bool] = None,
255
+ ) -> Union[Tuple, BaseModelOutput]:
256
+ r"""
257
+ Args:
258
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
259
+ Embedded representation of the inputs. Should be float, not int tokens.
260
+ output_hidden_states (`bool`, *optional*):
261
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
262
+ for more detail.
263
+ return_dict (`bool`, *optional*):
264
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
265
+ """
266
+ output_hidden_states = (
267
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
268
+ )
269
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
270
+
271
+ encoder_states = () if output_hidden_states else None
272
+ hidden_states = inputs_embeds
273
+
274
+ for idx, encoder_layer in enumerate(self.layers):
275
+ if output_hidden_states:
276
+ encoder_states = encoder_states + (hidden_states,)
277
+ if self.gradient_checkpointing and self.training:
278
+ layer_outputs = torch.utils.checkpoint.checkpoint(
279
+ encoder_layer,
280
+ hidden_states)
281
+ else:
282
+ layer_outputs = encoder_layer(
283
+ hidden_states,
284
+ )
285
+ hidden_states = layer_outputs
286
+
287
+ if output_hidden_states:
288
+ encoder_states = encoder_states + (hidden_states,)
289
+
290
+ if not return_dict:
291
+ return tuple(v for v in [hidden_states, encoder_states] if v is not None)
292
+ return BaseModelOutput(
293
+ last_hidden_state=hidden_states, hidden_states=encoder_states
294
+ )
295
+
296
+
297
+ class InternVisionModel(PreTrainedModel):
298
+ main_input_name = 'pixel_values'
299
+ config_class = InternVisionConfig
300
+ _no_split_modules = ['InternVisionEncoderLayer']
301
+
302
+ def __init__(self, config: InternVisionConfig):
303
+ super().__init__(config)
304
+ self.config = config
305
+
306
+ self.embeddings = InternVisionEmbeddings(config)
307
+ self.encoder = InternVisionEncoder(config)
308
+
309
+ def resize_pos_embeddings(self, old_size, new_size, patch_size):
310
+ pos_emb = self.embeddings.position_embedding
311
+ _, num_positions, embed_dim = pos_emb.shape
312
+ cls_emb = pos_emb[:, :1, :]
313
+ pos_emb = pos_emb[:, 1:, :].reshape(1, old_size // patch_size, old_size // patch_size, -1).permute(0, 3, 1, 2)
314
+ pos_emb = F.interpolate(pos_emb.float(), size=new_size // patch_size, mode='bicubic', align_corners=False)
315
+ pos_emb = pos_emb.to(cls_emb.dtype).reshape(1, embed_dim, -1).permute(0, 2, 1)
316
+ pos_emb = torch.cat([cls_emb, pos_emb], dim=1)
317
+ self.embeddings.position_embedding = nn.Parameter(pos_emb)
318
+ self.embeddings.image_size = new_size
319
+ logger.info('Resized position embeddings from {} to {}'.format(old_size, new_size))
320
+
321
+ def get_input_embeddings(self):
322
+ return self.embeddings
323
+
324
+ def forward(
325
+ self,
326
+ pixel_values: Optional[torch.FloatTensor] = None,
327
+ output_hidden_states: Optional[bool] = None,
328
+ return_dict: Optional[bool] = None,
329
+ pixel_embeds: Optional[torch.FloatTensor] = None,
330
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
331
+ output_hidden_states = (
332
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
333
+ )
334
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
335
+
336
+ if pixel_values is None and pixel_embeds is None:
337
+ raise ValueError('You have to specify pixel_values or pixel_embeds')
338
+
339
+ if pixel_embeds is not None:
340
+ hidden_states = pixel_embeds
341
+ else:
342
+ if len(pixel_values.shape) == 4:
343
+ hidden_states = self.embeddings(pixel_values)
344
+ else:
345
+ raise ValueError(f'wrong pixel_values size: {pixel_values.shape}')
346
+ encoder_outputs = self.encoder(
347
+ inputs_embeds=hidden_states,
348
+ output_hidden_states=output_hidden_states,
349
+ return_dict=return_dict,
350
+ )
351
+ last_hidden_state = encoder_outputs.last_hidden_state
352
+ pooled_output = last_hidden_state[:, 0, :]
353
+
354
+ if not return_dict:
355
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
356
+
357
+ return BaseModelOutputWithPooling(
358
+ last_hidden_state=last_hidden_state,
359
+ pooler_output=pooled_output,
360
+ hidden_states=encoder_outputs.hidden_states,
361
+ attentions=encoder_outputs.attentions,
362
+ )
internvl/model/internvl_chat/modeling_internvl_chat.py ADDED
@@ -0,0 +1,506 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+ import warnings
7
+ from typing import Any, List, Optional, Tuple, Union
8
+
9
+ import torch.distributed as dist
10
+ import torch.utils.checkpoint
11
+ import transformers
12
+ from internvl.conversation import get_conv_template
13
+ from internvl.model.internlm2.modeling_internlm2 import InternLM2ForCausalLM
14
+ from internvl.model.phi3.modeling_phi3 import Phi3ForCausalLM
15
+ from internvl.model.llama.modeling_llama import LlamaForCausalLM
16
+ from internvl.model.qwen2.modeling_qwen2 import Qwen2ForCausalLM
17
+
18
+ from peft import LoraConfig, get_peft_model
19
+ from torch import nn
20
+ from torch.nn import CrossEntropyLoss
21
+ from transformers import (AutoModel, GenerationConfig)
22
+ from transformers.modeling_outputs import CausalLMOutputWithPast
23
+ from transformers.modeling_utils import PreTrainedModel
24
+ from transformers.utils import ModelOutput, logging
25
+
26
+ from .configuration_internvl_chat import InternVLChatConfig
27
+ from .modeling_intern_vit import InternVisionModel
28
+ import time
29
+ import torch
30
+
31
+
32
+ logger = logging.get_logger(__name__)
33
+
34
+
35
+ def version_cmp(v1, v2, op='eq'):
36
+ import operator
37
+
38
+ from packaging import version
39
+ op_func = getattr(operator, op)
40
+ return op_func(version.parse(v1), version.parse(v2))
41
+
42
+
43
+ def get_attention_rank(visual_token_index, attentions):
44
+
45
+ # assert visual_token_index.shape[0] == 1 # batchsize = 1
46
+ # visual_token_index = visual_token_index.view(-1).nonzero()
47
+ visual_start_index, visual_end_index = visual_token_index[0], visual_token_index[-1]
48
+
49
+ attentions = [torch.stack(attention, dim=1) for attention in attentions] # [n l heads tokens, tokens]
50
+
51
+
52
+ visual_token_importance = 0.0
53
+ for i, attn in enumerate(attentions):
54
+ if i == 0:
55
+ visual_token_importance += attn[0].sum(dim=0).sum(dim=0)[visual_end_index+1:, visual_start_index:visual_end_index+1].sum(dim=0)
56
+ else:
57
+ visual_token_importance += attn[0].sum(dim=0).sum(dim=0)[0:1, visual_start_index:visual_end_index+1].sum(dim=0)
58
+
59
+ return visual_token_importance
60
+
61
+
62
+
63
+ class InternVLChatModel(PreTrainedModel):
64
+ config_class = InternVLChatConfig
65
+ main_input_name = 'pixel_values'
66
+ _no_split_modules = ['InternVisionModel', 'LlamaDecoderLayer', 'InternLM2DecoderLayer',
67
+ 'Phi3DecoderLayer', 'Qwen2DecoderLayer']
68
+ _supports_flash_attn_2 = True
69
+
70
+ def __init__(self, config: InternVLChatConfig, vision_model=None, language_model=None):
71
+ super().__init__(config)
72
+
73
+ assert version_cmp(transformers.__version__, '4.37.0', 'ge')
74
+ image_size = config.force_image_size or config.vision_config.image_size
75
+ patch_size = config.vision_config.patch_size
76
+ self.patch_size = patch_size
77
+ self.select_layer = config.select_layer
78
+ self.template = config.template
79
+ self.num_image_token = int((image_size // patch_size) ** 2 * (config.downsample_ratio ** 2))
80
+ self.downsample_ratio = config.downsample_ratio
81
+ self.ps_version = config.ps_version
82
+ self.llm_arch_name = config.llm_config.architectures[0]
83
+
84
+ logger.info(f'num_image_token: {self.num_image_token}')
85
+ logger.info(f'ps_version: {self.ps_version}')
86
+ if vision_model is not None:
87
+ self.vision_model = vision_model
88
+ else:
89
+ self.vision_model = InternVisionModel(config.vision_config)
90
+ if language_model is not None:
91
+ self.language_model = language_model
92
+ else:
93
+ if config.llm_config.architectures[0] == 'LlamaForCausalLM':
94
+ self.language_model = LlamaForCausalLM(config.llm_config)
95
+ elif config.llm_config.architectures[0] == 'InternLM2ForCausalLM':
96
+ self.language_model = InternLM2ForCausalLM(config.llm_config)
97
+ elif config.llm_config.architectures[0] == 'Phi3ForCausalLM':
98
+ self.language_model = Phi3ForCausalLM(config.llm_config)
99
+ elif config.llm_config.architectures[0] == 'Qwen2ForCausalLM':
100
+ self.language_model = Qwen2ForCausalLM(config.llm_config)
101
+ else:
102
+ raise NotImplementedError(f'{config.llm_config.architectures[0]} is not implemented.')
103
+
104
+ vit_hidden_size = config.vision_config.hidden_size
105
+ llm_hidden_size = config.llm_config.hidden_size
106
+
107
+ self.mlp1 = nn.Sequential(
108
+ nn.LayerNorm(vit_hidden_size * int(1 / self.downsample_ratio) ** 2),
109
+ nn.Linear(vit_hidden_size * int(1 / self.downsample_ratio) ** 2, llm_hidden_size),
110
+ nn.GELU(),
111
+ nn.Linear(llm_hidden_size, llm_hidden_size)
112
+ )
113
+
114
+ self.img_context_token_id = None
115
+ self.conv_template = get_conv_template(self.template)
116
+ self.system_message = self.conv_template.system_message
117
+ self.num_samples = 0
118
+
119
+ if config.use_backbone_lora:
120
+ self.wrap_backbone_lora(r=config.use_backbone_lora, lora_alpha=2 * config.use_backbone_lora)
121
+
122
+ if config.use_llm_lora:
123
+ self.wrap_llm_lora(r=config.use_llm_lora, lora_alpha=2 * config.use_llm_lora)
124
+
125
+ def wrap_backbone_lora(self, r=128, lora_alpha=256, lora_dropout=0.05):
126
+ lora_config = LoraConfig(
127
+ r=r,
128
+ target_modules=['attn.qkv', 'attn.proj', 'mlp.fc1', 'mlp.fc2'],
129
+ lora_alpha=lora_alpha,
130
+ lora_dropout=lora_dropout,
131
+ )
132
+ self.vision_model = get_peft_model(self.vision_model, lora_config)
133
+ self.vision_model.print_trainable_parameters()
134
+
135
+ def wrap_llm_lora(self, r=128, lora_alpha=256, lora_dropout=0.05):
136
+ # Determine the target modules based on the architecture of the language model
137
+ if self.llm_arch_name == 'InternLM2ForCausalLM':
138
+ target_modules = ['attention.wqkv', 'attention.wo', 'feed_forward.w1', 'feed_forward.w2', 'feed_forward.w3']
139
+ elif self.llm_arch_name == 'Phi3ForCausalLM':
140
+ target_modules = ['mlp.down_proj', 'mlp.gate_up_proj', 'self_attn.o_proj', 'self_attn.qkv_proj']
141
+ elif self.llm_arch_name in ['Qwen2ForCausalLM', 'LlamaForCausalLM']:
142
+ target_modules = ['self_attn.q_proj', 'self_attn.k_proj', 'self_attn.v_proj', 'self_attn.o_proj',
143
+ 'mlp.gate_proj', 'mlp.down_proj', 'mlp.up_proj']
144
+ else:
145
+ raise NotImplemented
146
+ lora_config = LoraConfig(
147
+ r=r,
148
+ target_modules=target_modules,
149
+ lora_alpha=lora_alpha,
150
+ lora_dropout=lora_dropout,
151
+ task_type='CAUSAL_LM'
152
+ )
153
+ self.language_model = get_peft_model(self.language_model, lora_config)
154
+ self.language_model.enable_input_require_grads()
155
+ self.language_model.print_trainable_parameters()
156
+
157
+ def forward(
158
+ self,
159
+ pixel_values: torch.FloatTensor,
160
+ input_ids: torch.LongTensor = None,
161
+ attention_mask: Optional[torch.Tensor] = None,
162
+ position_ids: Optional[torch.LongTensor] = None,
163
+ image_flags: Optional[torch.LongTensor] = None,
164
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
165
+ labels: Optional[torch.LongTensor] = None,
166
+ use_cache: Optional[bool] = None,
167
+ output_attentions: Optional[bool] = None,
168
+ output_hidden_states: Optional[bool] = None,
169
+ return_dict: Optional[bool] = None,
170
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
171
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
172
+
173
+ image_flags = image_flags.squeeze(-1)
174
+ input_embeds = self.language_model.get_input_embeddings()(input_ids).clone()
175
+
176
+ vit_embeds = self.extract_feature(pixel_values)
177
+ vit_embeds = vit_embeds[image_flags == 1]
178
+ vit_batch_size = pixel_values.shape[0]
179
+
180
+ B, N, C = input_embeds.shape
181
+ input_embeds = input_embeds.reshape(B * N, C)
182
+
183
+ if torch.distributed.is_initialized() and torch.distributed.get_rank() == 0:
184
+ print(f'dynamic ViT batch size: {vit_batch_size}, images per sample: {vit_batch_size / B}, dynamic token length: {N}')
185
+
186
+ input_ids = input_ids.reshape(B * N)
187
+ selected = (input_ids == self.img_context_token_id)
188
+ try:
189
+ input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds.reshape(-1, C)
190
+ ignore_flag = False
191
+ except Exception as e:
192
+ vit_embeds = vit_embeds.reshape(-1, C)
193
+ print(f'warning: {e}, input_embeds[selected].shape={input_embeds[selected].shape}, '
194
+ f'vit_embeds.shape={vit_embeds.shape}')
195
+ n_token = selected.sum()
196
+ input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds[:n_token]
197
+ ignore_flag = True
198
+
199
+ input_embeds = input_embeds.reshape(B, N, C)
200
+
201
+ outputs = self.language_model(
202
+ inputs_embeds=input_embeds,
203
+ attention_mask=attention_mask,
204
+ position_ids=position_ids,
205
+ past_key_values=past_key_values,
206
+ use_cache=use_cache,
207
+ output_attentions=output_attentions,
208
+ output_hidden_states=output_hidden_states,
209
+ return_dict=return_dict,
210
+ )
211
+ logits = outputs.logits
212
+
213
+ loss = None
214
+ if labels is not None:
215
+ # Shift so that tokens < n predict n
216
+ shift_logits = logits[..., :-1, :].contiguous()
217
+ shift_labels = labels[..., 1:].contiguous()
218
+ # Flatten the tokens
219
+ loss_fct = CrossEntropyLoss()
220
+ shift_logits = shift_logits.view(-1, self.language_model.config.vocab_size)
221
+ shift_labels = shift_labels.view(-1)
222
+ # Enable model parallelism
223
+ shift_labels = shift_labels.to(shift_logits.device)
224
+ loss = loss_fct(shift_logits, shift_labels)
225
+ if ignore_flag:
226
+ loss = loss * 0.0
227
+
228
+ if not return_dict:
229
+ output = (logits,) + outputs[1:]
230
+ return (loss,) + output if loss is not None else output
231
+
232
+ return CausalLMOutputWithPast(
233
+ loss=loss,
234
+ logits=logits,
235
+ past_key_values=outputs.past_key_values,
236
+ hidden_states=outputs.hidden_states,
237
+ attentions=outputs.attentions,
238
+ )
239
+
240
+ def pixel_shuffle(self, x, scale_factor=0.5):
241
+ n, w, h, c = x.size()
242
+ # N, W, H, C --> N, W, H * scale, C // scale
243
+ x = x.view(n, w, int(h * scale_factor), int(c / scale_factor))
244
+ # N, W, H * scale, C // scale --> N, H * scale, W, C // scale
245
+ x = x.permute(0, 2, 1, 3).contiguous()
246
+ # N, H * scale, W, C // scale --> N, H * scale, W * scale, C // (scale ** 2)
247
+ x = x.view(n, int(h * scale_factor), int(w * scale_factor),
248
+ int(c / (scale_factor * scale_factor)))
249
+ if self.ps_version == 'v1':
250
+ warnings.warn("In ps_version 'v1', the height and width have not been swapped back, "
251
+ 'which results in a transposed image.')
252
+ else:
253
+ x = x.permute(0, 2, 1, 3).contiguous()
254
+ return x
255
+
256
+ def extract_feature(self, pixel_values):
257
+ if self.select_layer == -1:
258
+ vit_embeds = self.vision_model(
259
+ pixel_values=pixel_values,
260
+ output_hidden_states=False,
261
+ return_dict=True).last_hidden_state
262
+ else:
263
+ vit_embeds = self.vision_model(
264
+ pixel_values=pixel_values,
265
+ output_hidden_states=True,
266
+ return_dict=True).hidden_states[self.select_layer]
267
+ vit_embeds = vit_embeds[:, 1:, :]
268
+
269
+ h = w = int(vit_embeds.shape[1] ** 0.5)
270
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], h, w, -1)
271
+ vit_embeds = self.pixel_shuffle(vit_embeds, scale_factor=self.downsample_ratio)
272
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], -1, vit_embeds.shape[-1])
273
+ vit_embeds = self.mlp1(vit_embeds)
274
+ return vit_embeds
275
+
276
+ def batch_chat(self, tokenizer, pixel_values, questions, generation_config, num_patches_list=None,
277
+ history=None, return_history=False, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>',
278
+ IMG_CONTEXT_TOKEN='<IMG_CONTEXT>', verbose=False, image_counts=None):
279
+ if history is not None or return_history:
280
+ print('Now multi-turn chat is not supported in batch_chat.')
281
+ raise NotImplementedError
282
+
283
+ if image_counts is not None:
284
+ num_patches_list = image_counts
285
+ print('Warning: `image_counts` is deprecated. Please use `num_patches_list` instead.')
286
+
287
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
288
+ self.img_context_token_id = img_context_token_id
289
+
290
+ if verbose and pixel_values is not None:
291
+ image_bs = pixel_values.shape[0]
292
+ print(f'dynamic ViT batch size: {image_bs}')
293
+
294
+ queries = []
295
+ for idx, num_patches in enumerate(num_patches_list):
296
+ question = questions[idx]
297
+ if pixel_values is not None and '<image>' not in question:
298
+ question = '<image>\n' + question
299
+ template = get_conv_template(self.template)
300
+ template.append_message(template.roles[0], question)
301
+ template.append_message(template.roles[1], None)
302
+ query = template.get_prompt()
303
+
304
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
305
+ query = query.replace('<image>', image_tokens, 1)
306
+ queries.append(query)
307
+
308
+ tokenizer.padding_side = 'left'
309
+ model_inputs = tokenizer(queries, return_tensors='pt', padding=True)
310
+ input_ids = model_inputs['input_ids'].cuda()
311
+ attention_mask = model_inputs['attention_mask'].cuda()
312
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
313
+ generation_config['eos_token_id'] = eos_token_id
314
+ generation_output = self.generate(
315
+ pixel_values=pixel_values,
316
+ input_ids=input_ids,
317
+ attention_mask=attention_mask,
318
+ **generation_config
319
+ )
320
+ responses = tokenizer.batch_decode(generation_output, skip_special_tokens=True)
321
+ responses = [response.split(template.sep)[0].strip() for response in responses]
322
+ return responses
323
+
324
+ def chat(self, tokenizer, pixel_values, question, generation_config, history=None, return_history=False,
325
+ num_patches_list=None, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>', IMG_CONTEXT_TOKEN='<IMG_CONTEXT>',
326
+ verbose=False, large_model=False):
327
+
328
+ if history is None and pixel_values is not None and '<image>' not in question:
329
+ question = '<image>\n' + question
330
+
331
+ if num_patches_list is None:
332
+ num_patches_list = [pixel_values.shape[0]] if pixel_values is not None else []
333
+ assert pixel_values is None or len(pixel_values) == sum(num_patches_list)
334
+
335
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
336
+ self.img_context_token_id = img_context_token_id
337
+
338
+ template = get_conv_template(self.template)
339
+ template.system_message = self.system_message
340
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
341
+
342
+ history = [] if history is None else history
343
+ for (old_question, old_answer) in history:
344
+ template.append_message(template.roles[0], old_question)
345
+ template.append_message(template.roles[1], old_answer)
346
+ template.append_message(template.roles[0], question)
347
+ template.append_message(template.roles[1], None)
348
+ query = template.get_prompt()
349
+
350
+ if verbose and pixel_values is not None:
351
+ image_bs = pixel_values.shape[0]
352
+ print(f'dynamic ViT batch size: {image_bs}')
353
+
354
+ for num_patches in num_patches_list:
355
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
356
+ query = query.replace('<image>', image_tokens, 1)
357
+
358
+ model_inputs = tokenizer(query, return_tensors='pt')
359
+ input_ids = model_inputs['input_ids'].cuda()
360
+ attention_mask = model_inputs['attention_mask'].cuda()
361
+ generation_config['eos_token_id'] = eos_token_id
362
+
363
+
364
+ visual_token_index = (input_ids == self.img_context_token_id)
365
+
366
+ visual_token_index = visual_token_index.view(-1).nonzero()
367
+ visual_start_index, visual_end_index = visual_token_index[0], visual_token_index[-1]
368
+
369
+
370
+ if large_model:
371
+ generation_config["visual_token_index"] = (visual_start_index, visual_end_index)
372
+ assert (visual_end_index - visual_start_index + 1) == generation_config["visual_token_importance"].shape[0]
373
+ else:
374
+ generation_config['consistency_config']["visual_token_index"] = (visual_start_index, visual_end_index)
375
+
376
+
377
+ if not large_model:
378
+ generation_output, consistency_score, visual_token_importance = self.generate(
379
+ pixel_values=pixel_values,
380
+ input_ids=input_ids,
381
+ attention_mask=attention_mask,
382
+ large_model=large_model,
383
+ **generation_config
384
+ )
385
+
386
+ response = tokenizer.batch_decode(generation_output['sequences'], skip_special_tokens=True)[0]
387
+ response = response.split(template.sep)[0].strip()
388
+ history.append((question, response))
389
+
390
+ if return_history:
391
+ return response, history
392
+ else:
393
+ query_to_print = query.replace(IMG_CONTEXT_TOKEN, '')
394
+ query_to_print = query_to_print.replace(f'{IMG_START_TOKEN}{IMG_END_TOKEN}', '<image>')
395
+ if verbose:
396
+ print(query_to_print, response)
397
+ return response, generation_output.scores, consistency_score, visual_token_importance
398
+
399
+
400
+ else:
401
+ generation_output = self.generate(
402
+ pixel_values=pixel_values,
403
+ input_ids=input_ids,
404
+ attention_mask=attention_mask,
405
+ large_model=large_model,
406
+ **generation_config
407
+ )
408
+
409
+ response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]
410
+ response = response.split(template.sep)[0].strip()
411
+ history.append((question, response))
412
+ if return_history:
413
+ return response, history
414
+ else:
415
+ query_to_print = query.replace(IMG_CONTEXT_TOKEN, '')
416
+ query_to_print = query_to_print.replace(f'{IMG_START_TOKEN}{IMG_END_TOKEN}', '<image>')
417
+ if verbose:
418
+ print(query_to_print, response)
419
+ return response
420
+
421
+
422
+
423
+ @torch.no_grad()
424
+ def generate(
425
+ self,
426
+ pixel_values: Optional[torch.FloatTensor] = None,
427
+ input_ids: Optional[torch.FloatTensor] = None,
428
+ attention_mask: Optional[torch.LongTensor] = None,
429
+ visual_features: Optional[torch.FloatTensor] = None,
430
+ generation_config: Optional[GenerationConfig] = None,
431
+ output_hidden_states: Optional[bool] = None,
432
+ return_dict: Optional[bool] = None,
433
+ large_model: Optional[bool] = False,
434
+ **generate_kwargs,
435
+ ) -> torch.LongTensor:
436
+
437
+ assert self.img_context_token_id is not None
438
+ if pixel_values is not None:
439
+ if visual_features is not None:
440
+ vit_embeds = visual_features
441
+ else:
442
+ vit_embeds = self.extract_feature(pixel_values)
443
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
444
+ B, N, C = input_embeds.shape
445
+ input_embeds = input_embeds.reshape(B * N, C)
446
+
447
+ input_ids = input_ids.reshape(B * N)
448
+ selected = (input_ids == self.img_context_token_id)
449
+ assert selected.sum() != 0
450
+ input_embeds[selected] = vit_embeds.reshape(-1, C).to(input_embeds.device)
451
+
452
+ input_embeds = input_embeds.reshape(B, N, C)
453
+ else:
454
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
455
+
456
+
457
+
458
+ if not large_model:
459
+ consistency_generate_kwargs = generate_kwargs.pop('consistency_config')
460
+ generate_kwargs['visual_token_index'] = consistency_generate_kwargs['visual_token_index']
461
+ outputs = self.language_model.generate(
462
+ inputs_embeds=input_embeds,
463
+ attention_mask=attention_mask,
464
+ generation_config=generation_config,
465
+ output_hidden_states=output_hidden_states,
466
+ return_dict=return_dict,
467
+ use_cache=True,
468
+ **generate_kwargs,
469
+ )
470
+
471
+ visual_token_importance = outputs.aggregated_viusal_token_attention
472
+ consistency_generate_kwargs['visual_token_importance'] = visual_token_importance
473
+
474
+ new_input_ids_ = outputs['sequences'][0]
475
+ new_token_num = outputs['sequences'].shape[-1]
476
+ new_input_embedding = torch.concatenate((input_embeds, self.language_model.get_input_embeddings()(new_input_ids_).unsqueeze(0)), dim=1)
477
+ new_attention_mask = torch.concatenate((attention_mask, torch.ones((1, new_input_ids_.shape[0]), device=attention_mask.device, dtype=attention_mask.dtype)), dim=-1)
478
+ new_input_ids = torch.concatenate((input_ids, new_input_ids_), dim=-1)
479
+ consistency_generate_kwargs['inputs_embeds'] = new_input_embedding
480
+ consistency_generate_kwargs['attention_mask'] = new_attention_mask
481
+ consistency_generate_kwargs['output_scores'] = False
482
+ consistency_generate_kwargs['output_attentions'] = False
483
+ consistency_generate_kwargs = self.language_model._get_initial_cache_position(new_input_ids, consistency_generate_kwargs)
484
+
485
+ model_inputs = self.language_model.prepare_inputs_for_generation(new_input_ids, **consistency_generate_kwargs)
486
+ consistency_output = self.language_model.forward(**model_inputs, return_dict=True)
487
+ consistency_score = torch.gather(consistency_output['logits'][:, -new_token_num-1:-1, :].softmax(dim=-1), index=new_input_ids_[None, :, None], dim=-1)
488
+
489
+ consistency_score = torch.prod(consistency_score)
490
+
491
+
492
+
493
+ return outputs, consistency_score, visual_token_importance
494
+
495
+
496
+
497
+ else:
498
+ return self.language_model.generate(
499
+ inputs_embeds=input_embeds,
500
+ attention_mask=attention_mask,
501
+ generation_config=generation_config,
502
+ output_hidden_states=output_hidden_states,
503
+ return_dict=return_dict,
504
+ use_cache=True,
505
+ **generate_kwargs,
506
+ )
internvl/model/llama/__init__.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 EleutherAI 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
+ from typing import TYPE_CHECKING
15
+
16
+ from transformers.utils import (
17
+ OptionalDependencyNotAvailable,
18
+ _LazyModule,
19
+ is_flax_available,
20
+ is_sentencepiece_available,
21
+ is_tokenizers_available,
22
+ is_torch_available,
23
+ )
24
+
25
+
26
+ _import_structure = {
27
+ "configuration_llama": ["LlamaConfig"],
28
+ }
29
+
30
+ try:
31
+ if not is_sentencepiece_available():
32
+ raise OptionalDependencyNotAvailable()
33
+ except OptionalDependencyNotAvailable:
34
+ pass
35
+ else:
36
+ _import_structure["tokenization_llama"] = ["LlamaTokenizer"]
37
+
38
+ try:
39
+ if not is_tokenizers_available():
40
+ raise OptionalDependencyNotAvailable()
41
+ except OptionalDependencyNotAvailable:
42
+ pass
43
+ else:
44
+ _import_structure["tokenization_llama_fast"] = ["LlamaTokenizerFast"]
45
+
46
+ try:
47
+ if not is_torch_available():
48
+ raise OptionalDependencyNotAvailable()
49
+ except OptionalDependencyNotAvailable:
50
+ pass
51
+ else:
52
+ _import_structure["modeling_llama"] = [
53
+ "LlamaForCausalLM",
54
+ "LlamaModel",
55
+ "LlamaPreTrainedModel",
56
+ "LlamaForSequenceClassification",
57
+ "LlamaForQuestionAnswering",
58
+ "LlamaForTokenClassification",
59
+ ]
60
+
61
+ try:
62
+ if not is_flax_available():
63
+ raise OptionalDependencyNotAvailable()
64
+ except OptionalDependencyNotAvailable:
65
+ pass
66
+ else:
67
+ _import_structure["modeling_flax_llama"] = ["FlaxLlamaForCausalLM", "FlaxLlamaModel", "FlaxLlamaPreTrainedModel"]
68
+
69
+
70
+ if TYPE_CHECKING:
71
+ from .configuration_llama import LlamaConfig
72
+
73
+ try:
74
+ if not is_sentencepiece_available():
75
+ raise OptionalDependencyNotAvailable()
76
+ except OptionalDependencyNotAvailable:
77
+ pass
78
+ else:
79
+ from .tokenization_llama import LlamaTokenizer
80
+
81
+ try:
82
+ if not is_tokenizers_available():
83
+ raise OptionalDependencyNotAvailable()
84
+ except OptionalDependencyNotAvailable:
85
+ pass
86
+ else:
87
+ from .tokenization_llama_fast import LlamaTokenizerFast
88
+
89
+ try:
90
+ if not is_torch_available():
91
+ raise OptionalDependencyNotAvailable()
92
+ except OptionalDependencyNotAvailable:
93
+ pass
94
+ else:
95
+ from .modeling_llama import (
96
+ LlamaForCausalLM,
97
+ LlamaForQuestionAnswering,
98
+ LlamaForSequenceClassification,
99
+ LlamaForTokenClassification,
100
+ LlamaModel,
101
+ LlamaPreTrainedModel,
102
+ )
103
+
104
+ try:
105
+ if not is_flax_available():
106
+ raise OptionalDependencyNotAvailable()
107
+ except OptionalDependencyNotAvailable:
108
+ pass
109
+ else:
110
+ from .modeling_flax_llama import FlaxLlamaForCausalLM, FlaxLlamaModel, FlaxLlamaPreTrainedModel
111
+
112
+
113
+ else:
114
+ import sys
115
+
116
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
internvl/model/llama/configuration_llama.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """LLaMA model configuration"""
21
+
22
+ from transformers.configuration_utils import PretrainedConfig
23
+ from transformers.modeling_rope_utils import rope_config_validation
24
+
25
+
26
+ class LlamaConfig(PretrainedConfig):
27
+ r"""
28
+ This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA
29
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
30
+ defaults will yield a similar configuration to that of the LLaMA-7B.
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 32000):
38
+ Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
39
+ `inputs_ids` passed when calling [`LlamaModel`]
40
+ hidden_size (`int`, *optional*, defaults to 4096):
41
+ Dimension of the hidden representations.
42
+ intermediate_size (`int`, *optional*, defaults to 11008):
43
+ Dimension of the MLP representations.
44
+ num_hidden_layers (`int`, *optional*, defaults to 32):
45
+ Number of hidden layers in the Transformer decoder.
46
+ num_attention_heads (`int`, *optional*, defaults to 32):
47
+ Number of attention heads for each attention layer in the Transformer decoder.
48
+ num_key_value_heads (`int`, *optional*):
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
55
+ `num_attention_heads`.
56
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
57
+ The non-linear activation function (function or string) in the decoder.
58
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
59
+ The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens,
60
+ Llama 2 up to 4096, CodeLlama up to 16384.
61
+ initializer_range (`float`, *optional*, defaults to 0.02):
62
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
63
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
64
+ The epsilon used by the rms normalization layers.
65
+ use_cache (`bool`, *optional*, defaults to `True`):
66
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
67
+ relevant if `config.is_decoder=True`.
68
+ pad_token_id (`int`, *optional*):
69
+ Padding token id.
70
+ bos_token_id (`int`, *optional*, defaults to 1):
71
+ Beginning of stream token id.
72
+ eos_token_id (`int`, *optional*, defaults to 2):
73
+ End of stream token id.
74
+ pretraining_tp (`int`, *optional*, defaults to 1):
75
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
76
+ document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to
77
+ understand more about it. This value is necessary to ensure exact reproducibility of the pretraining
78
+ results. Please refer to [this issue](https://github.com/pytorch/pytorch/issues/76232).
79
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
80
+ Whether to tie weight embeddings
81
+ rope_theta (`float`, *optional*, defaults to 10000.0):
82
+ The base period of the RoPE embeddings.
83
+ rope_scaling (`Dict`, *optional*):
84
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
85
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
86
+ accordingly.
87
+ Expected contents:
88
+ `rope_type` (`str`):
89
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
90
+ 'llama3'], with 'default' being the original RoPE implementation.
91
+ `factor` (`float`, *optional*):
92
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
93
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
94
+ original maximum pre-trained length.
95
+ `original_max_position_embeddings` (`int`, *optional*):
96
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
97
+ pretraining.
98
+ `attention_factor` (`float`, *optional*):
99
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
100
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
101
+ `factor` field to infer the suggested value.
102
+ `beta_fast` (`float`, *optional*):
103
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
104
+ ramp function. If unspecified, it defaults to 32.
105
+ `beta_slow` (`float`, *optional*):
106
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
107
+ ramp function. If unspecified, it defaults to 1.
108
+ `short_factor` (`List[float]`, *optional*):
109
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
110
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
111
+ size divided by the number of attention heads divided by 2
112
+ `long_factor` (`List[float]`, *optional*):
113
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
114
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
115
+ size divided by the number of attention heads divided by 2
116
+ `low_freq_factor` (`float`, *optional*):
117
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
118
+ `high_freq_factor` (`float`, *optional*):
119
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
120
+ attention_bias (`bool`, *optional*, defaults to `False`):
121
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
122
+ attention_dropout (`float`, *optional*, defaults to 0.0):
123
+ The dropout ratio for the attention probabilities.
124
+ mlp_bias (`bool`, *optional*, defaults to `False`):
125
+ Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
126
+
127
+ ```python
128
+ >>> from transformers import LlamaModel, LlamaConfig
129
+
130
+ >>> # Initializing a LLaMA llama-7b style configuration
131
+ >>> configuration = LlamaConfig()
132
+
133
+ >>> # Initializing a model from the llama-7b style configuration
134
+ >>> model = LlamaModel(configuration)
135
+
136
+ >>> # Accessing the model configuration
137
+ >>> configuration = model.config
138
+ ```"""
139
+
140
+ model_type = "llama"
141
+ keys_to_ignore_at_inference = ["past_key_values"]
142
+
143
+ def __init__(
144
+ self,
145
+ vocab_size=32000,
146
+ hidden_size=4096,
147
+ intermediate_size=11008,
148
+ num_hidden_layers=32,
149
+ num_attention_heads=32,
150
+ num_key_value_heads=None,
151
+ hidden_act="silu",
152
+ max_position_embeddings=2048,
153
+ initializer_range=0.02,
154
+ rms_norm_eps=1e-6,
155
+ use_cache=True,
156
+ pad_token_id=None,
157
+ bos_token_id=1,
158
+ eos_token_id=2,
159
+ pretraining_tp=1,
160
+ tie_word_embeddings=False,
161
+ rope_theta=10000.0,
162
+ rope_scaling=None,
163
+ attention_bias=False,
164
+ attention_dropout=0.0,
165
+ mlp_bias=False,
166
+ **kwargs,
167
+ ):
168
+ self.vocab_size = vocab_size
169
+ self.max_position_embeddings = max_position_embeddings
170
+ self.hidden_size = hidden_size
171
+ self.intermediate_size = intermediate_size
172
+ self.num_hidden_layers = num_hidden_layers
173
+ self.num_attention_heads = num_attention_heads
174
+
175
+ # for backward compatibility
176
+ if num_key_value_heads is None:
177
+ num_key_value_heads = num_attention_heads
178
+
179
+ self.num_key_value_heads = num_key_value_heads
180
+ self.hidden_act = hidden_act
181
+ self.initializer_range = initializer_range
182
+ self.rms_norm_eps = rms_norm_eps
183
+ self.pretraining_tp = pretraining_tp
184
+ self.use_cache = use_cache
185
+ self.rope_theta = rope_theta
186
+ self.rope_scaling = rope_scaling
187
+ self.attention_bias = attention_bias
188
+ self.attention_dropout = attention_dropout
189
+ self.mlp_bias = mlp_bias
190
+
191
+ # Validate the correctness of rotary position embeddings parameters
192
+ # BC: if there is a 'type' field, move it to 'rope_type'.
193
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
194
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
195
+ rope_config_validation(self)
196
+
197
+ super().__init__(
198
+ pad_token_id=pad_token_id,
199
+ bos_token_id=bos_token_id,
200
+ eos_token_id=eos_token_id,
201
+ tie_word_embeddings=tie_word_embeddings,
202
+ **kwargs,
203
+ )
internvl/model/llama/convert_llama_weights_to_hf.py ADDED
@@ -0,0 +1,479 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 EleutherAI 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
+ import argparse
15
+ import gc
16
+ import json
17
+ import os
18
+ import shutil
19
+ import warnings
20
+ from typing import List
21
+
22
+ import torch
23
+
24
+ from transformers import GenerationConfig, LlamaConfig, LlamaForCausalLM, LlamaTokenizer, PreTrainedTokenizerFast
25
+ from transformers.convert_slow_tokenizer import TikTokenConverter
26
+
27
+
28
+ try:
29
+ from transformers import LlamaTokenizerFast
30
+ except ImportError as e:
31
+ warnings.warn(e)
32
+ warnings.warn(
33
+ "The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion"
34
+ )
35
+ LlamaTokenizerFast = None
36
+
37
+ """
38
+ Sample usage:
39
+
40
+ ```
41
+ python src/transformers/models/llama/convert_llama_weights_to_hf.py \
42
+ --input_dir /path/to/downloaded/llama/weights --model_size 7B --output_dir /output/path
43
+ ```
44
+
45
+ Thereafter, models can be loaded via:
46
+
47
+ ```py
48
+ from transformers import LlamaForCausalLM, LlamaTokenizer
49
+
50
+ model = LlamaForCausalLM.from_pretrained("/output/path")
51
+ tokenizer = LlamaTokenizer.from_pretrained("/output/path")
52
+ ```
53
+
54
+ Important note: you need to be able to host the whole model in RAM to execute this script (even if the biggest versions
55
+ come in several checkpoints they each contain a part of each weight of the model, so we need to load them all in RAM).
56
+
57
+ If you want you tokenizer to add a bos automatically you should update the tokenizer._tokenizers.post_processor:
58
+
59
+ ```py
60
+ from tokenizers import processors
61
+ bos = "<|begin_of_text|>"
62
+ tokenizer._tokenizers.post_processor = processors.Sequence(
63
+ [
64
+ processors.ByteLevel(trim_offsets=False),
65
+ processors.TemplateProcessing(
66
+ single=f"{bos}:0 $A:0",
67
+ pair=f"{bos}:0 $A:0 {bos}:1 $B:1",
68
+ special_tokens=[
69
+ (bos, tokenizer.encode(bos)),
70
+ ],
71
+ ),
72
+ ]
73
+ )
74
+ ```
75
+ """
76
+
77
+ NUM_SHARDS = {
78
+ "7B": 1,
79
+ "8B": 1,
80
+ "8Bf": 1,
81
+ "7Bf": 1,
82
+ "13B": 2,
83
+ "13Bf": 2,
84
+ "34B": 4,
85
+ "30B": 4,
86
+ "65B": 8,
87
+ "70B": 8,
88
+ "70Bf": 8,
89
+ "405B": 8,
90
+ "405B-MP16": 16,
91
+ }
92
+
93
+ CONTEXT_LENGTH_FOR_VERSION = {"3.1": 131072, "3": 8192, "2": 4096, "1": 2048}
94
+
95
+
96
+ def compute_intermediate_size(n, ffn_dim_multiplier=1, multiple_of=256):
97
+ return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3)) + multiple_of - 1) // multiple_of)
98
+
99
+
100
+ def read_json(path):
101
+ with open(path, "r") as f:
102
+ return json.load(f)
103
+
104
+
105
+ def write_json(text, path):
106
+ with open(path, "w") as f:
107
+ json.dump(text, f)
108
+
109
+
110
+ def write_model(
111
+ model_path,
112
+ input_base_path,
113
+ model_size=None,
114
+ safe_serialization=True,
115
+ llama_version="1",
116
+ vocab_size=None,
117
+ num_shards=None,
118
+ instruct=False,
119
+ ):
120
+ os.makedirs(model_path, exist_ok=True)
121
+ tmp_model_path = os.path.join(model_path, "tmp")
122
+ os.makedirs(tmp_model_path, exist_ok=True)
123
+
124
+ params = read_json(os.path.join(input_base_path, "params.json"))
125
+ num_shards = NUM_SHARDS[model_size] if num_shards is None else num_shards
126
+ params = params.get("model", params)
127
+ n_layers = params["n_layers"]
128
+ n_heads = params["n_heads"]
129
+ n_heads_per_shard = n_heads // num_shards
130
+ dim = params["dim"]
131
+ dims_per_head = dim // n_heads
132
+ base = params.get("rope_theta", 10000.0)
133
+ inv_freq = 1.0 / (base ** (torch.arange(0, dims_per_head, 2).float() / dims_per_head))
134
+ if base > 10000.0 and float(llama_version) < 3:
135
+ max_position_embeddings = 16384
136
+ else:
137
+ max_position_embeddings = CONTEXT_LENGTH_FOR_VERSION[llama_version]
138
+
139
+ if params.get("n_kv_heads", None) is not None:
140
+ num_key_value_heads = params["n_kv_heads"] # for GQA / MQA
141
+ num_key_value_heads_per_shard = num_key_value_heads // num_shards
142
+ key_value_dim = dims_per_head * num_key_value_heads
143
+ else: # compatibility with other checkpoints
144
+ num_key_value_heads = n_heads
145
+ num_key_value_heads_per_shard = n_heads_per_shard
146
+ key_value_dim = dim
147
+
148
+ # permute for sliced rotary
149
+ def permute(w, n_heads, dim1=dim, dim2=dim):
150
+ return w.view(n_heads, dim1 // n_heads // 2, 2, dim2).transpose(1, 2).reshape(dim1, dim2)
151
+
152
+ print(f"Fetching all parameters from the checkpoint at {input_base_path}.")
153
+ # Load weights
154
+ if num_shards == 1:
155
+ # Not sharded
156
+ # (The sharded implementation would also work, but this is simpler.)
157
+ loaded = torch.load(os.path.join(input_base_path, "consolidated.00.pth"), map_location="cpu")
158
+ else:
159
+ # Sharded
160
+ checkpoint_list = sorted([file for file in os.listdir(input_base_path) if file.endswith(".pth")])
161
+ print("Loading in order:", checkpoint_list)
162
+ loaded = [torch.load(os.path.join(input_base_path, file), map_location="cpu") for file in checkpoint_list]
163
+ param_count = 0
164
+ index_dict = {"weight_map": {}}
165
+ for layer_i in range(n_layers):
166
+ filename = f"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin"
167
+ if num_shards == 1:
168
+ # Unsharded
169
+ state_dict = {
170
+ f"model.layers.{layer_i}.self_attn.q_proj.weight": permute(
171
+ loaded[f"layers.{layer_i}.attention.wq.weight"], n_heads=n_heads
172
+ ),
173
+ f"model.layers.{layer_i}.self_attn.k_proj.weight": permute(
174
+ loaded[f"layers.{layer_i}.attention.wk.weight"],
175
+ n_heads=num_key_value_heads,
176
+ dim1=key_value_dim,
177
+ ),
178
+ f"model.layers.{layer_i}.self_attn.v_proj.weight": loaded[f"layers.{layer_i}.attention.wv.weight"],
179
+ f"model.layers.{layer_i}.self_attn.o_proj.weight": loaded[f"layers.{layer_i}.attention.wo.weight"],
180
+ f"model.layers.{layer_i}.mlp.gate_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w1.weight"],
181
+ f"model.layers.{layer_i}.mlp.down_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w2.weight"],
182
+ f"model.layers.{layer_i}.mlp.up_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w3.weight"],
183
+ f"model.layers.{layer_i}.input_layernorm.weight": loaded[f"layers.{layer_i}.attention_norm.weight"],
184
+ f"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[f"layers.{layer_i}.ffn_norm.weight"],
185
+ }
186
+ else:
187
+ # Sharded
188
+ # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share
189
+ # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is
190
+ # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned.
191
+
192
+ state_dict = {
193
+ f"model.layers.{layer_i}.input_layernorm.weight": loaded[0][
194
+ f"layers.{layer_i}.attention_norm.weight"
195
+ ].clone(),
196
+ f"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[0][
197
+ f"layers.{layer_i}.ffn_norm.weight"
198
+ ].clone(),
199
+ }
200
+ state_dict[f"model.layers.{layer_i}.self_attn.q_proj.weight"] = permute(
201
+ torch.cat(
202
+ [
203
+ loaded[i][f"layers.{layer_i}.attention.wq.weight"].view(n_heads_per_shard, dims_per_head, dim)
204
+ for i in range(len(loaded))
205
+ ],
206
+ dim=0,
207
+ ).reshape(dim, dim),
208
+ n_heads=n_heads,
209
+ )
210
+ state_dict[f"model.layers.{layer_i}.self_attn.k_proj.weight"] = permute(
211
+ torch.cat(
212
+ [
213
+ loaded[i][f"layers.{layer_i}.attention.wk.weight"].view(
214
+ num_key_value_heads_per_shard, dims_per_head, dim
215
+ )
216
+ for i in range(len(loaded))
217
+ ],
218
+ dim=0,
219
+ ).reshape(key_value_dim, dim),
220
+ num_key_value_heads,
221
+ key_value_dim,
222
+ dim,
223
+ )
224
+ state_dict[f"model.layers.{layer_i}.self_attn.v_proj.weight"] = torch.cat(
225
+ [
226
+ loaded[i][f"layers.{layer_i}.attention.wv.weight"].view(
227
+ num_key_value_heads_per_shard, dims_per_head, dim
228
+ )
229
+ for i in range(len(loaded))
230
+ ],
231
+ dim=0,
232
+ ).reshape(key_value_dim, dim)
233
+
234
+ state_dict[f"model.layers.{layer_i}.self_attn.o_proj.weight"] = torch.cat(
235
+ [loaded[i][f"layers.{layer_i}.attention.wo.weight"] for i in range(len(loaded))], dim=1
236
+ )
237
+ state_dict[f"model.layers.{layer_i}.mlp.gate_proj.weight"] = torch.cat(
238
+ [loaded[i][f"layers.{layer_i}.feed_forward.w1.weight"] for i in range(len(loaded))], dim=0
239
+ )
240
+ state_dict[f"model.layers.{layer_i}.mlp.down_proj.weight"] = torch.cat(
241
+ [loaded[i][f"layers.{layer_i}.feed_forward.w2.weight"] for i in range(len(loaded))], dim=1
242
+ )
243
+ state_dict[f"model.layers.{layer_i}.mlp.up_proj.weight"] = torch.cat(
244
+ [loaded[i][f"layers.{layer_i}.feed_forward.w3.weight"] for i in range(len(loaded))], dim=0
245
+ )
246
+
247
+ state_dict[f"model.layers.{layer_i}.self_attn.rotary_emb.inv_freq"] = inv_freq
248
+ for k, v in state_dict.items():
249
+ index_dict["weight_map"][k] = filename
250
+ param_count += v.numel()
251
+ torch.save(state_dict, os.path.join(tmp_model_path, filename))
252
+
253
+ filename = f"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin"
254
+ if num_shards == 1:
255
+ # Unsharded
256
+ state_dict = {
257
+ "model.embed_tokens.weight": loaded["tok_embeddings.weight"],
258
+ "model.norm.weight": loaded["norm.weight"],
259
+ "lm_head.weight": loaded["output.weight"],
260
+ }
261
+ else:
262
+ concat_dim = 0 if llama_version in ["3", "3.1"] else 1
263
+ state_dict = {
264
+ "model.norm.weight": loaded[0]["norm.weight"],
265
+ "model.embed_tokens.weight": torch.cat(
266
+ [loaded[i]["tok_embeddings.weight"] for i in range(len(loaded))], dim=concat_dim
267
+ ),
268
+ "lm_head.weight": torch.cat([loaded[i]["output.weight"] for i in range(len(loaded))], dim=0),
269
+ }
270
+
271
+ for k, v in state_dict.items():
272
+ index_dict["weight_map"][k] = filename
273
+ param_count += v.numel()
274
+ torch.save(state_dict, os.path.join(tmp_model_path, filename))
275
+
276
+ # Write configs
277
+ index_dict["metadata"] = {"total_size": param_count * 2}
278
+ write_json(index_dict, os.path.join(tmp_model_path, "pytorch_model.bin.index.json"))
279
+ ffn_dim_multiplier = params["ffn_dim_multiplier"] if "ffn_dim_multiplier" in params else 1
280
+ multiple_of = params["multiple_of"] if "multiple_of" in params else 256
281
+
282
+ if llama_version in ["3", "3.1"]:
283
+ bos_token_id = 128000
284
+
285
+ if instruct:
286
+ eos_token_id = [128001, 128008, 128009]
287
+ else:
288
+ eos_token_id = 128001
289
+ else:
290
+ bos_token_id = 1
291
+ eos_token_id = 2
292
+
293
+ config = LlamaConfig(
294
+ hidden_size=dim,
295
+ intermediate_size=compute_intermediate_size(dim, ffn_dim_multiplier, multiple_of),
296
+ num_attention_heads=params["n_heads"],
297
+ num_hidden_layers=params["n_layers"],
298
+ rms_norm_eps=params["norm_eps"],
299
+ num_key_value_heads=num_key_value_heads,
300
+ vocab_size=vocab_size,
301
+ rope_theta=base,
302
+ max_position_embeddings=max_position_embeddings,
303
+ bos_token_id=bos_token_id,
304
+ eos_token_id=eos_token_id,
305
+ )
306
+ config.save_pretrained(tmp_model_path)
307
+
308
+ if instruct:
309
+ generation_config = GenerationConfig(
310
+ do_sample=True,
311
+ temperature=0.6,
312
+ top_p=0.9,
313
+ bos_token_id=bos_token_id,
314
+ eos_token_id=eos_token_id,
315
+ )
316
+ generation_config.save_pretrained(tmp_model_path)
317
+
318
+ # Make space so we can load the model properly now.
319
+ del state_dict
320
+ del loaded
321
+ gc.collect()
322
+
323
+ print("Loading the checkpoint in a Llama model.")
324
+ model = LlamaForCausalLM.from_pretrained(tmp_model_path, torch_dtype=torch.bfloat16, low_cpu_mem_usage=True)
325
+ # Avoid saving this as part of the config.
326
+ del model.config._name_or_path
327
+ model.config.torch_dtype = torch.float16
328
+ print("Saving in the Transformers format.")
329
+ model.save_pretrained(model_path, safe_serialization=safe_serialization)
330
+ shutil.rmtree(tmp_model_path, ignore_errors=True)
331
+
332
+
333
+ class Llama3Converter(TikTokenConverter):
334
+ def __init__(self, vocab_file, special_tokens=None, instruct=False, model_max_length=None, **kwargs):
335
+ super().__init__(vocab_file, **kwargs)
336
+ tokenizer = self.converted()
337
+ chat_template = (
338
+ "{% set loop_messages = messages %}"
339
+ "{% for message in loop_messages %}"
340
+ "{% set content = '<|start_header_id|>' + message['role'] + '<|end_header_id|>\n\n'+ message['content'] | trim + '<|eot_id|>' %}"
341
+ "{% if loop.index0 == 0 %}"
342
+ "{% set content = bos_token + content %}"
343
+ "{% endif %}"
344
+ "{{ content }}"
345
+ "{% endfor %}"
346
+ "{{ '<|start_header_id|>assistant<|end_header_id|>\n\n' }}"
347
+ )
348
+ tokenizer.add_special_tokens(special_tokens)
349
+
350
+ self.tokenizer = PreTrainedTokenizerFast(
351
+ tokenizer_object=tokenizer,
352
+ bos_token="<|begin_of_text|>",
353
+ eos_token="<|end_of_text|>" if not instruct else "<|eot_id|>",
354
+ chat_template=chat_template if instruct else None,
355
+ model_input_names=["input_ids", "attention_mask"],
356
+ model_max_length=model_max_length,
357
+ )
358
+
359
+
360
+ def write_tokenizer(tokenizer_path, input_tokenizer_path, llama_version="2", special_tokens=None, instruct=False):
361
+ tokenizer_class = LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast
362
+ if llama_version in ["3", "3.1"]:
363
+ tokenizer = Llama3Converter(
364
+ input_tokenizer_path, special_tokens, instruct, model_max_length=CONTEXT_LENGTH_FOR_VERSION[llama_version]
365
+ ).tokenizer
366
+ else:
367
+ tokenizer = tokenizer_class(input_tokenizer_path)
368
+ print(f"Saving a {tokenizer_class.__name__} to {tokenizer_path}.")
369
+ tokenizer.save_pretrained(tokenizer_path)
370
+ return tokenizer
371
+
372
+
373
+ DEFAULT_LLAMA_SPECIAL_TOKENS = {
374
+ "3": [
375
+ "<|begin_of_text|>",
376
+ "<|end_of_text|>",
377
+ "<|reserved_special_token_0|>",
378
+ "<|reserved_special_token_1|>",
379
+ "<|reserved_special_token_2|>",
380
+ "<|reserved_special_token_3|>",
381
+ "<|start_header_id|>",
382
+ "<|end_header_id|>",
383
+ "<|reserved_special_token_4|>",
384
+ "<|eot_id|>", # end of turn
385
+ ]
386
+ + [f"<|reserved_special_token_{i}|>" for i in range(5, 256 - 5)],
387
+ "3.1": [
388
+ "<|begin_of_text|>",
389
+ "<|end_of_text|>",
390
+ "<|reserved_special_token_0|>",
391
+ "<|reserved_special_token_1|>",
392
+ "<|finetune_right_pad_id|>",
393
+ "<|reserved_special_token_2|>",
394
+ "<|start_header_id|>",
395
+ "<|end_header_id|>",
396
+ "<|eom_id|>", # end of message
397
+ "<|eot_id|>", # end of turn
398
+ "<|python_tag|>",
399
+ ]
400
+ + [f"<|reserved_special_token_{i}|>" for i in range(3, 256 - 8)],
401
+ }
402
+
403
+
404
+ def main():
405
+ parser = argparse.ArgumentParser()
406
+ parser.add_argument(
407
+ "--input_dir",
408
+ help="Location of LLaMA weights, which contains tokenizer.model and model folders",
409
+ )
410
+ parser.add_argument(
411
+ "--model_size",
412
+ default=None,
413
+ help="'f' Deprecated in favor of `num_shards`: models correspond to the finetuned versions, and are specific to the Llama2 official release. For more details on Llama2, checkout the original repo: https://huggingface.co/meta-llama",
414
+ )
415
+ parser.add_argument(
416
+ "--output_dir",
417
+ help="Location to write HF model and tokenizer",
418
+ )
419
+ parser.add_argument(
420
+ "--safe_serialization", default=True, type=bool, help="Whether or not to save using `safetensors`."
421
+ )
422
+ # Different Llama versions used different default values for max_position_embeddings, hence the need to be able to specify which version is being used.
423
+ parser.add_argument(
424
+ "--llama_version",
425
+ choices=["1", "2", "3", "3.1"],
426
+ default="1",
427
+ type=str,
428
+ help="Version of the Llama model to convert. Currently supports Llama1 and Llama2. Controls the context size",
429
+ )
430
+ parser.add_argument(
431
+ "--num_shards",
432
+ default=None,
433
+ type=int,
434
+ help="The number of individual shards used for the model. Does not have to be the same as the number of consolidated_xx.pth",
435
+ )
436
+ parser.add_argument(
437
+ "--special_tokens",
438
+ default=None,
439
+ type=List[str],
440
+ help="The list of special tokens that should be added to the model.",
441
+ )
442
+ parser.add_argument(
443
+ "--instruct",
444
+ default=False,
445
+ type=bool,
446
+ help="Whether the model is an instruct model or not. Will affect special tokens for llama 3.1.",
447
+ )
448
+ args = parser.parse_args()
449
+ if args.model_size is None and args.num_shards is None:
450
+ raise ValueError("You have to set at least `num_shards` if you are not giving the `model_size`")
451
+ if args.special_tokens is None:
452
+ # no special tokens by default
453
+ args.special_tokens = DEFAULT_LLAMA_SPECIAL_TOKENS.get(str(args.llama_version), [])
454
+
455
+ spm_path = os.path.join(args.input_dir, "tokenizer.model")
456
+ vocab_size = len(
457
+ write_tokenizer(
458
+ args.output_dir,
459
+ spm_path,
460
+ llama_version=args.llama_version,
461
+ special_tokens=args.special_tokens,
462
+ instruct=args.instruct,
463
+ )
464
+ )
465
+ if args.model_size != "tokenizer_only":
466
+ write_model(
467
+ model_path=args.output_dir,
468
+ input_base_path=args.input_dir,
469
+ model_size=args.model_size,
470
+ safe_serialization=args.safe_serialization,
471
+ llama_version=args.llama_version,
472
+ vocab_size=vocab_size,
473
+ num_shards=args.num_shards,
474
+ instruct=args.instruct,
475
+ )
476
+
477
+
478
+ if __name__ == "__main__":
479
+ main()
internvl/model/llama/modeling_flax_llama.py ADDED
@@ -0,0 +1,750 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Meta AI, EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """Flax LLaMA model."""
21
+
22
+ from functools import partial
23
+ from typing import Optional, Tuple
24
+
25
+ import flax.linen as nn
26
+ import jax
27
+ import jax.numpy as jnp
28
+ import numpy as np
29
+ from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
30
+ from flax.linen import combine_masks, make_causal_mask
31
+ from flax.linen.attention import dot_product_attention_weights
32
+ from flax.traverse_util import flatten_dict, unflatten_dict
33
+ from jax import lax
34
+
35
+ from transformers.modeling_flax_outputs import FlaxBaseModelOutput, FlaxCausalLMOutput
36
+ from transformers.modeling_flax_utils import ACT2FN, FlaxPreTrainedModel, append_call_sample_docstring
37
+ from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging
38
+ from transformers.configuration_llama import LlamaConfig
39
+
40
+
41
+ logger = logging.get_logger(__name__)
42
+
43
+ _CONFIG_FOR_DOC = "LlamaConfig"
44
+ _CHECKPOINT_FOR_DOC = "afmck/testing-llama-tiny"
45
+ _REAL_CHECKPOINT_FOR_DOC = "openlm-research/open_llama_3b_v2"
46
+
47
+ LLAMA_START_DOCSTRING = r"""
48
+
49
+ This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
50
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
51
+ etc.)
52
+
53
+ This model is also a Flax Linen
54
+ [flax.nn.Module](https://flax.readthedocs.io/en/latest/_autosummary/flax.nn.module.html) subclass. Use it as a
55
+ regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior.
56
+
57
+ Finally, this model supports inherent JAX features such as:
58
+
59
+ - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
60
+ - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
61
+ - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
62
+ - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
63
+
64
+ Parameters:
65
+ config ([`LlamaConfig`]): Model configuration class with all the parameters of the model.
66
+ Initializing with a config file does not load the weights associated with the model, only the
67
+ configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
68
+ dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
69
+ The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16`, or
70
+ `jax.numpy.bfloat16`.
71
+
72
+ This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
73
+ specified all the computation will be performed with the given `dtype`.
74
+
75
+ **Note that this only specifies the dtype of the computation and does not influence the dtype of model
76
+ parameters.**
77
+
78
+ If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
79
+ [`~FlaxPreTrainedModel.to_bf16`].
80
+ """
81
+
82
+ LLAMA_INPUTS_DOCSTRING = r"""
83
+ Args:
84
+ input_ids (`numpy.ndarray` of shape `(batch_size, input_ids_length)`):
85
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
86
+ it.
87
+
88
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
89
+ [`PreTrainedTokenizer.__call__`] for details.
90
+
91
+ [What are input IDs?](../glossary#input-ids)
92
+ attention_mask (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
93
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
94
+
95
+ - 1 for tokens that are **not masked**,
96
+ - 0 for tokens that are **masked**.
97
+
98
+ [What are attention masks?](../glossary#attention-mask)
99
+
100
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
101
+ [`PreTrainedTokenizer.__call__`] for details.
102
+
103
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
104
+ `past_key_values`).
105
+
106
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
107
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
108
+ information on the default strategy.
109
+
110
+ - 1 indicates the head is **not masked**,
111
+ - 0 indicates the head is **masked**.
112
+ position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
113
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
114
+ config.n_positions - 1]`.
115
+
116
+ [What are position IDs?](../glossary#position-ids)
117
+ past_key_values (`Dict[str, np.ndarray]`, *optional*, returned by `init_cache` or when passing previous `past_key_values`):
118
+ Dictionary of pre-computed hidden-states (key and values in the attention blocks) that can be used for fast
119
+ auto-regressive decoding. Pre-computed key and value hidden-states are of shape *[batch_size, max_length]*.
120
+ output_attentions (`bool`, *optional*):
121
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
122
+ tensors for more detail.
123
+ output_hidden_states (`bool`, *optional*):
124
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
125
+ more detail.
126
+ return_dict (`bool`, *optional*):
127
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
128
+ """
129
+
130
+
131
+ def create_sinusoidal_positions(num_pos, dim):
132
+ inv_freq = 1.0 / (10000 ** (np.arange(0, dim, 2) / dim))
133
+ freqs = np.einsum("i , j -> i j", np.arange(num_pos), inv_freq).astype("float32")
134
+
135
+ emb = np.concatenate((freqs, freqs), axis=-1)
136
+ out = np.concatenate((np.sin(emb)[:, None, :], np.cos(emb)[:, None, :]), axis=-1)
137
+ return jnp.array(out[:, :, :num_pos])
138
+
139
+
140
+ def rotate_half(tensor):
141
+ """Rotates half the hidden dims of the input."""
142
+ rotate_half_tensor = jnp.concatenate(
143
+ (-tensor[..., tensor.shape[-1] // 2 :], tensor[..., : tensor.shape[-1] // 2]), axis=-1
144
+ )
145
+ return rotate_half_tensor
146
+
147
+
148
+ def apply_rotary_pos_emb(tensor, sin_pos, cos_pos):
149
+ return (tensor * cos_pos) + (rotate_half(tensor) * sin_pos)
150
+
151
+
152
+ class FlaxLlamaRMSNorm(nn.Module):
153
+ config: LlamaConfig
154
+ dtype: jnp.dtype = jnp.float32
155
+
156
+ def setup(self):
157
+ self.epsilon = self.config.rms_norm_eps
158
+ self.weight = self.param("weight", lambda _, shape: jnp.ones(shape), self.config.hidden_size)
159
+
160
+ def __call__(self, hidden_states):
161
+ variance = jnp.asarray(hidden_states, dtype=jnp.float32)
162
+ variance = jnp.power(variance, 2)
163
+ variance = variance.mean(-1, keepdims=True)
164
+ # use `jax.numpy.sqrt` as `jax.lax.rsqrt` does not match `torch.rsqrt`
165
+ hidden_states = hidden_states / jnp.sqrt(variance + self.epsilon)
166
+
167
+ return self.weight * jnp.asarray(hidden_states, dtype=self.dtype)
168
+
169
+
170
+ class FlaxLlamaRotaryEmbedding(nn.Module):
171
+ config: LlamaConfig
172
+ dtype: jnp.dtype = jnp.float32
173
+
174
+ def setup(self):
175
+ head_dim = self.config.hidden_size // self.config.num_attention_heads
176
+ self.sincos = create_sinusoidal_positions(self.config.max_position_embeddings, head_dim)
177
+
178
+ def __call__(self, key, query, position_ids):
179
+ sincos = self.sincos[position_ids]
180
+ sin_pos, cos_pos = jnp.split(sincos, 2, axis=-1)
181
+
182
+ key = apply_rotary_pos_emb(key, sin_pos, cos_pos)
183
+ query = apply_rotary_pos_emb(query, sin_pos, cos_pos)
184
+
185
+ key = jnp.asarray(key, dtype=self.dtype)
186
+ query = jnp.asarray(query, dtype=self.dtype)
187
+
188
+ return key, query
189
+
190
+
191
+ class FlaxLlamaAttention(nn.Module):
192
+ config: LlamaConfig
193
+ dtype: jnp.dtype = jnp.float32
194
+ causal: bool = True
195
+ is_cross_attention: bool = False
196
+
197
+ def setup(self):
198
+ config = self.config
199
+ self.embed_dim = config.hidden_size
200
+ self.num_heads = config.num_attention_heads
201
+ self.head_dim = self.embed_dim // self.num_heads
202
+ self.num_key_value_heads = config.num_key_value_heads
203
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
204
+ self.attention_softmax_in_fp32 = self.dtype is not jnp.float32
205
+
206
+ dense = partial(
207
+ nn.Dense,
208
+ use_bias=config.attention_bias,
209
+ dtype=self.dtype,
210
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
211
+ )
212
+
213
+ self.q_proj = dense(self.num_heads * self.head_dim)
214
+ self.k_proj = dense(self.num_key_value_heads * self.head_dim)
215
+ self.v_proj = dense(self.num_key_value_heads * self.head_dim)
216
+ self.o_proj = dense(self.embed_dim)
217
+ if (self.head_dim * self.num_heads) != self.embed_dim:
218
+ raise ValueError(
219
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.embed_dim}"
220
+ f" and `num_heads`: {self.num_heads})."
221
+ )
222
+
223
+ self.causal_mask = make_causal_mask(jnp.ones((1, config.max_position_embeddings), dtype="bool"), dtype="bool")
224
+ self.rotary_emb = FlaxLlamaRotaryEmbedding(config, dtype=self.dtype)
225
+
226
+ def _split_heads(self, hidden_states, num_heads):
227
+ return hidden_states.reshape(hidden_states.shape[:2] + (num_heads, self.head_dim))
228
+
229
+ def _merge_heads(self, hidden_states):
230
+ return hidden_states.reshape(hidden_states.shape[:2] + (self.embed_dim,))
231
+
232
+ @nn.compact
233
+ # Copied from transformers.models.gpt_neo.modeling_flax_gpt_neo.FlaxGPTNeoSelfAttention._concatenate_to_cache
234
+ def _concatenate_to_cache(self, key, value, query, attention_mask):
235
+ """
236
+ This function takes projected key, value states from a single input token and concatenates the states to cached
237
+ states from previous steps. This function is slighly adapted from the official Flax repository:
238
+ https://github.com/google/flax/blob/491ce18759622506588784b4fca0e4bf05f8c8cd/flax/linen/attention.py#L252
239
+ """
240
+ # detect if we're initializing by absence of existing cache data.
241
+ is_initialized = self.has_variable("cache", "cached_key")
242
+ cached_key = self.variable("cache", "cached_key", jnp.zeros, key.shape, key.dtype)
243
+ cached_value = self.variable("cache", "cached_value", jnp.zeros, value.shape, value.dtype)
244
+ cache_index = self.variable("cache", "cache_index", lambda: jnp.array(0, dtype=jnp.int32))
245
+
246
+ if is_initialized:
247
+ *batch_dims, max_length, num_heads, depth_per_head = cached_key.value.shape
248
+ # update key, value caches with our new 1d spatial slices
249
+ cur_index = cache_index.value
250
+ indices = (0,) * len(batch_dims) + (cur_index, 0, 0)
251
+ key = lax.dynamic_update_slice(cached_key.value, key, indices)
252
+ value = lax.dynamic_update_slice(cached_value.value, value, indices)
253
+ cached_key.value = key
254
+ cached_value.value = value
255
+ num_updated_cache_vectors = query.shape[1]
256
+ cache_index.value = cache_index.value + num_updated_cache_vectors
257
+ # causal mask for cached decoder self-attention: our single query position should only attend to those key positions that have already been generated and cached, not the remaining zero elements.
258
+ pad_mask = jnp.broadcast_to(
259
+ jnp.arange(max_length) < cur_index + num_updated_cache_vectors,
260
+ tuple(batch_dims) + (1, num_updated_cache_vectors, max_length),
261
+ )
262
+ attention_mask = combine_masks(pad_mask, attention_mask)
263
+ return key, value, attention_mask
264
+
265
+ def __call__(
266
+ self,
267
+ hidden_states,
268
+ attention_mask,
269
+ position_ids,
270
+ deterministic: bool = True,
271
+ init_cache: bool = False,
272
+ output_attentions: bool = False,
273
+ ):
274
+ query = self.q_proj(hidden_states)
275
+ key = self.k_proj(hidden_states)
276
+ value = self.v_proj(hidden_states)
277
+
278
+ query = self._split_heads(query, self.num_heads)
279
+ key = self._split_heads(key, self.num_key_value_heads)
280
+ value = self._split_heads(value, self.num_key_value_heads)
281
+
282
+ key, query = self.rotary_emb(key, query, position_ids)
283
+
284
+ query_length, key_length = query.shape[1], key.shape[1]
285
+
286
+ if self.has_variable("cache", "cached_key"):
287
+ mask_shift = self.variables["cache"]["cache_index"]
288
+ max_decoder_length = self.variables["cache"]["cached_key"].shape[1]
289
+ causal_mask = lax.dynamic_slice(
290
+ self.causal_mask, (0, 0, mask_shift, 0), (1, 1, query_length, max_decoder_length)
291
+ )
292
+ else:
293
+ causal_mask = self.causal_mask[:, :, :query_length, :key_length]
294
+
295
+ batch_size = hidden_states.shape[0]
296
+ causal_mask = jnp.broadcast_to(causal_mask, (batch_size,) + causal_mask.shape[1:])
297
+
298
+ attention_mask = jnp.broadcast_to(jnp.expand_dims(attention_mask, axis=(-3, -2)), causal_mask.shape)
299
+ attention_mask = combine_masks(attention_mask, causal_mask)
300
+
301
+ dropout_rng = None
302
+ if not deterministic and self.config.attention_dropout > 0.0:
303
+ dropout_rng = self.make_rng("dropout")
304
+
305
+ # During fast autoregressive decoding, we feed one position at a time,
306
+ # and cache the keys and values step by step.
307
+ if self.has_variable("cache", "cached_key") or init_cache:
308
+ key, value, attention_mask = self._concatenate_to_cache(key, value, query, attention_mask)
309
+
310
+ key = jnp.repeat(key, self.num_key_value_groups, axis=2)
311
+ value = jnp.repeat(value, self.num_key_value_groups, axis=2)
312
+
313
+ # transform boolean mask into float mask
314
+ attention_bias = lax.select(
315
+ attention_mask > 0,
316
+ jnp.full(attention_mask.shape, 0.0).astype(self.dtype),
317
+ jnp.full(attention_mask.shape, jnp.finfo(self.dtype).min).astype(self.dtype),
318
+ )
319
+
320
+ # usual dot product attention
321
+ attention_dtype = jnp.float32 if self.attention_softmax_in_fp32 else self.dtype
322
+ attn_weights = dot_product_attention_weights(
323
+ query,
324
+ key,
325
+ bias=attention_bias,
326
+ dropout_rng=dropout_rng,
327
+ dropout_rate=self.config.attention_dropout,
328
+ deterministic=deterministic,
329
+ dtype=attention_dtype,
330
+ )
331
+
332
+ if self.attention_softmax_in_fp32:
333
+ attn_weights = attn_weights.astype(self.dtype)
334
+
335
+ attn_output = jnp.einsum("...hqk,...khd->...qhd", attn_weights, value)
336
+ attn_output = self._merge_heads(attn_output)
337
+ attn_output = self.o_proj(attn_output)
338
+
339
+ outputs = (attn_output, attn_weights) if output_attentions else (attn_output,)
340
+ return outputs
341
+
342
+
343
+ class FlaxLlamaMLP(nn.Module):
344
+ config: LlamaConfig
345
+ dtype: jnp.dtype = jnp.float32
346
+
347
+ def setup(self):
348
+ embed_dim = self.config.hidden_size
349
+ inner_dim = self.config.intermediate_size if self.config.intermediate_size is not None else 4 * embed_dim
350
+
351
+ kernel_init = jax.nn.initializers.normal(self.config.initializer_range)
352
+ self.act = ACT2FN[self.config.hidden_act]
353
+
354
+ self.gate_proj = nn.Dense(inner_dim, use_bias=False, dtype=self.dtype, kernel_init=kernel_init)
355
+ self.down_proj = nn.Dense(embed_dim, use_bias=False, dtype=self.dtype, kernel_init=kernel_init)
356
+ self.up_proj = nn.Dense(inner_dim, use_bias=False, dtype=self.dtype, kernel_init=kernel_init)
357
+
358
+ def __call__(self, hidden_states):
359
+ up_proj_states = self.up_proj(hidden_states)
360
+ gate_states = self.act(self.gate_proj(hidden_states))
361
+
362
+ hidden_states = self.down_proj(up_proj_states * gate_states)
363
+ return hidden_states
364
+
365
+
366
+ class FlaxLlamaDecoderLayer(nn.Module):
367
+ config: LlamaConfig
368
+ dtype: jnp.dtype = jnp.float32
369
+
370
+ def setup(self):
371
+ self.input_layernorm = FlaxLlamaRMSNorm(self.config, dtype=self.dtype)
372
+ self.self_attn = FlaxLlamaAttention(self.config, dtype=self.dtype)
373
+ self.post_attention_layernorm = FlaxLlamaRMSNorm(self.config, dtype=self.dtype)
374
+ self.mlp = FlaxLlamaMLP(self.config, dtype=self.dtype)
375
+
376
+ def __call__(
377
+ self,
378
+ hidden_states,
379
+ attention_mask=None,
380
+ position_ids=None,
381
+ deterministic: bool = True,
382
+ init_cache: bool = False,
383
+ output_attentions: bool = False,
384
+ ):
385
+ residual = hidden_states
386
+ hidden_states = self.input_layernorm(hidden_states)
387
+ outputs = self.self_attn(
388
+ hidden_states,
389
+ attention_mask=attention_mask,
390
+ position_ids=position_ids,
391
+ deterministic=deterministic,
392
+ init_cache=init_cache,
393
+ output_attentions=output_attentions,
394
+ )
395
+ # residual connection
396
+ attn_output = outputs[0]
397
+ hidden_states = residual + attn_output
398
+
399
+ residual = hidden_states
400
+ hidden_states = self.post_attention_layernorm(hidden_states)
401
+ hidden_states = self.mlp(hidden_states)
402
+ # residual connection
403
+ hidden_states = residual + hidden_states
404
+
405
+ return (hidden_states,) + outputs[1:]
406
+
407
+
408
+ # Copied from transformers.models.gpt_neo.modeling_flax_gpt_neo.FlaxGPTNeoPreTrainedModel with GPTNeo->Llama, GPT_NEO->LLAMA, transformer->model
409
+ class FlaxLlamaPreTrainedModel(FlaxPreTrainedModel):
410
+ """
411
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
412
+ models.
413
+ """
414
+
415
+ config_class = LlamaConfig
416
+ base_model_prefix = "model"
417
+ module_class: nn.Module = None
418
+
419
+ def __init__(
420
+ self,
421
+ config: LlamaConfig,
422
+ input_shape: Tuple = (1, 1),
423
+ seed: int = 0,
424
+ dtype: jnp.dtype = jnp.float32,
425
+ _do_init: bool = True,
426
+ **kwargs,
427
+ ):
428
+ module = self.module_class(config=config, dtype=dtype, **kwargs)
429
+ super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
430
+
431
+ def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
432
+ # init input tensors
433
+ input_ids = jnp.zeros(input_shape, dtype="i4")
434
+ attention_mask = jnp.ones_like(input_ids)
435
+ position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_shape)
436
+ params_rng, dropout_rng = jax.random.split(rng)
437
+ rngs = {"params": params_rng, "dropout": dropout_rng}
438
+
439
+ random_params = self.module.init(rngs, input_ids, attention_mask, position_ids, return_dict=False)["params"]
440
+
441
+ if params is not None:
442
+ random_params = flatten_dict(unfreeze(random_params))
443
+ params = flatten_dict(unfreeze(params))
444
+ for missing_key in self._missing_keys:
445
+ params[missing_key] = random_params[missing_key]
446
+ self._missing_keys = set()
447
+ return freeze(unflatten_dict(params))
448
+ else:
449
+ return random_params
450
+
451
+ def init_cache(self, batch_size, max_length):
452
+ r"""
453
+ Args:
454
+ batch_size (`int`):
455
+ batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
456
+ max_length (`int`):
457
+ maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
458
+ cache.
459
+ """
460
+ # init input variables to retrieve cache
461
+ input_ids = jnp.ones((batch_size, max_length))
462
+ attention_mask = jnp.ones_like(input_ids)
463
+ position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
464
+
465
+ init_variables = self.module.init(
466
+ jax.random.PRNGKey(0), input_ids, attention_mask, position_ids, return_dict=False, init_cache=True
467
+ )
468
+ return unfreeze(init_variables["cache"])
469
+
470
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
471
+ def __call__(
472
+ self,
473
+ input_ids,
474
+ attention_mask=None,
475
+ position_ids=None,
476
+ params: dict = None,
477
+ past_key_values: dict = None,
478
+ dropout_rng: jax.random.PRNGKey = None,
479
+ train: bool = False,
480
+ output_attentions: Optional[bool] = None,
481
+ output_hidden_states: Optional[bool] = None,
482
+ return_dict: Optional[bool] = None,
483
+ ):
484
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
485
+ output_hidden_states = (
486
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
487
+ )
488
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
489
+
490
+ batch_size, sequence_length = input_ids.shape
491
+
492
+ if position_ids is None:
493
+ if past_key_values is not None:
494
+ raise ValueError("Make sure to provide `position_ids` when passing `past_key_values`.")
495
+
496
+ position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
497
+
498
+ if attention_mask is None:
499
+ attention_mask = jnp.ones((batch_size, sequence_length))
500
+
501
+ # Handle any PRNG if needed
502
+ rngs = {}
503
+ if dropout_rng is not None:
504
+ rngs["dropout"] = dropout_rng
505
+
506
+ inputs = {"params": params or self.params}
507
+
508
+ # if past_key_values are passed then cache is already initialized a private flag init_cache has to be passed down to ensure cache is used. It has to be made sure that cache is marked as mutable so that it can be changed by FlaxLlamaAttention module
509
+ if past_key_values:
510
+ inputs["cache"] = past_key_values
511
+ mutable = ["cache"]
512
+ else:
513
+ mutable = False
514
+
515
+ outputs = self.module.apply(
516
+ inputs,
517
+ jnp.array(input_ids, dtype="i4"),
518
+ jnp.array(attention_mask, dtype="i4"),
519
+ jnp.array(position_ids, dtype="i4"),
520
+ not train,
521
+ False,
522
+ output_attentions,
523
+ output_hidden_states,
524
+ return_dict,
525
+ rngs=rngs,
526
+ mutable=mutable,
527
+ )
528
+
529
+ # add updated cache to model output
530
+ if past_key_values is not None and return_dict:
531
+ outputs, past_key_values = outputs
532
+ outputs["past_key_values"] = unfreeze(past_key_values["cache"])
533
+ return outputs
534
+ elif past_key_values is not None and not return_dict:
535
+ outputs, past_key_values = outputs
536
+ outputs = outputs[:1] + (unfreeze(past_key_values["cache"]),) + outputs[1:]
537
+
538
+ return outputs
539
+
540
+
541
+ class FlaxLlamaLayerCollection(nn.Module):
542
+ config: LlamaConfig
543
+ dtype: jnp.dtype = jnp.float32
544
+
545
+ def setup(self):
546
+ self.blocks = [
547
+ FlaxLlamaDecoderLayer(self.config, dtype=self.dtype, name=str(i))
548
+ for i in range(self.config.num_hidden_layers)
549
+ ]
550
+
551
+ def __call__(
552
+ self,
553
+ hidden_states,
554
+ attention_mask=None,
555
+ position_ids=None,
556
+ deterministic: bool = True,
557
+ init_cache: bool = False,
558
+ output_attentions: bool = False,
559
+ output_hidden_states: bool = False,
560
+ return_dict: bool = False,
561
+ ):
562
+ all_attentions = () if output_attentions else None
563
+ all_hidden_states = () if output_hidden_states else None
564
+
565
+ for block in self.blocks:
566
+ if output_hidden_states:
567
+ all_hidden_states += (hidden_states,)
568
+ layer_outputs = block(
569
+ hidden_states,
570
+ attention_mask=attention_mask,
571
+ position_ids=position_ids,
572
+ deterministic=deterministic,
573
+ init_cache=init_cache,
574
+ output_attentions=output_attentions,
575
+ )
576
+ hidden_states = layer_outputs[0]
577
+
578
+ if output_attentions:
579
+ all_attentions += (layer_outputs[1],)
580
+
581
+ # this contains possible `None` values - `FlaxLlamaModule` will filter them out
582
+ outputs = (hidden_states, all_hidden_states, all_attentions)
583
+
584
+ return outputs
585
+
586
+
587
+ class FlaxLlamaModule(nn.Module):
588
+ config: LlamaConfig
589
+ dtype: jnp.dtype = jnp.float32
590
+
591
+ def setup(self):
592
+ self.hidden_size = self.config.hidden_size
593
+ embedding_init = jax.nn.initializers.normal(stddev=self.config.initializer_range)
594
+ self.embed_tokens = nn.Embed(
595
+ self.config.vocab_size,
596
+ self.hidden_size,
597
+ embedding_init=embedding_init,
598
+ dtype=self.dtype,
599
+ )
600
+ self.layers = FlaxLlamaLayerCollection(self.config, dtype=self.dtype)
601
+ self.norm = FlaxLlamaRMSNorm(self.config, dtype=self.dtype)
602
+
603
+ def __call__(
604
+ self,
605
+ input_ids,
606
+ attention_mask=None,
607
+ position_ids=None,
608
+ deterministic=True,
609
+ init_cache: bool = False,
610
+ output_attentions: bool = False,
611
+ output_hidden_states: bool = False,
612
+ return_dict: bool = True,
613
+ ):
614
+ input_embeds = self.embed_tokens(input_ids.astype("i4"))
615
+
616
+ outputs = self.layers(
617
+ input_embeds,
618
+ position_ids=position_ids,
619
+ attention_mask=attention_mask,
620
+ deterministic=deterministic,
621
+ init_cache=init_cache,
622
+ output_attentions=output_attentions,
623
+ output_hidden_states=output_hidden_states,
624
+ return_dict=return_dict,
625
+ )
626
+
627
+ hidden_states = outputs[0]
628
+ hidden_states = self.norm(hidden_states)
629
+
630
+ if output_hidden_states:
631
+ all_hidden_states = outputs[1] + (hidden_states,)
632
+ outputs = (hidden_states, all_hidden_states) + outputs[2:]
633
+ else:
634
+ outputs = (hidden_states,) + outputs[1:]
635
+
636
+ if not return_dict:
637
+ return tuple(v for v in outputs if v is not None)
638
+
639
+ return FlaxBaseModelOutput(
640
+ last_hidden_state=hidden_states,
641
+ hidden_states=outputs[1],
642
+ attentions=outputs[-1],
643
+ )
644
+
645
+
646
+ @add_start_docstrings(
647
+ "The bare Llama Model transformer outputting raw hidden-states without any specific head on top.",
648
+ LLAMA_START_DOCSTRING,
649
+ )
650
+ class FlaxLlamaModel(FlaxLlamaPreTrainedModel):
651
+ module_class = FlaxLlamaModule
652
+
653
+
654
+ append_call_sample_docstring(
655
+ FlaxLlamaModel,
656
+ _CHECKPOINT_FOR_DOC,
657
+ FlaxBaseModelOutput,
658
+ _CONFIG_FOR_DOC,
659
+ real_checkpoint=_REAL_CHECKPOINT_FOR_DOC,
660
+ )
661
+
662
+
663
+ class FlaxLlamaForCausalLMModule(nn.Module):
664
+ config: LlamaConfig
665
+ dtype: jnp.dtype = jnp.float32
666
+
667
+ def setup(self):
668
+ self.model = FlaxLlamaModule(self.config, dtype=self.dtype)
669
+ self.lm_head = nn.Dense(
670
+ self.config.vocab_size,
671
+ use_bias=False,
672
+ dtype=self.dtype,
673
+ kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
674
+ )
675
+
676
+ def __call__(
677
+ self,
678
+ input_ids,
679
+ attention_mask=None,
680
+ position_ids=None,
681
+ deterministic: bool = True,
682
+ init_cache: bool = False,
683
+ output_attentions: bool = False,
684
+ output_hidden_states: bool = False,
685
+ return_dict: bool = True,
686
+ ):
687
+ outputs = self.model(
688
+ input_ids,
689
+ position_ids=position_ids,
690
+ attention_mask=attention_mask,
691
+ deterministic=deterministic,
692
+ init_cache=init_cache,
693
+ output_attentions=output_attentions,
694
+ output_hidden_states=output_hidden_states,
695
+ return_dict=return_dict,
696
+ )
697
+
698
+ hidden_states = outputs[0]
699
+ lm_logits = self.lm_head(hidden_states)
700
+
701
+ if not return_dict:
702
+ return (lm_logits,) + outputs[1:]
703
+
704
+ return FlaxCausalLMOutput(logits=lm_logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions)
705
+
706
+
707
+ @add_start_docstrings(
708
+ """
709
+ The Llama Model transformer with a language modeling head (linear layer) on top.
710
+ """,
711
+ LLAMA_START_DOCSTRING,
712
+ )
713
+ # Copied from transformers.models.gptj.modeling_flax_gptj.FlaxGPTJForCausalLM with GPTJ->Llama
714
+ class FlaxLlamaForCausalLM(FlaxLlamaPreTrainedModel):
715
+ module_class = FlaxLlamaForCausalLMModule
716
+
717
+ def prepare_inputs_for_generation(self, input_ids, max_length, attention_mask: Optional[jax.Array] = None):
718
+ # initializing the cache
719
+ batch_size, seq_length = input_ids.shape
720
+
721
+ past_key_values = self.init_cache(batch_size, max_length)
722
+ # Note that usually one would have to put 0's in the attention_mask for x > input_ids.shape[-1] and x < cache_length.
723
+ # But since Llama uses a causal mask, those positions are masked anyways.
724
+ # Thus we can create a single static attention_mask here, which is more efficient for compilation
725
+ extended_attention_mask = jnp.ones((batch_size, max_length), dtype="i4")
726
+ if attention_mask is not None:
727
+ position_ids = attention_mask.cumsum(axis=-1) - 1
728
+ extended_attention_mask = lax.dynamic_update_slice(extended_attention_mask, attention_mask, (0, 0))
729
+ else:
730
+ position_ids = jnp.broadcast_to(jnp.arange(seq_length, dtype="i4")[None, :], (batch_size, seq_length))
731
+
732
+ return {
733
+ "past_key_values": past_key_values,
734
+ "attention_mask": extended_attention_mask,
735
+ "position_ids": position_ids,
736
+ }
737
+
738
+ def update_inputs_for_generation(self, model_outputs, model_kwargs):
739
+ model_kwargs["past_key_values"] = model_outputs.past_key_values
740
+ model_kwargs["position_ids"] = model_kwargs["position_ids"][:, -1:] + 1
741
+ return model_kwargs
742
+
743
+
744
+ append_call_sample_docstring(
745
+ FlaxLlamaForCausalLM,
746
+ _CHECKPOINT_FOR_DOC,
747
+ FlaxCausalLMOutput,
748
+ _CONFIG_FOR_DOC,
749
+ real_checkpoint=_REAL_CHECKPOINT_FOR_DOC,
750
+ )
internvl/model/llama/modeling_llama.py ADDED
@@ -0,0 +1,1838 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ import math
21
+ from typing import List, Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.nn.functional as F
25
+ import torch.utils.checkpoint
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
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
+ QuestionAnsweringModelOutput,
37
+ SequenceClassifierOutputWithPast,
38
+ TokenClassifierOutput,
39
+ )
40
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
41
+ from transformers.modeling_utils import PreTrainedModel
42
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
43
+ from transformers.utils import (
44
+ add_start_docstrings,
45
+ add_start_docstrings_to_model_forward,
46
+ is_flash_attn_greater_or_equal_2_10,
47
+ logging,
48
+ replace_return_docstrings,
49
+ )
50
+ from .configuration_llama import LlamaConfig
51
+ from transformers import LogitsProcessorList, StoppingCriteriaList, GenerationConfig
52
+ from transformers.generation.utils import GenerateNonBeamOutput, GenerateDecoderOnlyOutput
53
+
54
+ logger = logging.get_logger(__name__)
55
+
56
+ _CONFIG_FOR_DOC = "LlamaConfig"
57
+
58
+
59
+ def _prepare_4d_causal_attention_mask_with_cache_position(
60
+ attention_mask: torch.Tensor,
61
+ sequence_length: int,
62
+ target_length: int,
63
+ dtype: torch.dtype,
64
+ device: torch.device,
65
+ min_dtype: float,
66
+ cache_position: torch.Tensor,
67
+ batch_size: int,
68
+ ):
69
+ """
70
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
71
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
72
+
73
+ Args:
74
+ attention_mask (`torch.Tensor`):
75
+ 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)`.
76
+ sequence_length (`int`):
77
+ The sequence length being processed.
78
+ target_length (`int`):
79
+ 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.
80
+ dtype (`torch.dtype`):
81
+ The dtype to use for the 4D attention mask.
82
+ device (`torch.device`):
83
+ The device to plcae the 4D attention mask on.
84
+ min_dtype (`float`):
85
+ The minimum value representable with the dtype `dtype`.
86
+ cache_position (`torch.Tensor`):
87
+ Indices depicting the position of the input sequence tokens in the sequence.
88
+ batch_size (`torch.Tensor`):
89
+ Batch size.
90
+ """
91
+ if attention_mask is not None and attention_mask.dim() == 4:
92
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
93
+ causal_mask = attention_mask
94
+ else:
95
+ causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
96
+ if sequence_length != 1:
97
+ causal_mask = torch.triu(causal_mask, diagonal=1)
98
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
99
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
100
+ if attention_mask is not None:
101
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
102
+ mask_length = attention_mask.shape[-1]
103
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
104
+ padding_mask = padding_mask == 0
105
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
106
+ padding_mask, min_dtype
107
+ )
108
+
109
+ return causal_mask
110
+
111
+
112
+ class LlamaRMSNorm(nn.Module):
113
+ def __init__(self, hidden_size, eps=1e-6):
114
+ """
115
+ LlamaRMSNorm is equivalent to T5LayerNorm
116
+ """
117
+ super().__init__()
118
+ self.weight = nn.Parameter(torch.ones(hidden_size))
119
+ self.variance_epsilon = eps
120
+
121
+ def forward(self, hidden_states):
122
+ input_dtype = hidden_states.dtype
123
+ hidden_states = hidden_states.to(torch.float32)
124
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
125
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
126
+ return self.weight * hidden_states.to(input_dtype)
127
+
128
+ def extra_repr(self):
129
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
130
+
131
+
132
+ ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
133
+
134
+
135
+ class LlamaRotaryEmbedding(nn.Module):
136
+ def __init__(
137
+ self,
138
+ dim=None,
139
+ max_position_embeddings=2048,
140
+ base=10000,
141
+ device=None,
142
+ scaling_factor=1.0,
143
+ rope_type="default",
144
+ config: Optional[LlamaConfig] = None,
145
+ ):
146
+ super().__init__()
147
+ # TODO (joao): remove the `if` below, only used for BC
148
+ self.rope_kwargs = {}
149
+ if config is None:
150
+ logger.warning_once(
151
+ "`LlamaRotaryEmbedding` can now be fully parameterized by passing the model config through the "
152
+ "`config` argument. All other arguments will be removed in v4.45"
153
+ )
154
+ self.rope_kwargs = {
155
+ "rope_type": rope_type,
156
+ "factor": scaling_factor,
157
+ "dim": dim,
158
+ "base": base,
159
+ "max_position_embeddings": max_position_embeddings,
160
+ }
161
+ self.rope_type = rope_type
162
+ self.max_seq_len_cached = max_position_embeddings
163
+ self.original_max_seq_len = max_position_embeddings
164
+ else:
165
+ # BC: "rope_type" was originally "type"
166
+ if config.rope_scaling is not None:
167
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
168
+ else:
169
+ self.rope_type = "default"
170
+ self.max_seq_len_cached = config.max_position_embeddings
171
+ self.original_max_seq_len = config.max_position_embeddings
172
+
173
+ self.config = config
174
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
175
+
176
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
177
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
178
+ self.original_inv_freq = self.inv_freq
179
+
180
+ def _dynamic_frequency_update(self, position_ids, device):
181
+ """
182
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
183
+ 1 - growing beyond the cached sequence length (allow scaling)
184
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
185
+ """
186
+ seq_len = torch.max(position_ids) + 1
187
+ if seq_len > self.max_seq_len_cached: # growth
188
+ inv_freq, self.attention_scaling = self.rope_init_fn(
189
+ self.config, device, seq_len=seq_len, **self.rope_kwargs
190
+ )
191
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
192
+ self.max_seq_len_cached = seq_len
193
+
194
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
195
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
196
+ self.max_seq_len_cached = self.original_max_seq_len
197
+
198
+ @torch.no_grad()
199
+ def forward(self, x, position_ids):
200
+ if "dynamic" in self.rope_type:
201
+ self._dynamic_frequency_update(position_ids, device=x.device)
202
+
203
+ # Core RoPE block
204
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
205
+ position_ids_expanded = position_ids[:, None, :].float()
206
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
207
+ device_type = x.device.type
208
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
209
+ with torch.autocast(device_type=device_type, enabled=False):
210
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
211
+ emb = torch.cat((freqs, freqs), dim=-1)
212
+ cos = emb.cos()
213
+ sin = emb.sin()
214
+
215
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
216
+ cos = cos * self.attention_scaling
217
+ sin = sin * self.attention_scaling
218
+
219
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
220
+
221
+
222
+ class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
223
+ """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
224
+
225
+ def __init__(self, *args, **kwargs):
226
+ logger.warning_once(
227
+ "`LlamaLinearScalingRotaryEmbedding` is deprecated an will be removed in v4.45. Please use "
228
+ "`LlamaRotaryEmbedding`, which now also does linear scaling (simply pass the model config to __init__)."
229
+ )
230
+ kwargs["rope_type"] = "linear"
231
+ super().__init__(*args, **kwargs)
232
+
233
+
234
+ class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
235
+ """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
236
+
237
+ def __init__(self, *args, **kwargs):
238
+ logger.warning_once(
239
+ "`LlamaDynamicNTKScalingRotaryEmbedding` is deprecated an will be removed in v4.45. Please use "
240
+ "`LlamaRotaryEmbedding`, which now also does dynamic ntk scaling (simply pass the model config to "
241
+ "__init__)."
242
+ )
243
+ kwargs["rope_type"] = "dynamic"
244
+ super().__init__(*args, **kwargs)
245
+
246
+
247
+ def rotate_half(x):
248
+ """Rotates half the hidden dims of the input."""
249
+ x1 = x[..., : x.shape[-1] // 2]
250
+ x2 = x[..., x.shape[-1] // 2 :]
251
+ return torch.cat((-x2, x1), dim=-1)
252
+
253
+
254
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
255
+ """Applies Rotary Position Embedding to the query and key tensors.
256
+
257
+ Args:
258
+ q (`torch.Tensor`): The query tensor.
259
+ k (`torch.Tensor`): The key tensor.
260
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
261
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
262
+ position_ids (`torch.Tensor`, *optional*):
263
+ Deprecated and unused.
264
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
265
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
266
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
267
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
268
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
269
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
270
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
271
+ Returns:
272
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
273
+ """
274
+ cos = cos.unsqueeze(unsqueeze_dim)
275
+ sin = sin.unsqueeze(unsqueeze_dim)
276
+ q_embed = (q * cos) + (rotate_half(q) * sin)
277
+ k_embed = (k * cos) + (rotate_half(k) * sin)
278
+ return q_embed, k_embed
279
+
280
+
281
+ class LlamaMLP(nn.Module):
282
+ def __init__(self, config):
283
+ super().__init__()
284
+ self.config = config
285
+ self.hidden_size = config.hidden_size
286
+ self.intermediate_size = config.intermediate_size
287
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
288
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
289
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
290
+ self.act_fn = ACT2FN[config.hidden_act]
291
+
292
+ def forward(self, x):
293
+ if self.config.pretraining_tp > 1:
294
+ slice = self.intermediate_size // self.config.pretraining_tp
295
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
296
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
297
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
298
+
299
+ gate_proj = torch.cat(
300
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
301
+ )
302
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
303
+
304
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
305
+ down_proj = [
306
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
307
+ ]
308
+ down_proj = sum(down_proj)
309
+ else:
310
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
311
+
312
+ return down_proj
313
+
314
+
315
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
316
+ """
317
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
318
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
319
+ """
320
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
321
+ if n_rep == 1:
322
+ return hidden_states
323
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
324
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
325
+
326
+
327
+ class LlamaAttention(nn.Module):
328
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
329
+
330
+ def __init__(self, config: LlamaConfig, layer_idx: Optional[int] = None):
331
+ super().__init__()
332
+ self.config = config
333
+ self.layer_idx = layer_idx
334
+ if layer_idx is None:
335
+ logger.warning_once(
336
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
337
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
338
+ "when creating this class."
339
+ )
340
+
341
+ self.attention_dropout = config.attention_dropout
342
+ self.hidden_size = config.hidden_size
343
+ self.num_heads = config.num_attention_heads
344
+ self.head_dim = self.hidden_size // self.num_heads
345
+ self.num_key_value_heads = config.num_key_value_heads
346
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
347
+ self.max_position_embeddings = config.max_position_embeddings
348
+ self.rope_theta = config.rope_theta
349
+ self.is_causal = True
350
+
351
+ if (self.head_dim * self.num_heads) != self.hidden_size:
352
+ raise ValueError(
353
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
354
+ f" and `num_heads`: {self.num_heads})."
355
+ )
356
+
357
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
358
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
359
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
360
+ self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias)
361
+
362
+ # TODO (joao): remove in v4.45 (RoPE is computed in the model, not in the decoder layers)
363
+ self.rotary_emb = LlamaRotaryEmbedding(config=self.config)
364
+
365
+ def forward(
366
+ self,
367
+ hidden_states: torch.Tensor,
368
+ attention_mask: Optional[torch.Tensor] = None,
369
+ position_ids: Optional[torch.LongTensor] = None,
370
+ past_key_value: Optional[Cache] = None,
371
+ output_attentions: bool = False,
372
+ use_cache: bool = False,
373
+ cache_position: Optional[torch.LongTensor] = None,
374
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.45
375
+ **kwargs,
376
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
377
+ bsz, q_len, _ = hidden_states.size()
378
+
379
+ if self.config.pretraining_tp > 1:
380
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
381
+ query_slices = self.q_proj.weight.split(
382
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
383
+ )
384
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
385
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
386
+
387
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
388
+ query_states = torch.cat(query_states, dim=-1)
389
+
390
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
391
+ key_states = torch.cat(key_states, dim=-1)
392
+
393
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
394
+ value_states = torch.cat(value_states, dim=-1)
395
+
396
+ else:
397
+ query_states = self.q_proj(hidden_states)
398
+ key_states = self.k_proj(hidden_states)
399
+ value_states = self.v_proj(hidden_states)
400
+
401
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
402
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
403
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
404
+
405
+ if position_embeddings is None:
406
+ logger.warning_once(
407
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
408
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
409
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.45 `position_ids` will be "
410
+ "removed and `position_embeddings` will be mandatory."
411
+ )
412
+ cos, sin = self.rotary_emb(value_states, position_ids)
413
+ else:
414
+ cos, sin = position_embeddings
415
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
416
+
417
+ if past_key_value is not None:
418
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
419
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
420
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
421
+
422
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
423
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
424
+
425
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
426
+
427
+ if attention_mask is not None: # no matter the length, we just slice it
428
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
429
+ attn_weights = attn_weights + causal_mask
430
+
431
+ # upcast attention to fp32
432
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
433
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
434
+ attn_output = torch.matmul(attn_weights, value_states)
435
+
436
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
437
+ raise ValueError(
438
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
439
+ f" {attn_output.size()}"
440
+ )
441
+
442
+ attn_output = attn_output.transpose(1, 2).contiguous()
443
+
444
+ attn_output = attn_output.reshape(bsz, q_len, -1)
445
+
446
+ if self.config.pretraining_tp > 1:
447
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
448
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
449
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
450
+ else:
451
+ attn_output = self.o_proj(attn_output)
452
+
453
+ if not output_attentions:
454
+ attn_weights = None
455
+
456
+ return attn_output, attn_weights, past_key_value
457
+
458
+
459
+ class LlamaFlashAttention2(LlamaAttention):
460
+ """
461
+ Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
462
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
463
+ flash attention and deal with padding tokens in case the input contains any of them.
464
+ """
465
+
466
+ def __init__(self, *args, **kwargs):
467
+ super().__init__(*args, **kwargs)
468
+
469
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
470
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
471
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
472
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
473
+
474
+ def forward(
475
+ self,
476
+ hidden_states: torch.Tensor,
477
+ attention_mask: Optional[torch.LongTensor] = None,
478
+ position_ids: Optional[torch.LongTensor] = None,
479
+ past_key_value: Optional[Cache] = None,
480
+ output_attentions: bool = False,
481
+ use_cache: bool = False,
482
+ cache_position: Optional[torch.LongTensor] = None,
483
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.45
484
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
485
+ if isinstance(past_key_value, StaticCache):
486
+ raise ValueError(
487
+ "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
488
+ "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
489
+ )
490
+
491
+ output_attentions = False
492
+
493
+ bsz, q_len, _ = hidden_states.size()
494
+
495
+ query_states = self.q_proj(hidden_states)
496
+ key_states = self.k_proj(hidden_states)
497
+ value_states = self.v_proj(hidden_states)
498
+
499
+ # Flash attention requires the input to have the shape
500
+ # batch_size x seq_length x head_dim x hidden_dim
501
+ # therefore we just need to keep the original shape
502
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
503
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
504
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
505
+
506
+ if position_embeddings is None:
507
+ logger.warning_once(
508
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
509
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
510
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.45 `position_ids` will be "
511
+ "removed and `position_embeddings` will be mandatory."
512
+ )
513
+ cos, sin = self.rotary_emb(value_states, position_ids)
514
+ else:
515
+ cos, sin = position_embeddings
516
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
517
+
518
+ if past_key_value is not None:
519
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
520
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
521
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
522
+
523
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
524
+ # to be able to avoid many of these transpose/reshape/view.
525
+ query_states = query_states.transpose(1, 2)
526
+ key_states = key_states.transpose(1, 2)
527
+ value_states = value_states.transpose(1, 2)
528
+
529
+ dropout_rate = self.attention_dropout if self.training else 0.0
530
+
531
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
532
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
533
+ # cast them back in the correct dtype just to be sure everything works as expected.
534
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
535
+ # in fp32. (LlamaRMSNorm handles it correctly)
536
+
537
+ input_dtype = query_states.dtype
538
+ if input_dtype == torch.float32:
539
+ if torch.is_autocast_enabled():
540
+ target_dtype = torch.get_autocast_gpu_dtype()
541
+ # Handle the case where the model is quantized
542
+ elif hasattr(self.config, "_pre_quantization_dtype"):
543
+ target_dtype = self.config._pre_quantization_dtype
544
+ else:
545
+ target_dtype = self.q_proj.weight.dtype
546
+
547
+ logger.warning_once(
548
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
549
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
550
+ f" {target_dtype}."
551
+ )
552
+
553
+ query_states = query_states.to(target_dtype)
554
+ key_states = key_states.to(target_dtype)
555
+ value_states = value_states.to(target_dtype)
556
+
557
+ attn_output = _flash_attention_forward(
558
+ query_states,
559
+ key_states,
560
+ value_states,
561
+ attention_mask,
562
+ q_len,
563
+ position_ids=position_ids,
564
+ dropout=dropout_rate,
565
+ sliding_window=getattr(self, "sliding_window", None),
566
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
567
+ is_causal=self.is_causal,
568
+ )
569
+
570
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
571
+ attn_output = self.o_proj(attn_output)
572
+
573
+ if not output_attentions:
574
+ attn_weights = None
575
+
576
+ return attn_output, attn_weights, past_key_value
577
+
578
+
579
+ class LlamaSdpaAttention(LlamaAttention):
580
+ """
581
+ Llama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
582
+ `LlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
583
+ SDPA API.
584
+ """
585
+
586
+ # Adapted from LlamaAttention.forward
587
+ def forward(
588
+ self,
589
+ hidden_states: torch.Tensor,
590
+ attention_mask: Optional[torch.Tensor] = None,
591
+ position_ids: Optional[torch.LongTensor] = None,
592
+ past_key_value: Optional[Cache] = None,
593
+ output_attentions: bool = False,
594
+ use_cache: bool = False,
595
+ cache_position: Optional[torch.LongTensor] = None,
596
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.45
597
+ **kwargs,
598
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
599
+ if output_attentions:
600
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
601
+ logger.warning_once(
602
+ "LlamaModel is using LlamaSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
603
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
604
+ )
605
+ return super().forward(
606
+ hidden_states=hidden_states,
607
+ attention_mask=attention_mask,
608
+ position_ids=position_ids,
609
+ past_key_value=past_key_value,
610
+ output_attentions=output_attentions,
611
+ use_cache=use_cache,
612
+ cache_position=cache_position,
613
+ position_embeddings=position_embeddings,
614
+ )
615
+
616
+ bsz, q_len, _ = hidden_states.size()
617
+
618
+ query_states = self.q_proj(hidden_states)
619
+ key_states = self.k_proj(hidden_states)
620
+ value_states = self.v_proj(hidden_states)
621
+
622
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
623
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
624
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
625
+
626
+ if position_embeddings is None:
627
+ logger.warning_once(
628
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
629
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
630
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.45 `position_ids` will be "
631
+ "removed and `position_embeddings` will be mandatory."
632
+ )
633
+ cos, sin = self.rotary_emb(value_states, position_ids)
634
+ else:
635
+ cos, sin = position_embeddings
636
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
637
+
638
+ if past_key_value is not None:
639
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
640
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
641
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
642
+
643
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
644
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
645
+
646
+ causal_mask = attention_mask
647
+ if attention_mask is not None:
648
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
649
+
650
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
651
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
652
+ if query_states.device.type == "cuda" and causal_mask is not None:
653
+ query_states = query_states.contiguous()
654
+ key_states = key_states.contiguous()
655
+ value_states = value_states.contiguous()
656
+
657
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
658
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
659
+ is_causal = True if causal_mask is None and q_len > 1 else False
660
+
661
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
662
+ query_states,
663
+ key_states,
664
+ value_states,
665
+ attn_mask=causal_mask,
666
+ dropout_p=self.attention_dropout if self.training else 0.0,
667
+ is_causal=is_causal,
668
+ )
669
+
670
+ attn_output = attn_output.transpose(1, 2).contiguous()
671
+ attn_output = attn_output.view(bsz, q_len, -1)
672
+
673
+ attn_output = self.o_proj(attn_output)
674
+
675
+ return attn_output, None, past_key_value
676
+
677
+
678
+ LLAMA_ATTENTION_CLASSES = {
679
+ "eager": LlamaAttention,
680
+ "flash_attention_2": LlamaFlashAttention2,
681
+ "sdpa": LlamaSdpaAttention,
682
+ }
683
+
684
+
685
+ class LlamaDecoderLayer(nn.Module):
686
+ def __init__(self, config: LlamaConfig, layer_idx: int):
687
+ super().__init__()
688
+ self.hidden_size = config.hidden_size
689
+
690
+ self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
691
+
692
+ self.mlp = LlamaMLP(config)
693
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
694
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
695
+
696
+ def forward(
697
+ self,
698
+ hidden_states: torch.Tensor,
699
+ attention_mask: Optional[torch.Tensor] = None,
700
+ position_ids: Optional[torch.LongTensor] = None,
701
+ past_key_value: Optional[Cache] = None,
702
+ output_attentions: Optional[bool] = False,
703
+ use_cache: Optional[bool] = False,
704
+ cache_position: Optional[torch.LongTensor] = None,
705
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.45
706
+ **kwargs,
707
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
708
+ """
709
+ Args:
710
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
711
+ attention_mask (`torch.FloatTensor`, *optional*):
712
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
713
+ query_sequence_length, key_sequence_length)` if default attention is used.
714
+ output_attentions (`bool`, *optional*):
715
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
716
+ returned tensors for more detail.
717
+ use_cache (`bool`, *optional*):
718
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
719
+ (see `past_key_values`).
720
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
721
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
722
+ Indices depicting the position of the input sequence tokens in the sequence
723
+ position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
724
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
725
+ with `head_dim` being the embedding dimension of each attention head.
726
+ kwargs (`dict`, *optional*):
727
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
728
+ into the model
729
+ """
730
+ residual = hidden_states
731
+
732
+ hidden_states = self.input_layernorm(hidden_states)
733
+
734
+ # Self Attention
735
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
736
+ hidden_states=hidden_states,
737
+ attention_mask=attention_mask,
738
+ position_ids=position_ids,
739
+ past_key_value=past_key_value,
740
+ output_attentions=output_attentions,
741
+ use_cache=use_cache,
742
+ cache_position=cache_position,
743
+ position_embeddings=position_embeddings,
744
+ **kwargs,
745
+ )
746
+ hidden_states = residual + hidden_states
747
+
748
+ # Fully Connected
749
+ residual = hidden_states
750
+ hidden_states = self.post_attention_layernorm(hidden_states)
751
+ hidden_states = self.mlp(hidden_states)
752
+ hidden_states = residual + hidden_states
753
+
754
+ outputs = (hidden_states,)
755
+
756
+ if output_attentions:
757
+ outputs += (self_attn_weights,)
758
+
759
+ if use_cache:
760
+ outputs += (present_key_value,)
761
+
762
+ return outputs
763
+
764
+
765
+ LLAMA_START_DOCSTRING = r"""
766
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
767
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
768
+ etc.)
769
+
770
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
771
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
772
+ and behavior.
773
+
774
+ Parameters:
775
+ config ([`LlamaConfig`]):
776
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
777
+ load the weights associated with the model, only the configuration. Check out the
778
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
779
+ """
780
+
781
+
782
+ @add_start_docstrings(
783
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
784
+ LLAMA_START_DOCSTRING,
785
+ )
786
+ class LlamaPreTrainedModel(PreTrainedModel):
787
+ config_class = LlamaConfig
788
+ base_model_prefix = "model"
789
+ supports_gradient_checkpointing = True
790
+ _no_split_modules = ["LlamaDecoderLayer"]
791
+ _skip_keys_device_placement = ["past_key_values"]
792
+ _supports_flash_attn_2 = True
793
+ _supports_sdpa = True
794
+ _supports_cache_class = True
795
+ _supports_quantized_cache = True
796
+ _supports_static_cache = True
797
+
798
+ def _init_weights(self, module):
799
+ std = self.config.initializer_range
800
+ if isinstance(module, nn.Linear):
801
+ module.weight.data.normal_(mean=0.0, std=std)
802
+ if module.bias is not None:
803
+ module.bias.data.zero_()
804
+ elif isinstance(module, nn.Embedding):
805
+ module.weight.data.normal_(mean=0.0, std=std)
806
+ if module.padding_idx is not None:
807
+ module.weight.data[module.padding_idx].zero_()
808
+
809
+
810
+ LLAMA_INPUTS_DOCSTRING = r"""
811
+ Args:
812
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
813
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
814
+ it.
815
+
816
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
817
+ [`PreTrainedTokenizer.__call__`] for details.
818
+
819
+ [What are input IDs?](../glossary#input-ids)
820
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
821
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
822
+
823
+ - 1 for tokens that are **not masked**,
824
+ - 0 for tokens that are **masked**.
825
+
826
+ [What are attention masks?](../glossary#attention-mask)
827
+
828
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
829
+ [`PreTrainedTokenizer.__call__`] for details.
830
+
831
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
832
+ `past_key_values`).
833
+
834
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
835
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
836
+ information on the default strategy.
837
+
838
+ - 1 indicates the head is **not masked**,
839
+ - 0 indicates the head is **masked**.
840
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
841
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
842
+ config.n_positions - 1]`.
843
+
844
+ [What are position IDs?](../glossary#position-ids)
845
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
846
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
847
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
848
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
849
+
850
+ Two formats are allowed:
851
+ - a [`~cache_utils.Cache`] instance;
852
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
853
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
854
+ cache format.
855
+
856
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
857
+ legacy cache format will be returned.
858
+
859
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
860
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
861
+ of shape `(batch_size, sequence_length)`.
862
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
863
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
864
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
865
+ model's internal embedding lookup matrix.
866
+ use_cache (`bool`, *optional*):
867
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
868
+ `past_key_values`).
869
+ output_attentions (`bool`, *optional*):
870
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
871
+ tensors for more detail.
872
+ output_hidden_states (`bool`, *optional*):
873
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
874
+ more detail.
875
+ return_dict (`bool`, *optional*):
876
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
877
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
878
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
879
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
880
+ the complete sequence length.
881
+ """
882
+
883
+
884
+ @add_start_docstrings(
885
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
886
+ LLAMA_START_DOCSTRING,
887
+ )
888
+ class LlamaModel(LlamaPreTrainedModel):
889
+ """
890
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
891
+
892
+ Args:
893
+ config: LlamaConfig
894
+ """
895
+
896
+ def __init__(self, config: LlamaConfig):
897
+ super().__init__(config)
898
+ self.padding_idx = config.pad_token_id
899
+ self.vocab_size = config.vocab_size
900
+
901
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
902
+ self.layers = nn.ModuleList(
903
+ [LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
904
+ )
905
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
906
+ self.rotary_emb = LlamaRotaryEmbedding(config=config)
907
+ self.gradient_checkpointing = False
908
+
909
+ # Initialize weights and apply final processing
910
+ self.post_init()
911
+
912
+ def get_input_embeddings(self):
913
+ return self.embed_tokens
914
+
915
+ def set_input_embeddings(self, value):
916
+ self.embed_tokens = value
917
+
918
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
919
+ def forward(
920
+ self,
921
+ input_ids: torch.LongTensor = None,
922
+ attention_mask: Optional[torch.Tensor] = None,
923
+ position_ids: Optional[torch.LongTensor] = None,
924
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
925
+ inputs_embeds: Optional[torch.FloatTensor] = None,
926
+ use_cache: Optional[bool] = None,
927
+ output_attentions: Optional[bool] = None,
928
+ output_hidden_states: Optional[bool] = None,
929
+ return_dict: Optional[bool] = None,
930
+ cache_position: Optional[torch.LongTensor] = None,
931
+ visual_token_index: Optional[torch.Tensor] = None,
932
+ large_model_prune_layer: Optional[float] = None,
933
+ large_model_prune_ratio: Optional[float] = None,
934
+ visual_token_importance: Optional[torch.Tensor] = None,
935
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
936
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
937
+ output_hidden_states = (
938
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
939
+ )
940
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
941
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
942
+
943
+ if (input_ids is None) ^ (inputs_embeds is not None):
944
+ raise ValueError(
945
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
946
+ )
947
+
948
+ if self.gradient_checkpointing and self.training and use_cache:
949
+ logger.warning_once(
950
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
951
+ )
952
+ use_cache = False
953
+
954
+ # retrieve input_ids and inputs_embeds
955
+ if input_ids is not None and inputs_embeds is not None:
956
+ raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time')
957
+ elif input_ids is not None:
958
+ batch_size, seq_length = input_ids.shape[:2]
959
+ elif inputs_embeds is not None:
960
+ batch_size, seq_length = inputs_embeds.shape[:2]
961
+ else:
962
+ raise ValueError('You have to specify either input_ids or inputs_embeds')
963
+
964
+
965
+
966
+ if inputs_embeds is None:
967
+ inputs_embeds = self.embed_tokens(input_ids)
968
+
969
+ return_legacy_cache = False
970
+ if (
971
+ use_cache and not isinstance(past_key_values, Cache) and not self.training
972
+ ): # kept for BC (non `Cache` `past_key_values` inputs)
973
+ return_legacy_cache = True
974
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
975
+ logger.warning_once(
976
+ "We detected that you are passing `past_key_values` as a tuple and this is deprecated and will be removed in v4.43. "
977
+ "Please use an appropriate `Cache` class (https://huggingface.co/docs/transformers/v4.41.3/en/internal/generation_utils#transformers.Cache)"
978
+ )
979
+
980
+ if cache_position is None:
981
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
982
+ cache_position = torch.arange(
983
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
984
+ )
985
+ if position_ids is None:
986
+ position_ids = cache_position.unsqueeze(0)
987
+
988
+ causal_mask = self._update_causal_mask(
989
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
990
+ )
991
+ hidden_states = inputs_embeds
992
+
993
+ # create position embeddings to be shared across the decoder layers
994
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
995
+
996
+ # decoder layers
997
+ all_hidden_states = () if output_hidden_states else None
998
+ all_self_attns = () if output_attentions else None
999
+ next_decoder_cache = None
1000
+
1001
+ aggregated_viusal_token_attention = 0 if output_attentions else None
1002
+ for idx, decoder_layer in enumerate(self.layers):
1003
+ if output_hidden_states:
1004
+ all_hidden_states += (hidden_states,)
1005
+
1006
+ if self.gradient_checkpointing and self.training:
1007
+ layer_outputs = self._gradient_checkpointing_func(
1008
+ decoder_layer.__call__,
1009
+ hidden_states,
1010
+ causal_mask,
1011
+ position_ids,
1012
+ past_key_values,
1013
+ output_attentions,
1014
+ use_cache,
1015
+ cache_position,
1016
+ position_embeddings,
1017
+ )
1018
+ else:
1019
+
1020
+ ##### 某一层 random pruning #########
1021
+ K = int(len(self.layers) * large_model_prune_layer)
1022
+ keep_ratio = large_model_prune_ratio
1023
+
1024
+ if hidden_states.shape[1] != 1:
1025
+ if idx == K:
1026
+ device = hidden_states.device
1027
+ visual_token_length = visual_token_index[1] - visual_token_index[0] + 1
1028
+ image_attention_score = visual_token_importance.unsqueeze(0)
1029
+ top_attention_rank_index = image_attention_score.topk(int(visual_token_length * keep_ratio), dim=-1).indices[0] + int(visual_token_index[0])
1030
+ keep_indexs = torch.cat((torch.arange(int(visual_token_index[0]), device=device), top_attention_rank_index.to(device), torch.arange(int(visual_token_index[1]+1), seq_length, device=device)))
1031
+ keep_indexs = keep_indexs.sort().values
1032
+ hidden_states = hidden_states[:, keep_indexs,:]
1033
+ position_embeddings = (position_embeddings[0].to(device)[:, keep_indexs, :], position_embeddings[1].to(device)[:, keep_indexs,:], )
1034
+
1035
+ if causal_mask is not None:
1036
+ causal_mask = causal_mask[:,:,:hidden_states.shape[1], :hidden_states.shape[1]]
1037
+ position_ids = keep_indexs.unsqueeze(0)
1038
+ prunded_sequence_length = visual_token_length - int(visual_token_length * keep_ratio)
1039
+
1040
+
1041
+ else:
1042
+ if idx == K:
1043
+ visual_token_length = visual_token_index[1] - visual_token_index[0] + 1
1044
+ prunded_sequence_length = visual_token_length - int(visual_token_length * keep_ratio)
1045
+ if causal_mask is not None:
1046
+ causal_mask = causal_mask[:, :, :, prunded_sequence_length:]
1047
+
1048
+
1049
+
1050
+ layer_outputs = decoder_layer(
1051
+ hidden_states,
1052
+ attention_mask=causal_mask,
1053
+ position_ids=position_ids,
1054
+ past_key_value=past_key_values,
1055
+ output_attentions=output_attentions,
1056
+ use_cache=use_cache,
1057
+ cache_position=cache_position,
1058
+ position_embeddings=position_embeddings
1059
+ )
1060
+
1061
+ hidden_states = layer_outputs[0]
1062
+
1063
+ if use_cache:
1064
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1065
+
1066
+ if output_attentions:
1067
+ # all_self_attns += (layer_outputs[1],)
1068
+ if layer_outputs[1].shape[2] != 1:
1069
+ aggregated_viusal_token_attention = aggregated_viusal_token_attention + layer_outputs[1][:, :, visual_token_index[1]:, visual_token_index[0]:visual_token_index[1]+1].sum(dim=(0, 1, 2))
1070
+ else:
1071
+ aggregated_viusal_token_attention = aggregated_viusal_token_attention + layer_outputs[1][:, :, :, visual_token_index[0]:visual_token_index[1]+1].sum(dim=(0, 1, 2))
1072
+
1073
+
1074
+ hidden_states = self.norm(hidden_states)
1075
+
1076
+ # add hidden states from the last decoder layer
1077
+ if output_hidden_states:
1078
+ all_hidden_states += (hidden_states,)
1079
+
1080
+ next_cache = next_decoder_cache if use_cache else None
1081
+ if return_legacy_cache:
1082
+ next_cache = next_cache.to_legacy_cache()
1083
+
1084
+ if not return_dict:
1085
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1086
+
1087
+ out_dict = BaseModelOutputWithPast(
1088
+ last_hidden_state=hidden_states,
1089
+ past_key_values=next_cache,
1090
+ hidden_states=all_hidden_states,
1091
+ attentions=all_self_attns,
1092
+ )
1093
+ out_dict.aggregated_viusal_token_attention = aggregated_viusal_token_attention
1094
+ return out_dict
1095
+
1096
+ def _update_causal_mask(
1097
+ self,
1098
+ attention_mask: torch.Tensor,
1099
+ input_tensor: torch.Tensor,
1100
+ cache_position: torch.Tensor,
1101
+ past_key_values: Cache,
1102
+ output_attentions: bool,
1103
+ ):
1104
+ # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
1105
+ # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
1106
+ # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
1107
+ # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
1108
+
1109
+ if self.config._attn_implementation == "flash_attention_2":
1110
+ if attention_mask is not None and 0.0 in attention_mask:
1111
+ return attention_mask
1112
+ return None
1113
+
1114
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1115
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1116
+ # to infer the attention mask.
1117
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1118
+ using_static_cache = isinstance(past_key_values, StaticCache)
1119
+
1120
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1121
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
1122
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1123
+ attention_mask,
1124
+ inputs_embeds=input_tensor,
1125
+ past_key_values_length=past_seen_tokens,
1126
+ is_training=self.training,
1127
+ ):
1128
+ return None
1129
+
1130
+ dtype, device = input_tensor.dtype, input_tensor.device
1131
+ min_dtype = torch.finfo(dtype).min
1132
+ sequence_length = input_tensor.shape[1]
1133
+ if using_static_cache:
1134
+ target_length = past_key_values.get_max_length()
1135
+ else:
1136
+ target_length = (
1137
+ attention_mask.shape[-1]
1138
+ if isinstance(attention_mask, torch.Tensor)
1139
+ else past_seen_tokens + sequence_length + 1
1140
+ )
1141
+
1142
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1143
+ causal_mask = _prepare_4d_causal_attention_mask_with_cache_position(
1144
+ attention_mask,
1145
+ sequence_length=sequence_length,
1146
+ target_length=target_length,
1147
+ dtype=dtype,
1148
+ device=device,
1149
+ min_dtype=min_dtype,
1150
+ cache_position=cache_position,
1151
+ batch_size=input_tensor.shape[0],
1152
+ )
1153
+
1154
+ if (
1155
+ self.config._attn_implementation == "sdpa"
1156
+ and attention_mask is not None
1157
+ and attention_mask.device.type == "cuda"
1158
+ and not output_attentions
1159
+ ):
1160
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1161
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1162
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1163
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1164
+
1165
+ return causal_mask
1166
+
1167
+
1168
+ class LlamaForCausalLM(LlamaPreTrainedModel):
1169
+ _tied_weights_keys = ["lm_head.weight"]
1170
+
1171
+ def __init__(self, config):
1172
+ super().__init__(config)
1173
+ self.model = LlamaModel(config)
1174
+ self.vocab_size = config.vocab_size
1175
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1176
+
1177
+ # Initialize weights and apply final processing
1178
+ self.post_init()
1179
+
1180
+ def get_input_embeddings(self):
1181
+ return self.model.embed_tokens
1182
+
1183
+ def set_input_embeddings(self, value):
1184
+ self.model.embed_tokens = value
1185
+
1186
+ def get_output_embeddings(self):
1187
+ return self.lm_head
1188
+
1189
+ def set_output_embeddings(self, new_embeddings):
1190
+ self.lm_head = new_embeddings
1191
+
1192
+ def set_decoder(self, decoder):
1193
+ self.model = decoder
1194
+
1195
+ def get_decoder(self):
1196
+ return self.model
1197
+
1198
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1199
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1200
+ def forward(
1201
+ self,
1202
+ input_ids: torch.LongTensor = None,
1203
+ attention_mask: Optional[torch.Tensor] = None,
1204
+ position_ids: Optional[torch.LongTensor] = None,
1205
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1206
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1207
+ labels: Optional[torch.LongTensor] = None,
1208
+ use_cache: Optional[bool] = None,
1209
+ output_attentions: Optional[bool] = None,
1210
+ output_hidden_states: Optional[bool] = None,
1211
+ return_dict: Optional[bool] = None,
1212
+ cache_position: Optional[torch.LongTensor] = None,
1213
+ visual_token_index: Optional[torch.Tensor] = None,
1214
+ large_model_prune_layer: Optional[float] = None,
1215
+ large_model_prune_ratio: Optional[float] = None,
1216
+ visual_token_importance: Optional[torch.Tensor] = None,
1217
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1218
+ r"""
1219
+ Args:
1220
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1221
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1222
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1223
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1224
+
1225
+ Returns:
1226
+
1227
+ Example:
1228
+
1229
+ ```python
1230
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
1231
+
1232
+ >>> model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
1233
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
1234
+
1235
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1236
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1237
+
1238
+ >>> # Generate
1239
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1240
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1241
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1242
+ ```"""
1243
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1244
+ output_hidden_states = (
1245
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1246
+ )
1247
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1248
+
1249
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1250
+ outputs = self.model(
1251
+ input_ids=input_ids,
1252
+ attention_mask=attention_mask,
1253
+ position_ids=position_ids,
1254
+ past_key_values=past_key_values,
1255
+ inputs_embeds=inputs_embeds,
1256
+ use_cache=use_cache,
1257
+ output_attentions=output_attentions,
1258
+ output_hidden_states=output_hidden_states,
1259
+ return_dict=return_dict,
1260
+ cache_position=cache_position,
1261
+ visual_token_index=visual_token_index,
1262
+ large_model_prune_layer=large_model_prune_layer,
1263
+ large_model_prune_ratio=large_model_prune_ratio,
1264
+ visual_token_importance=visual_token_importance
1265
+ )
1266
+
1267
+ hidden_states = outputs[0]
1268
+ if self.config.pretraining_tp > 1:
1269
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1270
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1271
+ logits = torch.cat(logits, dim=-1)
1272
+ else:
1273
+ logits = self.lm_head(hidden_states)
1274
+ logits = logits.float()
1275
+
1276
+ loss = None
1277
+ if labels is not None:
1278
+ # Shift so that tokens < n predict n
1279
+ shift_logits = logits[..., :-1, :].contiguous()
1280
+ shift_labels = labels[..., 1:].contiguous()
1281
+ # Flatten the tokens
1282
+ loss_fct = CrossEntropyLoss()
1283
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1284
+ shift_labels = shift_labels.view(-1)
1285
+ # Enable model parallelism
1286
+ shift_labels = shift_labels.to(shift_logits.device)
1287
+ loss = loss_fct(shift_logits, shift_labels)
1288
+
1289
+ if not return_dict:
1290
+ output = (logits,) + outputs[1:]
1291
+ return (loss,) + output if loss is not None else output
1292
+
1293
+
1294
+ output = CausalLMOutputWithPast(
1295
+ loss=loss,
1296
+ logits=logits,
1297
+ past_key_values=outputs.past_key_values,
1298
+ hidden_states=outputs.hidden_states,
1299
+ attentions=outputs.attentions,
1300
+ )
1301
+ output['aggregated_viusal_token_attention'] = outputs.aggregated_viusal_token_attention
1302
+ return output
1303
+
1304
+ def _sample(
1305
+ self,
1306
+ input_ids: torch.LongTensor,
1307
+ logits_processor: LogitsProcessorList,
1308
+ stopping_criteria: StoppingCriteriaList,
1309
+ generation_config: GenerationConfig,
1310
+ synced_gpus: bool,
1311
+ streamer: Optional["BaseStreamer"],
1312
+ logits_warper: Optional[LogitsProcessorList],
1313
+ **model_kwargs,
1314
+ ) -> Union[GenerateNonBeamOutput, torch.LongTensor]:
1315
+ # init values
1316
+ pad_token_id = generation_config._pad_token_tensor
1317
+ output_attentions = generation_config.output_attentions
1318
+ output_hidden_states = generation_config.output_hidden_states
1319
+ output_scores = generation_config.output_scores
1320
+ output_logits = generation_config.output_logits
1321
+ return_dict_in_generate = generation_config.return_dict_in_generate
1322
+ max_length = generation_config.max_length
1323
+ has_eos_stopping_criteria = any(hasattr(criteria, "eos_token_id") for criteria in stopping_criteria)
1324
+ do_sample = generation_config.do_sample
1325
+ if do_sample is True and not isinstance(logits_warper, LogitsProcessorList):
1326
+ raise ValueError(
1327
+ "`do_sample` is set to `True`, `logits_warper` must be a `LogitsProcessorList` instance (it is "
1328
+ f"{logits_warper})."
1329
+ )
1330
+
1331
+ # init attention / hidden states / scores tuples
1332
+ scores = () if (return_dict_in_generate and output_scores) else None
1333
+ raw_logits = () if (return_dict_in_generate and output_logits) else None
1334
+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
1335
+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None
1336
+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
1337
+
1338
+ # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
1339
+ if return_dict_in_generate and self.config.is_encoder_decoder:
1340
+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
1341
+ encoder_hidden_states = (
1342
+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
1343
+ )
1344
+
1345
+ # keep track of which sequences are already finished
1346
+ batch_size, cur_len = input_ids.shape
1347
+ this_peer_finished = False
1348
+ unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
1349
+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
1350
+
1351
+ aggregated_viusal_token_attention = 0 if output_attentions else None
1352
+ while self._has_unfinished_sequences(
1353
+ this_peer_finished, synced_gpus, device=input_ids.device, cur_len=cur_len, max_length=max_length
1354
+ ):
1355
+ # prepare model inputs
1356
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
1357
+
1358
+ # prepare variable output controls (note: some models won't accept all output controls)
1359
+ model_inputs.update({"output_attentions": output_attentions} if output_attentions else {})
1360
+ model_inputs.update({"output_hidden_states": output_hidden_states} if output_hidden_states else {})
1361
+
1362
+ # forward pass to get next token
1363
+ outputs = self(**model_inputs, return_dict=True)
1364
+ if output_attentions:
1365
+ aggregated_viusal_token_attention = aggregated_viusal_token_attention + outputs['aggregated_viusal_token_attention']
1366
+
1367
+ if synced_gpus and this_peer_finished:
1368
+ continue # don't waste resources running the code we don't need
1369
+
1370
+ # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration
1371
+ # (the clone itself is always small)
1372
+ next_token_logits = outputs.logits[:, -1, :].clone()
1373
+
1374
+ # pre-process distribution
1375
+ next_token_scores = logits_processor(input_ids, next_token_logits)
1376
+ if do_sample:
1377
+ next_token_scores = logits_warper(input_ids, next_token_scores)
1378
+
1379
+ # Store scores, attentions and hidden_states when required
1380
+ if return_dict_in_generate:
1381
+ if output_scores:
1382
+ scores += (next_token_scores,)
1383
+ if output_logits:
1384
+ raw_logits += (next_token_logits,)
1385
+ if output_attentions:
1386
+ decoder_attentions += (
1387
+ (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
1388
+ )
1389
+ if self.config.is_encoder_decoder:
1390
+ cross_attentions += (outputs.cross_attentions,)
1391
+
1392
+ if output_hidden_states:
1393
+ decoder_hidden_states += (
1394
+ (outputs.decoder_hidden_states,)
1395
+ if self.config.is_encoder_decoder
1396
+ else (outputs.hidden_states,)
1397
+ )
1398
+
1399
+ # token selection
1400
+ if do_sample:
1401
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
1402
+ # TODO (joao): this OP throws "skipping cudagraphs due to ['incompatible ops']", find solution
1403
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
1404
+ else:
1405
+ next_tokens = torch.argmax(next_token_scores, dim=-1)
1406
+
1407
+ # finished sentences should have their next token be a padding token
1408
+ if has_eos_stopping_criteria:
1409
+ next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)
1410
+
1411
+ # update generated ids, model inputs, and length for next step
1412
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
1413
+ if streamer is not None:
1414
+ streamer.put(next_tokens.cpu())
1415
+ model_kwargs = self._update_model_kwargs_for_generation(
1416
+ outputs,
1417
+ model_kwargs,
1418
+ is_encoder_decoder=self.config.is_encoder_decoder,
1419
+ )
1420
+
1421
+ unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)
1422
+ this_peer_finished = unfinished_sequences.max() == 0
1423
+ cur_len += 1
1424
+
1425
+ # This is needed to properly delete outputs.logits which may be very large for first iteration
1426
+ # Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration
1427
+ del outputs
1428
+
1429
+ if streamer is not None:
1430
+ streamer.end()
1431
+
1432
+ if return_dict_in_generate:
1433
+ if self.config.is_encoder_decoder:
1434
+ return GenerateEncoderDecoderOutput(
1435
+ sequences=input_ids,
1436
+ scores=scores,
1437
+ logits=raw_logits,
1438
+ encoder_attentions=encoder_attentions,
1439
+ encoder_hidden_states=encoder_hidden_states,
1440
+ decoder_attentions=decoder_attentions,
1441
+ cross_attentions=cross_attentions,
1442
+ decoder_hidden_states=decoder_hidden_states,
1443
+ past_key_values=model_kwargs.get("past_key_values"),
1444
+ )
1445
+ else:
1446
+ out_dict = GenerateDecoderOnlyOutput(
1447
+ sequences=input_ids,
1448
+ scores=scores,
1449
+ logits=raw_logits,
1450
+ attentions=decoder_attentions,
1451
+ hidden_states=decoder_hidden_states,
1452
+ past_key_values=model_kwargs.get("past_key_values"),
1453
+ )
1454
+ out_dict["aggregated_viusal_token_attention"] = aggregated_viusal_token_attention
1455
+ return out_dict
1456
+ else:
1457
+ return input_ids
1458
+
1459
+
1460
+ def prepare_inputs_for_generation(
1461
+ self,
1462
+ input_ids,
1463
+ past_key_values=None,
1464
+ attention_mask=None,
1465
+ inputs_embeds=None,
1466
+ cache_position=None,
1467
+ position_ids=None,
1468
+ use_cache=True,
1469
+ **kwargs,
1470
+ ):
1471
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
1472
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
1473
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
1474
+ if past_key_values is not None:
1475
+ if inputs_embeds is not None: # Exception 1
1476
+ input_ids = input_ids[:, -cache_position.shape[0] :]
1477
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
1478
+ input_ids = input_ids[:, cache_position]
1479
+
1480
+ if attention_mask is not None and position_ids is None:
1481
+ # create position_ids on the fly for batch generation
1482
+ position_ids = attention_mask.long().cumsum(-1) - 1
1483
+ position_ids.masked_fill_(attention_mask == 0, 1)
1484
+ if past_key_values:
1485
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1486
+
1487
+ # This `clone` call is needed to avoid recapturing cuda graphs with `torch.compile`'s `mode="reduce-overhead`, as otherwise the input `position_ids` would have various stride during the decoding. Here, simply using `.contiguous()` is not sufficient as in the batch size = 1 case, `position_ids` is already contiguous but with varying stride which retriggers a capture.
1488
+ position_ids = position_ids.clone(memory_format=torch.contiguous_format)
1489
+
1490
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1491
+ if inputs_embeds is not None and cache_position[0] == 0:
1492
+ model_inputs = {"inputs_embeds": inputs_embeds, "input_ids": None}
1493
+ else:
1494
+ # The clone here is for the same reason as for `position_ids`.
1495
+ model_inputs = {"input_ids": input_ids.clone(memory_format=torch.contiguous_format), "inputs_embeds": None}
1496
+
1497
+ if isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2:
1498
+ if model_inputs["inputs_embeds"] is not None:
1499
+ batch_size, sequence_length, _ = model_inputs["inputs_embeds"].shape
1500
+ device = model_inputs["inputs_embeds"].device
1501
+ else:
1502
+ batch_size, sequence_length = model_inputs["input_ids"].shape
1503
+ device = model_inputs["input_ids"].device
1504
+
1505
+ dtype = self.lm_head.weight.dtype
1506
+ min_dtype = torch.finfo(dtype).min
1507
+
1508
+ attention_mask = _prepare_4d_causal_attention_mask_with_cache_position(
1509
+ attention_mask,
1510
+ sequence_length=sequence_length,
1511
+ target_length=past_key_values.get_max_length(),
1512
+ dtype=dtype,
1513
+ device=device,
1514
+ min_dtype=min_dtype,
1515
+ cache_position=cache_position,
1516
+ batch_size=batch_size,
1517
+ )
1518
+
1519
+ model_inputs.update(
1520
+ {
1521
+ "position_ids": position_ids,
1522
+ "cache_position": cache_position,
1523
+ "past_key_values": past_key_values,
1524
+ "use_cache": use_cache,
1525
+ "attention_mask": attention_mask,
1526
+ 'visual_token_index': kwargs.get('visual_token_index'),
1527
+ 'large_model_prune_layer': kwargs.get('large_model_prune_layer'),
1528
+ 'large_model_prune_ratio': kwargs.get('large_model_prune_ratio'),
1529
+ 'visual_token_importance': kwargs.get('visual_token_importance')
1530
+ }
1531
+ )
1532
+ return model_inputs
1533
+
1534
+
1535
+ @add_start_docstrings(
1536
+ """
1537
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
1538
+
1539
+ [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1540
+ (e.g. GPT-2) do.
1541
+
1542
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1543
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1544
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1545
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1546
+ each row of the batch).
1547
+ """,
1548
+ LLAMA_START_DOCSTRING,
1549
+ )
1550
+ class LlamaForSequenceClassification(LlamaPreTrainedModel):
1551
+ def __init__(self, config):
1552
+ super().__init__(config)
1553
+ self.num_labels = config.num_labels
1554
+ self.model = LlamaModel(config)
1555
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1556
+
1557
+ # Initialize weights and apply final processing
1558
+ self.post_init()
1559
+
1560
+ def get_input_embeddings(self):
1561
+ return self.model.embed_tokens
1562
+
1563
+ def set_input_embeddings(self, value):
1564
+ self.model.embed_tokens = value
1565
+
1566
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1567
+ def forward(
1568
+ self,
1569
+ input_ids: Optional[torch.LongTensor] = None,
1570
+ attention_mask: Optional[torch.Tensor] = None,
1571
+ position_ids: Optional[torch.LongTensor] = None,
1572
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1573
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1574
+ labels: Optional[torch.LongTensor] = None,
1575
+ use_cache: Optional[bool] = None,
1576
+ output_attentions: Optional[bool] = None,
1577
+ output_hidden_states: Optional[bool] = None,
1578
+ return_dict: Optional[bool] = None,
1579
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1580
+ r"""
1581
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1582
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1583
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1584
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1585
+ """
1586
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1587
+
1588
+ transformer_outputs = self.model(
1589
+ input_ids,
1590
+ attention_mask=attention_mask,
1591
+ position_ids=position_ids,
1592
+ past_key_values=past_key_values,
1593
+ inputs_embeds=inputs_embeds,
1594
+ use_cache=use_cache,
1595
+ output_attentions=output_attentions,
1596
+ output_hidden_states=output_hidden_states,
1597
+ return_dict=return_dict,
1598
+ )
1599
+ hidden_states = transformer_outputs[0]
1600
+ logits = self.score(hidden_states)
1601
+
1602
+ if input_ids is not None:
1603
+ batch_size = input_ids.shape[0]
1604
+ else:
1605
+ batch_size = inputs_embeds.shape[0]
1606
+
1607
+ if self.config.pad_token_id is None and batch_size != 1:
1608
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1609
+ if self.config.pad_token_id is None:
1610
+ sequence_lengths = -1
1611
+ else:
1612
+ if input_ids is not None:
1613
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1614
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1615
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1616
+ sequence_lengths = sequence_lengths.to(logits.device)
1617
+ else:
1618
+ sequence_lengths = -1
1619
+
1620
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1621
+
1622
+ loss = None
1623
+ if labels is not None:
1624
+ labels = labels.to(logits.device)
1625
+ if self.config.problem_type is None:
1626
+ if self.num_labels == 1:
1627
+ self.config.problem_type = "regression"
1628
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1629
+ self.config.problem_type = "single_label_classification"
1630
+ else:
1631
+ self.config.problem_type = "multi_label_classification"
1632
+
1633
+ if self.config.problem_type == "regression":
1634
+ loss_fct = MSELoss()
1635
+ if self.num_labels == 1:
1636
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1637
+ else:
1638
+ loss = loss_fct(pooled_logits, labels)
1639
+ elif self.config.problem_type == "single_label_classification":
1640
+ loss_fct = CrossEntropyLoss()
1641
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1642
+ elif self.config.problem_type == "multi_label_classification":
1643
+ loss_fct = BCEWithLogitsLoss()
1644
+ loss = loss_fct(pooled_logits, labels)
1645
+ if not return_dict:
1646
+ output = (pooled_logits,) + transformer_outputs[1:]
1647
+ return ((loss,) + output) if loss is not None else output
1648
+
1649
+ return SequenceClassifierOutputWithPast(
1650
+ loss=loss,
1651
+ logits=pooled_logits,
1652
+ past_key_values=transformer_outputs.past_key_values,
1653
+ hidden_states=transformer_outputs.hidden_states,
1654
+ attentions=transformer_outputs.attentions,
1655
+ )
1656
+
1657
+
1658
+ @add_start_docstrings(
1659
+ """
1660
+ The Llama Model transformer with a span classification head on top for extractive question-answering tasks like
1661
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1662
+ """,
1663
+ LLAMA_START_DOCSTRING,
1664
+ )
1665
+ class LlamaForQuestionAnswering(LlamaPreTrainedModel):
1666
+ base_model_prefix = "transformer"
1667
+
1668
+ # Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->Llama
1669
+ def __init__(self, config):
1670
+ super().__init__(config)
1671
+ self.transformer = LlamaModel(config)
1672
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1673
+
1674
+ # Initialize weights and apply final processing
1675
+ self.post_init()
1676
+
1677
+ def get_input_embeddings(self):
1678
+ return self.transformer.embed_tokens
1679
+
1680
+ def set_input_embeddings(self, value):
1681
+ self.transformer.embed_tokens = value
1682
+
1683
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1684
+ def forward(
1685
+ self,
1686
+ input_ids: Optional[torch.LongTensor] = None,
1687
+ attention_mask: Optional[torch.FloatTensor] = None,
1688
+ position_ids: Optional[torch.LongTensor] = None,
1689
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1690
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1691
+ start_positions: Optional[torch.LongTensor] = None,
1692
+ end_positions: Optional[torch.LongTensor] = None,
1693
+ output_attentions: Optional[bool] = None,
1694
+ output_hidden_states: Optional[bool] = None,
1695
+ return_dict: Optional[bool] = None,
1696
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1697
+ r"""
1698
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1699
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1700
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1701
+ are not taken into account for computing the loss.
1702
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1703
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1704
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1705
+ are not taken into account for computing the loss.
1706
+ """
1707
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1708
+
1709
+ outputs = self.transformer(
1710
+ input_ids,
1711
+ attention_mask=attention_mask,
1712
+ position_ids=position_ids,
1713
+ past_key_values=past_key_values,
1714
+ inputs_embeds=inputs_embeds,
1715
+ output_attentions=output_attentions,
1716
+ output_hidden_states=output_hidden_states,
1717
+ return_dict=return_dict,
1718
+ )
1719
+
1720
+ sequence_output = outputs[0]
1721
+
1722
+ logits = self.qa_outputs(sequence_output)
1723
+ start_logits, end_logits = logits.split(1, dim=-1)
1724
+ start_logits = start_logits.squeeze(-1).contiguous()
1725
+ end_logits = end_logits.squeeze(-1).contiguous()
1726
+
1727
+ total_loss = None
1728
+ if start_positions is not None and end_positions is not None:
1729
+ # If we are on multi-GPU, split add a dimension
1730
+ if len(start_positions.size()) > 1:
1731
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
1732
+ if len(end_positions.size()) > 1:
1733
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
1734
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1735
+ ignored_index = start_logits.size(1)
1736
+ start_positions = start_positions.clamp(0, ignored_index)
1737
+ end_positions = end_positions.clamp(0, ignored_index)
1738
+
1739
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1740
+ start_loss = loss_fct(start_logits, start_positions)
1741
+ end_loss = loss_fct(end_logits, end_positions)
1742
+ total_loss = (start_loss + end_loss) / 2
1743
+
1744
+ if not return_dict:
1745
+ output = (start_logits, end_logits) + outputs[2:]
1746
+ return ((total_loss,) + output) if total_loss is not None else output
1747
+
1748
+ return QuestionAnsweringModelOutput(
1749
+ loss=total_loss,
1750
+ start_logits=start_logits,
1751
+ end_logits=end_logits,
1752
+ hidden_states=outputs.hidden_states,
1753
+ attentions=outputs.attentions,
1754
+ )
1755
+
1756
+
1757
+ @add_start_docstrings(
1758
+ """
1759
+ The Llama Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1760
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1761
+ """,
1762
+ LLAMA_START_DOCSTRING,
1763
+ )
1764
+ class LlamaForTokenClassification(LlamaPreTrainedModel):
1765
+ def __init__(self, config):
1766
+ super().__init__(config)
1767
+ self.num_labels = config.num_labels
1768
+ self.model = LlamaModel(config)
1769
+ if getattr(config, "classifier_dropout", None) is not None:
1770
+ classifier_dropout = config.classifier_dropout
1771
+ elif getattr(config, "hidden_dropout", None) is not None:
1772
+ classifier_dropout = config.hidden_dropout
1773
+ else:
1774
+ classifier_dropout = 0.1
1775
+ self.dropout = nn.Dropout(classifier_dropout)
1776
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1777
+
1778
+ # Initialize weights and apply final processing
1779
+ self.post_init()
1780
+
1781
+ def get_input_embeddings(self):
1782
+ return self.model.embed_tokens
1783
+
1784
+ def set_input_embeddings(self, value):
1785
+ self.model.embed_tokens = value
1786
+
1787
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1788
+ def forward(
1789
+ self,
1790
+ input_ids: Optional[torch.LongTensor] = None,
1791
+ attention_mask: Optional[torch.Tensor] = None,
1792
+ position_ids: Optional[torch.LongTensor] = None,
1793
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1794
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1795
+ labels: Optional[torch.LongTensor] = None,
1796
+ use_cache: Optional[bool] = None,
1797
+ output_attentions: Optional[bool] = None,
1798
+ output_hidden_states: Optional[bool] = None,
1799
+ return_dict: Optional[bool] = None,
1800
+ ) -> Union[Tuple, TokenClassifierOutput]:
1801
+ r"""
1802
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1803
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1804
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1805
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1806
+ """
1807
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1808
+
1809
+ outputs = self.model(
1810
+ input_ids,
1811
+ attention_mask=attention_mask,
1812
+ position_ids=position_ids,
1813
+ past_key_values=past_key_values,
1814
+ inputs_embeds=inputs_embeds,
1815
+ use_cache=use_cache,
1816
+ output_attentions=output_attentions,
1817
+ output_hidden_states=output_hidden_states,
1818
+ return_dict=return_dict,
1819
+ )
1820
+ sequence_output = outputs[0]
1821
+ sequence_output = self.dropout(sequence_output)
1822
+ logits = self.score(sequence_output)
1823
+
1824
+ loss = None
1825
+ if labels is not None:
1826
+ loss_fct = CrossEntropyLoss()
1827
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1828
+
1829
+ if not return_dict:
1830
+ output = (logits,) + outputs[2:]
1831
+ return ((loss,) + output) if loss is not None else output
1832
+
1833
+ return TokenClassifierOutput(
1834
+ loss=loss,
1835
+ logits=logits,
1836
+ hidden_states=outputs.hidden_states,
1837
+ attentions=outputs.attentions,
1838
+ )
internvl/model/llama/tokenization_llama.py ADDED
@@ -0,0 +1,412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ """Tokenization classes for LLaMA."""
22
+
23
+ import os
24
+ from shutil import copyfile
25
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
26
+
27
+ import sentencepiece as spm
28
+
29
+ from transformers.convert_slow_tokenizer import import_protobuf
30
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
31
+ from transformers.tils import logging
32
+
33
+
34
+ if TYPE_CHECKING:
35
+ from transformers.tokenization_utils_base import TextInput
36
+
37
+ logger = logging.get_logger(__name__)
38
+
39
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
40
+
41
+ SPIECE_UNDERLINE = "▁"
42
+
43
+ B_INST, E_INST = "[INST]", "[/INST]"
44
+ B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
45
+
46
+ # fmt: off
47
+ DEFAULT_SYSTEM_PROMPT = """You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your \
48
+ answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
49
+ that your responses are socially unbiased and positive in nature.
50
+
51
+ If a question does not make any sense, or is not factually coherent, explain why instead of answering something not \
52
+ correct. If you don't know the answer to a question, please don't share false information."""
53
+ # fmt: on
54
+
55
+
56
+ class LlamaTokenizer(PreTrainedTokenizer):
57
+ """
58
+ Construct a Llama tokenizer. Based on byte-level Byte-Pair-Encoding. The default padding token is unset as there is
59
+ no padding token in the original model.
60
+
61
+ Args:
62
+ vocab_file (`str`):
63
+ Path to the vocabulary file.
64
+ unk_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<unk>"`):
65
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
66
+ token instead.
67
+ bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<s>"`):
68
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
69
+ eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"</s>"`):
70
+ The end of sequence token.
71
+ pad_token (`str` or `tokenizers.AddedToken`, *optional*):
72
+ A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by
73
+ attention mechanisms or loss computation.
74
+ sp_model_kwargs (`Dict[str, Any]`, `Optional`, *optional*):
75
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
76
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
77
+ to set:
78
+
79
+ - `enable_sampling`: Enable subword regularization.
80
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
81
+
82
+ - `nbest_size = {0,1}`: No sampling is performed.
83
+ - `nbest_size > 1`: samples from the nbest_size results.
84
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
85
+ using forward-filtering-and-backward-sampling algorithm.
86
+
87
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
88
+ BPE-dropout.
89
+
90
+ add_bos_token (`bool`, *optional*, defaults to `True`):
91
+ Whether or not to add an `bos_token` at the start of sequences.
92
+ add_eos_token (`bool`, *optional*, defaults to `False`):
93
+ Whether or not to add an `eos_token` at the end of sequences.
94
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
95
+ Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
96
+ extra spaces.
97
+ use_default_system_prompt (`bool`, *optional*, defaults to `False`):
98
+ Whether or not the default system prompt for Llama should be used.
99
+ spaces_between_special_tokens (`bool`, *optional*, defaults to `False`):
100
+ Whether or not to add spaces between special tokens.
101
+ legacy (`bool`, *optional*):
102
+ Whether or not the `legacy` behavior of the tokenizer should be used. Legacy is before the merge of #24622
103
+ and #25224 which includes fixes to properly handle tokens that appear after special tokens.
104
+ Make sure to also set `from_slow` to `True`.
105
+ A simple example:
106
+
107
+ - `legacy=True`:
108
+ ```python
109
+ >>> from transformers import LlamaTokenizerFast
110
+
111
+ >>> tokenizer = LlamaTokenizerFast.from_pretrained("huggyllama/llama-7b", legacy=True, from_slow=True)
112
+ >>> tokenizer.encode("Hello <s>.") # 869 is '▁.'
113
+ [1, 15043, 29871, 1, 869]
114
+ ```
115
+ - `legacy=False`:
116
+ ```python
117
+ >>> from transformers import LlamaTokenizerFast
118
+
119
+ >>> tokenizer = LlamaTokenizerFast.from_pretrained("huggyllama/llama-7b", legacy=False, from_slow=True)
120
+ >>> tokenizer.encode("Hello <s>.") # 29889 is '.'
121
+ [1, 15043, 29871, 1, 29889]
122
+ ```
123
+ Checkout the [pull request](https://github.com/huggingface/transformers/pull/24565) for more details.
124
+ add_prefix_space (`bool`, *optional*, defaults to `True`):
125
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
126
+ other word. Again, this should be set with `from_slow=True` to make sure it's taken into account.
127
+ """
128
+
129
+ vocab_files_names = VOCAB_FILES_NAMES
130
+ model_input_names = ["input_ids", "attention_mask"]
131
+
132
+ def __init__(
133
+ self,
134
+ vocab_file,
135
+ unk_token="<unk>",
136
+ bos_token="<s>",
137
+ eos_token="</s>",
138
+ pad_token=None,
139
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
140
+ add_bos_token=True,
141
+ add_eos_token=False,
142
+ clean_up_tokenization_spaces=False,
143
+ use_default_system_prompt=False,
144
+ spaces_between_special_tokens=False,
145
+ legacy=None,
146
+ add_prefix_space=True,
147
+ **kwargs,
148
+ ):
149
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
150
+ bos_token = AddedToken(bos_token, normalized=False, special=True) if isinstance(bos_token, str) else bos_token
151
+ eos_token = AddedToken(eos_token, normalized=False, special=True) if isinstance(eos_token, str) else eos_token
152
+ unk_token = AddedToken(unk_token, normalized=False, special=True) if isinstance(unk_token, str) else unk_token
153
+ pad_token = AddedToken(pad_token, normalized=False, special=True) if isinstance(pad_token, str) else pad_token
154
+
155
+ if legacy is None:
156
+ logger.warning_once(
157
+ f"You are using the default legacy behaviour of the {self.__class__}. This is"
158
+ " expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you."
159
+ " If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it"
160
+ " means, and thoroughly read the reason why this was added as explained in"
161
+ " https://github.com/huggingface/transformers/pull/24565 - if you loaded a llama tokenizer from a GGUF file"
162
+ " you can ignore this message"
163
+ )
164
+ legacy = True
165
+
166
+ self.legacy = legacy
167
+ self.vocab_file = vocab_file
168
+ self.add_bos_token = add_bos_token
169
+ self.add_eos_token = add_eos_token
170
+ self.use_default_system_prompt = use_default_system_prompt
171
+ self.sp_model = self.get_spm_processor(kwargs.pop("from_slow", False))
172
+ self.add_prefix_space = add_prefix_space
173
+
174
+ super().__init__(
175
+ bos_token=bos_token,
176
+ eos_token=eos_token,
177
+ unk_token=unk_token,
178
+ pad_token=pad_token,
179
+ add_bos_token=add_bos_token,
180
+ add_eos_token=add_eos_token,
181
+ sp_model_kwargs=self.sp_model_kwargs,
182
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
183
+ use_default_system_prompt=use_default_system_prompt,
184
+ spaces_between_special_tokens=spaces_between_special_tokens,
185
+ legacy=legacy,
186
+ add_prefix_space=add_prefix_space,
187
+ **kwargs,
188
+ )
189
+
190
+ @property
191
+ def unk_token_length(self):
192
+ return len(self.sp_model.encode(str(self.unk_token)))
193
+
194
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.get_spm_processor
195
+ def get_spm_processor(self, from_slow=False):
196
+ tokenizer = spm.SentencePieceProcessor(**self.sp_model_kwargs)
197
+ if self.legacy or from_slow: # no dependency on protobuf
198
+ tokenizer.Load(self.vocab_file)
199
+ return tokenizer
200
+
201
+ with open(self.vocab_file, "rb") as f:
202
+ sp_model = f.read()
203
+ model_pb2 = import_protobuf(f"The new behaviour of {self.__class__.__name__} (with `self.legacy = False`)")
204
+ model = model_pb2.ModelProto.FromString(sp_model)
205
+ normalizer_spec = model_pb2.NormalizerSpec()
206
+ normalizer_spec.add_dummy_prefix = False
207
+ model.normalizer_spec.MergeFrom(normalizer_spec)
208
+ sp_model = model.SerializeToString()
209
+ tokenizer.LoadFromSerializedProto(sp_model)
210
+ return tokenizer
211
+
212
+ def __getstate__(self):
213
+ state = self.__dict__.copy()
214
+ state["sp_model"] = None
215
+ state["sp_model_proto"] = self.sp_model.serialized_model_proto()
216
+ return state
217
+
218
+ def __setstate__(self, d):
219
+ self.__dict__ = d
220
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
221
+ self.sp_model.LoadFromSerializedProto(self.sp_model_proto)
222
+
223
+ @property
224
+ def vocab_size(self):
225
+ """Returns vocab size"""
226
+ return self.sp_model.get_piece_size()
227
+
228
+ def get_vocab(self):
229
+ """Returns vocab as a dict"""
230
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
231
+ vocab.update(self.added_tokens_encoder)
232
+ return vocab
233
+
234
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.tokenize
235
+ def tokenize(self, text: "TextInput", **kwargs) -> List[str]:
236
+ """
237
+ Converts a string to a list of tokens. If `self.legacy` is set to `False`, a prefix token is added unless the
238
+ first token is special.
239
+ """
240
+ if self.legacy or len(text) == 0:
241
+ return super().tokenize(text, **kwargs)
242
+
243
+ text = text.replace(SPIECE_UNDERLINE, " ")
244
+ if self.add_prefix_space:
245
+ text = SPIECE_UNDERLINE + text
246
+
247
+ tokens = super().tokenize(text, **kwargs)
248
+
249
+ if len(tokens) > 1 and tokens[0] == SPIECE_UNDERLINE and tokens[1] in self.all_special_tokens:
250
+ tokens = tokens[1:]
251
+ return tokens
252
+
253
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer._tokenize
254
+ def _tokenize(self, text, **kwargs):
255
+ """
256
+ Returns a tokenized string.
257
+
258
+ We de-activated the `add_dummy_prefix` option, thus the sentencepiece internals will always strip any
259
+ SPIECE_UNDERLINE. For example: `self.sp_model.encode(f"{SPIECE_UNDERLINE}Hey", out_type = str)` will give
260
+ `['H', 'e', 'y']` instead of `['▁He', 'y']`. Thus we always encode `f"{unk_token}text"` and strip the
261
+ `unk_token`. Here is an example with `unk_token = "<unk>"` and `unk_token_length = 4`.
262
+ `self.tokenizer.sp_model.encode("<unk> Hey", out_type = str)[4:]`.
263
+ """
264
+ if self.legacy or not text.startswith((SPIECE_UNDERLINE, " ")):
265
+ return self.sp_model.encode(text, out_type=str)
266
+
267
+ # 1. Encode string + prefix ex: "<unk> Hey"
268
+ tokens = self.sp_model.encode(self.unk_token + text, out_type=str)
269
+ # 2. Remove self.unk_token from ['<','unk','>', '▁Hey']
270
+ return tokens[self.unk_token_length :] if len(tokens) >= self.unk_token_length else tokens
271
+
272
+ def _convert_token_to_id(self, token):
273
+ """Converts a token (str) in an id using the vocab."""
274
+ return self.sp_model.piece_to_id(token)
275
+
276
+ def _convert_id_to_token(self, index):
277
+ """Converts an index (integer) in a token (str) using the vocab."""
278
+ token = self.sp_model.IdToPiece(index)
279
+ return token
280
+
281
+ def convert_tokens_to_string(self, tokens):
282
+ """Converts a sequence of tokens (string) in a single string."""
283
+ # since we manually add the prefix space, we have to remove it when decoding
284
+ if tokens[0].startswith(SPIECE_UNDERLINE) and self.add_prefix_space:
285
+ tokens[0] = tokens[0][1:]
286
+
287
+ current_sub_tokens = []
288
+ out_string = ""
289
+ prev_is_special = False
290
+ for i, token in enumerate(tokens):
291
+ # make sure that special tokens are not decoded using sentencepiece model
292
+ if token in self.all_special_tokens:
293
+ if not prev_is_special and i != 0 and self.legacy:
294
+ out_string += " "
295
+ out_string += self.sp_model.decode(current_sub_tokens) + token
296
+ prev_is_special = True
297
+ current_sub_tokens = []
298
+ else:
299
+ if prev_is_special and i == 1 and self.add_prefix_space and not token.startswith(SPIECE_UNDERLINE):
300
+ out_string += " "
301
+ current_sub_tokens.append(token)
302
+ prev_is_special = False
303
+ out_string += self.sp_model.decode(current_sub_tokens)
304
+ return out_string
305
+
306
+ def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
307
+ """
308
+ Save the vocabulary and special tokens file to a directory.
309
+
310
+ Args:
311
+ save_directory (`str`):
312
+ The directory in which to save the vocabulary.
313
+
314
+ Returns:
315
+ `Tuple(str)`: Paths to the files saved.
316
+ """
317
+ if not os.path.isdir(save_directory):
318
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
319
+ return
320
+ out_vocab_file = os.path.join(
321
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
322
+ )
323
+
324
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
325
+ copyfile(self.vocab_file, out_vocab_file)
326
+ elif not os.path.isfile(self.vocab_file):
327
+ with open(out_vocab_file, "wb") as fi:
328
+ content_spiece_model = self.sp_model.serialized_model_proto()
329
+ fi.write(content_spiece_model)
330
+
331
+ return (out_vocab_file,)
332
+
333
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
334
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
335
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
336
+
337
+ output = bos_token_id + token_ids_0 + eos_token_id
338
+
339
+ if token_ids_1 is not None:
340
+ output = output + bos_token_id + token_ids_1 + eos_token_id
341
+
342
+ return output
343
+
344
+ def get_special_tokens_mask(
345
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
346
+ ) -> List[int]:
347
+ """
348
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
349
+ special tokens using the tokenizer `prepare_for_model` method.
350
+
351
+ Args:
352
+ token_ids_0 (`List[int]`):
353
+ List of IDs.
354
+ token_ids_1 (`List[int]`, *optional*):
355
+ Optional second list of IDs for sequence pairs.
356
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
357
+ Whether or not the token list is already formatted with special tokens for the model.
358
+
359
+ Returns:
360
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
361
+ """
362
+ if already_has_special_tokens:
363
+ return super().get_special_tokens_mask(
364
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
365
+ )
366
+
367
+ bos_token_id = [1] if self.add_bos_token else []
368
+ eos_token_id = [1] if self.add_eos_token else []
369
+
370
+ if token_ids_1 is None:
371
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
372
+ return (
373
+ bos_token_id
374
+ + ([0] * len(token_ids_0))
375
+ + eos_token_id
376
+ + bos_token_id
377
+ + ([0] * len(token_ids_1))
378
+ + eos_token_id
379
+ )
380
+
381
+ def create_token_type_ids_from_sequences(
382
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
383
+ ) -> List[int]:
384
+ """
385
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
386
+ sequence pair mask has the following format:
387
+
388
+ ```
389
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
390
+ | first sequence | second sequence |
391
+ ```
392
+
393
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
394
+
395
+ Args:
396
+ token_ids_0 (`List[int]`):
397
+ List of ids.
398
+ token_ids_1 (`List[int]`, *optional*):
399
+ Optional second list of IDs for sequence pairs.
400
+
401
+ Returns:
402
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
403
+ """
404
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
405
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
406
+
407
+ output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
408
+
409
+ if token_ids_1 is not None:
410
+ output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
411
+
412
+ return output
internvl/model/llama/tokenization_llama_fast.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The HuggingFace Inc. team.
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
+ import os
16
+ from shutil import copyfile
17
+ from typing import Optional, Tuple
18
+
19
+ from tokenizers import processors
20
+
21
+ from transformers.tokenization_utils_fast import PreTrainedTokenizerFast
22
+ from transformers.utils import is_sentencepiece_available, logging
23
+ from transformers.utils.versions import require_version
24
+
25
+
26
+ require_version("tokenizers>=0.13.3")
27
+
28
+ if is_sentencepiece_available():
29
+ from .tokenization_llama import LlamaTokenizer
30
+ else:
31
+ LlamaTokenizer = None
32
+
33
+ logger = logging.get_logger(__name__)
34
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model", "tokenizer_file": "tokenizer.json"}
35
+
36
+ B_INST, E_INST = "[INST]", "[/INST]"
37
+ B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
38
+
39
+ # fmt: off
40
+ DEFAULT_SYSTEM_PROMPT = """You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your \
41
+ answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
42
+ that your responses are socially unbiased and positive in nature.
43
+
44
+ If a question does not make any sense, or is not factually coherent, explain why instead of answering something not \
45
+ correct. If you don't know the answer to a question, please don't share false information."""
46
+ # fmt: on
47
+
48
+
49
+ class LlamaTokenizerFast(PreTrainedTokenizerFast):
50
+ """
51
+ Construct a Llama tokenizer. Based on byte-level Byte-Pair-Encoding.
52
+
53
+ This uses notably ByteFallback and no normalization.
54
+
55
+ ```python
56
+ >>> from transformers import LlamaTokenizerFast
57
+
58
+ >>> tokenizer = LlamaTokenizerFast.from_pretrained("hf-internal-testing/llama-tokenizer")
59
+ >>> tokenizer.encode("Hello this is a test")
60
+ [1, 15043, 445, 338, 263, 1243]
61
+ ```
62
+
63
+ If you want to change the `bos_token` or the `eos_token`, make sure to specify them when initializing the model, or
64
+ call `tokenizer.update_post_processor()` to make sure that the post-processing is correctly done (otherwise the
65
+ values of the first token and final token of an encoded sequence will not be correct). For more details, checkout
66
+ [post-processors] (https://huggingface.co/docs/tokenizers/api/post-processors) documentation.
67
+
68
+
69
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
70
+ refer to this superclass for more information regarding those methods.
71
+
72
+ Args:
73
+ vocab_file (`str`, *optional*):
74
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .model extension) that
75
+ contains the vocabulary necessary to instantiate a tokenizer.
76
+ tokenizer_file (`str`, *optional*):
77
+ [tokenizers](https://github.com/huggingface/tokenizers) file (generally has a .json extension) that
78
+ contains everything needed to load the tokenizer.
79
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
80
+ Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
81
+ extra spaces.
82
+ unk_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<unk>"`):
83
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
84
+ token instead.
85
+ bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<s>"`):
86
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
87
+ eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"</s>"`):
88
+ The end of sequence token.
89
+ add_bos_token (`bool`, *optional*, defaults to `True`):
90
+ Whether or not to add an `bos_token` at the start of sequences.
91
+ add_eos_token (`bool`, *optional*, defaults to `False`):
92
+ Whether or not to add an `eos_token` at the end of sequences.
93
+ use_default_system_prompt (`bool`, *optional*, defaults to `False`):
94
+ Whether or not the default system prompt for Llama should be used
95
+ legacy (`bool`, *optional*):
96
+ Whether or not the `legacy` behavior of the tokenizer should be used. Legacy is before the merge of #24622
97
+ and #25224 which includes fixes to properly handle tokens that appear after special tokens.
98
+ Make sure to also set `from_slow` to `True`.
99
+ A simple example:
100
+
101
+ - `legacy=True`:
102
+ ```python
103
+ >>> from transformers import LlamaTokenizerFast
104
+
105
+ >>> tokenizer = LlamaTokenizerFast.from_pretrained("huggyllama/llama-7b", legacy=True, from_slow=True)
106
+ >>> tokenizer.encode("Hello <s>.") # 869 is '▁.'
107
+ [1, 15043, 29871, 1, 869]
108
+ ```
109
+ - `legacy=False`:
110
+ ```python
111
+ >>> from transformers import LlamaTokenizerFast
112
+
113
+ >>> tokenizer = LlamaTokenizerFast.from_pretrained("huggyllama/llama-7b", legacy=False, from_slow=True)
114
+ >>> tokenizer.encode("Hello <s>.") # 29889 is '.'
115
+ [1, 15043, 29871, 1, 29889]
116
+ ```
117
+ Checkout the [pull request](https://github.com/huggingface/transformers/pull/24565) for more details.
118
+ add_prefix_space (`bool`, *optional*):
119
+ Whether or not the tokenizer should automatically add a prefix space
120
+ """
121
+
122
+ vocab_files_names = VOCAB_FILES_NAMES
123
+ slow_tokenizer_class = LlamaTokenizer
124
+ padding_side = "left"
125
+ model_input_names = ["input_ids", "attention_mask"]
126
+
127
+ def __init__(
128
+ self,
129
+ vocab_file=None,
130
+ tokenizer_file=None,
131
+ clean_up_tokenization_spaces=False,
132
+ unk_token="<unk>",
133
+ bos_token="<s>",
134
+ eos_token="</s>",
135
+ add_bos_token=True,
136
+ add_eos_token=False,
137
+ use_default_system_prompt=False,
138
+ legacy=None,
139
+ add_prefix_space=None,
140
+ **kwargs,
141
+ ):
142
+ if legacy is None:
143
+ logger.warning_once(
144
+ f"You are using the default legacy behaviour of the {self.__class__}. This is"
145
+ " expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you."
146
+ " If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it"
147
+ " means, and thoroughly read the reason why this was added as explained in"
148
+ " https://github.com/huggingface/transformers/pull/24565 - if you loaded a llama tokenizer from a GGUF file"
149
+ " you can ignore this message."
150
+ )
151
+ legacy = True
152
+ self.legacy = legacy
153
+
154
+ if add_prefix_space is not None:
155
+ kwargs["from_slow"] = True
156
+
157
+ super().__init__(
158
+ vocab_file=vocab_file,
159
+ tokenizer_file=tokenizer_file,
160
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
161
+ unk_token=unk_token,
162
+ bos_token=bos_token,
163
+ eos_token=eos_token,
164
+ add_bos_token=add_bos_token,
165
+ add_eos_token=add_eos_token,
166
+ use_default_system_prompt=use_default_system_prompt,
167
+ add_prefix_space=add_prefix_space,
168
+ legacy=legacy,
169
+ **kwargs,
170
+ )
171
+ self._add_bos_token = add_bos_token
172
+ self._add_eos_token = add_eos_token
173
+ self.update_post_processor()
174
+ self.use_default_system_prompt = use_default_system_prompt
175
+ self.vocab_file = vocab_file
176
+
177
+ @property
178
+ def can_save_slow_tokenizer(self) -> bool:
179
+ return os.path.isfile(self.vocab_file) if self.vocab_file else False
180
+
181
+ def update_post_processor(self):
182
+ """
183
+ Updates the underlying post processor with the current `bos_token` and `eos_token`.
184
+ """
185
+ bos = self.bos_token
186
+ bos_token_id = self.bos_token_id
187
+ if bos is None and self.add_bos_token:
188
+ raise ValueError("add_bos_token = True but bos_token = None")
189
+
190
+ eos = self.eos_token
191
+ eos_token_id = self.eos_token_id
192
+ if eos is None and self.add_eos_token:
193
+ raise ValueError("add_eos_token = True but eos_token = None")
194
+
195
+ single = f"{(bos+':0 ') if self.add_bos_token else ''}$A:0{(' '+eos+':0') if self.add_eos_token else ''}"
196
+ pair = f"{single}{(' '+bos+':1') if self.add_bos_token else ''} $B:1{(' '+eos+':1') if self.add_eos_token else ''}"
197
+
198
+ special_tokens = []
199
+ if self.add_bos_token:
200
+ special_tokens.append((bos, bos_token_id))
201
+ if self.add_eos_token:
202
+ special_tokens.append((eos, eos_token_id))
203
+ self._tokenizer.post_processor = processors.TemplateProcessing(
204
+ single=single, pair=pair, special_tokens=special_tokens
205
+ )
206
+
207
+ @property
208
+ def add_eos_token(self):
209
+ return self._add_eos_token
210
+
211
+ @property
212
+ def add_bos_token(self):
213
+ return self._add_bos_token
214
+
215
+ @add_eos_token.setter
216
+ def add_eos_token(self, value):
217
+ self._add_eos_token = value
218
+ self.update_post_processor()
219
+
220
+ @add_bos_token.setter
221
+ def add_bos_token(self, value):
222
+ self._add_bos_token = value
223
+ self.update_post_processor()
224
+
225
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
226
+ if not self.can_save_slow_tokenizer:
227
+ raise ValueError(
228
+ "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
229
+ "tokenizer."
230
+ )
231
+
232
+ if not os.path.isdir(save_directory):
233
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
234
+ return
235
+ out_vocab_file = os.path.join(
236
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
237
+ )
238
+
239
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
240
+ copyfile(self.vocab_file, out_vocab_file)
241
+
242
+ return (out_vocab_file,)
243
+
244
+ # TODO ArthurZ let's rely on the template processor instead, refactor all fast tokenizers
245
+ # Copied from transformers.models.llama.tokenization_llama.LlamaTokenizer.build_inputs_with_special_tokens
246
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
247
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
248
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
249
+
250
+ output = bos_token_id + token_ids_0 + eos_token_id
251
+
252
+ if token_ids_1 is not None:
253
+ output = output + bos_token_id + token_ids_1 + eos_token_id
254
+
255
+ return output
internvl/model/phi3/configuration_phi3.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Microsoft 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 atd
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
+ """ Phi-3 model configuration"""
16
+
17
+
18
+ from transformers.configuration_utils import PretrainedConfig
19
+ from transformers.utils import logging
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+ PHI3_PRETRAINED_CONFIG_ARCHIVE_MAP = {
24
+ 'microsoft/Phi-3-mini-4k-instruct': 'https://huggingface.co/microsoft/Phi-3-mini-4k-instruct/resolve/main/config.json',
25
+ 'microsoft/Phi-3-mini-128k-instruct': 'https://huggingface.co/microsoft/Phi-3-mini-128k-instruct/resolve/main/config.json',
26
+ }
27
+
28
+
29
+ class Phi3Config(PretrainedConfig):
30
+ r"""
31
+ This is the configuration class to store the configuration of a [`Phi3Model`]. It is used to instantiate a Phi-3
32
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
33
+ defaults will yield a similar configuration to that of the
34
+ [microsoft/Phi-3-mini-4k-instruct](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct).
35
+
36
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
37
+ documentation from [`PretrainedConfig`] for more information.
38
+
39
+ Args:
40
+ vocab_size (`int`, *optional*, defaults to 32064):
41
+ Vocabulary size of the Phi-3 model. Defines the number of different tokens that can be represented by the
42
+ `inputs_ids` passed when calling [`Phi3Model`].
43
+ hidden_size (`int`, *optional*, defaults to 3072):
44
+ Dimension of the hidden representations.
45
+ intermediate_size (`int`, *optional*, defaults to 8192):
46
+ Dimension of the MLP representations.
47
+ num_hidden_layers (`int`, *optional*, defaults to 32):
48
+ Number of hidden layers in the Transformer decoder.
49
+ num_attention_heads (`int`, *optional*, defaults to 32):
50
+ Number of attention heads for each attention layer in the Transformer decoder.
51
+ num_key_value_heads (`int`, *optional*):
52
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
53
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
54
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
55
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
56
+ by meanpooling all the original heads within that group. For more details checkout [this
57
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
58
+ `num_attention_heads`.
59
+ resid_pdrop (`float`, *optional*, defaults to 0.0):
60
+ Dropout probability for mlp outputs.
61
+ embd_pdrop (`int`, *optional*, defaults to 0.0):
62
+ The dropout ratio for the embeddings.
63
+ attention_dropout (`float`, *optional*, defaults to 0.0):
64
+ The dropout ratio after computing the attention scores.
65
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
66
+ The non-linear activation function (function or string) in the decoder.
67
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
68
+ The maximum sequence length that this model might ever be used with.
69
+ original_max_position_embeddings (`int`, *optional*, defaults to 4096):
70
+ The maximum sequence length that this model was trained with. This is used to determine the size of the
71
+ original RoPE embeddings when using long scaling.
72
+ initializer_range (`float`, *optional*, defaults to 0.02):
73
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
74
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
75
+ The epsilon value used for the RMSNorm.
76
+ use_cache (`bool`, *optional*, defaults to `True`):
77
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
78
+ relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
79
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
80
+ Whether to tie weight embeddings
81
+ rope_theta (`float`, *optional*, defaults to 10000.0):
82
+ The base period of the RoPE embeddings.
83
+ rope_scaling (`dict`, *optional*):
84
+ The scaling strategy for the RoPE embeddings. If `None`, no scaling is applied. If a dictionary, it must
85
+ contain the following keys: `type`, `short_factor` and `long_factor`. The `type` must be either `su` or `yarn` and
86
+ the `short_factor` and `long_factor` must be lists of numbers with the same length as the hidden size
87
+ divided by the number of attention heads divided by 2.
88
+ bos_token_id (`int`, *optional*, defaults to 1):
89
+ The id of the "beginning-of-sequence" token.
90
+ eos_token_id (`int`, *optional*, defaults to 32000):
91
+ The id of the "end-of-sequence" token.
92
+ pad_token_id (`int`, *optional*, defaults to 32000):
93
+ The id of the padding token.
94
+ sliding_window (`int`, *optional*):
95
+ Sliding window attention window size. If `None`, no sliding window is applied.
96
+
97
+ Example:
98
+
99
+ ```python
100
+ >>> from transformers import Phi3Model, Phi3Config
101
+
102
+ >>> # Initializing a Phi-3 style configuration
103
+ >>> configuration = Phi3Config.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
104
+
105
+ >>> # Initializing a model from the configuration
106
+ >>> model = Phi3Model(configuration)
107
+
108
+ >>> # Accessing the model configuration
109
+ >>> configuration = model.config
110
+ ```"""
111
+
112
+ model_type = 'phi3'
113
+ keys_to_ignore_at_inference = ['past_key_values']
114
+
115
+ def __init__(
116
+ self,
117
+ vocab_size=32064,
118
+ hidden_size=3072,
119
+ intermediate_size=8192,
120
+ num_hidden_layers=32,
121
+ num_attention_heads=32,
122
+ num_key_value_heads=None,
123
+ resid_pdrop=0.0,
124
+ embd_pdrop=0.0,
125
+ attention_dropout=0.0,
126
+ hidden_act='silu',
127
+ max_position_embeddings=4096,
128
+ original_max_position_embeddings=4096,
129
+ initializer_range=0.02,
130
+ rms_norm_eps=1e-5,
131
+ use_cache=True,
132
+ tie_word_embeddings=False,
133
+ rope_theta=10000.0,
134
+ rope_scaling=None,
135
+ bos_token_id=1,
136
+ eos_token_id=32000,
137
+ pad_token_id=32000,
138
+ sliding_window=None,
139
+ **kwargs,
140
+ ):
141
+ self.vocab_size = vocab_size
142
+ self.hidden_size = hidden_size
143
+ self.intermediate_size = intermediate_size
144
+ self.num_hidden_layers = num_hidden_layers
145
+ self.num_attention_heads = num_attention_heads
146
+
147
+ if num_key_value_heads is None:
148
+ num_key_value_heads = num_attention_heads
149
+
150
+ self.num_key_value_heads = num_key_value_heads
151
+ self.resid_pdrop = resid_pdrop
152
+ self.embd_pdrop = embd_pdrop
153
+ self.attention_dropout = attention_dropout
154
+ self.hidden_act = hidden_act
155
+ self.max_position_embeddings = max_position_embeddings
156
+ self.original_max_position_embeddings = original_max_position_embeddings
157
+ self.initializer_range = initializer_range
158
+ self.rms_norm_eps = rms_norm_eps
159
+ self.use_cache = use_cache
160
+ self.rope_theta = rope_theta
161
+ self.rope_scaling = rope_scaling
162
+ self._rope_scaling_validation()
163
+ self.sliding_window = sliding_window
164
+
165
+ super().__init__(
166
+ bos_token_id=bos_token_id,
167
+ eos_token_id=eos_token_id,
168
+ pad_token_id=pad_token_id,
169
+ tie_word_embeddings=tie_word_embeddings,
170
+ **kwargs,
171
+ )
172
+
173
+ def _rope_scaling_validation(self):
174
+ """
175
+ Validate the `rope_scaling` configuration.
176
+ """
177
+ if self.rope_scaling is None:
178
+ return
179
+
180
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 3:
181
+ raise ValueError(
182
+ '`rope_scaling` must be a dictionary with three fields, `type`, `short_factor` and `long_factor`, '
183
+ f'got {self.rope_scaling}'
184
+ )
185
+ rope_scaling_type = self.rope_scaling.get('type', None)
186
+ rope_scaling_short_factor = self.rope_scaling.get('short_factor', None)
187
+ rope_scaling_long_factor = self.rope_scaling.get('long_factor', None)
188
+ if rope_scaling_type is None or rope_scaling_type not in ['su', 'yarn']:
189
+ raise ValueError(f"`rope_scaling`'s type field must be one of ['su', 'yarn'], got {rope_scaling_type}")
190
+ if not (
191
+ isinstance(rope_scaling_short_factor, list)
192
+ and all(isinstance(x, (int, float)) for x in rope_scaling_short_factor)
193
+ ):
194
+ raise ValueError(
195
+ f"`rope_scaling`'s short_factor field must be a list of numbers, got {rope_scaling_short_factor}"
196
+ )
197
+ if not len(rope_scaling_short_factor) == self.hidden_size // self.num_attention_heads // 2:
198
+ raise ValueError(
199
+ f"`rope_scaling`'s short_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_short_factor)}"
200
+ )
201
+ if not (
202
+ isinstance(rope_scaling_long_factor, list)
203
+ and all(isinstance(x, (int, float)) for x in rope_scaling_long_factor)
204
+ ):
205
+ raise ValueError(
206
+ f"`rope_scaling`'s long_factor field must be a list of numbers, got {rope_scaling_long_factor}"
207
+ )
208
+ if not len(rope_scaling_long_factor) == self.hidden_size // self.num_attention_heads // 2:
209
+ raise ValueError(
210
+ f"`rope_scaling`'s long_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_long_factor)}"
211
+ )
internvl/model/phi3/modeling_phi3.py ADDED
@@ -0,0 +1,1601 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Microsoft 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
+ """ PyTorch Phi-3 model."""
16
+
17
+ import inspect
18
+ import math
19
+ import warnings
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.nn.functional as F
24
+ import torch.utils.checkpoint
25
+ from torch import nn
26
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
27
+ from transformers.activations import ACT2FN
28
+ from transformers.cache_utils import Cache, DynamicCache
29
+ from transformers.modeling_attn_mask_utils import \
30
+ _prepare_4d_causal_attention_mask
31
+ from transformers.modeling_outputs import (BaseModelOutputWithPast,
32
+ CausalLMOutputWithPast,
33
+ SequenceClassifierOutputWithPast,
34
+ TokenClassifierOutput)
35
+ from transformers.modeling_utils import PreTrainedModel
36
+ from transformers.utils import (add_code_sample_docstrings,
37
+ add_start_docstrings,
38
+ add_start_docstrings_to_model_forward,
39
+ is_flash_attn_2_available,
40
+ is_flash_attn_greater_or_equal_2_10, logging,
41
+ replace_return_docstrings)
42
+
43
+ from .configuration_phi3 import Phi3Config
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+ # Transformers scans dependencies in the modeling file, causing issues on conditional loading. The regex only ignores try/catch blocks, but not if statements
48
+ # if is_flash_attn_2_available():
49
+ _flash_supports_window_size = False
50
+ try:
51
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
52
+ from flash_attn.bert_padding import (index_first_axis, pad_input, # noqa
53
+ unpad_input)
54
+
55
+ _flash_supports_window_size = 'window_size' in list(inspect.signature(flash_attn_func).parameters)
56
+ except ImportError as error:
57
+ logger.warning(
58
+ f'`flash-attention` package not found, consider installing for better performance: {error}.'
59
+ )
60
+ if not _flash_supports_window_size:
61
+ logger.warning(
62
+ "Current `flash-attenton` does not support `window_size`. Either upgrade or use `attn_implementation='eager'`."
63
+ )
64
+
65
+ _CHECKPOINT_FOR_DOC = 'microsoft/Phi-3-mini-4k-instruct'
66
+ _CONFIG_FOR_DOC = 'Phi3Config'
67
+
68
+ PHI3_PRETRAINED_MODEL_ARCHIVE_LIST = [
69
+ 'microsoft/Phi-3-mini-4k-instruct',
70
+ 'microsoft/Phi-3-mini-128k-instruct',
71
+ # See all Phi-3 models at https://huggingface.co/models?filter=Phi-3
72
+ ]
73
+
74
+
75
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Phi3
76
+ class Phi3RMSNorm(nn.Module):
77
+ def __init__(self, hidden_size, eps=1e-6):
78
+ """
79
+ Phi3RMSNorm is equivalent to T5LayerNorm
80
+ """
81
+ super().__init__()
82
+ self.weight = nn.Parameter(torch.ones(hidden_size))
83
+ self.variance_epsilon = eps
84
+
85
+ def forward(self, hidden_states):
86
+ input_dtype = hidden_states.dtype
87
+ hidden_states = hidden_states.to(torch.float32)
88
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
89
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
90
+ return self.weight * hidden_states.to(input_dtype)
91
+
92
+
93
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
94
+ def _get_unpad_data(attention_mask):
95
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
96
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
97
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
98
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
99
+ return (
100
+ indices,
101
+ cu_seqlens,
102
+ max_seqlen_in_batch,
103
+ )
104
+
105
+
106
+ # Copied from transformers.models.gemma.modeling_gemma.GemmaRotaryEmbedding with gemma->phi3, Gemma->Phi3
107
+ class Phi3RotaryEmbedding(nn.Module):
108
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
109
+ super().__init__()
110
+
111
+ self.dim = dim
112
+ self.max_position_embeddings = max_position_embeddings
113
+ self.base = base
114
+ self.register_buffer('inv_freq', None, persistent=False)
115
+
116
+ @torch.no_grad()
117
+ def forward(self, x, position_ids, seq_len=None):
118
+ # x: [bs, num_attention_heads, seq_len, head_size]
119
+ if self.inv_freq is None:
120
+ self.inv_freq = 1.0 / (
121
+ self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim)
122
+ )
123
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
124
+ position_ids_expanded = position_ids[:, None, :].float()
125
+ # Force float32 since bfloat16 loses precision on long contexts
126
+ # See https://github.com/huggingface/transformers/pull/29285
127
+ device_type = x.device.type
128
+ device_type = device_type if isinstance(device_type, str) and device_type != 'mps' else 'cpu'
129
+ with torch.autocast(device_type=device_type, enabled=False):
130
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
131
+ emb = torch.cat((freqs, freqs), dim=-1)
132
+ cos = emb.cos()
133
+ sin = emb.sin()
134
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
135
+
136
+
137
+ class Phi3SuScaledRotaryEmbedding(Phi3RotaryEmbedding):
138
+ def __init__(self, dim, config, device=None):
139
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
140
+
141
+ self.short_factor = config.rope_scaling['short_factor']
142
+ self.long_factor = config.rope_scaling['long_factor']
143
+ self.original_max_position_embeddings = config.original_max_position_embeddings
144
+
145
+ @torch.no_grad()
146
+ def forward(self, x, position_ids, seq_len=None):
147
+ seq_len = torch.max(position_ids) + 1
148
+ if seq_len > self.original_max_position_embeddings:
149
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
150
+ else:
151
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
152
+
153
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
154
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
155
+
156
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
157
+ position_ids_expanded = position_ids[:, None, :].float()
158
+
159
+ # Force float32 since bfloat16 loses precision on long contexts
160
+ # See https://github.com/huggingface/transformers/pull/29285
161
+ device_type = x.device.type
162
+ device_type = device_type if isinstance(device_type, str) and device_type != 'mps' else 'cpu'
163
+ with torch.autocast(device_type=device_type, enabled=False):
164
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
165
+ emb = torch.cat((freqs, freqs), dim=-1)
166
+
167
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
168
+ if scale <= 1.0:
169
+ scaling_factor = 1.0
170
+ else:
171
+ scaling_factor = math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
172
+
173
+ cos = emb.cos() * scaling_factor
174
+ sin = emb.sin() * scaling_factor
175
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
176
+
177
+
178
+ class Phi3YarnScaledRotaryEmbedding(Phi3RotaryEmbedding):
179
+ def __init__(self, dim, config, device=None):
180
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
181
+
182
+ self.short_factor = config.rope_scaling['short_factor']
183
+ self.long_factor = config.rope_scaling['long_factor']
184
+ self.original_max_position_embeddings = config.original_max_position_embeddings
185
+
186
+ @torch.no_grad()
187
+ def forward(self, x, position_ids, seq_len=None):
188
+ seq_len = torch.max(position_ids) + 1
189
+ if seq_len > self.original_max_position_embeddings:
190
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
191
+ else:
192
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
193
+
194
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
195
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
196
+
197
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
198
+ position_ids_expanded = position_ids[:, None, :].float()
199
+
200
+ # Force float32 since bfloat16 loses precision on long contexts
201
+ # See https://github.com/huggingface/transformers/pull/29285
202
+ device_type = x.device.type
203
+ device_type = device_type if isinstance(device_type, str) and device_type != 'mps' else 'cpu'
204
+ with torch.autocast(device_type=device_type, enabled=False):
205
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
206
+ emb = torch.cat((freqs, freqs), dim=-1)
207
+
208
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
209
+ if scale <= 1.0:
210
+ scaling_factor = 1.0
211
+ else:
212
+ scaling_factor = 0.1 * math.log(scale) + 1.0
213
+
214
+ cos = emb.cos() * scaling_factor
215
+ sin = emb.sin() * scaling_factor
216
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
217
+
218
+
219
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
220
+ def rotate_half(x):
221
+ """Rotates half the hidden dims of the input."""
222
+ x1 = x[..., : x.shape[-1] // 2]
223
+ x2 = x[..., x.shape[-1] // 2 :]
224
+ return torch.cat((-x2, x1), dim=-1)
225
+
226
+
227
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
228
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
229
+ """Applies Rotary Position Embedding to the query and key tensors.
230
+
231
+ Args:
232
+ q (`torch.Tensor`): The query tensor.
233
+ k (`torch.Tensor`): The key tensor.
234
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
235
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
236
+ position_ids (`torch.Tensor`, *optional*):
237
+ Deprecated and unused.
238
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
239
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
240
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
241
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
242
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
243
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
244
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
245
+ Returns:
246
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
247
+ """
248
+ cos = cos.unsqueeze(unsqueeze_dim)
249
+ sin = sin.unsqueeze(unsqueeze_dim)
250
+ q_embed = (q * cos) + (rotate_half(q) * sin)
251
+ k_embed = (k * cos) + (rotate_half(k) * sin)
252
+ return q_embed, k_embed
253
+
254
+
255
+ class Phi3MLP(nn.Module):
256
+ def __init__(self, config):
257
+ super().__init__()
258
+
259
+ self.config = config
260
+ self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
261
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
262
+
263
+ self.activation_fn = ACT2FN[config.hidden_act]
264
+
265
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
266
+ up_states = self.gate_up_proj(hidden_states)
267
+
268
+ gate, up_states = up_states.chunk(2, dim=-1)
269
+ up_states = up_states * self.activation_fn(gate)
270
+
271
+ return self.down_proj(up_states)
272
+
273
+
274
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
275
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
276
+ """
277
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
278
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
279
+ """
280
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
281
+ if n_rep == 1:
282
+ return hidden_states
283
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
284
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
285
+
286
+
287
+ class Phi3Attention(nn.Module):
288
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
289
+
290
+ def __init__(self, config: Phi3Config, layer_idx: Optional[int] = None):
291
+ super().__init__()
292
+ self.config = config
293
+ self.layer_idx = layer_idx
294
+ if layer_idx is None:
295
+ logger.warning_once(
296
+ f'Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will '
297
+ 'lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` '
298
+ 'when creating this class.'
299
+ )
300
+
301
+ self.attention_dropout = config.attention_dropout
302
+ self.hidden_size = config.hidden_size
303
+ self.num_heads = config.num_attention_heads
304
+ self.head_dim = self.hidden_size // self.num_heads
305
+ self.num_key_value_heads = config.num_key_value_heads
306
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
307
+ self.max_position_embeddings = config.max_position_embeddings
308
+ self.original_max_position_embeddings = config.original_max_position_embeddings
309
+ self.rope_theta = config.rope_theta
310
+ self.rope_scaling = config.rope_scaling
311
+ self.is_causal = True
312
+
313
+ if (self.head_dim * self.num_heads) != self.hidden_size:
314
+ raise ValueError(
315
+ f'hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}'
316
+ f' and `num_heads`: {self.num_heads}).'
317
+ )
318
+
319
+ op_size = self.num_heads * self.head_dim + 2 * (self.num_key_value_heads * self.head_dim)
320
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
321
+ self.qkv_proj = nn.Linear(self.hidden_size, op_size, bias=False)
322
+ self._init_rope()
323
+
324
+ def _init_rope(self):
325
+ if self.rope_scaling is None:
326
+ self.rotary_emb = Phi3RotaryEmbedding(
327
+ self.head_dim,
328
+ max_position_embeddings=self.max_position_embeddings,
329
+ base=self.rope_theta,
330
+ )
331
+ else:
332
+ scaling_type = self.config.rope_scaling['type']
333
+ if scaling_type == 'su':
334
+ self.rotary_emb = Phi3SuScaledRotaryEmbedding(self.head_dim, self.config)
335
+ elif scaling_type == 'yarn':
336
+ self.rotary_emb = Phi3YarnScaledRotaryEmbedding(self.head_dim, self.config)
337
+ else:
338
+ raise ValueError(f'Unknown RoPE scaling type {scaling_type}')
339
+
340
+ def forward(
341
+ self,
342
+ hidden_states: torch.Tensor,
343
+ attention_mask: Optional[torch.Tensor] = None,
344
+ position_ids: Optional[torch.LongTensor] = None,
345
+ past_key_value: Optional[Cache] = None,
346
+ output_attentions: bool = False,
347
+ use_cache: bool = False,
348
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
349
+ logger.warning_once('You are not running the flash-attention implementation, expect numerical differences.')
350
+
351
+ bsz, q_len, _ = hidden_states.size()
352
+
353
+ qkv = self.qkv_proj(hidden_states)
354
+ query_pos = self.num_heads * self.head_dim
355
+ query_states = qkv[..., :query_pos]
356
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
357
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
358
+
359
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
360
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
361
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
362
+
363
+ kv_seq_len = key_states.shape[-2]
364
+ if past_key_value is not None:
365
+ if self.layer_idx is None:
366
+ raise ValueError(
367
+ f'The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} '
368
+ 'for auto-regressive decoding with k/v caching, please make sure to initialize the attention class '
369
+ 'with a layer index.'
370
+ )
371
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
372
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
373
+
374
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
375
+
376
+ if past_key_value is not None:
377
+ cache_kwargs = {'sin': sin, 'cos': cos} # Specific to RoPE models
378
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
379
+
380
+ # repeat k/v heads if n_kv_heads < n_heads
381
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
382
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
383
+
384
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
385
+
386
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
387
+ raise ValueError(
388
+ f'Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is'
389
+ f' {attn_weights.size()}'
390
+ )
391
+
392
+ if attention_mask is not None:
393
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
394
+ raise ValueError(
395
+ f'Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}'
396
+ )
397
+ attn_weights = attn_weights + attention_mask
398
+
399
+ # upcast attention to fp32
400
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
401
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
402
+
403
+ attn_output = torch.matmul(attn_weights, value_states)
404
+
405
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
406
+ raise ValueError(
407
+ f'`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is'
408
+ f' {attn_output.size()}'
409
+ )
410
+
411
+ attn_output = attn_output.transpose(1, 2).contiguous()
412
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
413
+
414
+ attn_output = self.o_proj(attn_output)
415
+
416
+ if not output_attentions:
417
+ attn_weights = None
418
+
419
+ return attn_output, attn_weights, past_key_value
420
+
421
+
422
+ class Phi3FlashAttention2(Phi3Attention):
423
+ """
424
+ Phi-3 flash attention module. This module inherits from `Phi3Attention` as the weights of the module stays
425
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
426
+ flash attention and deal with padding tokens in case the input contains any of them.
427
+ """
428
+
429
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
430
+ def __init__(self, *args, **kwargs):
431
+ super().__init__(*args, **kwargs)
432
+
433
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
434
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
435
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
436
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
437
+
438
+ def forward(
439
+ self,
440
+ hidden_states: torch.Tensor,
441
+ attention_mask: Optional[torch.LongTensor] = None,
442
+ position_ids: Optional[torch.LongTensor] = None,
443
+ past_key_value: Optional[Cache] = None,
444
+ output_attentions: bool = False,
445
+ use_cache: bool = False,
446
+ **kwargs,
447
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
448
+ # Phi3FlashAttention2 attention does not support output_attentions
449
+
450
+ if not _flash_supports_window_size:
451
+ logger.warning_once(
452
+ "The current flash attention version does not support sliding window attention. Please use `attn_implementation='eager'` or upgrade flash-attn library."
453
+ )
454
+ raise ValueError('The current flash attention version does not support sliding window attention.')
455
+
456
+ output_attentions = False
457
+
458
+ if 'padding_mask' in kwargs:
459
+ warnings.warn(
460
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`'
461
+ )
462
+
463
+ # overwrite attention_mask with padding_mask
464
+ attention_mask = kwargs.pop('padding_mask')
465
+
466
+ bsz, q_len, _ = hidden_states.size()
467
+
468
+ qkv = self.qkv_proj(hidden_states)
469
+ query_pos = self.num_heads * self.head_dim
470
+ query_states = qkv[..., :query_pos]
471
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
472
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
473
+
474
+ # Flash attention requires the input to have the shape
475
+ # batch_size x seq_length x head_dim x hidden_dim
476
+ # therefore we just need to keep the original shape
477
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
478
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
479
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
480
+
481
+ kv_seq_len = key_states.shape[-2]
482
+ if past_key_value is not None:
483
+ if self.layer_idx is None:
484
+ raise ValueError(
485
+ f'The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} '
486
+ 'for auto-regressive decoding with k/v caching, please make sure to initialize the attention class '
487
+ 'with a layer index.'
488
+ )
489
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
490
+
491
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
492
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
493
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=rotary_seq_len)
494
+
495
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
496
+
497
+ use_sliding_windows = (
498
+ _flash_supports_window_size
499
+ and getattr(self.config, 'sliding_window', None) is not None
500
+ and kv_seq_len > self.config.sliding_window
501
+ )
502
+
503
+ if past_key_value is not None:
504
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
505
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
506
+ if (
507
+ getattr(self.config, 'sliding_window', None) is not None
508
+ and kv_seq_len > self.config.sliding_window
509
+ and cache_has_contents
510
+ ):
511
+ slicing_tokens = 1 - self.config.sliding_window
512
+
513
+ past_key = past_key_value[self.layer_idx][0]
514
+ past_value = past_key_value[self.layer_idx][1]
515
+
516
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
517
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
518
+
519
+ if past_key.shape[-2] != self.config.sliding_window - 1:
520
+ raise ValueError(
521
+ f'past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got'
522
+ f' {past_key.shape}'
523
+ )
524
+
525
+ if attention_mask is not None:
526
+ attention_mask = attention_mask[:, slicing_tokens:]
527
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
528
+
529
+ cache_kwargs = {'sin': sin, 'cos': cos} # Specific to RoPE models
530
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
531
+
532
+ # repeat k/v heads if n_kv_heads < n_heads
533
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
534
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
535
+
536
+ attn_dropout = self.attention_dropout if self.training else 0.0
537
+
538
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
539
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
540
+ # cast them back in the correct dtype just to be sure everything works as expected.
541
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
542
+ # in fp32.
543
+
544
+ if query_states.dtype == torch.float32:
545
+ if torch.is_autocast_enabled():
546
+ target_dtype = torch.get_autocast_gpu_dtype()
547
+ # Handle the case where the model is quantized
548
+ elif hasattr(self.config, '_pre_quantization_dtype'):
549
+ target_dtype = self.config._pre_quantization_dtype
550
+ else:
551
+ target_dtype = self.qkv_proj.weight.dtype
552
+
553
+ logger.warning_once(
554
+ f'The input hidden states seems to be silently casted in float32, this might be related to'
555
+ f' the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in'
556
+ f' {target_dtype}.'
557
+ )
558
+
559
+ query_states = query_states.to(target_dtype)
560
+ key_states = key_states.to(target_dtype)
561
+ value_states = value_states.to(target_dtype)
562
+
563
+ # Reashape to the expected shape for Flash Attention
564
+ query_states = query_states.transpose(1, 2)
565
+ key_states = key_states.transpose(1, 2)
566
+ value_states = value_states.transpose(1, 2)
567
+
568
+ attn_output = self._flash_attention_forward(
569
+ query_states,
570
+ key_states,
571
+ value_states,
572
+ attention_mask,
573
+ q_len,
574
+ dropout=attn_dropout,
575
+ use_sliding_windows=use_sliding_windows,
576
+ )
577
+
578
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
579
+ attn_output = self.o_proj(attn_output)
580
+
581
+ if not output_attentions:
582
+ attn_weights = None
583
+
584
+ return attn_output, attn_weights, past_key_value
585
+
586
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._flash_attention_forward
587
+ def _flash_attention_forward(
588
+ self,
589
+ query_states,
590
+ key_states,
591
+ value_states,
592
+ attention_mask,
593
+ query_length,
594
+ dropout=0.0,
595
+ softmax_scale=None,
596
+ use_sliding_windows=False,
597
+ ):
598
+ """
599
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
600
+ first unpad the input, then computes the attention scores and pad the final attention scores.
601
+
602
+ Args:
603
+ query_states (`torch.Tensor`):
604
+ Input query states to be passed to Flash Attention API
605
+ key_states (`torch.Tensor`):
606
+ Input key states to be passed to Flash Attention API
607
+ value_states (`torch.Tensor`):
608
+ Input value states to be passed to Flash Attention API
609
+ attention_mask (`torch.Tensor`):
610
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
611
+ position of padding tokens and 1 for the position of non-padding tokens.
612
+ dropout (`float`):
613
+ Attention dropout
614
+ softmax_scale (`float`, *optional*):
615
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
616
+ use_sliding_windows (`bool`, *optional*):
617
+ Whether to activate sliding window attention.
618
+ """
619
+ if not self._flash_attn_uses_top_left_mask:
620
+ causal = self.is_causal
621
+ else:
622
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
623
+ causal = self.is_causal and query_length != 1
624
+
625
+ # Contains at least one padding token in the sequence
626
+ if attention_mask is not None:
627
+ batch_size = query_states.shape[0]
628
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
629
+ query_states, key_states, value_states, attention_mask, query_length
630
+ )
631
+
632
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
633
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
634
+
635
+ if not use_sliding_windows:
636
+ attn_output_unpad = flash_attn_varlen_func(
637
+ query_states,
638
+ key_states,
639
+ value_states,
640
+ cu_seqlens_q=cu_seqlens_q,
641
+ cu_seqlens_k=cu_seqlens_k,
642
+ max_seqlen_q=max_seqlen_in_batch_q,
643
+ max_seqlen_k=max_seqlen_in_batch_k,
644
+ dropout_p=dropout,
645
+ softmax_scale=softmax_scale,
646
+ causal=causal,
647
+ )
648
+ else:
649
+ attn_output_unpad = flash_attn_varlen_func(
650
+ query_states,
651
+ key_states,
652
+ value_states,
653
+ cu_seqlens_q=cu_seqlens_q,
654
+ cu_seqlens_k=cu_seqlens_k,
655
+ max_seqlen_q=max_seqlen_in_batch_q,
656
+ max_seqlen_k=max_seqlen_in_batch_k,
657
+ dropout_p=dropout,
658
+ softmax_scale=softmax_scale,
659
+ causal=causal,
660
+ window_size=(self.config.sliding_window, self.config.sliding_window),
661
+ )
662
+
663
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
664
+ else:
665
+ if not use_sliding_windows:
666
+ attn_output = flash_attn_func(
667
+ query_states,
668
+ key_states,
669
+ value_states,
670
+ dropout,
671
+ softmax_scale=softmax_scale,
672
+ causal=causal,
673
+ )
674
+ else:
675
+ attn_output = flash_attn_func(
676
+ query_states,
677
+ key_states,
678
+ value_states,
679
+ dropout,
680
+ softmax_scale=softmax_scale,
681
+ causal=causal,
682
+ window_size=(self.config.sliding_window, self.config.sliding_window),
683
+ )
684
+
685
+ return attn_output
686
+
687
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
688
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
689
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
690
+
691
+ # On the first iteration we need to properly re-create the padding mask
692
+ # by slicing it on the proper place
693
+ if kv_seq_len != attention_mask.shape[-1]:
694
+ attention_mask_num_tokens = attention_mask.shape[-1]
695
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
696
+
697
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
698
+
699
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
700
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
701
+
702
+ if query_length == kv_seq_len:
703
+ query_layer = index_first_axis(
704
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
705
+ )
706
+ cu_seqlens_q = cu_seqlens_k
707
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
708
+ indices_q = indices_k
709
+ elif query_length == 1:
710
+ max_seqlen_in_batch_q = 1
711
+ cu_seqlens_q = torch.arange(
712
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
713
+ ) # There is a memcpy here, that is very bad.
714
+ indices_q = cu_seqlens_q[:-1]
715
+ query_layer = query_layer.squeeze(1)
716
+ else:
717
+ # The -q_len: slice assumes left padding.
718
+ attention_mask = attention_mask[:, -query_length:]
719
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
720
+
721
+ return (
722
+ query_layer,
723
+ key_layer,
724
+ value_layer,
725
+ indices_q,
726
+ (cu_seqlens_q, cu_seqlens_k),
727
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
728
+ )
729
+
730
+
731
+ # copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Phi3
732
+ # TODO @Arthur no longer copied from LLama after static cache
733
+ class Phi3SdpaAttention(Phi3Attention):
734
+ """
735
+ Phi3 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
736
+ `Phi3Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
737
+ SDPA API.
738
+ """
739
+
740
+ # Adapted from Phi3Attention.forward
741
+ def forward(
742
+ self,
743
+ hidden_states: torch.Tensor,
744
+ attention_mask: Optional[torch.Tensor] = None,
745
+ position_ids: Optional[torch.LongTensor] = None,
746
+ past_key_value: Optional[Cache] = None,
747
+ output_attentions: bool = False,
748
+ use_cache: bool = False,
749
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
750
+ if output_attentions:
751
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
752
+ logger.warning_once(
753
+ 'Phi3Model is using Phi3SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, '
754
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
755
+ )
756
+ return super().forward(
757
+ hidden_states=hidden_states,
758
+ attention_mask=attention_mask,
759
+ position_ids=position_ids,
760
+ past_key_value=past_key_value,
761
+ output_attentions=output_attentions,
762
+ use_cache=use_cache,
763
+ )
764
+
765
+ bsz, q_len, _ = hidden_states.size()
766
+
767
+ qkv = self.qkv_proj(hidden_states)
768
+ query_pos = self.num_heads * self.head_dim
769
+ query_states = qkv[..., :query_pos]
770
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
771
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
772
+
773
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
774
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
775
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
776
+
777
+ kv_seq_len = key_states.shape[-2]
778
+ if past_key_value is not None:
779
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
780
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
781
+
782
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
783
+
784
+ if past_key_value is not None:
785
+ cache_kwargs = {'sin': sin, 'cos': cos} # Specific to RoPE models
786
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
787
+
788
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
789
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
790
+
791
+ if attention_mask is not None:
792
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
793
+ raise ValueError(
794
+ f'Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}'
795
+ )
796
+
797
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
798
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
799
+ if query_states.device.type == 'cuda' and attention_mask is not None:
800
+ query_states = query_states.contiguous()
801
+ key_states = key_states.contiguous()
802
+ value_states = value_states.contiguous()
803
+
804
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
805
+ query_states,
806
+ key_states,
807
+ value_states,
808
+ attn_mask=attention_mask,
809
+ dropout_p=self.attention_dropout if self.training else 0.0,
810
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
811
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
812
+ )
813
+
814
+ attn_output = attn_output.transpose(1, 2).contiguous()
815
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
816
+
817
+ attn_output = self.o_proj(attn_output)
818
+
819
+ return attn_output, None, past_key_value
820
+
821
+
822
+ PHI3_ATTENTION_CLASSES = {
823
+ 'eager': Phi3Attention,
824
+ 'flash_attention_2': Phi3FlashAttention2,
825
+ 'sdpa': Phi3SdpaAttention,
826
+ }
827
+
828
+
829
+ class Phi3DecoderLayer(nn.Module):
830
+ def __init__(self, config: Phi3Config, layer_idx: int):
831
+ super().__init__()
832
+
833
+ self.config = config
834
+ self.self_attn = PHI3_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
835
+
836
+ self.mlp = Phi3MLP(config)
837
+ self.input_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
838
+
839
+ self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)
840
+ self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)
841
+ self.post_attention_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
842
+
843
+ def forward(
844
+ self,
845
+ hidden_states: torch.Tensor,
846
+ attention_mask: Optional[torch.Tensor] = None,
847
+ position_ids: Optional[torch.LongTensor] = None,
848
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
849
+ output_attentions: Optional[bool] = False,
850
+ use_cache: Optional[bool] = False,
851
+ **kwargs,
852
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
853
+ if 'padding_mask' in kwargs:
854
+ warnings.warn(
855
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`'
856
+ )
857
+ """
858
+ Args:
859
+ hidden_states (`torch.FloatTensor`):
860
+ input to the layer of shape `(batch, seq_len, embed_dim)`
861
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
862
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
863
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
864
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
865
+ `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
866
+ output_attentions (`bool`, *optional*):
867
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
868
+ returned tensors for more detail.
869
+ use_cache (`bool`, *optional*):
870
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
871
+ (see `past_key_values`).
872
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
873
+ """
874
+
875
+ residual = hidden_states
876
+
877
+ hidden_states = self.input_layernorm(hidden_states)
878
+
879
+ # Self Attention
880
+ attn_outputs, self_attn_weights, present_key_value = self.self_attn(
881
+ hidden_states=hidden_states,
882
+ attention_mask=attention_mask,
883
+ position_ids=position_ids,
884
+ past_key_value=past_key_value,
885
+ output_attentions=output_attentions,
886
+ use_cache=use_cache,
887
+ )
888
+
889
+ hidden_states = residual + self.resid_attn_dropout(attn_outputs)
890
+
891
+ residual = hidden_states
892
+ hidden_states = self.post_attention_layernorm(hidden_states)
893
+ hidden_states = self.mlp(hidden_states)
894
+ hidden_states = residual + self.resid_mlp_dropout(hidden_states)
895
+
896
+ outputs = (hidden_states,)
897
+
898
+ if output_attentions:
899
+ outputs += (self_attn_weights,)
900
+
901
+ if use_cache:
902
+ outputs += (present_key_value,)
903
+
904
+ return outputs
905
+
906
+
907
+ PHI3_START_DOCSTRING = r"""
908
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
909
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
910
+ etc.)
911
+
912
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
913
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
914
+ and behavior.
915
+
916
+ Parameters:
917
+ config ([`Phi3Config`]):
918
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
919
+ load the weights associated with the model, only the configuration. Check out the
920
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
921
+ """
922
+
923
+
924
+ @add_start_docstrings(
925
+ 'The bare Phi-3 model outputting raw hidden-states without any specific head on top.',
926
+ PHI3_START_DOCSTRING,
927
+ )
928
+ class Phi3PreTrainedModel(PreTrainedModel):
929
+ config_class = Phi3Config
930
+ base_model_prefix = 'model'
931
+ supports_gradient_checkpointing = True
932
+ _no_split_modules = ['Phi3DecoderLayer']
933
+ _skip_keys_device_placement = 'past_key_values'
934
+ _supports_flash_attn_2 = True
935
+ _supports_sdpa = False
936
+ _supports_cache_class = True
937
+
938
+ _version = '0.0.5'
939
+
940
+ def _init_weights(self, module):
941
+ std = self.config.initializer_range
942
+ if isinstance(module, nn.Linear):
943
+ module.weight.data.normal_(mean=0.0, std=std)
944
+ if module.bias is not None:
945
+ module.bias.data.zero_()
946
+ elif isinstance(module, nn.Embedding):
947
+ module.weight.data.normal_(mean=0.0, std=std)
948
+ if module.padding_idx is not None:
949
+ module.weight.data[module.padding_idx].zero_()
950
+
951
+
952
+ PHI3_INPUTS_DOCSTRING = r"""
953
+ Args:
954
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
955
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
956
+ it.
957
+
958
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
959
+ [`PreTrainedTokenizer.__call__`] for details.
960
+
961
+ [What are input IDs?](../glossary#input-ids)
962
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
963
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
964
+
965
+ - 1 for tokens that are **not masked**,
966
+ - 0 for tokens that are **masked**.
967
+
968
+ [What are attention masks?](../glossary#attention-mask)
969
+
970
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
971
+ [`PreTrainedTokenizer.__call__`] for details.
972
+
973
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
974
+ `past_key_values`).
975
+
976
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
977
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
978
+ information on the default strategy.
979
+
980
+ - 1 indicates the head is **not masked**,
981
+ - 0 indicates the head is **masked**.
982
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
983
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
984
+ config.n_positions - 1]`.
985
+
986
+ [What are position IDs?](../glossary#position-ids)
987
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
988
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
989
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
990
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
991
+
992
+ Two formats are allowed:
993
+ - a [`~cache_utils.Cache`] instance;
994
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
995
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
996
+ cache format.
997
+
998
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
999
+ legacy cache format will be returned.
1000
+
1001
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1002
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1003
+ of shape `(batch_size, sequence_length)`.
1004
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1005
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1006
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1007
+ model's internal embedding lookup matrix.
1008
+ use_cache (`bool`, *optional*):
1009
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1010
+ `past_key_values`).
1011
+ output_attentions (`bool`, *optional*):
1012
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1013
+ tensors for more detail.
1014
+ output_hidden_states (`bool`, *optional*):
1015
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1016
+ more detail.
1017
+ return_dict (`bool`, *optional*):
1018
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1019
+ """
1020
+
1021
+
1022
+ @add_start_docstrings(
1023
+ 'The bare Phi-3 model outputting raw hidden-states without any specific head on top.',
1024
+ PHI3_START_DOCSTRING,
1025
+ )
1026
+ class Phi3Model(Phi3PreTrainedModel):
1027
+ """
1028
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Phi3DecoderLayer`]
1029
+
1030
+ Args:
1031
+ config: Phi3Config
1032
+ """
1033
+
1034
+ def __init__(self, config: Phi3Config):
1035
+ super().__init__(config)
1036
+ self.padding_idx = config.pad_token_id
1037
+ self.vocab_size = config.vocab_size
1038
+
1039
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1040
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
1041
+ self.layers = nn.ModuleList(
1042
+ [Phi3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1043
+ )
1044
+ self._attn_implementation = config._attn_implementation
1045
+ self.norm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1046
+
1047
+ self.gradient_checkpointing = False
1048
+ # Initialize weights and apply final processing
1049
+ self.post_init()
1050
+
1051
+ def get_input_embeddings(self):
1052
+ return self.embed_tokens
1053
+
1054
+ def set_input_embeddings(self, value):
1055
+ self.embed_tokens = value
1056
+
1057
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1058
+ def forward(
1059
+ self,
1060
+ input_ids: torch.LongTensor = None,
1061
+ attention_mask: Optional[torch.Tensor] = None,
1062
+ position_ids: Optional[torch.LongTensor] = None,
1063
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1064
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1065
+ use_cache: Optional[bool] = None,
1066
+ output_attentions: Optional[bool] = None,
1067
+ output_hidden_states: Optional[bool] = None,
1068
+ return_dict: Optional[bool] = None,
1069
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1070
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1071
+ output_hidden_states = (
1072
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1073
+ )
1074
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1075
+
1076
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1077
+
1078
+ # retrieve input_ids and inputs_embeds
1079
+ if input_ids is not None and inputs_embeds is not None:
1080
+ raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time')
1081
+ elif input_ids is not None:
1082
+ batch_size, seq_length = input_ids.shape[:2]
1083
+ elif inputs_embeds is not None:
1084
+ batch_size, seq_length = inputs_embeds.shape[:2]
1085
+ else:
1086
+ raise ValueError('You have to specify either input_ids or inputs_embeds')
1087
+
1088
+ past_key_values_length = 0
1089
+
1090
+ if self.gradient_checkpointing and self.training:
1091
+ if use_cache:
1092
+ logger.warning_once(
1093
+ '`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...'
1094
+ )
1095
+ use_cache = False
1096
+
1097
+ if use_cache:
1098
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1099
+ if use_legacy_cache:
1100
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1101
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1102
+
1103
+ if position_ids is None:
1104
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1105
+ position_ids = torch.arange(
1106
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1107
+ )
1108
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1109
+ else:
1110
+ position_ids = position_ids.view(-1, seq_length).long()
1111
+
1112
+ if inputs_embeds is None:
1113
+ inputs_embeds = self.embed_tokens(input_ids)
1114
+
1115
+ if attention_mask is not None and self._attn_implementation == 'flash_attention_2' and use_cache:
1116
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1117
+ if is_padding_right:
1118
+ raise ValueError(
1119
+ "You are attempting to perform batched generation with padding_side='right'"
1120
+ ' this may lead to unexpected behaviour for Flash Attention version of Phi3. Make sure to '
1121
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1122
+ )
1123
+
1124
+ if self._attn_implementation == 'flash_attention_2':
1125
+ # 2d mask is passed through the layers
1126
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1127
+ else:
1128
+ # 4d mask is passed through the layers
1129
+ attention_mask = _prepare_4d_causal_attention_mask(
1130
+ attention_mask,
1131
+ (batch_size, seq_length),
1132
+ inputs_embeds,
1133
+ past_key_values_length,
1134
+ sliding_window=self.config.sliding_window,
1135
+ )
1136
+
1137
+ hidden_states = inputs_embeds
1138
+
1139
+ # decoder layers
1140
+ all_hidden_states = () if output_hidden_states else None
1141
+ all_self_attns = () if output_attentions else None
1142
+ next_decoder_cache = None
1143
+
1144
+ for decoder_layer in self.layers:
1145
+ if output_hidden_states:
1146
+ all_hidden_states += (hidden_states,)
1147
+
1148
+ if self.gradient_checkpointing and self.training:
1149
+ layer_outputs = self._gradient_checkpointing_func(
1150
+ decoder_layer.__call__,
1151
+ hidden_states,
1152
+ attention_mask,
1153
+ position_ids,
1154
+ past_key_values,
1155
+ output_attentions,
1156
+ use_cache,
1157
+ )
1158
+ else:
1159
+ layer_outputs = decoder_layer(
1160
+ hidden_states,
1161
+ attention_mask=attention_mask,
1162
+ position_ids=position_ids,
1163
+ past_key_value=past_key_values,
1164
+ output_attentions=output_attentions,
1165
+ use_cache=use_cache,
1166
+ )
1167
+
1168
+ hidden_states = layer_outputs[0]
1169
+
1170
+ if use_cache:
1171
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1172
+
1173
+ if output_attentions:
1174
+ all_self_attns += (layer_outputs[1],)
1175
+
1176
+ hidden_states = self.norm(hidden_states)
1177
+
1178
+ # add hidden states from the last decoder layer
1179
+ if output_hidden_states:
1180
+ all_hidden_states += (hidden_states,)
1181
+
1182
+ next_cache = None
1183
+ if use_cache:
1184
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1185
+ if not return_dict:
1186
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1187
+ return BaseModelOutputWithPast(
1188
+ last_hidden_state=hidden_states,
1189
+ past_key_values=next_cache,
1190
+ hidden_states=all_hidden_states,
1191
+ attentions=all_self_attns,
1192
+ )
1193
+
1194
+
1195
+ class Phi3ForCausalLM(Phi3PreTrainedModel):
1196
+ _tied_weights_keys = ['lm_head.weight']
1197
+
1198
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi3
1199
+ def __init__(self, config):
1200
+ super().__init__(config)
1201
+ self.model = Phi3Model(config)
1202
+ self.vocab_size = config.vocab_size
1203
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1204
+
1205
+ # Initialize weights and apply final processing
1206
+ self.post_init()
1207
+
1208
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
1209
+ def get_input_embeddings(self):
1210
+ return self.model.embed_tokens
1211
+
1212
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
1213
+ def set_input_embeddings(self, value):
1214
+ self.model.embed_tokens = value
1215
+
1216
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
1217
+ def get_output_embeddings(self):
1218
+ return self.lm_head
1219
+
1220
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
1221
+ def set_output_embeddings(self, new_embeddings):
1222
+ self.lm_head = new_embeddings
1223
+
1224
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
1225
+ def set_decoder(self, decoder):
1226
+ self.model = decoder
1227
+
1228
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
1229
+ def get_decoder(self):
1230
+ return self.model
1231
+
1232
+ # Ignore copy
1233
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1234
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1235
+ def forward(
1236
+ self,
1237
+ input_ids: torch.LongTensor = None,
1238
+ attention_mask: Optional[torch.Tensor] = None,
1239
+ position_ids: Optional[torch.LongTensor] = None,
1240
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1241
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1242
+ labels: Optional[torch.LongTensor] = None,
1243
+ use_cache: Optional[bool] = None,
1244
+ output_attentions: Optional[bool] = None,
1245
+ output_hidden_states: Optional[bool] = None,
1246
+ return_dict: Optional[bool] = None,
1247
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1248
+ r"""
1249
+ Args:
1250
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1251
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1252
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1253
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1254
+
1255
+ Returns:
1256
+
1257
+ Example:
1258
+
1259
+ ```python
1260
+ >>> from transformers import AutoTokenizer, Phi3ForCausalLM
1261
+
1262
+ >>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1263
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1264
+
1265
+ >>> prompt = "This is an example script ."
1266
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1267
+
1268
+ >>> # Generate
1269
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1270
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1271
+ 'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
1272
+ ```"""
1273
+
1274
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1275
+ output_hidden_states = (
1276
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1277
+ )
1278
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1279
+
1280
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1281
+ outputs = self.model(
1282
+ input_ids=input_ids,
1283
+ attention_mask=attention_mask,
1284
+ position_ids=position_ids,
1285
+ past_key_values=past_key_values,
1286
+ inputs_embeds=inputs_embeds,
1287
+ use_cache=use_cache,
1288
+ output_attentions=output_attentions,
1289
+ output_hidden_states=output_hidden_states,
1290
+ return_dict=return_dict,
1291
+ )
1292
+
1293
+ hidden_states = outputs[0]
1294
+ logits = self.lm_head(hidden_states)
1295
+ logits = logits.float()
1296
+
1297
+ loss = None
1298
+ if labels is not None:
1299
+ # Shift so that tokens < n predict n
1300
+ shift_logits = logits[..., :-1, :].contiguous()
1301
+ shift_labels = labels[..., 1:].contiguous()
1302
+ # Flatten the tokens
1303
+ loss_fct = CrossEntropyLoss()
1304
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1305
+ shift_labels = shift_labels.view(-1)
1306
+ # Enable model parallelism
1307
+ shift_labels = shift_labels.to(shift_logits.device)
1308
+ loss = loss_fct(shift_logits, shift_labels)
1309
+
1310
+ if not return_dict:
1311
+ output = (logits,) + outputs[1:]
1312
+ return (loss,) + output if loss is not None else output
1313
+
1314
+ return CausalLMOutputWithPast(
1315
+ loss=loss,
1316
+ logits=logits,
1317
+ past_key_values=outputs.past_key_values,
1318
+ hidden_states=outputs.hidden_states,
1319
+ attentions=outputs.attentions,
1320
+ )
1321
+
1322
+ # Copied from transformers.models.persimmon.modeling_persimmon.PersimmonForCausalLM.prepare_inputs_for_generation
1323
+ def prepare_inputs_for_generation(
1324
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1325
+ ):
1326
+ if past_key_values is not None:
1327
+ if isinstance(past_key_values, Cache):
1328
+ cache_length = past_key_values.get_seq_length()
1329
+ past_length = past_key_values.seen_tokens
1330
+ max_cache_length = past_key_values.get_max_length()
1331
+ else:
1332
+ cache_length = past_length = past_key_values[0][0].shape[2]
1333
+ max_cache_length = None
1334
+
1335
+ # Keep only the unprocessed tokens:
1336
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1337
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1338
+ # input)
1339
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1340
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1341
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1342
+ # input_ids based on the past_length.
1343
+ elif past_length < input_ids.shape[1]:
1344
+ input_ids = input_ids[:, past_length:]
1345
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1346
+
1347
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1348
+ if (
1349
+ max_cache_length is not None
1350
+ and attention_mask is not None
1351
+ and cache_length + input_ids.shape[1] > max_cache_length
1352
+ ):
1353
+ attention_mask = attention_mask[:, -max_cache_length:]
1354
+
1355
+ position_ids = kwargs.get('position_ids', None)
1356
+ if attention_mask is not None and position_ids is None:
1357
+ # create position_ids on the fly for batch generation
1358
+ position_ids = attention_mask.long().cumsum(-1) - 1
1359
+ position_ids.masked_fill_(attention_mask == 0, 1)
1360
+ if past_key_values:
1361
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1362
+
1363
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1364
+ if inputs_embeds is not None and past_key_values is None:
1365
+ model_inputs = {'inputs_embeds': inputs_embeds}
1366
+ else:
1367
+ model_inputs = {'input_ids': input_ids}
1368
+
1369
+ model_inputs.update(
1370
+ {
1371
+ 'position_ids': position_ids,
1372
+ 'past_key_values': past_key_values,
1373
+ 'use_cache': kwargs.get('use_cache'),
1374
+ 'attention_mask': attention_mask,
1375
+ }
1376
+ )
1377
+ return model_inputs
1378
+
1379
+ @staticmethod
1380
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM._reorder_cache
1381
+ def _reorder_cache(past_key_values, beam_idx):
1382
+ reordered_past = ()
1383
+ for layer_past in past_key_values:
1384
+ reordered_past += (
1385
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1386
+ )
1387
+ return reordered_past
1388
+
1389
+
1390
+ @add_start_docstrings(
1391
+ """
1392
+ The [`Phi3Model`] with a sequence classification head on top (linear layer).
1393
+
1394
+ [`Phi3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1395
+ (e.g. GPT-2) do.
1396
+
1397
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1398
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1399
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1400
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1401
+ each row of the batch).
1402
+ """,
1403
+ PHI3_START_DOCSTRING,
1404
+ )
1405
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Phi3, LLAMA->PHI3, self.transformer->self.model, transformer_outputs->model_outputs
1406
+ class Phi3ForSequenceClassification(Phi3PreTrainedModel):
1407
+ def __init__(self, config):
1408
+ super().__init__(config)
1409
+ self.num_labels = config.num_labels
1410
+ self.model = Phi3Model(config)
1411
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1412
+
1413
+ # Initialize weights and apply final processing
1414
+ self.post_init()
1415
+
1416
+ def get_input_embeddings(self):
1417
+ return self.model.embed_tokens
1418
+
1419
+ def set_input_embeddings(self, value):
1420
+ self.model.embed_tokens = value
1421
+
1422
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1423
+ def forward(
1424
+ self,
1425
+ input_ids: torch.LongTensor = None,
1426
+ attention_mask: Optional[torch.Tensor] = None,
1427
+ position_ids: Optional[torch.LongTensor] = None,
1428
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1429
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1430
+ labels: Optional[torch.LongTensor] = None,
1431
+ use_cache: Optional[bool] = None,
1432
+ output_attentions: Optional[bool] = None,
1433
+ output_hidden_states: Optional[bool] = None,
1434
+ return_dict: Optional[bool] = None,
1435
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1436
+ r"""
1437
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1438
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1439
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1440
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1441
+ """
1442
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1443
+
1444
+ model_outputs = self.model(
1445
+ input_ids,
1446
+ attention_mask=attention_mask,
1447
+ position_ids=position_ids,
1448
+ past_key_values=past_key_values,
1449
+ inputs_embeds=inputs_embeds,
1450
+ use_cache=use_cache,
1451
+ output_attentions=output_attentions,
1452
+ output_hidden_states=output_hidden_states,
1453
+ return_dict=return_dict,
1454
+ )
1455
+ hidden_states = model_outputs[0]
1456
+ logits = self.score(hidden_states)
1457
+
1458
+ if input_ids is not None:
1459
+ batch_size = input_ids.shape[0]
1460
+ else:
1461
+ batch_size = inputs_embeds.shape[0]
1462
+
1463
+ if self.config.pad_token_id is None and batch_size != 1:
1464
+ raise ValueError('Cannot handle batch sizes > 1 if no padding token is defined.')
1465
+ if self.config.pad_token_id is None:
1466
+ sequence_lengths = -1
1467
+ else:
1468
+ if input_ids is not None:
1469
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1470
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1471
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1472
+ sequence_lengths = sequence_lengths.to(logits.device)
1473
+ else:
1474
+ sequence_lengths = -1
1475
+
1476
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1477
+
1478
+ loss = None
1479
+ if labels is not None:
1480
+ labels = labels.to(logits.device)
1481
+ if self.config.problem_type is None:
1482
+ if self.num_labels == 1:
1483
+ self.config.problem_type = 'regression'
1484
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1485
+ self.config.problem_type = 'single_label_classification'
1486
+ else:
1487
+ self.config.problem_type = 'multi_label_classification'
1488
+
1489
+ if self.config.problem_type == 'regression':
1490
+ loss_fct = MSELoss()
1491
+ if self.num_labels == 1:
1492
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1493
+ else:
1494
+ loss = loss_fct(pooled_logits, labels)
1495
+ elif self.config.problem_type == 'single_label_classification':
1496
+ loss_fct = CrossEntropyLoss()
1497
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1498
+ elif self.config.problem_type == 'multi_label_classification':
1499
+ loss_fct = BCEWithLogitsLoss()
1500
+ loss = loss_fct(pooled_logits, labels)
1501
+ if not return_dict:
1502
+ output = (pooled_logits,) + model_outputs[1:]
1503
+ return ((loss,) + output) if loss is not None else output
1504
+
1505
+ return SequenceClassifierOutputWithPast(
1506
+ loss=loss,
1507
+ logits=pooled_logits,
1508
+ past_key_values=model_outputs.past_key_values,
1509
+ hidden_states=model_outputs.hidden_states,
1510
+ attentions=model_outputs.attentions,
1511
+ )
1512
+
1513
+
1514
+ @add_start_docstrings(
1515
+ """
1516
+ [`Phi3Model`] with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1517
+ Named-Entity-Recognition (NER) tasks.
1518
+ """,
1519
+ PHI3_START_DOCSTRING,
1520
+ )
1521
+ # Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with Mpt->Phi3,MPT->PHI3,self.transformer->self.model,transformer_outputs->model_outputs
1522
+ class Phi3ForTokenClassification(Phi3PreTrainedModel):
1523
+ def __init__(self, config: Phi3Config):
1524
+ super().__init__(config)
1525
+ self.num_labels = config.num_labels
1526
+
1527
+ self.model = Phi3Model(config)
1528
+ if hasattr(config, 'classifier_dropout') and config.classifier_dropout is not None:
1529
+ classifier_dropout = config.classifier_dropout
1530
+ elif hasattr(config, 'hidden_dropout') and config.hidden_dropout is not None:
1531
+ classifier_dropout = config.hidden_dropout
1532
+ else:
1533
+ classifier_dropout = 0.1
1534
+ self.dropout = nn.Dropout(classifier_dropout)
1535
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1536
+
1537
+ # Initialize weights and apply final processing
1538
+ self.post_init()
1539
+
1540
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1541
+ @add_code_sample_docstrings(
1542
+ checkpoint=_CHECKPOINT_FOR_DOC,
1543
+ output_type=TokenClassifierOutput,
1544
+ config_class=_CONFIG_FOR_DOC,
1545
+ )
1546
+ def forward(
1547
+ self,
1548
+ input_ids: Optional[torch.LongTensor] = None,
1549
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1550
+ attention_mask: Optional[torch.Tensor] = None,
1551
+ inputs_embeds: Optional[torch.Tensor] = None,
1552
+ labels: Optional[torch.Tensor] = None,
1553
+ use_cache: Optional[bool] = None,
1554
+ output_attentions: Optional[bool] = None,
1555
+ output_hidden_states: Optional[bool] = None,
1556
+ return_dict: Optional[bool] = None,
1557
+ **deprecated_arguments,
1558
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1559
+ r"""
1560
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1561
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1562
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1563
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1564
+ """
1565
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1566
+
1567
+ model_outputs = self.model(
1568
+ input_ids,
1569
+ past_key_values=past_key_values,
1570
+ attention_mask=attention_mask,
1571
+ inputs_embeds=inputs_embeds,
1572
+ use_cache=use_cache,
1573
+ output_attentions=output_attentions,
1574
+ output_hidden_states=output_hidden_states,
1575
+ return_dict=return_dict,
1576
+ )
1577
+
1578
+ hidden_states = model_outputs[0]
1579
+ hidden_states = self.dropout(hidden_states)
1580
+ logits = self.classifier(hidden_states)
1581
+
1582
+ loss = None
1583
+ if labels is not None:
1584
+ # move labels to correct device to enable model parallelism
1585
+ labels = labels.to(logits.device)
1586
+ batch_size, seq_length = labels.shape
1587
+ loss_fct = CrossEntropyLoss()
1588
+ loss = loss_fct(
1589
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
1590
+ )
1591
+
1592
+ if not return_dict:
1593
+ output = (logits,) + model_outputs[2:]
1594
+ return ((loss,) + output) if loss is not None else output
1595
+
1596
+ return TokenClassifierOutput(
1597
+ loss=loss,
1598
+ logits=logits,
1599
+ hidden_states=model_outputs.hidden_states,
1600
+ attentions=model_outputs.attentions,
1601
+ )
internvl/model/qwen2/__init__.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The Qwen Team 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
+ from typing import TYPE_CHECKING
15
+
16
+ from transformers.utils import (
17
+ OptionalDependencyNotAvailable,
18
+ _LazyModule,
19
+ is_tokenizers_available,
20
+ is_torch_available,
21
+ )
22
+
23
+
24
+ _import_structure = {
25
+ "configuration_qwen2": ["Qwen2Config"],
26
+ "tokenization_qwen2": ["Qwen2Tokenizer"],
27
+ }
28
+
29
+ try:
30
+ if not is_tokenizers_available():
31
+ raise OptionalDependencyNotAvailable()
32
+ except OptionalDependencyNotAvailable:
33
+ pass
34
+ else:
35
+ _import_structure["tokenization_qwen2_fast"] = ["Qwen2TokenizerFast"]
36
+
37
+ try:
38
+ if not is_torch_available():
39
+ raise OptionalDependencyNotAvailable()
40
+ except OptionalDependencyNotAvailable:
41
+ pass
42
+ else:
43
+ _import_structure["modeling_qwen2"] = [
44
+ "Qwen2ForCausalLM",
45
+ "Qwen2Model",
46
+ "Qwen2PreTrainedModel",
47
+ "Qwen2ForSequenceClassification",
48
+ "Qwen2ForTokenClassification",
49
+ ]
50
+
51
+
52
+ if TYPE_CHECKING:
53
+ from .configuration_qwen2 import Qwen2Config
54
+ from .tokenization_qwen2 import Qwen2Tokenizer
55
+
56
+ try:
57
+ if not is_tokenizers_available():
58
+ raise OptionalDependencyNotAvailable()
59
+ except OptionalDependencyNotAvailable:
60
+ pass
61
+ else:
62
+ from .tokenization_qwen2_fast import Qwen2TokenizerFast
63
+
64
+ try:
65
+ if not is_torch_available():
66
+ raise OptionalDependencyNotAvailable()
67
+ except OptionalDependencyNotAvailable:
68
+ pass
69
+ else:
70
+ from .modeling_qwen2 import (
71
+ Qwen2ForCausalLM,
72
+ Qwen2ForSequenceClassification,
73
+ Qwen2ForTokenClassification,
74
+ Qwen2Model,
75
+ Qwen2PreTrainedModel,
76
+ )
77
+
78
+
79
+ else:
80
+ import sys
81
+
82
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
internvl/model/qwen2/configuration_qwen2.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class Qwen2Config(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`Qwen2Model`]. It is used to instantiate a
27
+ Qwen2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
28
+ with the defaults will yield a similar configuration to that of
29
+ Qwen2-7B-beta [Qwen/Qwen2-7B-beta](https://huggingface.co/Qwen/Qwen2-7B-beta).
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 151936):
37
+ Vocabulary size of the Qwen2 model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`Qwen2Model`]
39
+ hidden_size (`int`, *optional*, defaults to 4096):
40
+ Dimension of the hidden representations.
41
+ intermediate_size (`int`, *optional*, defaults to 22016):
42
+ Dimension of the MLP representations.
43
+ num_hidden_layers (`int`, *optional*, defaults to 32):
44
+ Number of hidden layers in the Transformer encoder.
45
+ num_attention_heads (`int`, *optional*, defaults to 32):
46
+ Number of attention heads for each attention layer in the Transformer encoder.
47
+ num_key_value_heads (`int`, *optional*, defaults to 32):
48
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
49
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
50
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
51
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
52
+ by meanpooling all the original heads within that group. For more details checkout [this
53
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
54
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
55
+ The non-linear activation function (function or string) in the decoder.
56
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
57
+ The maximum sequence length that this model might ever be used with.
58
+ initializer_range (`float`, *optional*, defaults to 0.02):
59
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
60
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
61
+ The epsilon used by the rms normalization layers.
62
+ use_cache (`bool`, *optional*, defaults to `True`):
63
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
64
+ relevant if `config.is_decoder=True`.
65
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
66
+ Whether the model's input and output word embeddings should be tied.
67
+ rope_theta (`float`, *optional*, defaults to 10000.0):
68
+ The base period of the RoPE embeddings.
69
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
70
+ Whether to use sliding window attention.
71
+ sliding_window (`int`, *optional*, defaults to 4096):
72
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
73
+ max_window_layers (`int`, *optional*, defaults to 28):
74
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
75
+ attention_dropout (`float`, *optional*, defaults to 0.0):
76
+ The dropout ratio for the attention probabilities.
77
+
78
+ ```python
79
+ >>> from transformers import Qwen2Model, Qwen2Config
80
+
81
+ >>> # Initializing a Qwen2 style configuration
82
+ >>> configuration = Qwen2Config()
83
+
84
+ >>> # Initializing a model from the Qwen2-7B style configuration
85
+ >>> model = Qwen2Model(configuration)
86
+
87
+ >>> # Accessing the model configuration
88
+ >>> configuration = model.config
89
+ ```"""
90
+
91
+ model_type = "qwen2"
92
+ keys_to_ignore_at_inference = ["past_key_values"]
93
+
94
+ def __init__(
95
+ self,
96
+ vocab_size=151936,
97
+ hidden_size=4096,
98
+ intermediate_size=22016,
99
+ num_hidden_layers=32,
100
+ num_attention_heads=32,
101
+ num_key_value_heads=32,
102
+ hidden_act="silu",
103
+ max_position_embeddings=32768,
104
+ initializer_range=0.02,
105
+ rms_norm_eps=1e-6,
106
+ use_cache=True,
107
+ tie_word_embeddings=False,
108
+ rope_theta=10000.0,
109
+ use_sliding_window=False,
110
+ sliding_window=4096,
111
+ max_window_layers=28,
112
+ attention_dropout=0.0,
113
+ **kwargs,
114
+ ):
115
+ self.vocab_size = vocab_size
116
+ self.max_position_embeddings = max_position_embeddings
117
+ self.hidden_size = hidden_size
118
+ self.intermediate_size = intermediate_size
119
+ self.num_hidden_layers = num_hidden_layers
120
+ self.num_attention_heads = num_attention_heads
121
+ self.use_sliding_window = use_sliding_window
122
+ self.sliding_window = sliding_window if use_sliding_window else None
123
+ self.max_window_layers = max_window_layers
124
+
125
+ # for backward compatibility
126
+ if num_key_value_heads is None:
127
+ num_key_value_heads = num_attention_heads
128
+
129
+ self.num_key_value_heads = num_key_value_heads
130
+ self.hidden_act = hidden_act
131
+ self.initializer_range = initializer_range
132
+ self.rms_norm_eps = rms_norm_eps
133
+ self.use_cache = use_cache
134
+ self.rope_theta = rope_theta
135
+ self.attention_dropout = attention_dropout
136
+
137
+ super().__init__(
138
+ tie_word_embeddings=tie_word_embeddings,
139
+ **kwargs,
140
+ )
internvl/model/qwen2/modeling_qwen2.py ADDED
@@ -0,0 +1,1517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """PyTorch Qwen2 model."""
21
+
22
+ import math
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.utils.checkpoint
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+
30
+ from transformers.activations import ACT2FN
31
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
32
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
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_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ is_flash_attn_2_available,
44
+ is_flash_attn_greater_or_equal_2_10,
45
+ logging,
46
+ replace_return_docstrings,
47
+ )
48
+ from .configuration_qwen2 import Qwen2Config
49
+
50
+
51
+ if is_flash_attn_2_available():
52
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
53
+
54
+
55
+ logger = logging.get_logger(__name__)
56
+
57
+
58
+ _CHECKPOINT_FOR_DOC = "Qwen/Qwen2-7B-beta"
59
+ _CONFIG_FOR_DOC = "Qwen2Config"
60
+
61
+
62
+ # Copied from transformers.models.llama.modeling_llama._prepare_4d_causal_attention_mask_with_cache_position
63
+ def _prepare_4d_causal_attention_mask_with_cache_position(
64
+ attention_mask: torch.Tensor,
65
+ sequence_length: int,
66
+ target_length: int,
67
+ dtype: torch.dtype,
68
+ device: torch.device,
69
+ min_dtype: float,
70
+ cache_position: torch.Tensor,
71
+ batch_size: int,
72
+ ):
73
+ """
74
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
75
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
76
+
77
+ Args:
78
+ attention_mask (`torch.Tensor`):
79
+ 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)`.
80
+ sequence_length (`int`):
81
+ The sequence length being processed.
82
+ target_length (`int`):
83
+ 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.
84
+ dtype (`torch.dtype`):
85
+ The dtype to use for the 4D attention mask.
86
+ device (`torch.device`):
87
+ The device to plcae the 4D attention mask on.
88
+ min_dtype (`float`):
89
+ The minimum value representable with the dtype `dtype`.
90
+ cache_position (`torch.Tensor`):
91
+ Indices depicting the position of the input sequence tokens in the sequence.
92
+ batch_size (`torch.Tensor`):
93
+ Batch size.
94
+ """
95
+ if attention_mask is not None and attention_mask.dim() == 4:
96
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
97
+ causal_mask = attention_mask
98
+ else:
99
+ causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
100
+ if sequence_length != 1:
101
+ causal_mask = torch.triu(causal_mask, diagonal=1)
102
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
103
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
104
+ if attention_mask is not None:
105
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
106
+ mask_length = attention_mask.shape[-1]
107
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
108
+ padding_mask = padding_mask == 0
109
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
110
+ padding_mask, min_dtype
111
+ )
112
+
113
+ return causal_mask
114
+
115
+
116
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Qwen2
117
+ class Qwen2RMSNorm(nn.Module):
118
+ def __init__(self, hidden_size, eps=1e-6):
119
+ """
120
+ Qwen2RMSNorm is equivalent to T5LayerNorm
121
+ """
122
+ super().__init__()
123
+ self.weight = nn.Parameter(torch.ones(hidden_size))
124
+ self.variance_epsilon = eps
125
+
126
+ def forward(self, hidden_states):
127
+ input_dtype = hidden_states.dtype
128
+ hidden_states = hidden_states.to(torch.float32)
129
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
130
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
131
+ return self.weight * hidden_states.to(input_dtype)
132
+
133
+ def extra_repr(self):
134
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
135
+
136
+
137
+ # Copied from transformers.models.mixtral.modeling_mixtral.MixtralRotaryEmbedding with Mixtral->Qwen2
138
+ class Qwen2RotaryEmbedding(nn.Module):
139
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
140
+ super().__init__()
141
+
142
+ self.dim = dim
143
+ self.max_position_embeddings = max_position_embeddings
144
+ self.base = base
145
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
146
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
147
+
148
+ # Build here to make `torch.jit.trace` work.
149
+ self._set_cos_sin_cache(
150
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
151
+ )
152
+
153
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
154
+ self.max_seq_len_cached = seq_len
155
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
156
+
157
+ freqs = torch.outer(t, self.inv_freq)
158
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
159
+ emb = torch.cat((freqs, freqs), dim=-1)
160
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
161
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
162
+
163
+ def forward(self, x, seq_len=None):
164
+ # x: [bs, num_attention_heads, seq_len, head_size]
165
+ if seq_len > self.max_seq_len_cached:
166
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
167
+
168
+ return (
169
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
170
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
171
+ )
172
+
173
+
174
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
175
+ def rotate_half(x):
176
+ """Rotates half the hidden dims of the input."""
177
+ x1 = x[..., : x.shape[-1] // 2]
178
+ x2 = x[..., x.shape[-1] // 2 :]
179
+ return torch.cat((-x2, x1), dim=-1)
180
+
181
+
182
+ # Copied from transformers.models.mixtral.modeling_mixtral.apply_rotary_pos_emb
183
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
184
+ """Applies Rotary Position Embedding to the query and key tensors.
185
+
186
+ Args:
187
+ q (`torch.Tensor`): The query tensor.
188
+ k (`torch.Tensor`): The key tensor.
189
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
190
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
191
+ position_ids (`torch.Tensor`):
192
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
193
+ used to pass offsetted position ids when working with a KV-cache.
194
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
195
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
196
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
197
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
198
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
199
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
200
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
201
+ Returns:
202
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
203
+ """
204
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
205
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
206
+ q_embed = (q * cos) + (rotate_half(q) * sin)
207
+ k_embed = (k * cos) + (rotate_half(k) * sin)
208
+ return q_embed, k_embed
209
+
210
+
211
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Qwen2
212
+ class Qwen2MLP(nn.Module):
213
+ def __init__(self, config):
214
+ super().__init__()
215
+ self.hidden_size = config.hidden_size
216
+ self.intermediate_size = config.intermediate_size
217
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
218
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
219
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
220
+ self.act_fn = ACT2FN[config.hidden_act]
221
+
222
+ def forward(self, hidden_state):
223
+ return self.down_proj(self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state))
224
+
225
+
226
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
227
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
228
+ """
229
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
230
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
231
+ """
232
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
233
+ if n_rep == 1:
234
+ return hidden_states
235
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
236
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
237
+
238
+
239
+ class Qwen2Attention(nn.Module):
240
+ """
241
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
242
+ and "Generating Long Sequences with Sparse Transformers".
243
+ """
244
+
245
+ def __init__(self, config: Qwen2Config, layer_idx: Optional[int] = None):
246
+ super().__init__()
247
+ self.config = config
248
+ self.layer_idx = layer_idx
249
+ if layer_idx is None:
250
+ logger.warning_once(
251
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
252
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
253
+ "when creating this class."
254
+ )
255
+
256
+ self.hidden_size = config.hidden_size
257
+ self.num_heads = config.num_attention_heads
258
+ self.head_dim = self.hidden_size // self.num_heads
259
+ self.num_key_value_heads = config.num_key_value_heads
260
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
261
+ self.max_position_embeddings = config.max_position_embeddings
262
+ self.rope_theta = config.rope_theta
263
+ self.is_causal = True
264
+ self.attention_dropout = config.attention_dropout
265
+
266
+ if (self.head_dim * self.num_heads) != self.hidden_size:
267
+ raise ValueError(
268
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
269
+ f" and `num_heads`: {self.num_heads})."
270
+ )
271
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
272
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
273
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
274
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
275
+
276
+ self.rotary_emb = Qwen2RotaryEmbedding(
277
+ self.head_dim,
278
+ max_position_embeddings=self.max_position_embeddings,
279
+ base=self.rope_theta,
280
+ )
281
+
282
+ def forward(
283
+ self,
284
+ hidden_states: torch.Tensor,
285
+ attention_mask: Optional[torch.Tensor] = None,
286
+ position_ids: Optional[torch.LongTensor] = None,
287
+ past_key_value: Optional[Cache] = None,
288
+ output_attentions: bool = False,
289
+ use_cache: bool = False,
290
+ cache_position: Optional[torch.LongTensor] = None,
291
+ **kwargs,
292
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
293
+ bsz, q_len, _ = hidden_states.size()
294
+
295
+ query_states = self.q_proj(hidden_states)
296
+ key_states = self.k_proj(hidden_states)
297
+ value_states = self.v_proj(hidden_states)
298
+
299
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
300
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
301
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
302
+
303
+ kv_seq_len = key_states.shape[-2]
304
+ if past_key_value is not None:
305
+ if self.layer_idx is None:
306
+ raise ValueError(
307
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
308
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
309
+ "with a layer index."
310
+ )
311
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
312
+
313
+ prunded_sequence_length = kwargs["prunded_sequence_length"]
314
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len + prunded_sequence_length)
315
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
316
+
317
+ if past_key_value is not None:
318
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
319
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
320
+
321
+ # repeat k/v heads if n_kv_heads < n_heads
322
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
323
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
324
+
325
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
326
+
327
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
328
+ raise ValueError(
329
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
330
+ f" {attn_weights.size()}"
331
+ )
332
+
333
+ if attention_mask is not None: # no matter the length, we just slice it
334
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
335
+ attn_weights = attn_weights + causal_mask
336
+
337
+ # upcast attention to fp32
338
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
339
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
340
+ attn_output = torch.matmul(attn_weights, value_states)
341
+
342
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
343
+ raise ValueError(
344
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
345
+ f" {attn_output.size()}"
346
+ )
347
+
348
+ attn_output = attn_output.transpose(1, 2).contiguous()
349
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
350
+
351
+ attn_output = self.o_proj(attn_output)
352
+
353
+ if not output_attentions:
354
+ attn_weights = None
355
+
356
+ return attn_output, attn_weights, past_key_value
357
+
358
+
359
+ class Qwen2FlashAttention2(Qwen2Attention):
360
+ """
361
+ Qwen2 flash attention module, following Qwen2 attention module. This module inherits from `Qwen2Attention`
362
+ as the weights of the module stays untouched. The only required change would be on the forward pass
363
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
364
+ in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
365
+ config.max_window_layers layers.
366
+ """
367
+
368
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
369
+ def __init__(self, *args, **kwargs):
370
+ super().__init__(*args, **kwargs)
371
+
372
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
373
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
374
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
375
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
376
+
377
+ def forward(
378
+ self,
379
+ hidden_states: torch.Tensor,
380
+ attention_mask: Optional[torch.Tensor] = None,
381
+ position_ids: Optional[torch.LongTensor] = None,
382
+ past_key_value: Optional[Cache] = None,
383
+ output_attentions: bool = False,
384
+ use_cache: bool = False,
385
+ cache_position: Optional[torch.LongTensor] = None,
386
+ **kwargs,
387
+ ):
388
+ if output_attentions:
389
+
390
+ return super().forward(
391
+ hidden_states=hidden_states,
392
+ attention_mask=attention_mask,
393
+ position_ids=position_ids,
394
+ past_key_value=past_key_value,
395
+ output_attentions=output_attentions,
396
+ use_cache=use_cache,
397
+ **kwargs,
398
+ )
399
+
400
+
401
+ bsz, q_len, _ = hidden_states.size()
402
+
403
+ query_states = self.q_proj(hidden_states)
404
+ key_states = self.k_proj(hidden_states)
405
+ value_states = self.v_proj(hidden_states)
406
+
407
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
408
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
409
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
410
+
411
+ kv_seq_len = key_states.shape[-2]
412
+ if past_key_value is not None:
413
+ if self.layer_idx is None:
414
+ raise ValueError(
415
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
416
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
417
+ "with a layer index."
418
+ )
419
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
420
+
421
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
422
+ rotary_seq_len = (
423
+ max(kv_seq_len, position_ids[:, -1].max().item() + 1) if position_ids is not None else kv_seq_len
424
+ )
425
+
426
+ prunded_sequence_length = kwargs["prunded_sequence_length"]
427
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len + prunded_sequence_length)
428
+
429
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
430
+
431
+ if past_key_value is not None:
432
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
433
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
434
+ if (
435
+ getattr(self.config, "sliding_window", None) is not None
436
+ and kv_seq_len > self.config.sliding_window
437
+ and cache_has_contents
438
+ ):
439
+ slicing_tokens = 1 - self.config.sliding_window
440
+
441
+ past_key = past_key_value[self.layer_idx][0]
442
+ past_value = past_key_value[self.layer_idx][1]
443
+
444
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
445
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
446
+
447
+ if past_key.shape[-2] != self.config.sliding_window - 1:
448
+ raise ValueError(
449
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
450
+ f" {past_key.shape}"
451
+ )
452
+
453
+ if attention_mask is not None:
454
+ attention_mask = attention_mask[:, slicing_tokens:]
455
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
456
+
457
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
458
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
459
+
460
+ # repeat k/v heads if n_kv_heads < n_heads
461
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
462
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
463
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
464
+
465
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
466
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
467
+ # cast them back in float16 just to be sure everything works as expected.
468
+ input_dtype = query_states.dtype
469
+ if input_dtype == torch.float32:
470
+ if torch.is_autocast_enabled():
471
+ target_dtype = torch.get_autocast_gpu_dtype()
472
+ # Handle the case where the model is quantized
473
+ elif hasattr(self.config, "_pre_quantization_dtype"):
474
+ target_dtype = self.config._pre_quantization_dtype
475
+ else:
476
+ target_dtype = self.q_proj.weight.dtype
477
+
478
+ logger.warning_once(
479
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
480
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
481
+ f" {target_dtype}."
482
+ )
483
+
484
+ query_states = query_states.to(target_dtype)
485
+ key_states = key_states.to(target_dtype)
486
+ value_states = value_states.to(target_dtype)
487
+
488
+ # Reashape to the expected shape for Flash Attention
489
+ query_states = query_states.transpose(1, 2)
490
+ key_states = key_states.transpose(1, 2)
491
+ value_states = value_states.transpose(1, 2)
492
+
493
+ if (
494
+ self.config.use_sliding_window
495
+ and getattr(self.config, "sliding_window", None) is not None
496
+ and self.layer_idx >= self.config.max_window_layers
497
+ ):
498
+ sliding_window = self.config.sliding_window
499
+ else:
500
+ sliding_window = None
501
+
502
+ attn_output = _flash_attention_forward(
503
+ query_states,
504
+ key_states,
505
+ value_states,
506
+ attention_mask,
507
+ q_len,
508
+ position_ids=position_ids,
509
+ dropout=dropout_rate,
510
+ sliding_window=sliding_window,
511
+ is_causal=self.is_causal,
512
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
513
+ )
514
+
515
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
516
+ attn_output = self.o_proj(attn_output)
517
+
518
+
519
+ attn_weights = None
520
+
521
+ return attn_output, attn_weights, past_key_value
522
+
523
+
524
+ # Copied from transformers.models.mixtral.modeling_mixtral.MixtralSdpaAttention with Mixtral->Qwen2
525
+ class Qwen2SdpaAttention(Qwen2Attention):
526
+ """
527
+ Qwen2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
528
+ `Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
529
+ SDPA API.
530
+ """
531
+
532
+ # Adapted from Qwen2Attention.forward
533
+ def forward(
534
+ self,
535
+ hidden_states: torch.Tensor,
536
+ attention_mask: Optional[torch.Tensor] = None,
537
+ position_ids: Optional[torch.LongTensor] = None,
538
+ past_key_value: Optional[Cache] = None,
539
+ output_attentions: bool = False,
540
+ use_cache: bool = False,
541
+ cache_position: Optional[torch.LongTensor] = None,
542
+ **kwargs,
543
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
544
+ if output_attentions:
545
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
546
+ logger.warning_once(
547
+ "Qwen2Model is using Qwen2SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
548
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
549
+ )
550
+ return super().forward(
551
+ hidden_states=hidden_states,
552
+ attention_mask=attention_mask,
553
+ position_ids=position_ids,
554
+ past_key_value=past_key_value,
555
+ output_attentions=output_attentions,
556
+ use_cache=use_cache,
557
+ **kwargs,
558
+ )
559
+
560
+ bsz, q_len, _ = hidden_states.size()
561
+
562
+ query_states = self.q_proj(hidden_states)
563
+ key_states = self.k_proj(hidden_states)
564
+ value_states = self.v_proj(hidden_states)
565
+
566
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
567
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
568
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
569
+
570
+ kv_seq_len = key_states.shape[-2]
571
+ if past_key_value is not None:
572
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
573
+
574
+ prunded_sequence_length = kwargs["prunded_sequence_length"]
575
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len + prunded_sequence_length)
576
+
577
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
578
+
579
+ if past_key_value is not None:
580
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
581
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
582
+
583
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
584
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
585
+
586
+ causal_mask = attention_mask
587
+ if attention_mask is not None: # no matter the length, we just slice it
588
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
589
+
590
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
591
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
592
+ if query_states.device.type == "cuda" and attention_mask is not None:
593
+ query_states = query_states.contiguous()
594
+ key_states = key_states.contiguous()
595
+ value_states = value_states.contiguous()
596
+
597
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
598
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
599
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
600
+ is_causal = True if causal_mask is None and q_len > 1 else False
601
+
602
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
603
+ query_states,
604
+ key_states,
605
+ value_states,
606
+ attn_mask=causal_mask,
607
+ dropout_p=self.attention_dropout if self.training else 0.0,
608
+ is_causal=is_causal,
609
+ )
610
+
611
+ attn_output = attn_output.transpose(1, 2).contiguous()
612
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
613
+
614
+ attn_output = self.o_proj(attn_output)
615
+
616
+ return attn_output, None, past_key_value
617
+
618
+
619
+ QWEN2_ATTENTION_CLASSES = {
620
+ "eager": Qwen2Attention,
621
+ "flash_attention_2": Qwen2FlashAttention2,
622
+ "sdpa": Qwen2SdpaAttention,
623
+ }
624
+
625
+
626
+ class Qwen2DecoderLayer(nn.Module):
627
+ def __init__(self, config: Qwen2Config, layer_idx: int):
628
+ super().__init__()
629
+ self.hidden_size = config.hidden_size
630
+
631
+ if config.sliding_window and config._attn_implementation != "flash_attention_2":
632
+ logger.warning_once(
633
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
634
+ "unexpected results may be encountered."
635
+ )
636
+ self.self_attn = QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
637
+
638
+ self.mlp = Qwen2MLP(config)
639
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
640
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
641
+
642
+ def forward(
643
+ self,
644
+ hidden_states: torch.Tensor,
645
+ attention_mask: Optional[torch.Tensor] = None,
646
+ position_ids: Optional[torch.LongTensor] = None,
647
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
648
+ output_attentions: Optional[bool] = False,
649
+ use_cache: Optional[bool] = False,
650
+ cache_position: Optional[torch.LongTensor] = None,
651
+ **kwargs,
652
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
653
+ """
654
+ Args:
655
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
656
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
657
+ `(batch, sequence_length)` where padding elements are indicated by 0.
658
+ output_attentions (`bool`, *optional*):
659
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
660
+ returned tensors for more detail.
661
+ use_cache (`bool`, *optional*):
662
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
663
+ (see `past_key_values`).
664
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
665
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
666
+ Indices depicting the position of the input sequence tokens in the sequence.
667
+ kwargs (`dict`, *optional*):
668
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
669
+ into the model
670
+ """
671
+
672
+ residual = hidden_states
673
+
674
+ hidden_states = self.input_layernorm(hidden_states)
675
+
676
+ # Self Attention
677
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
678
+ hidden_states=hidden_states,
679
+ attention_mask=attention_mask,
680
+ position_ids=position_ids,
681
+ past_key_value=past_key_value,
682
+ output_attentions=output_attentions,
683
+ use_cache=use_cache,
684
+ cache_position=cache_position,
685
+ **kwargs,
686
+ )
687
+ hidden_states = residual + hidden_states
688
+
689
+ # Fully Connected
690
+ residual = hidden_states
691
+ hidden_states = self.post_attention_layernorm(hidden_states)
692
+ hidden_states = self.mlp(hidden_states)
693
+ hidden_states = residual + hidden_states
694
+
695
+ outputs = (hidden_states,)
696
+
697
+ if output_attentions:
698
+ outputs += (self_attn_weights,)
699
+
700
+ if use_cache:
701
+ outputs += (present_key_value,)
702
+
703
+ return outputs
704
+
705
+
706
+ QWEN2_START_DOCSTRING = r"""
707
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
708
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
709
+ etc.)
710
+
711
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
712
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
713
+ and behavior.
714
+
715
+ Parameters:
716
+ config ([`Qwen2Config`]):
717
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
718
+ load the weights associated with the model, only the configuration. Check out the
719
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
720
+ """
721
+
722
+
723
+ @add_start_docstrings(
724
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
725
+ QWEN2_START_DOCSTRING,
726
+ )
727
+ class Qwen2PreTrainedModel(PreTrainedModel):
728
+ config_class = Qwen2Config
729
+ base_model_prefix = "model"
730
+ supports_gradient_checkpointing = True
731
+ _no_split_modules = ["Qwen2DecoderLayer"]
732
+ _skip_keys_device_placement = "past_key_values"
733
+ _supports_flash_attn_2 = True
734
+ _supports_sdpa = True
735
+ _supports_cache_class = True
736
+
737
+ def _init_weights(self, module):
738
+ std = self.config.initializer_range
739
+ if isinstance(module, nn.Linear):
740
+ module.weight.data.normal_(mean=0.0, std=std)
741
+ if module.bias is not None:
742
+ module.bias.data.zero_()
743
+ elif isinstance(module, nn.Embedding):
744
+ module.weight.data.normal_(mean=0.0, std=std)
745
+ if module.padding_idx is not None:
746
+ module.weight.data[module.padding_idx].zero_()
747
+
748
+
749
+ QWEN2_INPUTS_DOCSTRING = r"""
750
+ Args:
751
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
752
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
753
+ it.
754
+
755
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
756
+ [`PreTrainedTokenizer.__call__`] for details.
757
+
758
+ [What are input IDs?](../glossary#input-ids)
759
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
760
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
761
+
762
+ - 1 for tokens that are **not masked**,
763
+ - 0 for tokens that are **masked**.
764
+
765
+ [What are attention masks?](../glossary#attention-mask)
766
+
767
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
768
+ [`PreTrainedTokenizer.__call__`] for details.
769
+
770
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
771
+ `past_key_values`).
772
+
773
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
774
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
775
+ information on the default strategy.
776
+
777
+ - 1 indicates the head is **not masked**,
778
+ - 0 indicates the head is **masked**.
779
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
780
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
781
+ config.n_positions - 1]`.
782
+
783
+ [What are position IDs?](../glossary#position-ids)
784
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
785
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
786
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
787
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
788
+
789
+ Two formats are allowed:
790
+ - a [`~cache_utils.Cache`] instance;
791
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
792
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
793
+ cache format.
794
+
795
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
796
+ legacy cache format will be returned.
797
+
798
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
799
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
800
+ of shape `(batch_size, sequence_length)`.
801
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
802
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
803
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
804
+ model's internal embedding lookup matrix.
805
+ use_cache (`bool`, *optional*):
806
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
807
+ `past_key_values`).
808
+ output_attentions (`bool`, *optional*):
809
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
810
+ tensors for more detail.
811
+ output_hidden_states (`bool`, *optional*):
812
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
813
+ more detail.
814
+ return_dict (`bool`, *optional*):
815
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
816
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
817
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
818
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
819
+ the complete sequence length.
820
+ """
821
+
822
+
823
+ @add_start_docstrings(
824
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
825
+ QWEN2_START_DOCSTRING,
826
+ )
827
+ class Qwen2Model(Qwen2PreTrainedModel):
828
+ """
829
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
830
+
831
+ Args:
832
+ config: Qwen2Config
833
+ """
834
+
835
+ def __init__(self, config: Qwen2Config):
836
+ super().__init__(config)
837
+ self.padding_idx = config.pad_token_id
838
+ self.vocab_size = config.vocab_size
839
+
840
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
841
+ self.layers = nn.ModuleList(
842
+ [Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
843
+ )
844
+ self._attn_implementation = config._attn_implementation
845
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
846
+
847
+ self.gradient_checkpointing = False
848
+ # Initialize weights and apply final processing
849
+ self.post_init()
850
+
851
+ def get_input_embeddings(self):
852
+ return self.embed_tokens
853
+
854
+ def set_input_embeddings(self, value):
855
+ self.embed_tokens = value
856
+
857
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
858
+ def forward(
859
+ self,
860
+ input_ids: torch.LongTensor = None,
861
+ attention_mask: Optional[torch.Tensor] = None,
862
+ position_ids: Optional[torch.LongTensor] = None,
863
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
864
+ inputs_embeds: Optional[torch.FloatTensor] = None,
865
+ use_cache: Optional[bool] = None,
866
+ output_attentions: Optional[bool] = None,
867
+ output_hidden_states: Optional[bool] = None,
868
+ return_dict: Optional[bool] = None,
869
+ cache_position: Optional[torch.LongTensor] = None,
870
+ visual_token_index: Optional[torch.Tensor] = None,
871
+ large_model_prune_layer: Optional[float] = None,
872
+ large_model_prune_ratio: Optional[float] = None,
873
+ visual_token_importance: Optional[torch.Tensor] = None,
874
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
875
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
876
+ output_hidden_states = (
877
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
878
+ )
879
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
880
+
881
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
882
+
883
+
884
+ # retrieve input_ids and inputs_embeds
885
+ if input_ids is not None and inputs_embeds is not None:
886
+ raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time')
887
+ elif input_ids is not None:
888
+ batch_size, seq_length = input_ids.shape[:2]
889
+ elif inputs_embeds is not None:
890
+ batch_size, seq_length = inputs_embeds.shape[:2]
891
+ else:
892
+ raise ValueError('You have to specify either input_ids or inputs_embeds')
893
+
894
+
895
+
896
+ if (input_ids is None) ^ (inputs_embeds is not None):
897
+ raise ValueError(
898
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
899
+ )
900
+
901
+ if self.gradient_checkpointing and self.training:
902
+ if use_cache:
903
+ logger.warning_once(
904
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
905
+ )
906
+ use_cache = False
907
+
908
+ use_legacy_cache = False
909
+ if use_cache and not isinstance(past_key_values, Cache) and not self.training:
910
+ use_legacy_cache = True
911
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
912
+ logger.warning_once(
913
+ "We detected that you are passing `past_key_values` as a tuple and this is deprecated and will be removed in v4.43. "
914
+ "Please use an appropriate `Cache` class (https://huggingface.co/docs/transformers/v4.41.3/en/internal/generation_utils#transformers.Cache)"
915
+ )
916
+
917
+ if inputs_embeds is None:
918
+ inputs_embeds = self.embed_tokens(input_ids)
919
+
920
+ if cache_position is None:
921
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
922
+ cache_position = torch.arange(
923
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
924
+ )
925
+ if position_ids is None:
926
+ position_ids = cache_position.unsqueeze(0)
927
+
928
+ causal_mask = self._update_causal_mask(
929
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
930
+ )
931
+
932
+ hidden_states = inputs_embeds
933
+
934
+ # decoder layers
935
+ all_hidden_states = () if output_hidden_states else None
936
+ all_self_attns = () if output_attentions else None
937
+ next_decoder_cache = None
938
+
939
+
940
+ if large_model_prune_layer is not None:
941
+ token_prune = True
942
+ K = int(len(self.layers) * large_model_prune_layer)
943
+ keep_ratio = large_model_prune_ratio
944
+ else:
945
+ token_prune = False
946
+
947
+ prunded_sequence_length = 0
948
+
949
+
950
+
951
+ for idx, decoder_layer in enumerate(self.layers):
952
+ if output_hidden_states:
953
+ all_hidden_states += (hidden_states,)
954
+
955
+ if self.gradient_checkpointing and self.training:
956
+ layer_outputs = self._gradient_checkpointing_func(
957
+ decoder_layer.__call__,
958
+ hidden_states,
959
+ causal_mask,
960
+ position_ids,
961
+ past_key_values,
962
+ output_attentions,
963
+ use_cache,
964
+ cache_position,
965
+ )
966
+ else:
967
+
968
+
969
+ ##### 某一层 random pruning #########
970
+ if token_prune:
971
+ if hidden_states.shape[1] != 1:
972
+ if idx == K:
973
+ device = hidden_states.device
974
+ visual_token_length = visual_token_index[1] - visual_token_index[0] + 1
975
+ image_attention_score = visual_token_importance.unsqueeze(0)
976
+ top_attention_rank_index = image_attention_score.topk(int(visual_token_length * keep_ratio), dim=-1).indices[0] + int(visual_token_index[0])
977
+ keep_indexs = torch.cat((torch.arange(int(visual_token_index[0]), device=device), top_attention_rank_index, torch.arange(int(visual_token_index[1]+1), seq_length, device=device)))
978
+ keep_indexs = keep_indexs.sort().values
979
+ hidden_states = hidden_states[:, keep_indexs,:]
980
+ if causal_mask is not None:
981
+ causal_mask = causal_mask[:,:,:hidden_states.shape[1], :hidden_states.shape[1]]
982
+ position_ids = keep_indexs.unsqueeze(0)
983
+ prunded_sequence_length = visual_token_length - int(visual_token_length * keep_ratio)
984
+
985
+
986
+ else:
987
+ if idx == K:
988
+ visual_token_length = visual_token_index[1] - visual_token_index[0] + 1
989
+ prunded_sequence_length = visual_token_length - int(visual_token_length * keep_ratio)
990
+ if causal_mask is not None:
991
+ causal_mask = causal_mask[:, :, :, prunded_sequence_length:]
992
+
993
+
994
+
995
+
996
+ layer_outputs = decoder_layer(
997
+ hidden_states,
998
+ attention_mask=causal_mask,
999
+ position_ids=position_ids,
1000
+ past_key_value=past_key_values,
1001
+ output_attentions=output_attentions,
1002
+ use_cache=use_cache,
1003
+ cache_position=cache_position,
1004
+ prunded_sequence_length=prunded_sequence_length
1005
+ )
1006
+
1007
+ hidden_states = layer_outputs[0]
1008
+
1009
+ if use_cache:
1010
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1011
+
1012
+ if output_attentions:
1013
+ all_self_attns += (layer_outputs[1],)
1014
+
1015
+ hidden_states = self.norm(hidden_states)
1016
+
1017
+ # add hidden states from the last decoder layer
1018
+ if output_hidden_states:
1019
+ all_hidden_states += (hidden_states,)
1020
+
1021
+ next_cache = None
1022
+ if use_cache:
1023
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1024
+
1025
+ if not return_dict:
1026
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1027
+ return BaseModelOutputWithPast(
1028
+ last_hidden_state=hidden_states,
1029
+ past_key_values=next_cache,
1030
+ hidden_states=all_hidden_states,
1031
+ attentions=all_self_attns,
1032
+ )
1033
+
1034
+ # Copied from transformers.models.llama.modeling_llama.LlamaModel._update_causal_mask
1035
+ def _update_causal_mask(
1036
+ self,
1037
+ attention_mask: torch.Tensor,
1038
+ input_tensor: torch.Tensor,
1039
+ cache_position: torch.Tensor,
1040
+ past_key_values: Cache,
1041
+ output_attentions: bool,
1042
+ ):
1043
+ # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
1044
+ # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
1045
+ # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
1046
+ # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
1047
+
1048
+ if self.config._attn_implementation == "flash_attention_2":
1049
+ if attention_mask is not None and 0.0 in attention_mask:
1050
+ return attention_mask
1051
+ return None
1052
+
1053
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1054
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1055
+ # to infer the attention mask.
1056
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1057
+ using_static_cache = isinstance(past_key_values, StaticCache)
1058
+
1059
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1060
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
1061
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1062
+ attention_mask,
1063
+ inputs_embeds=input_tensor,
1064
+ past_key_values_length=past_seen_tokens,
1065
+ is_training=self.training,
1066
+ ):
1067
+ return None
1068
+
1069
+ dtype, device = input_tensor.dtype, input_tensor.device
1070
+ min_dtype = torch.finfo(dtype).min
1071
+ sequence_length = input_tensor.shape[1]
1072
+ if using_static_cache:
1073
+ target_length = past_key_values.get_max_length()
1074
+ else:
1075
+ target_length = (
1076
+ attention_mask.shape[-1]
1077
+ if isinstance(attention_mask, torch.Tensor)
1078
+ else past_seen_tokens + sequence_length + 1
1079
+ )
1080
+
1081
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1082
+ causal_mask = _prepare_4d_causal_attention_mask_with_cache_position(
1083
+ attention_mask,
1084
+ sequence_length=sequence_length,
1085
+ target_length=target_length,
1086
+ dtype=dtype,
1087
+ device=device,
1088
+ min_dtype=min_dtype,
1089
+ cache_position=cache_position,
1090
+ batch_size=input_tensor.shape[0],
1091
+ )
1092
+
1093
+ if (
1094
+ self.config._attn_implementation == "sdpa"
1095
+ and attention_mask is not None
1096
+ and attention_mask.device.type == "cuda"
1097
+ and not output_attentions
1098
+ ):
1099
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1100
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1101
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1102
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1103
+
1104
+ return causal_mask
1105
+
1106
+
1107
+ class Qwen2ForCausalLM(Qwen2PreTrainedModel):
1108
+ _tied_weights_keys = ["lm_head.weight"]
1109
+
1110
+ def __init__(self, config):
1111
+ super().__init__(config)
1112
+ self.model = Qwen2Model(config)
1113
+ self.vocab_size = config.vocab_size
1114
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1115
+
1116
+ # Initialize weights and apply final processing
1117
+ self.post_init()
1118
+
1119
+ def get_input_embeddings(self):
1120
+ return self.model.embed_tokens
1121
+
1122
+ def set_input_embeddings(self, value):
1123
+ self.model.embed_tokens = value
1124
+
1125
+ def get_output_embeddings(self):
1126
+ return self.lm_head
1127
+
1128
+ def set_output_embeddings(self, new_embeddings):
1129
+ self.lm_head = new_embeddings
1130
+
1131
+ def set_decoder(self, decoder):
1132
+ self.model = decoder
1133
+
1134
+ def get_decoder(self):
1135
+ return self.model
1136
+
1137
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1138
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1139
+ def forward(
1140
+ self,
1141
+ input_ids: torch.LongTensor = None,
1142
+ attention_mask: Optional[torch.Tensor] = None,
1143
+ position_ids: Optional[torch.LongTensor] = None,
1144
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1145
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1146
+ labels: Optional[torch.LongTensor] = None,
1147
+ use_cache: Optional[bool] = None,
1148
+ output_attentions: Optional[bool] = None,
1149
+ output_hidden_states: Optional[bool] = None,
1150
+ return_dict: Optional[bool] = None,
1151
+ cache_position: Optional[torch.LongTensor] = None,
1152
+ visual_token_index: Optional[torch.Tensor] = None,
1153
+ large_model_prune_layer: Optional[float] = None,
1154
+ large_model_prune_ratio: Optional[float] = None,
1155
+ visual_token_importance: Optional[torch.Tensor] = None,
1156
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1157
+ r"""
1158
+ Args:
1159
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1160
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1161
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1162
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1163
+
1164
+ Returns:
1165
+
1166
+ Example:
1167
+
1168
+ ```python
1169
+ >>> from transformers import AutoTokenizer, Qwen2ForCausalLM
1170
+
1171
+ >>> model = Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1172
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1173
+
1174
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1175
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1176
+
1177
+ >>> # Generate
1178
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1179
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1180
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1181
+ ```"""
1182
+
1183
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1184
+ output_hidden_states = (
1185
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1186
+ )
1187
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1188
+
1189
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1190
+ outputs = self.model(
1191
+ input_ids=input_ids,
1192
+ attention_mask=attention_mask,
1193
+ position_ids=position_ids,
1194
+ past_key_values=past_key_values,
1195
+ inputs_embeds=inputs_embeds,
1196
+ use_cache=use_cache,
1197
+ output_attentions=output_attentions,
1198
+ output_hidden_states=output_hidden_states,
1199
+ return_dict=return_dict,
1200
+ cache_position=cache_position,
1201
+ visual_token_index=visual_token_index,
1202
+ large_model_prune_layer=large_model_prune_layer,
1203
+ large_model_prune_ratio=large_model_prune_ratio,
1204
+ visual_token_importance=visual_token_importance
1205
+ )
1206
+
1207
+ hidden_states = outputs[0]
1208
+ logits = self.lm_head(hidden_states)
1209
+ logits = logits.float()
1210
+
1211
+ loss = None
1212
+ if labels is not None:
1213
+ # Shift so that tokens < n predict n
1214
+ shift_logits = logits[..., :-1, :].contiguous()
1215
+ shift_labels = labels[..., 1:].contiguous()
1216
+ # Flatten the tokens
1217
+ loss_fct = CrossEntropyLoss()
1218
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1219
+ shift_labels = shift_labels.view(-1)
1220
+ # Enable model parallelism
1221
+ shift_labels = shift_labels.to(shift_logits.device)
1222
+ loss = loss_fct(shift_logits, shift_labels)
1223
+
1224
+ if not return_dict:
1225
+ output = (logits,) + outputs[1:]
1226
+ return (loss,) + output if loss is not None else output
1227
+
1228
+ return CausalLMOutputWithPast(
1229
+ loss=loss,
1230
+ logits=logits,
1231
+ past_key_values=outputs.past_key_values,
1232
+ hidden_states=outputs.hidden_states,
1233
+ attentions=outputs.attentions,
1234
+ )
1235
+
1236
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.prepare_inputs_for_generation
1237
+ def prepare_inputs_for_generation(
1238
+ self,
1239
+ input_ids,
1240
+ past_key_values=None,
1241
+ attention_mask=None,
1242
+ inputs_embeds=None,
1243
+ cache_position=None,
1244
+ position_ids=None,
1245
+ use_cache=True,
1246
+ **kwargs,
1247
+ ):
1248
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
1249
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
1250
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
1251
+ if past_key_values is not None:
1252
+ if inputs_embeds is not None: # Exception 1
1253
+ input_ids = input_ids[:, -cache_position.shape[0] :]
1254
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
1255
+ input_ids = input_ids[:, cache_position]
1256
+
1257
+ if attention_mask is not None and position_ids is None:
1258
+ # create position_ids on the fly for batch generation
1259
+ position_ids = attention_mask.long().cumsum(-1) - 1
1260
+ position_ids.masked_fill_(attention_mask == 0, 1)
1261
+ if past_key_values:
1262
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1263
+
1264
+ # This `clone` call is needed to avoid recapturing cuda graphs with `torch.compile`'s `mode="reduce-overhead`, as otherwise the input `position_ids` would have various stride during the decoding. Here, simply using `.contiguous()` is not sufficient as in the batch size = 1 case, `position_ids` is already contiguous but with varying stride which retriggers a capture.
1265
+ position_ids = position_ids.clone(memory_format=torch.contiguous_format)
1266
+
1267
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1268
+ if inputs_embeds is not None and cache_position[0] == 0:
1269
+ model_inputs = {"inputs_embeds": inputs_embeds, "input_ids": None}
1270
+ else:
1271
+ # The clone here is for the same reason as for `position_ids`.
1272
+ model_inputs = {"input_ids": input_ids.clone(memory_format=torch.contiguous_format), "inputs_embeds": None}
1273
+
1274
+ if isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2:
1275
+ if model_inputs["inputs_embeds"] is not None:
1276
+ batch_size, sequence_length, _ = model_inputs["inputs_embeds"].shape
1277
+ device = model_inputs["inputs_embeds"].device
1278
+ else:
1279
+ batch_size, sequence_length = model_inputs["input_ids"].shape
1280
+ device = model_inputs["input_ids"].device
1281
+
1282
+ dtype = self.lm_head.weight.dtype
1283
+ min_dtype = torch.finfo(dtype).min
1284
+
1285
+ attention_mask = _prepare_4d_causal_attention_mask_with_cache_position(
1286
+ attention_mask,
1287
+ sequence_length=sequence_length,
1288
+ target_length=past_key_values.get_max_length(),
1289
+ dtype=dtype,
1290
+ device=device,
1291
+ min_dtype=min_dtype,
1292
+ cache_position=cache_position,
1293
+ batch_size=batch_size,
1294
+ )
1295
+
1296
+ model_inputs.update(
1297
+ {
1298
+ "position_ids": position_ids,
1299
+ "cache_position": cache_position,
1300
+ "past_key_values": past_key_values,
1301
+ "use_cache": use_cache,
1302
+ "attention_mask": attention_mask,
1303
+ 'visual_token_index': kwargs.get('visual_token_index'),
1304
+ 'large_model_prune_layer': kwargs.get('large_model_prune_layer'),
1305
+ 'large_model_prune_ratio': kwargs.get('large_model_prune_ratio'),
1306
+ 'visual_token_importance': kwargs.get('visual_token_importance')
1307
+ }
1308
+ )
1309
+ return model_inputs
1310
+
1311
+
1312
+ @add_start_docstrings(
1313
+ """
1314
+ The Qwen2 Model transformer with a sequence classification head on top (linear layer).
1315
+
1316
+ [`Qwen2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1317
+ (e.g. GPT-2) do.
1318
+
1319
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1320
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1321
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1322
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1323
+ each row of the batch).
1324
+ """,
1325
+ QWEN2_START_DOCSTRING,
1326
+ )
1327
+ class Qwen2ForSequenceClassification(Qwen2PreTrainedModel):
1328
+ def __init__(self, config):
1329
+ super().__init__(config)
1330
+ self.num_labels = config.num_labels
1331
+ self.model = Qwen2Model(config)
1332
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1333
+
1334
+ # Initialize weights and apply final processing
1335
+ self.post_init()
1336
+
1337
+ def get_input_embeddings(self):
1338
+ return self.model.embed_tokens
1339
+
1340
+ def set_input_embeddings(self, value):
1341
+ self.model.embed_tokens = value
1342
+
1343
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1344
+ def forward(
1345
+ self,
1346
+ input_ids: torch.LongTensor = None,
1347
+ attention_mask: Optional[torch.Tensor] = None,
1348
+ position_ids: Optional[torch.LongTensor] = None,
1349
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1350
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1351
+ labels: Optional[torch.LongTensor] = 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
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1357
+ r"""
1358
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1359
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1360
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1361
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1362
+ """
1363
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1364
+
1365
+ transformer_outputs = self.model(
1366
+ input_ids,
1367
+ attention_mask=attention_mask,
1368
+ position_ids=position_ids,
1369
+ past_key_values=past_key_values,
1370
+ inputs_embeds=inputs_embeds,
1371
+ use_cache=use_cache,
1372
+ output_attentions=output_attentions,
1373
+ output_hidden_states=output_hidden_states,
1374
+ return_dict=return_dict,
1375
+ )
1376
+ hidden_states = transformer_outputs[0]
1377
+ logits = self.score(hidden_states)
1378
+
1379
+ if input_ids is not None:
1380
+ batch_size = input_ids.shape[0]
1381
+ else:
1382
+ batch_size = inputs_embeds.shape[0]
1383
+
1384
+ if self.config.pad_token_id is None and batch_size != 1:
1385
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1386
+ if self.config.pad_token_id is None:
1387
+ sequence_lengths = -1
1388
+ else:
1389
+ if input_ids is not None:
1390
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1391
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1392
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1393
+ sequence_lengths = sequence_lengths.to(logits.device)
1394
+ else:
1395
+ sequence_lengths = -1
1396
+
1397
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1398
+
1399
+ loss = None
1400
+ if labels is not None:
1401
+ labels = labels.to(logits.device)
1402
+ if self.config.problem_type is None:
1403
+ if self.num_labels == 1:
1404
+ self.config.problem_type = "regression"
1405
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1406
+ self.config.problem_type = "single_label_classification"
1407
+ else:
1408
+ self.config.problem_type = "multi_label_classification"
1409
+
1410
+ if self.config.problem_type == "regression":
1411
+ loss_fct = MSELoss()
1412
+ if self.num_labels == 1:
1413
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1414
+ else:
1415
+ loss = loss_fct(pooled_logits, labels)
1416
+ elif self.config.problem_type == "single_label_classification":
1417
+ loss_fct = CrossEntropyLoss()
1418
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1419
+ elif self.config.problem_type == "multi_label_classification":
1420
+ loss_fct = BCEWithLogitsLoss()
1421
+ loss = loss_fct(pooled_logits, labels)
1422
+ if not return_dict:
1423
+ output = (pooled_logits,) + transformer_outputs[1:]
1424
+ return ((loss,) + output) if loss is not None else output
1425
+
1426
+ return SequenceClassifierOutputWithPast(
1427
+ loss=loss,
1428
+ logits=pooled_logits,
1429
+ past_key_values=transformer_outputs.past_key_values,
1430
+ hidden_states=transformer_outputs.hidden_states,
1431
+ attentions=transformer_outputs.attentions,
1432
+ )
1433
+
1434
+
1435
+ @add_start_docstrings(
1436
+ """
1437
+ The Qwen2 Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1438
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1439
+ """,
1440
+ QWEN2_START_DOCSTRING,
1441
+ )
1442
+ # Copied from transformers.models.llama.modeling_llama.LlamaForTokenClassification with Llama->Qwen2, LLAMA->QWEN2
1443
+ class Qwen2ForTokenClassification(Qwen2PreTrainedModel):
1444
+ def __init__(self, config):
1445
+ super().__init__(config)
1446
+ self.num_labels = config.num_labels
1447
+ self.model = Qwen2Model(config)
1448
+ if getattr(config, "classifier_dropout", None) is not None:
1449
+ classifier_dropout = config.classifier_dropout
1450
+ elif getattr(config, "hidden_dropout", None) is not None:
1451
+ classifier_dropout = config.hidden_dropout
1452
+ else:
1453
+ classifier_dropout = 0.1
1454
+ self.dropout = nn.Dropout(classifier_dropout)
1455
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1456
+
1457
+ # Initialize weights and apply final processing
1458
+ self.post_init()
1459
+
1460
+ def get_input_embeddings(self):
1461
+ return self.model.embed_tokens
1462
+
1463
+ def set_input_embeddings(self, value):
1464
+ self.model.embed_tokens = value
1465
+
1466
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1467
+ def forward(
1468
+ self,
1469
+ input_ids: Optional[torch.LongTensor] = None,
1470
+ attention_mask: Optional[torch.Tensor] = None,
1471
+ position_ids: Optional[torch.LongTensor] = None,
1472
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1473
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1474
+ labels: Optional[torch.LongTensor] = None,
1475
+ use_cache: Optional[bool] = None,
1476
+ output_attentions: Optional[bool] = None,
1477
+ output_hidden_states: Optional[bool] = None,
1478
+ return_dict: Optional[bool] = None,
1479
+ ) -> Union[Tuple, TokenClassifierOutput]:
1480
+ r"""
1481
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1482
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1483
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1484
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1485
+ """
1486
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1487
+
1488
+ outputs = self.model(
1489
+ input_ids,
1490
+ attention_mask=attention_mask,
1491
+ position_ids=position_ids,
1492
+ past_key_values=past_key_values,
1493
+ inputs_embeds=inputs_embeds,
1494
+ use_cache=use_cache,
1495
+ output_attentions=output_attentions,
1496
+ output_hidden_states=output_hidden_states,
1497
+ return_dict=return_dict,
1498
+ )
1499
+ sequence_output = outputs[0]
1500
+ sequence_output = self.dropout(sequence_output)
1501
+ logits = self.score(sequence_output)
1502
+
1503
+ loss = None
1504
+ if labels is not None:
1505
+ loss_fct = CrossEntropyLoss()
1506
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1507
+
1508
+ if not return_dict:
1509
+ output = (logits,) + outputs[2:]
1510
+ return ((loss,) + output) if loss is not None else output
1511
+
1512
+ return TokenClassifierOutput(
1513
+ loss=loss,
1514
+ logits=logits,
1515
+ hidden_states=outputs.hidden_states,
1516
+ attentions=outputs.attentions,
1517
+ )
internvl/model/qwen2/tokenization_qwen2.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization classes for Qwen2."""
16
+
17
+ import json
18
+ import os
19
+ import unicodedata
20
+ from functools import lru_cache
21
+ from typing import Optional, Tuple
22
+
23
+ import regex as re
24
+
25
+ from ...tokenization_utils import AddedToken, PreTrainedTokenizer
26
+ from ...utils import logging
27
+
28
+
29
+ logger = logging.get_logger(__name__)
30
+
31
+ VOCAB_FILES_NAMES = {
32
+ "vocab_file": "vocab.json",
33
+ "merges_file": "merges.txt",
34
+ }
35
+
36
+
37
+ MAX_MODEL_INPUT_SIZES = {"qwen/qwen-tokenizer": 32768}
38
+
39
+ PRETOKENIZE_REGEX = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
40
+
41
+
42
+ @lru_cache()
43
+ # Copied from transformers.models.gpt2.tokenization_gpt2.bytes_to_unicode
44
+ def bytes_to_unicode():
45
+ """
46
+ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
47
+ characters the bpe code barfs on.
48
+
49
+ The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
50
+ if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
51
+ decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
52
+ tables between utf-8 bytes and unicode strings.
53
+ """
54
+ bs = (
55
+ list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
56
+ )
57
+ cs = bs[:]
58
+ n = 0
59
+ for b in range(2**8):
60
+ if b not in bs:
61
+ bs.append(b)
62
+ cs.append(2**8 + n)
63
+ n += 1
64
+ cs = [chr(n) for n in cs]
65
+ return dict(zip(bs, cs))
66
+
67
+
68
+ # Copied from transformers.models.gpt2.tokenization_gpt2.get_pairs
69
+ def get_pairs(word):
70
+ """
71
+ Return set of symbol pairs in a word.
72
+
73
+ Word is represented as tuple of symbols (symbols being variable-length strings).
74
+ """
75
+ pairs = set()
76
+ prev_char = word[0]
77
+ for char in word[1:]:
78
+ pairs.add((prev_char, char))
79
+ prev_char = char
80
+ return pairs
81
+
82
+
83
+ class Qwen2Tokenizer(PreTrainedTokenizer):
84
+ """
85
+ Construct a Qwen2 tokenizer. Based on byte-level Byte-Pair-Encoding.
86
+
87
+ Same with GPT2Tokenizer, this tokenizer has been trained to treat spaces like parts of the tokens so a word will
88
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
89
+
90
+ ```python
91
+ >>> from transformers import Qwen2Tokenizer
92
+
93
+ >>> tokenizer = Qwen2Tokenizer.from_pretrained("Qwen/Qwen-tokenizer")
94
+ >>> tokenizer("Hello world")["input_ids"]
95
+ [9707, 1879]
96
+
97
+ >>> tokenizer(" Hello world")["input_ids"]
98
+ [21927, 1879]
99
+ ```
100
+ This is expected.
101
+
102
+ You should not use GPT2Tokenizer instead, because of the different pretokenization rules.
103
+
104
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
105
+ this superclass for more information regarding those methods.
106
+
107
+ Args:
108
+ vocab_file (`str`):
109
+ Path to the vocabulary file.
110
+ merges_file (`str`):
111
+ Path to the merges file.
112
+ errors (`str`, *optional*, defaults to `"replace"`):
113
+ Paradigm to follow when decoding bytes to UTF-8. See
114
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
115
+ unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
116
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
117
+ token instead.
118
+ bos_token (`str`, *optional*):
119
+ The beginning of sequence token. Not applicable for this tokenizer.
120
+ eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
121
+ The end of sequence token.
122
+ pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
123
+ The token used for padding, for example when batching sequences of different lengths.
124
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
125
+ Whether or not the model should cleanup the spaces that were added when splitting the input text during the
126
+ tokenization process. Not applicable to this tokenizer, since tokenization does not add spaces.
127
+ split_special_tokens (`bool`, *optional*, defaults to `False`):
128
+ Whether or not the special tokens should be split during the tokenization process. The default behavior is
129
+ to not split special tokens. This means that if `<|endoftext|>` is the `eos_token`, then `tokenizer.tokenize("<|endoftext|>") =
130
+ ['<|endoftext|>`]. Otherwise, if `split_special_tokens=True`, then `tokenizer.tokenize("<|endoftext|>")` will be give `['<',
131
+ '|', 'endo', 'ft', 'ext', '|', '>']`. This argument is only supported for `slow` tokenizers for the moment.
132
+ """
133
+
134
+ vocab_files_names = VOCAB_FILES_NAMES
135
+ model_input_names = ["input_ids", "attention_mask"]
136
+
137
+ def __init__(
138
+ self,
139
+ vocab_file,
140
+ merges_file,
141
+ errors="replace",
142
+ unk_token="<|endoftext|>",
143
+ bos_token=None,
144
+ eos_token="<|endoftext|>",
145
+ pad_token="<|endoftext|>",
146
+ clean_up_tokenization_spaces=False,
147
+ split_special_tokens=False,
148
+ **kwargs,
149
+ ):
150
+ # Qwen vocab does not contain control tokens; added tokens need to be special
151
+ bos_token = (
152
+ AddedToken(bos_token, lstrip=False, rstrip=False, special=True, normalized=False)
153
+ if isinstance(bos_token, str)
154
+ else bos_token
155
+ )
156
+ eos_token = (
157
+ AddedToken(eos_token, lstrip=False, rstrip=False, special=True, normalized=False)
158
+ if isinstance(eos_token, str)
159
+ else eos_token
160
+ )
161
+ unk_token = (
162
+ AddedToken(unk_token, lstrip=False, rstrip=False, special=True, normalized=False)
163
+ if isinstance(unk_token, str)
164
+ else unk_token
165
+ )
166
+ pad_token = (
167
+ AddedToken(pad_token, lstrip=False, rstrip=False, special=True, normalized=False)
168
+ if isinstance(pad_token, str)
169
+ else pad_token
170
+ )
171
+
172
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
173
+ self.encoder = json.load(vocab_handle)
174
+ self.decoder = {v: k for k, v in self.encoder.items()}
175
+ self.errors = errors # how to handle errors in decoding
176
+ self.byte_encoder = bytes_to_unicode()
177
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
178
+ bpe_merges = []
179
+ with open(merges_file, encoding="utf-8") as merges_handle:
180
+ for i, line in enumerate(merges_handle):
181
+ line = line.strip()
182
+ if (i == 0 and line.startswith("#version:")) or not line:
183
+ continue
184
+ bpe_merges.append(tuple(line.split()))
185
+ self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
186
+ # NOTE: the cache can grow without bound and will get really large for long running processes
187
+ # (esp. for texts of language that do not use space between word, e.g. Chinese); technically
188
+ # not a memory leak but appears as one.
189
+ # GPT2Tokenizer has the same problem, so let's be consistent.
190
+ self.cache = {}
191
+
192
+ self.pat = re.compile(PRETOKENIZE_REGEX)
193
+
194
+ if kwargs.get("add_prefix_space", False):
195
+ logger.warning_once(
196
+ f"{self.__class__.__name} does not support `add_prefix_space`, setting it to True has no effect."
197
+ )
198
+
199
+ super().__init__(
200
+ errors=errors,
201
+ bos_token=bos_token,
202
+ eos_token=eos_token,
203
+ pad_token=pad_token,
204
+ unk_token=unk_token,
205
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
206
+ split_special_tokens=split_special_tokens,
207
+ **kwargs,
208
+ )
209
+
210
+ @property
211
+ def vocab_size(self) -> int:
212
+ return len(self.encoder)
213
+
214
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.get_vocab
215
+ def get_vocab(self):
216
+ return dict(self.encoder, **self.added_tokens_encoder)
217
+
218
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.bpe
219
+ def bpe(self, token):
220
+ if token in self.cache:
221
+ return self.cache[token]
222
+ word = tuple(token)
223
+ pairs = get_pairs(word)
224
+
225
+ if not pairs:
226
+ return token
227
+
228
+ while True:
229
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
230
+ if bigram not in self.bpe_ranks:
231
+ break
232
+ first, second = bigram
233
+ new_word = []
234
+ i = 0
235
+ while i < len(word):
236
+ try:
237
+ j = word.index(first, i)
238
+ except ValueError:
239
+ new_word.extend(word[i:])
240
+ break
241
+ else:
242
+ new_word.extend(word[i:j])
243
+ i = j
244
+
245
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
246
+ new_word.append(first + second)
247
+ i += 2
248
+ else:
249
+ new_word.append(word[i])
250
+ i += 1
251
+ new_word = tuple(new_word)
252
+ word = new_word
253
+ if len(word) == 1:
254
+ break
255
+ else:
256
+ pairs = get_pairs(word)
257
+ word = " ".join(word)
258
+ self.cache[token] = word
259
+ return word
260
+
261
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._tokenize
262
+ def _tokenize(self, text):
263
+ """Tokenize a string."""
264
+ bpe_tokens = []
265
+ for token in re.findall(self.pat, text):
266
+ token = "".join(
267
+ self.byte_encoder[b] for b in token.encode("utf-8")
268
+ ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
269
+ bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
270
+ return bpe_tokens
271
+
272
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_token_to_id
273
+ def _convert_token_to_id(self, token):
274
+ """Converts a token (str) in an id using the vocab."""
275
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
276
+
277
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_id_to_token
278
+ def _convert_id_to_token(self, index):
279
+ """Converts an index (integer) in a token (str) using the vocab."""
280
+ return self.decoder.get(index)
281
+
282
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.convert_tokens_to_string
283
+ def convert_tokens_to_string(self, tokens):
284
+ """Converts a sequence of tokens (string) in a single string."""
285
+ text = "".join(tokens)
286
+ text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
287
+ return text
288
+
289
+ def decode(
290
+ self,
291
+ token_ids,
292
+ skip_special_tokens: bool = False,
293
+ clean_up_tokenization_spaces: Optional[bool] = False,
294
+ spaces_between_special_tokens: bool = False,
295
+ **kwargs,
296
+ ) -> str:
297
+ # `spaces_between_special_tokens` defaults to True for _decode in slow tokenizers
298
+ # and cannot be configured elsewhere, but it should default to False for Qwen2Tokenizer
299
+ return super().decode(
300
+ token_ids,
301
+ skip_special_tokens=skip_special_tokens,
302
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
303
+ spaces_between_special_tokens=spaces_between_special_tokens,
304
+ **kwargs,
305
+ )
306
+
307
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.save_vocabulary
308
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
309
+ if not os.path.isdir(save_directory):
310
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
311
+ return
312
+ vocab_file = os.path.join(
313
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
314
+ )
315
+ merge_file = os.path.join(
316
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
317
+ )
318
+
319
+ with open(vocab_file, "w", encoding="utf-8") as f:
320
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
321
+
322
+ index = 0
323
+ with open(merge_file, "w", encoding="utf-8") as writer:
324
+ writer.write("#version: 0.2\n")
325
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
326
+ if index != token_index:
327
+ logger.warning(
328
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
329
+ " Please check that the tokenizer is not corrupted!"
330
+ )
331
+ index = token_index
332
+ writer.write(" ".join(bpe_tokens) + "\n")
333
+ index += 1
334
+
335
+ return vocab_file, merge_file
336
+
337
+ def prepare_for_tokenization(self, text, **kwargs):
338
+ text = unicodedata.normalize("NFC", text)
339
+ return (text, kwargs)
internvl/model/qwen2/tokenization_qwen2_fast.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization classes for Qwen2."""
16
+
17
+ from typing import Optional, Tuple
18
+
19
+ from transformers.tokenization_utils import AddedToken
20
+ from transformers.tokenization_utils_fast import PreTrainedTokenizerFast
21
+ from transformers.utils import logging
22
+ from transformers.tokenization_qwen2 import Qwen2Tokenizer
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+ VOCAB_FILES_NAMES = {
28
+ "vocab_file": "vocab.json",
29
+ "merges_file": "merges.txt",
30
+ "tokenizer_file": "tokenizer.json",
31
+ }
32
+
33
+
34
+ MAX_MODEL_INPUT_SIZES = {"qwen/qwen-tokenizer": 32768}
35
+
36
+
37
+ class Qwen2TokenizerFast(PreTrainedTokenizerFast):
38
+ """
39
+ Construct a "fast" Qwen2 tokenizer (backed by HuggingFace's *tokenizers* library). Based on byte-level
40
+ Byte-Pair-Encoding.
41
+
42
+ Same with GPT2Tokenizer, this tokenizer has been trained to treat spaces like parts of the tokens so a word will
43
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
44
+
45
+ ```python
46
+ >>> from transformers import Qwen2TokenizerFast
47
+
48
+ >>> tokenizer = Qwen2TokenizerFast.from_pretrained("Qwen/Qwen-tokenizer")
49
+ >>> tokenizer("Hello world")["input_ids"]
50
+ [9707, 1879]
51
+
52
+ >>> tokenizer(" Hello world")["input_ids"]
53
+ [21927, 1879]
54
+ ```
55
+ This is expected.
56
+
57
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
58
+ refer to this superclass for more information regarding those methods.
59
+
60
+ Args:
61
+ vocab_file (`str`, *optional*):
62
+ Path to the vocabulary file.
63
+ merges_file (`str`, *optional*):
64
+ Path to the merges file.
65
+ tokenizer_file (`str`, *optional*):
66
+ Path to [tokenizers](https://github.com/huggingface/tokenizers) file (generally has a .json extension) that
67
+ contains everything needed to load the tokenizer.
68
+ unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
69
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
70
+ token instead. Not applicable to this tokenizer.
71
+ bos_token (`str`, *optional*):
72
+ The beginning of sequence token. Not applicable for this tokenizer.
73
+ eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
74
+ The end of sequence token.
75
+ pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
76
+ The token used for padding, for example when batching sequences of different lengths.
77
+ """
78
+
79
+ vocab_files_names = VOCAB_FILES_NAMES
80
+ model_input_names = ["input_ids", "attention_mask"]
81
+ slow_tokenizer_class = Qwen2Tokenizer
82
+
83
+ def __init__(
84
+ self,
85
+ vocab_file=None,
86
+ merges_file=None,
87
+ tokenizer_file=None,
88
+ unk_token="<|endoftext|>",
89
+ bos_token=None,
90
+ eos_token="<|endoftext|>",
91
+ pad_token="<|endoftext|>",
92
+ **kwargs,
93
+ ):
94
+ # We need to at least pass vocab_file and merges_file to base class
95
+ # in case a slow tokenizer needs to be initialized; other can be
96
+ # configured through files.
97
+ # following GPT2TokenizerFast, also adding unk_token, bos_token, and eos_token
98
+
99
+ bos_token = (
100
+ AddedToken(bos_token, lstrip=False, rstrip=False, special=True, normalized=False)
101
+ if isinstance(bos_token, str)
102
+ else bos_token
103
+ )
104
+ eos_token = (
105
+ AddedToken(eos_token, lstrip=False, rstrip=False, special=True, normalized=False)
106
+ if isinstance(eos_token, str)
107
+ else eos_token
108
+ )
109
+ unk_token = (
110
+ AddedToken(unk_token, lstrip=False, rstrip=False, special=True, normalized=False)
111
+ if isinstance(unk_token, str)
112
+ else unk_token
113
+ )
114
+ pad_token = (
115
+ AddedToken(pad_token, lstrip=False, rstrip=False, special=True, normalized=False)
116
+ if isinstance(pad_token, str)
117
+ else pad_token
118
+ )
119
+
120
+ super().__init__(
121
+ vocab_file=vocab_file,
122
+ merges_file=merges_file,
123
+ tokenizer_file=tokenizer_file,
124
+ unk_token=unk_token,
125
+ bos_token=bos_token,
126
+ eos_token=eos_token,
127
+ pad_token=pad_token,
128
+ **kwargs,
129
+ )
130
+
131
+ # Copied from transformers.models.gpt2.tokenization_gpt2_fast.GPT2TokenizerFast.save_vocabulary
132
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
133
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
134
+ return tuple(files)
internvl/patch/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .llama2_flash_attn_monkey_patch import replace_llama2_attn_with_flash_attn
2
+ from .llama_flash_attn_monkey_patch import replace_llama_attn_with_flash_attn
3
+ from .llama_rmsnorm_monkey_patch import \
4
+ replace_llama_rmsnorm_with_fused_rmsnorm
5
+ from .pad_data_collator import concat_pad_data_collator, pad_data_collator
6
+ from .train_sampler_patch import replace_train_sampler
7
+
8
+ __all__ = ['replace_llama_attn_with_flash_attn',
9
+ 'replace_llama_rmsnorm_with_fused_rmsnorm',
10
+ 'replace_llama2_attn_with_flash_attn',
11
+ 'replace_train_sampler',
12
+ 'pad_data_collator',
13
+ 'concat_pad_data_collator']
internvl/patch/llama2_flash_attn_monkey_patch.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This file is copied from: https://github.com/lm-sys/FastChat
3
+ """
4
+ import warnings
5
+ from typing import Optional, Tuple
6
+
7
+ import torch
8
+ from flash_attn import __version__ as flash_attn_version
9
+ from flash_attn.bert_padding import pad_input, unpad_input
10
+ from flash_attn.flash_attn_interface import (flash_attn_func,
11
+ flash_attn_varlen_kvpacked_func)
12
+ from transformers.models.llama.modeling_llama import (LlamaAttention,
13
+ LlamaModel, rotate_half)
14
+
15
+
16
+ def apply_rotary_pos_emb(q, k, cos_sin, position_ids):
17
+ gather_indices = position_ids[:, :, None, None] # [bsz, seq_len, 1, 1]
18
+ gather_indices = gather_indices.repeat(
19
+ 1, 1, cos_sin[0].shape[1], cos_sin[0].shape[3]
20
+ )
21
+ bsz = gather_indices.shape[0]
22
+ cos, sin = (
23
+ torch.gather(x.transpose(1, 2).repeat(bsz, 1, 1, 1), 1, gather_indices)
24
+ for x in cos_sin
25
+ )
26
+ q, k = ((x * cos) + (rotate_half(x) * sin) for x in (q, k))
27
+ return q, k
28
+
29
+
30
+ def forward(
31
+ self,
32
+ hidden_states: torch.Tensor,
33
+ attention_mask: Optional[torch.Tensor] = None,
34
+ position_ids: Optional[torch.Tensor] = None,
35
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
36
+ output_attentions: bool = False,
37
+ use_cache: bool = False,
38
+ padding_mask: Optional[torch.Tensor] = None,
39
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
40
+ if output_attentions:
41
+ warnings.warn(
42
+ 'Output attentions is not supported for patched `LlamaAttention`, returning `None` instead.'
43
+ )
44
+
45
+ bsz, q_len, _ = hidden_states.size()
46
+ kv_heads = getattr(self, 'num_key_value_heads', self.num_heads)
47
+
48
+ q, k, v = (
49
+ op(hidden_states).view(bsz, q_len, nh, self.head_dim)
50
+ for op, nh in (
51
+ (self.q_proj, self.num_heads),
52
+ (self.k_proj, kv_heads),
53
+ (self.v_proj, kv_heads),
54
+ )
55
+ )
56
+ # shape: (b, s, num_heads, head_dim)
57
+
58
+ kv_seq_len = k.shape[1]
59
+ past_kv_len = 0
60
+ if past_key_value is not None:
61
+ past_kv_len = past_key_value[0].shape[2]
62
+ kv_seq_len += past_kv_len
63
+
64
+ cos_sin = self.rotary_emb(v, seq_len=kv_seq_len)
65
+ q, k = apply_rotary_pos_emb(q, k, cos_sin, position_ids)
66
+
67
+ if past_key_value is not None:
68
+ assert (
69
+ flash_attn_version >= '2.1.0'
70
+ ), 'past_key_value support requires flash-attn >= 2.1.0'
71
+ # reuse k, v
72
+ k = torch.cat([past_key_value[0].transpose(1, 2), k], dim=1)
73
+ v = torch.cat([past_key_value[1].transpose(1, 2), v], dim=1)
74
+
75
+ past_key_value = (k.transpose(1, 2), v.transpose(1, 2)) if use_cache else None
76
+
77
+ if attention_mask is None:
78
+ output = flash_attn_func(q, k, v, 0.0, softmax_scale=None, causal=True).view(
79
+ bsz, q_len, -1
80
+ )
81
+ else:
82
+ q, indices, cu_q_lens, max_s = unpad_input(q, attention_mask[:, -q_len:])
83
+ # We can skip concat and call unpad twice but seems better to call unpad only once.
84
+ kv, _, cu_k_lens, max_k = unpad_input(
85
+ torch.stack((k, v), dim=2), attention_mask
86
+ )
87
+ output_unpad = flash_attn_varlen_kvpacked_func(
88
+ q,
89
+ kv,
90
+ cu_q_lens,
91
+ cu_k_lens,
92
+ max_s,
93
+ max_k,
94
+ 0.0,
95
+ softmax_scale=None,
96
+ causal=True,
97
+ )
98
+ output_unpad = output_unpad.reshape(-1, self.num_heads * self.head_dim)
99
+ output = pad_input(output_unpad, indices, bsz, q_len)
100
+
101
+ return self.o_proj(output), None, past_key_value
102
+
103
+
104
+ # Disable the transformation of the attention mask in LlamaModel as flash attention
105
+ # takes a boolean key_padding_mask. Fills in the past kv length for use in forward.
106
+ def _prepare_decoder_attention_mask(
107
+ self, attention_mask, input_shape, inputs_embeds, past_key_values_length
108
+ ):
109
+ # [bsz, seq_len]
110
+ if past_key_values_length > 0 and attention_mask is not None:
111
+ attention_mask = torch.cat(
112
+ (
113
+ torch.full(
114
+ (input_shape[0], past_key_values_length),
115
+ True,
116
+ dtype=attention_mask.dtype,
117
+ device=attention_mask.device,
118
+ ),
119
+ attention_mask,
120
+ ),
121
+ dim=-1,
122
+ )
123
+
124
+ if attention_mask is not None and torch.all(attention_mask):
125
+ return None # This uses the faster call when training with full samples
126
+
127
+ return attention_mask
128
+
129
+
130
+ def replace_llama2_attn_with_flash_attn():
131
+ cuda_major, cuda_minor = torch.cuda.get_device_capability()
132
+ if cuda_major < 8:
133
+ warnings.warn(
134
+ 'Flash attention is only supported on A100 or H100 GPU during training due to head dim > 64 backward.'
135
+ 'ref: https://github.com/HazyResearch/flash-attention/issues/190#issuecomment-1523359593'
136
+ )
137
+
138
+ LlamaModel._prepare_decoder_attention_mask = _prepare_decoder_attention_mask
139
+ LlamaAttention.forward = forward
140
+
141
+
142
+ def test():
143
+ from fastchat.train.llama_flash_attn_monkey_patch import \
144
+ forward as fastchat_forward
145
+ from transformers.models.llama.configuration_llama import LlamaConfig
146
+
147
+ config = LlamaConfig(
148
+ hidden_size=1024,
149
+ intermediate_size=128,
150
+ num_hidden_layers=1,
151
+ num_attention_heads=8,
152
+ max_position_embeddings=16,
153
+ )
154
+ device = torch.device('cuda')
155
+ model = LlamaModel(config)
156
+ attn = LlamaAttention(config).to(device).half()
157
+ bsz, hs, seqlen = 2, config.hidden_size, config.max_position_embeddings
158
+ position_ids = torch.arange(seqlen, dtype=torch.long, device=device).view(
159
+ -1, seqlen
160
+ )
161
+
162
+ mask = torch.full((bsz, seqlen), True, dtype=torch.bool, device=device)
163
+ for i in range(4):
164
+ hidden = torch.rand((bsz, seqlen, hs), dtype=torch.float16, device=device)
165
+ if i:
166
+ mask[0, -i:] = False
167
+ mask[1, :i] = False
168
+
169
+ lmask = model._prepare_decoder_attention_mask(mask, hidden.shape[:2], hidden, 0)
170
+ ref, _, _ = attn.forward(
171
+ hidden, attention_mask=lmask, position_ids=position_ids
172
+ )
173
+
174
+ fast, _, _ = fastchat_forward(
175
+ attn, hidden, attention_mask=mask, position_ids=position_ids
176
+ )
177
+
178
+ lmask = _prepare_decoder_attention_mask(
179
+ model, mask, hidden.shape[:2], hidden, 0
180
+ )
181
+ test, _, _ = forward(
182
+ attn, hidden, attention_mask=lmask, position_ids=position_ids
183
+ )
184
+
185
+ print(f'Mean(abs(ref)) = {torch.mean(torch.abs(ref))}')
186
+ print(f'Mean(abs(ref - fast)) = {torch.mean(torch.abs(ref - fast))}')
187
+ print(f'Mean(abs(ref - test)) = {torch.mean(torch.abs(ref - test))}')
188
+ print(f'Mean(abs(fast - test)) = {torch.mean(torch.abs(fast - test))}')
189
+ print(f'allclose(fast, test) = {torch.allclose(fast, test)}')
190
+
191
+ with torch.no_grad():
192
+ # Also check that past_kv is handled properly
193
+ hidden = torch.rand((bsz, seqlen, hs), dtype=torch.float16, device=device)
194
+ part_len = seqlen // 4
195
+ assert part_len * 4 == seqlen
196
+ mask = torch.full((bsz, seqlen), True, dtype=torch.bool, device=device)
197
+ mask[0, -2:] = False
198
+ lmask = _prepare_decoder_attention_mask(
199
+ model, mask, hidden.shape[:2], hidden, 0
200
+ )
201
+ oneshot, _, _ = forward(
202
+ attn, hidden, attention_mask=lmask, position_ids=position_ids
203
+ )
204
+ parts = []
205
+ past_kv, past_kv_len = None, 0
206
+ for i in range(4):
207
+ start = part_len * i
208
+ end = start + part_len
209
+ hidden_part = hidden[:, start:end, ...]
210
+ lmask = _prepare_decoder_attention_mask(
211
+ model,
212
+ mask[:, start:end],
213
+ hidden_part.shape[:2],
214
+ hidden_part,
215
+ past_kv_len,
216
+ )
217
+ part, _, past_kv = forward(
218
+ attn,
219
+ hidden_part.clone(),
220
+ attention_mask=lmask,
221
+ position_ids=position_ids[:, start:end],
222
+ past_key_value=past_kv,
223
+ use_cache=True,
224
+ )
225
+ parts.append(part)
226
+ past_kv_len = past_kv[0].shape[2]
227
+
228
+ print(
229
+ f'allclose(oneshot[:, 0], parts[0]) = {torch.allclose(oneshot[:, :part_len], parts[0])}'
230
+ )
231
+ print(
232
+ f'allclose(oneshot, parts) = {torch.allclose(oneshot, torch.cat(parts, dim=1))}'
233
+ )
234
+
235
+
236
+ if __name__ == '__main__':
237
+ test()
internvl/patch/llama_flash_attn_monkey_patch.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import Optional, Tuple
3
+
4
+ import torch
5
+ import torch.nn.functional as F
6
+ import transformers
7
+ from torch import nn
8
+ from transformers.models.llama.modeling_llama import apply_rotary_pos_emb
9
+
10
+
11
+ def forward(
12
+ self,
13
+ hidden_states: torch.Tensor,
14
+ attention_mask: Optional[torch.Tensor] = None,
15
+ position_ids: Optional[torch.Tensor] = None,
16
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
17
+ output_attentions: bool = False,
18
+ use_cache: bool = False,
19
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
20
+ """Input shape: Batch x Time x Channel
21
+
22
+ attention_mask: [bsz, q_len]
23
+ """
24
+ from einops import rearrange
25
+ try: # v1
26
+ from flash_attn.flash_attn_interface import \
27
+ flash_attn_unpadded_qkvpacked_func
28
+ except: # v2
29
+ from flash_attn.flash_attn_interface import \
30
+ flash_attn_varlen_qkvpacked_func as flash_attn_unpadded_qkvpacked_func
31
+ from flash_attn.bert_padding import pad_input, unpad_input
32
+
33
+ bsz, q_len, _ = hidden_states.size()
34
+
35
+ query_states = (
36
+ self.q_proj(hidden_states)
37
+ .view(bsz, q_len, self.num_heads, self.head_dim)
38
+ .transpose(1, 2)
39
+ )
40
+ key_states = (
41
+ self.k_proj(hidden_states)
42
+ .view(bsz, q_len, self.num_heads, self.head_dim)
43
+ .transpose(1, 2)
44
+ )
45
+ value_states = (
46
+ self.v_proj(hidden_states)
47
+ .view(bsz, q_len, self.num_heads, self.head_dim)
48
+ .transpose(1, 2)
49
+ )
50
+ # [bsz, q_len, nh, hd]
51
+ # [bsz, nh, q_len, hd]
52
+
53
+ kv_seq_len = key_states.shape[-2]
54
+ assert past_key_value is None, 'past_key_value is not supported'
55
+
56
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
57
+ query_states, key_states = apply_rotary_pos_emb(
58
+ query_states, key_states, cos, sin, position_ids
59
+ )
60
+ # [bsz, nh, t, hd]
61
+ assert not output_attentions, 'output_attentions is not supported'
62
+ assert not use_cache, 'use_cache is not supported'
63
+
64
+ # Flash attention codes from
65
+ # https://github.com/HazyResearch/flash-attention/blob/main/flash_attn/flash_attention.py
66
+
67
+ # transform the data into the format required by flash attention
68
+ qkv = torch.stack(
69
+ [query_states, key_states, value_states], dim=2
70
+ ) # [bsz, nh, 3, q_len, hd]
71
+ qkv = qkv.transpose(1, 3) # [bsz, q_len, 3, nh, hd]
72
+ # We have disabled _prepare_decoder_attention_mask in LlamaModel
73
+ # the attention_mask should be the same as the key_padding_mask
74
+ key_padding_mask = attention_mask
75
+
76
+ if key_padding_mask is None:
77
+ qkv = rearrange(qkv, 'b s ... -> (b s) ...')
78
+ max_s = q_len
79
+ cu_q_lens = torch.arange(
80
+ 0, (bsz + 1) * q_len, step=q_len, dtype=torch.int32, device=qkv.device
81
+ )
82
+ output = flash_attn_unpadded_qkvpacked_func(
83
+ qkv, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True
84
+ )
85
+ output = rearrange(output, '(b s) ... -> b s ...', b=bsz)
86
+ else:
87
+ nheads = qkv.shape[-2]
88
+ x = rearrange(qkv, 'b s three h d -> b s (three h d)')
89
+ x_unpad, indices, cu_q_lens, max_s = unpad_input(x, key_padding_mask)
90
+ x_unpad = rearrange(
91
+ x_unpad, 'nnz (three h d) -> nnz three h d', three=3, h=nheads
92
+ )
93
+ output_unpad = flash_attn_unpadded_qkvpacked_func(
94
+ x_unpad, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True
95
+ )
96
+ output = rearrange(
97
+ pad_input(
98
+ rearrange(output_unpad, 'nnz h d -> nnz (h d)'), indices, bsz, q_len
99
+ ),
100
+ 'b s (h d) -> b s h d',
101
+ h=nheads,
102
+ )
103
+ return self.o_proj(rearrange(output, 'b s h d -> b s (h d)')), None, None
104
+
105
+
106
+ # Disable the transformation of the attention mask in LlamaModel as the flash attention
107
+ # requires the attention mask to be the same as the key_padding_mask
108
+ def _prepare_decoder_attention_mask(
109
+ self, attention_mask, input_shape, inputs_embeds, past_key_values_length
110
+ ):
111
+ # [bsz, seq_len]
112
+ return attention_mask
113
+
114
+
115
+ def forward_2(
116
+ self,
117
+ hidden_states: torch.Tensor,
118
+ attention_mask: Optional[torch.Tensor] = None,
119
+ position_ids: Optional[torch.LongTensor] = None,
120
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
121
+ output_attentions: bool = False,
122
+ use_cache: bool = False,
123
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
124
+ bsz, q_len, _ = hidden_states.size()
125
+
126
+ query_states = (
127
+ self.q_proj(hidden_states)
128
+ .view(bsz, q_len, self.num_heads, self.head_dim)
129
+ .transpose(1, 2)
130
+ )
131
+ key_states = (
132
+ self.k_proj(hidden_states)
133
+ .view(bsz, q_len, self.num_heads, self.head_dim)
134
+ .transpose(1, 2)
135
+ )
136
+ value_states = (
137
+ self.v_proj(hidden_states)
138
+ .view(bsz, q_len, self.num_heads, self.head_dim)
139
+ .transpose(1, 2)
140
+ )
141
+
142
+ kv_seq_len = key_states.shape[-2]
143
+ if past_key_value is not None:
144
+ kv_seq_len += past_key_value[0].shape[-2]
145
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
146
+ query_states, key_states = apply_rotary_pos_emb(
147
+ query_states, key_states, cos, sin, position_ids
148
+ )
149
+
150
+ assert not output_attentions, 'output_attentions is not supported'
151
+ assert not use_cache, 'use_cache is not supported'
152
+ assert past_key_value is None, 'past_key_value is not supported'
153
+
154
+ if past_key_value is not None:
155
+ # reuse k, v, self_attention
156
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
157
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
158
+
159
+ past_key_value = (key_states, value_states) if use_cache else None
160
+ if self.training:
161
+ attn_output = F.scaled_dot_product_attention(
162
+ query_states, key_states, value_states, dropout_p=0.0, is_causal=True
163
+ )
164
+ attn_weights = None
165
+ else:
166
+ attn_weights = torch.matmul(
167
+ query_states, key_states.transpose(2, 3)
168
+ ) / math.sqrt(self.head_dim)
169
+
170
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
171
+ raise ValueError(
172
+ f'Attention weights should be of size {(bsz * self.num_heads, q_len, kv_seq_len)}, but is'
173
+ f' {attn_weights.size()}'
174
+ )
175
+
176
+ if attention_mask is not None:
177
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
178
+ raise ValueError(
179
+ f'Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}'
180
+ )
181
+ attn_weights = attn_weights + attention_mask
182
+ attn_weights = torch.max(
183
+ attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min)
184
+ )
185
+
186
+ # upcast attention to fp32
187
+ attn_weights = nn.functional.softmax(
188
+ attn_weights, dim=-1, dtype=torch.float32
189
+ ).to(query_states.dtype)
190
+ attn_output = torch.matmul(attn_weights, value_states)
191
+
192
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
193
+ raise ValueError(
194
+ f'`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is'
195
+ f' {attn_output.size()}'
196
+ )
197
+
198
+ attn_output = attn_output.transpose(1, 2)
199
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
200
+
201
+ attn_output = self.o_proj(attn_output)
202
+
203
+ if not output_attentions:
204
+ attn_weights = None
205
+
206
+ return attn_output, attn_weights, past_key_value
207
+
208
+
209
+ def replace_llama_attn_with_flash_attn():
210
+ if hasattr(F, 'scaled_dot_product_attention'):
211
+ transformers.models.llama.modeling_llama.LlamaAttention.forward = forward_2
212
+ else:
213
+ transformers.models.llama.modeling_llama.LlamaModel._prepare_decoder_attention_mask = (
214
+ _prepare_decoder_attention_mask
215
+ )
216
+ transformers.models.llama.modeling_llama.LlamaAttention.forward = forward
internvl/patch/pad_data_collator.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+
4
+ IGNORE_INDEX = -100
5
+
6
+
7
+ def pad_data_collator(features, pad_id=0):
8
+
9
+ first = features[0]
10
+ batch = {}
11
+
12
+ batch_lens = [feat['input_ids'].shape for feat in features]
13
+ max_item_length = max(batch_lens)[0]
14
+ for idx in range(len(features)):
15
+ feat = features[idx]
16
+ temp_input_ids = torch.LongTensor([pad_id] * max_item_length)
17
+ temp_input_ids[:feat['input_ids'].shape[0]] = feat['input_ids']
18
+ feat['input_ids'] = temp_input_ids
19
+ temp_labels = torch.LongTensor([IGNORE_INDEX] * max_item_length)
20
+ temp_labels[:feat['labels'].shape[0]] = feat['labels']
21
+ feat['labels'] = temp_labels
22
+ feat['attention_mask'] = feat['input_ids'].ne(pad_id)
23
+
24
+ # Special handling for labels.
25
+ # Ensure that tensor is created with the correct type
26
+ # (it should be automatically the case, but let's make sure of it.)
27
+ if 'label' in first and first['label'] is not None:
28
+ label = first['label'].item() if isinstance(first['label'], torch.Tensor) else first['label']
29
+ dtype = torch.long if isinstance(label, int) else torch.float
30
+ batch['labels'] = torch.tensor([f['label'] for f in features], dtype=dtype)
31
+ elif 'label_ids' in first and first['label_ids'] is not None:
32
+ if isinstance(first['label_ids'], torch.Tensor):
33
+ batch['labels'] = torch.stack([f['label_ids'] for f in features])
34
+ else:
35
+ dtype = torch.long if isinstance(first['label_ids'][0], int) else torch.float
36
+ batch['labels'] = torch.tensor([f['label_ids'] for f in features], dtype=dtype)
37
+
38
+ # Handling of all other possible keys.
39
+ # Again, we will use the first element to figure out which key/values are not None for this model.
40
+ for k, v in first.items():
41
+ if k not in ('label', 'label_ids') and v is not None and not isinstance(v, str):
42
+ if isinstance(v, torch.Tensor):
43
+ batch[k] = torch.stack([f[k] for f in features])
44
+ elif isinstance(v, np.ndarray):
45
+ batch[k] = torch.tensor(np.stack([f[k] for f in features]))
46
+ else:
47
+ batch[k] = torch.tensor([f[k] for f in features])
48
+ return batch
49
+
50
+
51
+ def concat_pad_data_collator(features, pad_id=0):
52
+
53
+ first = features[0]
54
+ batch = {}
55
+
56
+ batch_lens = [feat['input_ids'].shape for feat in features]
57
+ max_item_length = max(batch_lens)[0]
58
+ for idx in range(len(features)):
59
+ feat = features[idx]
60
+ temp_input_ids = torch.LongTensor([pad_id] * max_item_length)
61
+ temp_input_ids[:feat['input_ids'].shape[0]] = feat['input_ids']
62
+ feat['input_ids'] = temp_input_ids
63
+ temp_labels = torch.LongTensor([IGNORE_INDEX] * max_item_length)
64
+ temp_labels[:feat['labels'].shape[0]] = feat['labels']
65
+ feat['labels'] = temp_labels
66
+ feat['attention_mask'] = feat['input_ids'].ne(pad_id)
67
+
68
+ # Special handling for labels.
69
+ # Ensure that tensor is created with the correct type
70
+ # (it should be automatically the case, but let's make sure of it.)
71
+ if 'label' in first and first['label'] is not None:
72
+ label = first['label'].item() if isinstance(first['label'], torch.Tensor) else first['label']
73
+ dtype = torch.long if isinstance(label, int) else torch.float
74
+ batch['labels'] = torch.tensor([f['label'] for f in features], dtype=dtype)
75
+ elif 'label_ids' in first and first['label_ids'] is not None:
76
+ if isinstance(first['label_ids'], torch.Tensor):
77
+ batch['labels'] = torch.stack([f['label_ids'] for f in features])
78
+ else:
79
+ dtype = torch.long if isinstance(first['label_ids'][0], int) else torch.float
80
+ batch['labels'] = torch.tensor([f['label_ids'] for f in features], dtype=dtype)
81
+
82
+ # Handling of all other possible keys.
83
+ # Again, we will use the first element to figure out which key/values are not None for this model.
84
+ for k, v in first.items():
85
+ if k not in ('label', 'label_ids', 'pixel_values', 'image_flags') and \
86
+ v is not None and not isinstance(v, str):
87
+ if isinstance(v, torch.Tensor):
88
+ batch[k] = torch.stack([f[k] for f in features])
89
+ elif isinstance(v, np.ndarray):
90
+ batch[k] = torch.tensor(np.stack([f[k] for f in features]))
91
+ else:
92
+ batch[k] = torch.tensor([f[k] for f in features])
93
+ if k in ('pixel_values', 'image_flags'):
94
+ if isinstance(v, torch.Tensor):
95
+ batch[k] = torch.concat([f[k] for f in features])
96
+ elif isinstance(v, np.ndarray):
97
+ batch[k] = torch.concat(np.stack([f[k] for f in features]))
98
+ else:
99
+ batch[k] = torch.concat([f[k] for f in features])
100
+ return batch
internvl/patch/train_sampler_patch.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional
2
+
3
+ import torch
4
+ import transformers
5
+ from torch.utils.data import Dataset, Sampler
6
+ from transformers.tokenization_utils_base import BatchEncoding
7
+ from transformers.trainer import (LengthGroupedSampler, RandomSampler,
8
+ has_length)
9
+ from transformers.trainer_pt_utils import logger
10
+
11
+
12
+ # copy from https://github.com/haotian-liu/LLaVA/blob/main/llava/train/llava_trainer.py#L38
13
+ def split_to_even_chunks(indices, lengths, num_chunks):
14
+ """
15
+ Split a list of indices into `chunks` chunks of roughly equal lengths.
16
+ """
17
+
18
+ if len(indices) % num_chunks != 0:
19
+ return [indices[i::num_chunks] for i in range(num_chunks)]
20
+
21
+ num_indices_per_chunk = len(indices) // num_chunks
22
+
23
+ chunks = [[] for _ in range(num_chunks)]
24
+ chunks_lengths = [0 for _ in range(num_chunks)]
25
+ for index in indices:
26
+ shortest_chunk = chunks_lengths.index(min(chunks_lengths))
27
+ chunks[shortest_chunk].append(index)
28
+ chunks_lengths[shortest_chunk] += lengths[index]
29
+ if len(chunks[shortest_chunk]) == num_indices_per_chunk:
30
+ chunks_lengths[shortest_chunk] = float('inf')
31
+
32
+ return chunks
33
+
34
+
35
+ # copy from https://github.com/haotian-liu/LLaVA/blob/main/llava/train/llava_trainer.py#L88
36
+ def get_length_grouped_indices(lengths, batch_size, world_size, generator=None, merge=True):
37
+ # We need to use torch for the random part as a distributed sampler will set the random seed for torch.
38
+ indices = torch.randperm(len(lengths), generator=generator)
39
+ megabatch_size = world_size * batch_size
40
+ megabatches = [indices[i : i + megabatch_size].tolist() for i in range(0, len(lengths), megabatch_size)]
41
+ megabatches = [sorted(megabatch, key=lambda i: lengths[i], reverse=True) for megabatch in megabatches]
42
+ megabatches = [split_to_even_chunks(megabatch, lengths, world_size) for megabatch in megabatches]
43
+
44
+ return [i for megabatch in megabatches for batch in megabatch for i in batch]
45
+
46
+
47
+ # modified from https://github.com/haotian-liu/LLaVA/blob/main/llava/train/llava_trainer.py#L99
48
+ class LengthGroupedSampler(Sampler):
49
+ r"""
50
+ Sampler that samples indices in a way that groups together features of the dataset of roughly the same length while
51
+ keeping a bit of randomness.
52
+ """
53
+
54
+ def __init__(
55
+ self,
56
+ batch_size: int,
57
+ world_size: int,
58
+ dataset: Optional[Dataset] = None,
59
+ lengths: Optional[List[int]] = None,
60
+ model_input_name: Optional[str] = None,
61
+ generator=None,
62
+ ):
63
+ if dataset is None and lengths is None:
64
+ raise ValueError('One of dataset and lengths must be provided.')
65
+
66
+ self.batch_size = batch_size
67
+ if lengths is None:
68
+ model_input_name = model_input_name if model_input_name is not None else 'input_ids'
69
+ if (
70
+ not (isinstance(dataset[0], dict) or isinstance(dataset[0], BatchEncoding))
71
+ or model_input_name not in dataset[0]
72
+ ):
73
+ raise ValueError(
74
+ 'Can only automatically infer lengths for datasets whose items are dictionaries with an '
75
+ f"'{model_input_name}' key."
76
+ )
77
+ lengths = [len(feature[model_input_name]) for feature in dataset]
78
+ elif isinstance(lengths, torch.Tensor):
79
+ logger.info(
80
+ 'If lengths is a torch.Tensor, LengthGroupedSampler will be slow. Converting lengths to List[int]...'
81
+ )
82
+ lengths = lengths.tolist()
83
+ self.world_size = world_size
84
+ self.lengths = lengths
85
+ self.generator = generator
86
+
87
+ def __len__(self):
88
+ return len(self.lengths)
89
+
90
+ def __iter__(self):
91
+ indices = get_length_grouped_indices(self.lengths, self.batch_size, self.world_size, generator=self.generator)
92
+ return iter(indices)
93
+
94
+
95
+ # patch trainer
96
+ def _get_train_sampler(self) -> Optional[torch.utils.data.Sampler]:
97
+ if self.train_dataset is None or not has_length(self.train_dataset):
98
+ return None
99
+ # Build the sampler.
100
+ if self.args.group_by_length:
101
+ lengths = []
102
+ for dataset in self.train_dataset.datasets:
103
+ lengths = lengths + dataset.length
104
+ model_input_name = self.tokenizer.model_input_names[0] if self.tokenizer is not None else None
105
+ return LengthGroupedSampler(
106
+ self.args.train_batch_size,
107
+ world_size=self.args.world_size * self.args.gradient_accumulation_steps,
108
+ # self.args.train_batch_size * self.args.gradient_accumulation_steps,
109
+ dataset=self.train_dataset,
110
+ lengths=lengths,
111
+ model_input_name=model_input_name,
112
+ )
113
+ else:
114
+ return RandomSampler(self.train_dataset)
115
+
116
+
117
+ def replace_train_sampler():
118
+ transformers.Trainer._get_train_sampler = _get_train_sampler
119
+ print('Replace train sampler!!')
misc.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+ # --------------------------------------------------------
7
+ # References:
8
+ # DeiT: https://github.com/facebookresearch/deit
9
+ # BEiT: https://github.com/microsoft/unilm/tree/master/beit
10
+ # --------------------------------------------------------
11
+
12
+ import builtins
13
+ import datetime
14
+ import os
15
+ import time
16
+ from collections import defaultdict, deque
17
+ from pathlib import Path
18
+
19
+ import torch
20
+ import torch.distributed as dist
21
+ # from torch._six import inf
22
+
23
+
24
+ class SmoothedValue(object):
25
+ """Track a series of values and provide access to smoothed values over a
26
+ window or the global series average.
27
+ """
28
+
29
+ def __init__(self, window_size=20, fmt=None):
30
+ if fmt is None:
31
+ fmt = "{median:.4f} ({global_avg:.4f})"
32
+ self.deque = deque(maxlen=window_size)
33
+ self.total = 0.0
34
+ self.count = 0
35
+ self.fmt = fmt
36
+
37
+ def update(self, value, n=1):
38
+ self.deque.append(value)
39
+ self.count += n
40
+ self.total += value * n
41
+
42
+ def synchronize_between_processes(self):
43
+ """
44
+ Warning: does not synchronize the deque!
45
+ """
46
+ if not is_dist_avail_and_initialized():
47
+ return
48
+ t = torch.tensor([self.count, self.total], dtype=torch.float64, device='cuda')
49
+ dist.barrier()
50
+ dist.all_reduce(t)
51
+ t = t.tolist()
52
+ self.count = int(t[0])
53
+ self.total = t[1]
54
+
55
+ @property
56
+ def median(self):
57
+ d = torch.tensor(list(self.deque))
58
+ return d.median().item()
59
+
60
+ @property
61
+ def avg(self):
62
+ d = torch.tensor(list(self.deque), dtype=torch.float32)
63
+ return d.mean().item()
64
+
65
+ @property
66
+ def global_avg(self):
67
+ return self.total / self.count
68
+
69
+ @property
70
+ def max(self):
71
+ return max(self.deque)
72
+
73
+ @property
74
+ def value(self):
75
+ return self.deque[-1]
76
+
77
+ def __str__(self):
78
+ return self.fmt.format(
79
+ median=self.median,
80
+ avg=self.avg,
81
+ global_avg=self.global_avg,
82
+ max=self.max,
83
+ value=self.value)
84
+
85
+
86
+ class MetricLogger(object):
87
+ def __init__(self, delimiter="\t", logger=None):
88
+ self.meters = defaultdict(SmoothedValue)
89
+ self.delimiter = delimiter
90
+ self.logger = logger
91
+
92
+ def update(self, **kwargs):
93
+ for k, v in kwargs.items():
94
+ if v is None:
95
+ continue
96
+ if isinstance(v, torch.Tensor):
97
+ v = v.item()
98
+ assert isinstance(v, (float, int))
99
+ self.meters[k].update(v)
100
+
101
+ def __getattr__(self, attr):
102
+ if attr in self.meters:
103
+ return self.meters[attr]
104
+ if attr in self.__dict__:
105
+ return self.__dict__[attr]
106
+ raise AttributeError("'{}' object has no attribute '{}'".format(
107
+ type(self).__name__, attr))
108
+
109
+ def __str__(self):
110
+ loss_str = []
111
+ for name, meter in self.meters.items():
112
+ loss_str.append(
113
+ "{}: {}".format(name, str(meter))
114
+ )
115
+ return self.delimiter.join(loss_str)
116
+
117
+ def synchronize_between_processes(self):
118
+ for meter in self.meters.values():
119
+ meter.synchronize_between_processes()
120
+
121
+ def add_meter(self, name, meter):
122
+ self.meters[name] = meter
123
+
124
+ def log_every(self, iterable, print_freq, header=None):
125
+ i = 0
126
+ if not header:
127
+ header = ''
128
+ start_time = time.time()
129
+ end = time.time()
130
+ iter_time = SmoothedValue(fmt='{avg:.4f}')
131
+ data_time = SmoothedValue(fmt='{avg:.4f}')
132
+ space_fmt = ':' + str(len(str(len(iterable)))) + 'd'
133
+ log_msg = [
134
+ header,
135
+ '[{0' + space_fmt + '}/{1}]',
136
+ 'eta: {eta}',
137
+ '{meters}',
138
+ 'time: {time}',
139
+ 'data: {data}'
140
+ ]
141
+ if torch.cuda.is_available():
142
+ log_msg.append('max mem: {memory:.0f}')
143
+ log_msg = self.delimiter.join(log_msg)
144
+ MB = 1024.0 * 1024.0
145
+ for obj in iterable:
146
+ data_time.update(time.time() - end)
147
+ yield obj
148
+ iter_time.update(time.time() - end)
149
+ if i % print_freq == 0 or i == len(iterable) - 1:
150
+ eta_seconds = iter_time.global_avg * (len(iterable) - i)
151
+ eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
152
+ if torch.cuda.is_available():
153
+ self.logger.info(log_msg.format(
154
+ i, len(iterable), eta=eta_string,
155
+ meters=str(self),
156
+ time=str(iter_time), data=str(data_time),
157
+ memory=torch.cuda.max_memory_allocated() / MB))
158
+ else:
159
+ self.logger.info(log_msg.format(
160
+ i, len(iterable), eta=eta_string,
161
+ meters=str(self),
162
+ time=str(iter_time), data=str(data_time)))
163
+ i += 1
164
+ end = time.time()
165
+ total_time = time.time() - start_time
166
+ total_time_str = str(datetime.timedelta(seconds=int(total_time)))
167
+ self.logger.info('{} Total time: {} ({:.4f} s / it)'.format(
168
+ header, total_time_str, total_time / len(iterable)))
169
+
170
+
171
+ def setup_for_distributed(is_master):
172
+ """
173
+ This function disables printing when not in master process
174
+ """
175
+ builtin_print = builtins.print
176
+
177
+ def print(*args, **kwargs):
178
+ force = kwargs.pop('force', False)
179
+ # force = force or (get_world_size() > 8)
180
+ if is_master or force:
181
+ now = datetime.datetime.now().time()
182
+ builtin_print('[{}] '.format(now), end='') # print with time stamp
183
+ builtin_print(*args, **kwargs)
184
+
185
+ builtins.print = print
186
+
187
+
188
+ def is_dist_avail_and_initialized():
189
+ if not dist.is_available():
190
+ return False
191
+ if not dist.is_initialized():
192
+ return False
193
+ return True
194
+
195
+
196
+ def get_world_size():
197
+ if not is_dist_avail_and_initialized():
198
+ return 1
199
+ return dist.get_world_size()
200
+
201
+
202
+ def get_rank():
203
+ if not is_dist_avail_and_initialized():
204
+ return 0
205
+ return dist.get_rank()
206
+
207
+
208
+ def is_main_process():
209
+ return get_rank() == 0
210
+
211
+
212
+ def save_on_master(*args, **kwargs):
213
+ if is_main_process():
214
+ torch.save(*args, **kwargs)
215
+
216
+
217
+ def init_distributed_mode(args):
218
+ if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ and 'LOCAL_RANK' in os.environ:
219
+ args.rank = int(os.environ["RANK"])
220
+ args.world_size = int(os.environ['WORLD_SIZE'])
221
+ args.gpu = int(os.environ['LOCAL_RANK'])
222
+ elif 'SLURM_PROCID' in os.environ:
223
+ args.rank = int(os.environ['SLURM_PROCID'])
224
+ args.gpu = args.rank % torch.cuda.device_count()
225
+ else:
226
+ print('Not using distributed mode')
227
+ setup_for_distributed(is_master=True) # hack
228
+ args.distributed = False
229
+ return
230
+
231
+ args.distributed = True
232
+
233
+ torch.cuda.set_device(args.gpu)
234
+ args.dist_backend = 'nccl'
235
+ print('| distributed init (rank {}): gpu {}'.format(
236
+ args.rank, args.gpu), flush=True)
237
+
238
+ from datetime import timedelta
239
+ torch.distributed.init_process_group(backend=args.dist_backend, world_size=args.world_size, rank=args.rank, timeout=timedelta(seconds=7200000))
240
+ torch.distributed.barrier()
241
+ setup_for_distributed(args.rank == 0)
242
+
243
+
244
+ class NativeScalerWithGradNormCount:
245
+ state_dict_key = "amp_scaler"
246
+
247
+ def __init__(self):
248
+ self._scaler = torch.cuda.amp.GradScaler()
249
+
250
+ def __call__(self, loss, optimizer, clip_grad=None, parameters=None, create_graph=False, update_grad=True):
251
+ self._scaler.scale(loss).backward(create_graph=create_graph)
252
+ if update_grad:
253
+ if clip_grad is not None:
254
+ assert parameters is not None
255
+ self._scaler.unscale_(optimizer) # unscale the gradients of optimizer's assigned params in-place
256
+ norm = torch.nn.utils.clip_grad_norm_(parameters, clip_grad)
257
+ else:
258
+ self._scaler.unscale_(optimizer)
259
+ norm = get_grad_norm_(parameters)
260
+ self._scaler.step(optimizer)
261
+ self._scaler.update()
262
+ else:
263
+ norm = None
264
+ return norm
265
+
266
+ def state_dict(self):
267
+ return self._scaler.state_dict()
268
+
269
+ def load_state_dict(self, state_dict):
270
+ self._scaler.load_state_dict(state_dict)
271
+
272
+
273
+ def get_grad_norm_(parameters, norm_type: float = 2.0) -> torch.Tensor:
274
+ if isinstance(parameters, torch.Tensor):
275
+ parameters = [parameters]
276
+ parameters = [p for p in parameters if p.grad is not None]
277
+ norm_type = float(norm_type)
278
+ if len(parameters) == 0:
279
+ return torch.tensor(0.)
280
+ device = parameters[0].grad.device
281
+ if norm_type == inf:
282
+ total_norm = max(p.grad.detach().abs().max().to(device) for p in parameters)
283
+ else:
284
+ total_norm = torch.norm(torch.stack([torch.norm(p.grad.detach(), norm_type).to(device) for p in parameters]), norm_type)
285
+ return total_norm
286
+
287
+
288
+ def save_model(args, epoch, model, model_without_ddp, optimizer, loss_scaler, save_force=False):
289
+ if get_rank() == 0 and ((epoch + 1) % args.save_freq == 0 or (epoch + 1) == args.epochs or save_force):
290
+ output_dir = Path(args.output_dir)
291
+ epoch_name = str(epoch)
292
+ if loss_scaler is not None:
293
+ checkpoint_paths = [output_dir / ('checkpoint-%s.pth' % epoch_name)]
294
+ for checkpoint_path in checkpoint_paths:
295
+ to_save = {
296
+ 'model': model_without_ddp.state_dict(),
297
+ 'optimizer': optimizer.state_dict(),
298
+ 'epoch': epoch,
299
+ 'scaler': loss_scaler.state_dict(),
300
+ 'args': args,
301
+ }
302
+
303
+ save_on_master(to_save, checkpoint_path)
304
+ else:
305
+ client_state = {'epoch': epoch}
306
+ model.save_checkpoint(save_dir=args.output_dir, tag="checkpoint-%s" % epoch_name, client_state=client_state)
307
+
308
+ if args.auto_remove:
309
+
310
+ for ckpt in os.listdir(args.output_dir):
311
+ try:
312
+ if not (ckpt.startswith('checkpoint-') and ckpt.endswith('.pth')):
313
+ raise ValueError()
314
+ ckpt_epoch = int(ckpt[len('checkpoint-'):-len('.pth')])
315
+ except ValueError:
316
+ continue
317
+
318
+ if ckpt_epoch < epoch:
319
+ ckpt_path = os.path.join(args.output_dir, ckpt)
320
+ print('removing old checkpoint:', ckpt_path)
321
+ os.remove(ckpt_path)
322
+
323
+
324
+ def load_model(args, model_without_ddp, optimizer, loss_scaler):
325
+ if args.resume:
326
+ if args.resume.startswith('https'):
327
+ checkpoint = torch.hub.load_state_dict_from_url(
328
+ args.resume, map_location='cpu', check_hash=True)
329
+ else:
330
+ checkpoint = torch.load(args.resume, map_location='cpu')
331
+ if 'model' in checkpoint:
332
+ _ckp = checkpoint['model']
333
+ elif 'module' in checkpoint:
334
+ _ckp = checkpoint['module']
335
+ else:
336
+ _ckp = checkpoint
337
+ model_without_ddp.load_state_dict(_ckp)
338
+ print("Resume checkpoint %s" % args.resume)
339
+ if 'optimizer' in checkpoint and 'epoch' in checkpoint and not (hasattr(args, 'eval') and args.eval):
340
+ optimizer.load_state_dict(checkpoint['optimizer'])
341
+ args.start_epoch = checkpoint['epoch'] + 1
342
+ if 'scaler' in checkpoint:
343
+ loss_scaler.load_state_dict(checkpoint['scaler'])
344
+ print("With optim & sched!")
345
+
346
+
347
+ def all_reduce_mean(x):
348
+ world_size = get_world_size()
349
+ if world_size > 1:
350
+ x_reduce = torch.tensor(x).cuda()
351
+ dist.all_reduce(x_reduce)
352
+ x_reduce /= world_size
353
+ return x_reduce.item()
354
+ else:
355
+ return x
356
+
357
+ def all_reduce(x, op):
358
+ world_size = get_world_size()
359
+ if world_size > 1:
360
+ x_reduce = torch.tensor(x).cuda()
361
+ dist.all_reduce(x_reduce, op)
362
+ return x_reduce.item()
363
+ else:
364
+ return x
results_qwen35_guided_vqav2/run.log ADDED
The diff for this file is too large to render. See raw diff
 
results_qwen35_guided_vqav2_reasoning_on4096_off16_bg/run_260425024028/analysis_on_vs_off/both_correct.json ADDED
The diff for this file is too large to render. See raw diff
 
results_qwen35_guided_vqav2_reasoning_on4096_off16_bg/run_260425024028/analysis_on_vs_off/both_reason_correct.json ADDED
The diff for this file is too large to render. See raw diff
 
results_qwen35_guided_vqav2_reasoning_on4096_off16_bg/run_260425024028/analysis_on_vs_off/both_wrong.json ADDED
The diff for this file is too large to render. See raw diff
 
results_qwen35_guided_vqav2_reasoning_on4096_off16_bg/run_260425024028/analysis_on_vs_off/both_wrong_with_on_off_reasoning.json ADDED
The diff for this file is too large to render. See raw diff
 
results_qwen35_guided_vqav2_reasoning_on4096_off16_bg/run_260425024028/analysis_on_vs_off/off_reason_correct_on_reason_wrong.json ADDED
The diff for this file is too large to render. See raw diff
 
results_qwen35_guided_vqav2_reasoning_on4096_off16_bg/run_260425024028/qwen35_4b_thinking_on/PruneLayer_0.0416667_PruneRatio_0.05/console_260425024028.log ADDED
The diff for this file is too large to render. See raw diff
 
results_qwen35_guided_vqav2_smoke/qwen35_4b_thinking_off/PruneLayer_0.0416667_PruneRatio_0.05/vqav2_val_260423091708.json ADDED
@@ -0,0 +1 @@
 
 
1
+ [{"question": "Where is he looking? Answer the question using a single word or phrase.", "question_id": 262148000, "answer": "down", "large_answer": "down", "large_model_time": 1.317284345626831, "small_answer": "down", "small_model_time": 0.929917573928833, "original_confidence": 0.9462397048770936, "consistency_score": 0.9462397048770936}]
run.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ import torchvision.transforms as T
4
+ from decord import VideoReader, cpu
5
+ from PIL import Image
6
+ from torchvision.transforms.functional import InterpolationMode
7
+ from transformers import AutoModel, AutoTokenizer
8
+
9
+ IMAGENET_MEAN = (0.485, 0.456, 0.406)
10
+ IMAGENET_STD = (0.229, 0.224, 0.225)
11
+
12
+
13
+ def build_transform(input_size):
14
+ MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
15
+ transform = T.Compose([
16
+ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
17
+ T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
18
+ T.ToTensor(),
19
+ T.Normalize(mean=MEAN, std=STD)
20
+ ])
21
+ return transform
22
+
23
+
24
+ def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
25
+ best_ratio_diff = float('inf')
26
+ best_ratio = (1, 1)
27
+ area = width * height
28
+ for ratio in target_ratios:
29
+ target_aspect_ratio = ratio[0] / ratio[1]
30
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
31
+ if ratio_diff < best_ratio_diff:
32
+ best_ratio_diff = ratio_diff
33
+ best_ratio = ratio
34
+ elif ratio_diff == best_ratio_diff:
35
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
36
+ best_ratio = ratio
37
+ return best_ratio
38
+
39
+
40
+ def dynamic_preprocess(image, min_num=1, max_num=6, image_size=448, use_thumbnail=False):
41
+ orig_width, orig_height = image.size
42
+ aspect_ratio = orig_width / orig_height
43
+
44
+ # calculate the existing image aspect ratio
45
+ target_ratios = set(
46
+ (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
47
+ i * j <= max_num and i * j >= min_num)
48
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
49
+
50
+ # find the closest aspect ratio to the target
51
+ target_aspect_ratio = find_closest_aspect_ratio(
52
+ aspect_ratio, target_ratios, orig_width, orig_height, image_size)
53
+
54
+ # calculate the target width and height
55
+ target_width = image_size * target_aspect_ratio[0]
56
+ target_height = image_size * target_aspect_ratio[1]
57
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
58
+
59
+ # resize the image
60
+ resized_img = image.resize((target_width, target_height))
61
+ processed_images = []
62
+ for i in range(blocks):
63
+ box = (
64
+ (i % (target_width // image_size)) * image_size,
65
+ (i // (target_width // image_size)) * image_size,
66
+ ((i % (target_width // image_size)) + 1) * image_size,
67
+ ((i // (target_width // image_size)) + 1) * image_size
68
+ )
69
+ # split the image
70
+ split_img = resized_img.crop(box)
71
+ processed_images.append(split_img)
72
+ assert len(processed_images) == blocks
73
+ if use_thumbnail and len(processed_images) != 1:
74
+ thumbnail_img = image.resize((image_size, image_size))
75
+ processed_images.append(thumbnail_img)
76
+ return processed_images
77
+
78
+
79
+ def load_image(image_file, input_size=448, max_num=6):
80
+ image = Image.open(image_file).convert('RGB')
81
+ transform = build_transform(input_size=input_size)
82
+ images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
83
+ pixel_values = [transform(image) for image in images]
84
+ pixel_values = torch.stack(pixel_values)
85
+ return pixel_values
86
+
87
+
88
+ path = '/mnt/nas_jiasheng/zhaowangbo/early_exit_vl_CVPR2025/model_ckpts/models--OpenGVLab--InternVL2-1B'
89
+ model = AutoModel.from_pretrained(
90
+ path,
91
+ torch_dtype=torch.bfloat16,
92
+ low_cpu_mem_usage=True,
93
+ trust_remote_code=True).eval().cuda()
94
+
95
+ tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
96
+ # set the max number of tiles in `max_num`
97
+ pixel_values = load_image('internvl_chat/examples/image1.jpg', max_num=6).to(torch.bfloat16).cuda()
98
+
99
+ generation_config = dict(
100
+ num_beams=1,
101
+ max_new_tokens=1024,
102
+ do_sample=False,
103
+ )
104
+
105
+
106
+
107
+ # single-image single-round conversation (单图单轮对话)
108
+ question = '<image>\nPlease describe the image with 1 word.'
109
+ response = model.chat(tokenizer, pixel_values, question, generation_config)
110
+ print(f'User: {question}')
111
+ print(f'Assistant: {response}')
112
+
113
+
setup_sgl_2b_env.sh ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ set -e
2
+
3
+ ENV_NAME=${1:-sgl2b}
4
+
5
+ if conda env list | awk '{print $1}' | grep -qx "sgl26b"; then
6
+ conda create -y -n "${ENV_NAME}" --clone sgl26b
7
+ echo "Cloned sgl26b into ${ENV_NAME}"
8
+ exit 0
9
+ fi
10
+
11
+ echo "sgl26b was not found."
12
+ echo "Create a fresh environment manually following the official InternVL dependency stack, then install this repo in editable mode."
13
+ exit 1
textvqa2B-26B.sh ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ set -x
2
+
3
+ export PYTHONPATH="$(pwd):${PYTHONPATH}"
4
+
5
+ MASTER_PORT=${MASTER_PORT:-63669}
6
+ PORT=${PORT:-63665}
7
+ GPUS=${GPUS:-8}
8
+ export MASTER_PORT=${MASTER_PORT}
9
+ export PORT=${PORT}
10
+
11
+
12
+ CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \
13
+ torchrun \
14
+ --nnodes=1 \
15
+ --node_rank=0 \
16
+ --master_addr=127.0.0.1 \
17
+ --nproc_per_node=${GPUS} \
18
+ --master_port=${MASTER_PORT} \
19
+ eval/vqa/evaluate_vqa.py \
20
+ --small_checkpoint "/root/model_ckpts/models--OpenGVLab--InternVL2-2B" \
21
+ --large_checkpoint "/root/model_ckpts/models--OpenGVLab--InternVL2-26B" \
22
+ --datasets "textvqa_val" --dynamic \
23
+ --out-dir "results-2B-26B_textvqa_val" \
24
+ --large_model_prune_layer 0.4 \
25
+ --large_model_prune_ratio 0.4
26
+
textvqa2B-largeonly.sh ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ set -x
2
+
3
+ export PYTHONPATH="$(pwd):${PYTHONPATH}"
4
+
5
+ MASTER_PORT=${MASTER_PORT:-63669}
6
+ GPUS=${GPUS:-1}
7
+ CHECKPOINT=${CHECKPOINT:-/home/gxr/model_ckpts/models--OpenGVLab--InternVL2-2B}
8
+ OUT_DIR=${OUT_DIR:-results_textvqa_largeonly_2b}
9
+
10
+ export MASTER_PORT=${MASTER_PORT}
11
+
12
+ torchrun \
13
+ --nnodes=1 \
14
+ --node_rank=0 \
15
+ --master_addr=127.0.0.1 \
16
+ --nproc_per_node=${GPUS} \
17
+ --master_port=${MASTER_PORT} \
18
+ eval/vqa/evaluate_vqa_large_only.py \
19
+ --checkpoint "${CHECKPOINT}" \
20
+ --datasets "textvqa_val" \
21
+ --dynamic \
22
+ --out-dir "${OUT_DIR}"
tools/extract_mlp.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os.path
3
+
4
+ import torch
5
+ from internvl.model.internvl_chat import InternVLChatModel
6
+
7
+ argparse = argparse.ArgumentParser()
8
+ argparse.add_argument('model_path', type=str, default='')
9
+ argparse.add_argument('output_path', type=str, default='')
10
+
11
+ args = argparse.parse_args()
12
+
13
+ model = InternVLChatModel.from_pretrained(args.model_path, torch_dtype=torch.bfloat16)
14
+ model = model.mlp1.to(torch.bfloat16)
15
+
16
+ ckpt = model.state_dict()
17
+ output_path = os.path.join(args.output_path, 'mlp_projector.pth')
18
+ torch.save(ckpt, output_path)
19
+ print('finished')
tools/extract_video_frames.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import concurrent.futures
2
+ import json
3
+ import os
4
+ import random
5
+
6
+ import av
7
+ import numpy as np
8
+ import torch
9
+ from decord import VideoReader, cpu
10
+ from PIL import Image
11
+ from tqdm.auto import tqdm
12
+
13
+ num_segments = 1
14
+
15
+ # root directory of evaluation dimension 10
16
+ dimension10_dir = './videos/20bn-something-something-v2'
17
+ # root directory of evaluation dimension 11
18
+ dimension11_dir = './videos/EPIC-KITCHENS'
19
+ # root directory of evaluation dimension 12
20
+ dimension12_dir = './videos/BreakfastII_15fps_qvga_sync'
21
+
22
+
23
+ def transform_video(buffer):
24
+ try:
25
+ buffer = buffer.numpy()
26
+ except AttributeError:
27
+ try:
28
+ buffer = buffer.asnumpy()
29
+ except AttributeError:
30
+ print('Both buffer.numpy() and buffer.asnumpy() failed.')
31
+ buffer = None
32
+ images_group = list()
33
+ for fid in range(len(buffer)):
34
+ images_group.append(Image.fromarray(buffer[fid]))
35
+ return images_group
36
+
37
+
38
+ def get_index(num_frames, num_segments):
39
+ if num_segments > num_frames:
40
+ offsets = np.array([
41
+ idx for idx in range(num_frames)
42
+ ])
43
+ else:
44
+ # uniform sampling
45
+ seg_size = float(num_frames - 1) / num_segments
46
+ start = int(seg_size / 2)
47
+ offsets = np.array([
48
+ start + int(np.round(seg_size * idx)) for idx in range(num_segments)
49
+ ])
50
+ return offsets
51
+
52
+
53
+ def fetch_images(qa_item):
54
+ use_pyav = False
55
+ segment = None
56
+ if qa_item['question_type_id'] == 10:
57
+ data_path = os.path.join(dimension10_dir, qa_item['data_id'])
58
+ start = 0.0
59
+ end = 0.0
60
+ elif qa_item['question_type_id'] == 11:
61
+ data_path = os.path.join(dimension11_dir, qa_item['data_id'].split('/')[-1])
62
+ segment = qa_item['segment']
63
+ start, end = segment[0], segment[1]
64
+ elif qa_item['question_type_id'] == 12:
65
+ data_path = os.path.join(dimension12_dir, qa_item['data_id'])
66
+ segment = qa_item['segment']
67
+ start, end = segment[0], segment[1]
68
+ use_pyav = True
69
+
70
+ if use_pyav:
71
+ # using pyav for decoding videos in evaluation dimension 12
72
+ reader = av.open(data_path)
73
+ frames = [torch.from_numpy(f.to_rgb().to_ndarray()) for f in reader.decode(video=0)]
74
+ video_len = len(frames)
75
+ start_frame, end_frame = start, end
76
+ end_frame = min(end_frame, video_len)
77
+ offset = get_index(end_frame - start_frame, num_segments)
78
+ frame_indices = offset + start_frame
79
+ buffer = torch.stack([frames[idx] for idx in frame_indices])
80
+ else:
81
+ # using decord for decoding videos in evaluation dimension 10-11
82
+ vr = VideoReader(data_path, num_threads=1, ctx=cpu(0))
83
+ video_len = len(vr)
84
+ fps = vr.get_avg_fps()
85
+ if segment is not None:
86
+ # obtain start and end frame for the video segment in evaluation dimension 11
87
+ start_frame = int(min(max(start * fps, 0), video_len - 1))
88
+ end_frame = int(min(max(end * fps, 0), video_len - 1))
89
+ tot_frames = int(end_frame - start_frame)
90
+ offset = get_index(tot_frames, num_segments)
91
+ frame_indices = offset + start_frame
92
+ else:
93
+ # sample frames of the video in evaluation dimension 10
94
+ frame_indices = get_index(video_len - 1, num_segments)
95
+ vr.seek(0)
96
+ buffer = vr.get_batch(frame_indices)
97
+ return transform_video(buffer)
98
+
99
+
100
+ def fetch_images_parallel(qa_item):
101
+ return qa_item, fetch_images(qa_item)
102
+
103
+
104
+ if __name__ == '__main__':
105
+ data = json.load(open('SEED-Bench.json'))
106
+ video_img_dir = 'SEED-Bench-video-image'
107
+ ques_type_id_to_name = {id:n for n,id in data['question_type'].items()}
108
+
109
+ video_data = [x for x in data['questions'] if x['data_type'] == 'video']
110
+
111
+ with open(output, 'w') as f, concurrent.futures.ThreadPoolExecutor() as executor:
112
+ future_to_images = {executor.submit(fetch_images_parallel, qa_item): qa_item for qa_item in video_data}
113
+ for future in tqdm(concurrent.futures.as_completed(future_to_images), total=len(future_to_images)):
114
+ qa_item = future_to_images[future]
115
+ try:
116
+ qa_item, images = future.result()
117
+ except Exception as exc:
118
+ print(f'{qa_item} generated an exception: {exc}')
119
+ else:
120
+ img_file = f"{qa_item['question_type_id']}_{qa_item['question_id']}.png"
121
+ images[0].save(os.path.join(video_img_dir, img_file))