Mizukiluke
commited on
Commit
•
a465221
1
Parent(s):
60f1357
Upload folder using huggingface_hub (#1)
Browse files- b5a7a3bc561bab323d9df715e2b833e058fc8a1e1a7cbfb282a567f1ff396e9e (4219dc92949a91b733283cfb6033dda766d0a2b2)
- ab115dbcff4be1744853da1d3e2aeafb974ae1449a181bb3c757fcfbb49f6b1a (b31989d6aae91e05fe4501cac64456d5c5d6b6b4)
- README.md +126 -3
- config.json +47 -0
- configuration_hyper_qwen2.py +123 -0
- configuration_mplugowl3.py +47 -0
- generation_config.json +14 -0
- image_processing_mplugowl3.py +406 -0
- merges.txt +0 -0
- model.safetensors +3 -0
- modeling_hyper_qwen2.py +1541 -0
- modeling_mplugowl3.py +246 -0
- processing_mplugowl3.py +372 -0
- sdpa.py +61 -0
- tokenizer.json +0 -0
- tokenizer_config.json +40 -0
- vocab.json +0 -0
- x_sdpa.py +61 -0
README.md
CHANGED
@@ -1,3 +1,126 @@
|
|
1 |
-
---
|
2 |
-
license: apache-2.0
|
3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
license: apache-2.0
|
3 |
+
language:
|
4 |
+
- en
|
5 |
+
pipeline_tag: visual-question-answering
|
6 |
+
tags:
|
7 |
+
- chat
|
8 |
+
---
|
9 |
+
|
10 |
+
# mPLUG-Owl3
|
11 |
+
|
12 |
+
## Introduction
|
13 |
+
mPLUG-Owl3 is a state-of-the-art multi-modal large language model designed to tackle the challenges of long image sequence understanding. We propose Hyper Attention, which boosts the speed of long visual sequence understanding in multimodal large language models by sixfold, allowing for processing of visual sequences that are eight times longer. Meanwhile, we maintain excellent performance on single-image, multi-image, and video tasks.
|
14 |
+
|
15 |
+
Github: [mPLUG-Owl](https://github.com/X-PLUG/mPLUG-Owl)
|
16 |
+
|
17 |
+
## Quickstart
|
18 |
+
|
19 |
+
Load the mPLUG-Owl3. We now only support attn_implementation in ```['sdpa', 'flash_attention_2']```.
|
20 |
+
```Python
|
21 |
+
import torch
|
22 |
+
config = mPLUGOwl3Config.from_pretrained('./checkpoint_240728')
|
23 |
+
print(config)
|
24 |
+
# model = mPLUGOwl3Model(config).cuda().half()
|
25 |
+
model = mPLUGOwl3Model.from_pretrained('./checkpoint_240728', attn_implementation='sdpa', torch_dtype=torch.half)
|
26 |
+
model.eval().cuda()
|
27 |
+
```
|
28 |
+
Chat with images.
|
29 |
+
```Python
|
30 |
+
from PIL import Image
|
31 |
+
|
32 |
+
from transformers import AutoTokenizer, AutoProcessor
|
33 |
+
from decord import VideoReader, cpu # pip install decord
|
34 |
+
model_path = 'mPLUG/mPLUG-Owl3-7B-240728'
|
35 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path)
|
36 |
+
processor = model.init_processor(tokenizer)
|
37 |
+
|
38 |
+
image = Image.new('RGB', (500, 500), color='red')
|
39 |
+
|
40 |
+
messages = [
|
41 |
+
{"role": "user", "content": """<|image|>
|
42 |
+
Describe this image."""},
|
43 |
+
{"role": "assistant", "content": ""}
|
44 |
+
]
|
45 |
+
|
46 |
+
inputs = processor(messages, images=image, videos=None)
|
47 |
+
|
48 |
+
inputs.to('cuda')
|
49 |
+
inputs.update({
|
50 |
+
'tokenizer': tokenizer,
|
51 |
+
'max_new_tokens':100,
|
52 |
+
'decode_text':True,
|
53 |
+
})
|
54 |
+
|
55 |
+
|
56 |
+
g = model.generate(**inputs)
|
57 |
+
print(g)
|
58 |
+
```
|
59 |
+
|
60 |
+
Chat with a video.
|
61 |
+
```Python
|
62 |
+
from PIL import Image
|
63 |
+
|
64 |
+
from transformers import AutoTokenizer, AutoProcessor
|
65 |
+
from decord import VideoReader, cpu # pip install decord
|
66 |
+
model_path = 'mPLUG/mPLUG-Owl3-7B-240728'
|
67 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path)
|
68 |
+
processor = model.init_processor(tokenizer)
|
69 |
+
|
70 |
+
|
71 |
+
messages = [
|
72 |
+
{"role": "user", "content": """<|video|>
|
73 |
+
Describe this video."""},
|
74 |
+
{"role": "assistant", "content": ""}
|
75 |
+
]
|
76 |
+
|
77 |
+
videos = ['/nas-mmu-data/examples/car_room.mp4']
|
78 |
+
|
79 |
+
MAX_NUM_FRAMES=16
|
80 |
+
|
81 |
+
def encode_video(video_path):
|
82 |
+
def uniform_sample(l, n):
|
83 |
+
gap = len(l) / n
|
84 |
+
idxs = [int(i * gap + gap / 2) for i in range(n)]
|
85 |
+
return [l[i] for i in idxs]
|
86 |
+
|
87 |
+
vr = VideoReader(video_path, ctx=cpu(0))
|
88 |
+
sample_fps = round(vr.get_avg_fps() / 1) # FPS
|
89 |
+
frame_idx = [i for i in range(0, len(vr), sample_fps)]
|
90 |
+
if len(frame_idx) > MAX_NUM_FRAMES:
|
91 |
+
frame_idx = uniform_sample(frame_idx, MAX_NUM_FRAMES)
|
92 |
+
frames = vr.get_batch(frame_idx).asnumpy()
|
93 |
+
frames = [Image.fromarray(v.astype('uint8')) for v in frames]
|
94 |
+
print('num frames:', len(frames))
|
95 |
+
return frames
|
96 |
+
video_frames = [encode_video(_) for _ in videos]
|
97 |
+
inputs = processor(messages, images=None, videos=video_frames)
|
98 |
+
|
99 |
+
inputs.to('cuda')
|
100 |
+
inputs.update({
|
101 |
+
'tokenizer': tokenizer,
|
102 |
+
'max_new_tokens':100,
|
103 |
+
'decode_text':True,
|
104 |
+
})
|
105 |
+
|
106 |
+
|
107 |
+
g = model.generate(**inputs)
|
108 |
+
print(g)
|
109 |
+
```
|
110 |
+
|
111 |
+
|
112 |
+
## Citation
|
113 |
+
|
114 |
+
If you find our work helpful, feel free to give us a cite.
|
115 |
+
|
116 |
+
```
|
117 |
+
@misc{ye2024mplugowl3longimagesequenceunderstanding,
|
118 |
+
title={mPLUG-Owl3: Towards Long Image-Sequence Understanding in Multi-Modal Large Language Models},
|
119 |
+
author={Jiabo Ye and Haiyang Xu and Haowei Liu and Anwen Hu and Ming Yan and Qi Qian and Ji Zhang and Fei Huang and Jingren Zhou},
|
120 |
+
year={2024},
|
121 |
+
eprint={2408.04840},
|
122 |
+
archivePrefix={arXiv},
|
123 |
+
primaryClass={cs.CV},
|
124 |
+
url={https://arxiv.org/abs/2408.04840},
|
125 |
+
}
|
126 |
+
```
|
config.json
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"mPLUGOwl3Model"
|
4 |
+
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoConfig": "configuration_mplugowl3.mPLUGOwl3Config",
|
7 |
+
"AutoModel": "modeling_mplugowl3.mPLUGOwl3Model",
|
8 |
+
"AutoModelForCausalLM": "modeling_mplugowl3.mPLUGOwl3Model"
|
9 |
+
},
|
10 |
+
"attention_dropout": 0.0,
|
11 |
+
"bos_token_id": 151643,
|
12 |
+
"eos_token_id": 151645,
|
13 |
+
"hidden_act": "silu",
|
14 |
+
"hidden_size": 3584,
|
15 |
+
"initializer_range": 0.02,
|
16 |
+
"intermediate_size": 18944,
|
17 |
+
"max_position_embeddings": 32768,
|
18 |
+
"max_window_layers": 28,
|
19 |
+
"model_type": "mplugowl3",
|
20 |
+
"num_attention_heads": 28,
|
21 |
+
"num_hidden_layers": 28,
|
22 |
+
"num_key_value_heads": 4,
|
23 |
+
"rms_norm_eps": 1e-06,
|
24 |
+
"rope_theta": 1000000.0,
|
25 |
+
"sliding_window": 131072,
|
26 |
+
"tie_word_embeddings": false,
|
27 |
+
"torch_dtype": "bfloat16",
|
28 |
+
"transformers_version": "4.41.2",
|
29 |
+
"use_cache": true,
|
30 |
+
"use_sliding_window": false,
|
31 |
+
"vocab_size": 151851,
|
32 |
+
"hyper_layers": [
|
33 |
+
1,
|
34 |
+
9,
|
35 |
+
17,
|
36 |
+
25
|
37 |
+
],
|
38 |
+
"vision_config": {
|
39 |
+
"hidden_size": 1152,
|
40 |
+
"image_size": 384,
|
41 |
+
"intermediate_size": 4304,
|
42 |
+
"model_type": "siglip_vision_model",
|
43 |
+
"num_attention_heads": 16,
|
44 |
+
"num_hidden_layers": 27,
|
45 |
+
"patch_size": 14
|
46 |
+
}
|
47 |
+
}
|
configuration_hyper_qwen2.py
ADDED
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers.configuration_utils import PretrainedConfig
|
2 |
+
|
3 |
+
|
4 |
+
|
5 |
+
|
6 |
+
class HyperQwen2Config(PretrainedConfig):
|
7 |
+
r"""
|
8 |
+
This is the configuration class to store the configuration of a [`Qwen2Model`]. It is used to instantiate a
|
9 |
+
Qwen2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
10 |
+
with the defaults will yield a similar configuration to that of
|
11 |
+
Qwen2-7B-beta [Qwen/Qwen2-7B-beta](https://huggingface.co/Qwen/Qwen2-7B-beta).
|
12 |
+
|
13 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
14 |
+
documentation from [`PretrainedConfig`] for more information.
|
15 |
+
|
16 |
+
|
17 |
+
Args:
|
18 |
+
vocab_size (`int`, *optional*, defaults to 151936):
|
19 |
+
Vocabulary size of the Qwen2 model. Defines the number of different tokens that can be represented by the
|
20 |
+
`inputs_ids` passed when calling [`Qwen2Model`]
|
21 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
22 |
+
Dimension of the hidden representations.
|
23 |
+
intermediate_size (`int`, *optional*, defaults to 22016):
|
24 |
+
Dimension of the MLP representations.
|
25 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
26 |
+
Number of hidden layers in the Transformer encoder.
|
27 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
28 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
29 |
+
num_key_value_heads (`int`, *optional*, defaults to 32):
|
30 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
31 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
32 |
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
33 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
34 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
35 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
|
36 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
37 |
+
The non-linear activation function (function or string) in the decoder.
|
38 |
+
max_position_embeddings (`int`, *optional*, defaults to 32768):
|
39 |
+
The maximum sequence length that this model might ever be used with.
|
40 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
41 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
42 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
43 |
+
The epsilon used by the rms normalization layers.
|
44 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
45 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
46 |
+
relevant if `config.is_decoder=True`.
|
47 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
48 |
+
Whether the model's input and output word embeddings should be tied.
|
49 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
50 |
+
The base period of the RoPE embeddings.
|
51 |
+
use_sliding_window (`bool`, *optional*, defaults to `False`):
|
52 |
+
Whether to use sliding window attention.
|
53 |
+
sliding_window (`int`, *optional*, defaults to 4096):
|
54 |
+
Sliding window attention (SWA) window size. If not specified, will default to `4096`.
|
55 |
+
max_window_layers (`int`, *optional*, defaults to 28):
|
56 |
+
The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
|
57 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
58 |
+
The dropout ratio for the attention probabilities.
|
59 |
+
|
60 |
+
```python
|
61 |
+
>>> from transformers import Qwen2Model, Qwen2Config
|
62 |
+
|
63 |
+
>>> # Initializing a Qwen2 style configuration
|
64 |
+
>>> configuration = Qwen2Config()
|
65 |
+
|
66 |
+
>>> # Initializing a model from the Qwen2-7B style configuration
|
67 |
+
>>> model = Qwen2Model(configuration)
|
68 |
+
|
69 |
+
>>> # Accessing the model configuration
|
70 |
+
>>> configuration = model.config
|
71 |
+
```"""
|
72 |
+
|
73 |
+
model_type = "qwen2"
|
74 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
75 |
+
|
76 |
+
def __init__(
|
77 |
+
self,
|
78 |
+
vocab_size=151936,
|
79 |
+
hidden_size=4096,
|
80 |
+
intermediate_size=22016,
|
81 |
+
num_hidden_layers=32,
|
82 |
+
num_attention_heads=32,
|
83 |
+
num_key_value_heads=32,
|
84 |
+
hidden_act="silu",
|
85 |
+
max_position_embeddings=32768,
|
86 |
+
initializer_range=0.02,
|
87 |
+
rms_norm_eps=1e-6,
|
88 |
+
use_cache=True,
|
89 |
+
tie_word_embeddings=False,
|
90 |
+
rope_theta=10000.0,
|
91 |
+
use_sliding_window=False,
|
92 |
+
sliding_window=4096,
|
93 |
+
max_window_layers=28,
|
94 |
+
attention_dropout=0.0,
|
95 |
+
hyper_layers=[1,9,17,25],
|
96 |
+
**kwargs,
|
97 |
+
):
|
98 |
+
self.vocab_size = vocab_size
|
99 |
+
self.max_position_embeddings = max_position_embeddings
|
100 |
+
self.hidden_size = hidden_size
|
101 |
+
self.intermediate_size = intermediate_size
|
102 |
+
self.num_hidden_layers = num_hidden_layers
|
103 |
+
self.num_attention_heads = num_attention_heads
|
104 |
+
self.use_sliding_window = use_sliding_window
|
105 |
+
self.sliding_window = sliding_window if use_sliding_window else None
|
106 |
+
self.max_window_layers = max_window_layers
|
107 |
+
|
108 |
+
# for backward compatibility
|
109 |
+
if num_key_value_heads is None:
|
110 |
+
num_key_value_heads = num_attention_heads
|
111 |
+
|
112 |
+
self.num_key_value_heads = num_key_value_heads
|
113 |
+
self.hidden_act = hidden_act
|
114 |
+
self.initializer_range = initializer_range
|
115 |
+
self.rms_norm_eps = rms_norm_eps
|
116 |
+
self.use_cache = use_cache
|
117 |
+
self.rope_theta = rope_theta
|
118 |
+
self.attention_dropout = attention_dropout
|
119 |
+
self.hyper_layers = hyper_layers
|
120 |
+
super().__init__(
|
121 |
+
tie_word_embeddings=tie_word_embeddings,
|
122 |
+
**kwargs,
|
123 |
+
)
|
configuration_mplugowl3.py
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
""" mPLUGOwl3 model configuration"""
|
3 |
+
|
4 |
+
import os
|
5 |
+
from typing import Union
|
6 |
+
|
7 |
+
from transformers.utils import logging
|
8 |
+
from .configuration_hyper_qwen2 import HyperQwen2Config
|
9 |
+
from transformers.models.siglip.configuration_siglip import SiglipVisionConfig
|
10 |
+
logger = logging.get_logger(__name__)
|
11 |
+
|
12 |
+
|
13 |
+
class mPLUGOwl3Config(HyperQwen2Config):
|
14 |
+
model_type = "mplugowl3"
|
15 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
16 |
+
|
17 |
+
default_vision_config = {
|
18 |
+
"hidden_size": 1152,
|
19 |
+
"image_size": 384,
|
20 |
+
"intermediate_size": 4304,
|
21 |
+
"model_type": "siglip_vision_model",
|
22 |
+
"num_attention_heads": 16,
|
23 |
+
"num_hidden_layers": 27,
|
24 |
+
"patch_size": 14
|
25 |
+
}
|
26 |
+
|
27 |
+
|
28 |
+
def __init__(
|
29 |
+
self,
|
30 |
+
use_cache=True,
|
31 |
+
vision_config=None,
|
32 |
+
**kwargs,
|
33 |
+
):
|
34 |
+
self.use_cache = use_cache
|
35 |
+
|
36 |
+
# same as HuggingFaceM4/siglip-so400m-14-980-flash-attn2-navit add tgt_sizes
|
37 |
+
if vision_config is None:
|
38 |
+
self.vision_config = SiglipVisionConfig(**self.default_vision_config)
|
39 |
+
logger.info("vision_config is None, using default vision config")
|
40 |
+
elif isinstance(vision_config, dict):
|
41 |
+
self.vision_config = SiglipVisionConfig(**vision_config)
|
42 |
+
elif isinstance(vision_config, SiglipVisionConfig):
|
43 |
+
self.vision_config = vision_config
|
44 |
+
self.image_size = self.vision_config.image_size
|
45 |
+
self.patch_size = self.vision_config.patch_size
|
46 |
+
|
47 |
+
super().__init__(**kwargs)
|
generation_config.json
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token_id": 151643,
|
3 |
+
"pad_token_id": 151643,
|
4 |
+
"do_sample": true,
|
5 |
+
"eos_token_id": [
|
6 |
+
151645,
|
7 |
+
151643
|
8 |
+
],
|
9 |
+
"repetition_penalty": 1.05,
|
10 |
+
"temperature": 0.7,
|
11 |
+
"top_p": 0.8,
|
12 |
+
"top_k": 20,
|
13 |
+
"transformers_version": "4.37.0"
|
14 |
+
}
|
image_processing_mplugowl3.py
ADDED
@@ -0,0 +1,406 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import random
|
2 |
+
from typing import Optional, Union, Dict, Any, List
|
3 |
+
|
4 |
+
from einops import rearrange, repeat
|
5 |
+
import torch
|
6 |
+
import math
|
7 |
+
import PIL.Image
|
8 |
+
import PIL.ImageSequence
|
9 |
+
import numpy as np
|
10 |
+
import PIL
|
11 |
+
from PIL import Image
|
12 |
+
|
13 |
+
from transformers.utils import TensorType, requires_backends, is_torch_dtype, is_torch_device
|
14 |
+
from transformers.image_processing_utils import BaseImageProcessor, BatchFeature
|
15 |
+
from transformers import AutoImageProcessor
|
16 |
+
from transformers.image_transforms import to_channel_dimension_format
|
17 |
+
from transformers.image_utils import (
|
18 |
+
ImageInput,
|
19 |
+
make_list_of_images,
|
20 |
+
valid_images,
|
21 |
+
is_torch_tensor,
|
22 |
+
is_batched,
|
23 |
+
to_numpy_array,
|
24 |
+
infer_channel_dimension_format,
|
25 |
+
ChannelDimension
|
26 |
+
)
|
27 |
+
from torchvision.ops.boxes import box_area
|
28 |
+
from torchvision.transforms import functional as F
|
29 |
+
from torchvision.transforms.transforms import InterpolationMode
|
30 |
+
from torchvision import transforms
|
31 |
+
|
32 |
+
def recursive_converter(converter, value):
|
33 |
+
if isinstance(value, list):
|
34 |
+
new_value = []
|
35 |
+
for v in value:
|
36 |
+
new_value += [recursive_converter(converter, v)]
|
37 |
+
return new_value
|
38 |
+
else:
|
39 |
+
return converter(value)
|
40 |
+
|
41 |
+
def box_iou(boxes1, area1, boxes2, eps=1e-5):
|
42 |
+
area2 = box_area(boxes2)
|
43 |
+
|
44 |
+
lt = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2]
|
45 |
+
rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2]
|
46 |
+
|
47 |
+
wh = (rb - lt).clamp(min=0) # [N,M,2]
|
48 |
+
inter = wh[:, :, 0] * wh[:, :, 1] # [N,M]
|
49 |
+
|
50 |
+
union = area1[:, None] + area2 - inter
|
51 |
+
|
52 |
+
iou = inter / (union+eps)
|
53 |
+
return iou, union
|
54 |
+
|
55 |
+
available_anchor_strategy = ['docowl', 'random', 'highest', 'last', 'llava']
|
56 |
+
|
57 |
+
grid_dict = {
|
58 |
+
'grid_33':[
|
59 |
+
(1,1),
|
60 |
+
(1,2),(2,1),
|
61 |
+
(1,3),(3,1),
|
62 |
+
(2,2),(1,4),(4,1),
|
63 |
+
(1,5),(5,1),
|
64 |
+
(1,6),(6,1),(2,3),(3,2),
|
65 |
+
(1,7),(7,1),
|
66 |
+
(4,2),(2,4),(1,8),(8,1),
|
67 |
+
(3,3),(1,9),(9,1)],
|
68 |
+
'grid_squ_3x3':[
|
69 |
+
(1,1),(2,2),(3,3)
|
70 |
+
],
|
71 |
+
'grid_squ_4':[
|
72 |
+
(2,2),(1,3),(1,4),(3,1),(4,1)
|
73 |
+
],
|
74 |
+
'grid_squ_6':[
|
75 |
+
(2,2),(1,3),(1,4),(3,1),(4,1), (2,3),(3,2)
|
76 |
+
],
|
77 |
+
'grid_squ_2':[
|
78 |
+
(2,1)
|
79 |
+
],
|
80 |
+
'grid_squ_9':[
|
81 |
+
(1,1),
|
82 |
+
(1,2),(2,1),
|
83 |
+
(1,3),(3,1),
|
84 |
+
(2,2),(1,4),(4,1),
|
85 |
+
(1,5),(5,1),
|
86 |
+
(1,6),(6,1),(2,3),(3,2),
|
87 |
+
(1,7),(7,1),
|
88 |
+
(4,2),(2,4),(1,8),(8,1),
|
89 |
+
(3,3),(1,9),(9,1)],
|
90 |
+
}
|
91 |
+
|
92 |
+
cut_prompt_template_dict = {
|
93 |
+
'v0': lambda img_token, h, w: f''.join([f"{img_token}" for i in range(h) for j in range(w)]),
|
94 |
+
'v1': lambda img_token, h, w: f'Cut to {h} rows {w} columns, '+ ' '.join([f"subimg({i},{j}){img_token}"for i in range(h) for j in range(w)]),
|
95 |
+
'v1_global': lambda img_token, h, w: f'Cut to {h} rows {w} columns with a global view, '+ ' '.join([f"subimg({i},{j}){img_token}"for i in range(h) for j in range(w)]+[f"global_view{img_token}"]),
|
96 |
+
'v2_global': lambda img_token, h, w: f'Cut to {h} rows {w} columns with a global view\n'+ '\n'.join([' '.join([f"subimg({i},{j}){img_token}" for j in range(w)]) for i in range(h)])+f"\nglobal_view{img_token}",
|
97 |
+
}
|
98 |
+
|
99 |
+
def anchor_rank(anchors, anchors_areas, input_image_size, eps=1e-5):
|
100 |
+
# anchors x1 y1 x2 y2
|
101 |
+
|
102 |
+
# image_size: (h, w)
|
103 |
+
# xyxy
|
104 |
+
input_image_bbox = torch.tensor([0, 0, input_image_size[1], input_image_size[0]]).unsqueeze(0)
|
105 |
+
|
106 |
+
boxes1 = anchors
|
107 |
+
boxes2 = input_image_bbox
|
108 |
+
boxes3 = anchors.clone()
|
109 |
+
# y2
|
110 |
+
boxes3[:,3] = input_image_size[0]/input_image_size[1]*anchors[:,2] # 用于算分辨率无关的iou
|
111 |
+
|
112 |
+
area1 = anchors_areas
|
113 |
+
|
114 |
+
iou, _ = box_iou(boxes1, area1, boxes2)
|
115 |
+
iou = iou.squeeze(1)
|
116 |
+
shape_iou, _ = box_iou(boxes1, area1, boxes3)
|
117 |
+
shape_iou = shape_iou.diag()
|
118 |
+
# 优先匹配形状接近 再匹配分辨率接近
|
119 |
+
index = torch.argmax(shape_iou*100+iou,dim=0)
|
120 |
+
return index
|
121 |
+
|
122 |
+
def select_best_resolution(anchors, anchors_areas, input_image_size): # TODO For a futher check
|
123 |
+
"""
|
124 |
+
Selects the best resolution from a list of possible resolutions based on the original size.
|
125 |
+
|
126 |
+
Args:
|
127 |
+
original_size (tuple): The original size of the image in the format (width, height).
|
128 |
+
possible_resolutions (list): A list of possible resolutions in the format [(width1, height1), (width2, height2), ...].
|
129 |
+
|
130 |
+
Returns:
|
131 |
+
tuple: The best fit resolution in the format (width, height).
|
132 |
+
"""
|
133 |
+
original_size = (input_image_size[1], input_image_size[0])
|
134 |
+
possible_resolutions = [(_[2], _[3]) for _ in anchors] # xyxy -> w,h
|
135 |
+
|
136 |
+
original_width, original_height = original_size
|
137 |
+
best_fit = None
|
138 |
+
max_effective_resolution = 0
|
139 |
+
min_wasted_resolution = float('inf')
|
140 |
+
|
141 |
+
index = 0
|
142 |
+
for i, (width, height) in enumerate(possible_resolutions):
|
143 |
+
scale = min(width / original_width, height / original_height)
|
144 |
+
downscaled_width, downscaled_height = int(original_width * scale), int(original_height * scale)
|
145 |
+
effective_resolution = min(downscaled_width * downscaled_height, original_width * original_height)
|
146 |
+
wasted_resolution = (width * height) - effective_resolution
|
147 |
+
|
148 |
+
if effective_resolution > max_effective_resolution or (effective_resolution == max_effective_resolution and wasted_resolution < min_wasted_resolution):
|
149 |
+
max_effective_resolution = effective_resolution
|
150 |
+
min_wasted_resolution = wasted_resolution
|
151 |
+
best_fit = (width, height)
|
152 |
+
index = i
|
153 |
+
|
154 |
+
return index
|
155 |
+
|
156 |
+
def build_cut_shape_indices(cut_shape):
|
157 |
+
# cut_shape: a list of (nh,nw)
|
158 |
+
cut_shape_indices = []
|
159 |
+
for shape in cut_shape:
|
160 |
+
n=shape[0]*shape[1]
|
161 |
+
indices = torch.cat([
|
162 |
+
repeat(torch.tensor(shape),'l -> n l',n=n),
|
163 |
+
torch.arange(n).unsqueeze(1)
|
164 |
+
], dim=1)
|
165 |
+
assert indices.shape[0] == n
|
166 |
+
assert indices.shape[1] == 3 # nh,nw,idx
|
167 |
+
|
168 |
+
cut_shape_indices.append(indices)
|
169 |
+
cut_shape_indices = torch.cat(cut_shape_indices,dim=0).long()
|
170 |
+
return cut_shape_indices
|
171 |
+
|
172 |
+
class AnchorResize(torch.nn.Module):
|
173 |
+
|
174 |
+
def __init__(self, image_size, anchors, interpolation=InterpolationMode.BILINEAR, antialias=None, anchor_strategy='docowl'):
|
175 |
+
super().__init__()
|
176 |
+
self.image_size = image_size
|
177 |
+
# xyxy
|
178 |
+
self.anchors = torch.tensor(
|
179 |
+
[[0, 0, _[1]*image_size[1], _[0]*image_size[0]]
|
180 |
+
for _ in anchors], requires_grad=False
|
181 |
+
)
|
182 |
+
|
183 |
+
self.anchor_areas = box_area(self.anchors)
|
184 |
+
|
185 |
+
self.interpolation = interpolation
|
186 |
+
self.antialias = antialias
|
187 |
+
self.anchor_strategy = anchor_strategy
|
188 |
+
assert self.anchor_strategy in available_anchor_strategy
|
189 |
+
|
190 |
+
def resize_global(self, img):
|
191 |
+
return F.resize(img, self.image_size, self.interpolation, max_size=None, antialias=self.antialias)
|
192 |
+
|
193 |
+
def forward(self, img, skip_resize=False):
|
194 |
+
"""
|
195 |
+
Args:
|
196 |
+
img (PIL Image or Tensor): Image to be scaled.
|
197 |
+
|
198 |
+
Returns:
|
199 |
+
PIL Image or Tensor: Rescaled image.
|
200 |
+
"""
|
201 |
+
if self.anchor_strategy == 'docowl':
|
202 |
+
selected_anchor = anchor_rank(self.anchors, self.anchor_areas, (img.size[1], img.size[0]))
|
203 |
+
elif self.anchor_strategy == 'random':
|
204 |
+
selected_anchor = random.randint(0,len(self.anchors)-1)
|
205 |
+
elif self.anchor_strategy == 'highest':
|
206 |
+
# 选面积最大的 在这个基础上 尽可能选最方正的
|
207 |
+
selected_anchor = torch.argmax(self.anchors[:,2]*self.anchors[:,3]*100-torch.abs(self.anchors[:,2]-self.anchors[:,3]))
|
208 |
+
elif self.anchor_strategy == 'last':
|
209 |
+
selected_anchor = len(self.anchors)-1
|
210 |
+
elif self.anchor_strategy == 'llava':
|
211 |
+
selected_anchor = select_best_resolution(self.anchors, self.anchor_areas, (img.size[1], img.size[0]))
|
212 |
+
else:
|
213 |
+
selected_anchor = None
|
214 |
+
assert selected_anchor is not None
|
215 |
+
|
216 |
+
target_size = self.anchors[selected_anchor][2:].tolist() # w,h
|
217 |
+
if skip_resize:
|
218 |
+
# for debug
|
219 |
+
return selected_anchor
|
220 |
+
return F.resize(img, [target_size[1],target_size[0]], self.interpolation, max_size=None, antialias=self.antialias), selected_anchor
|
221 |
+
|
222 |
+
def __repr__(self) -> str:
|
223 |
+
detail = f"(size={self.image_size}, anchor={self.anchors}, interpolation={self.interpolation.value}, antialias={self.antialias})"
|
224 |
+
return f"{self.__class__.__name__}{detail}"
|
225 |
+
|
226 |
+
class CutMixin:
|
227 |
+
def __init__(self, cut_cfg={"anchors": "grid_squ_6", "anchor_strategy": "docowl", "cut_prompt": "v2", "add_global": True, "cut_prob": 1.0}) -> None:
|
228 |
+
if cut_cfg is None:
|
229 |
+
self.cut_enable = False
|
230 |
+
return
|
231 |
+
else:
|
232 |
+
self.cut_enable = True
|
233 |
+
image_size = self.image_size
|
234 |
+
anchors = cut_cfg.get('anchors','grid_33')
|
235 |
+
anchor_strategy = cut_cfg.get('anchor_strategy','docowl')
|
236 |
+
cut_prompt = cut_cfg.get('cut_prompt','v0')
|
237 |
+
self.cut_prob = cut_cfg.get('cut_prob', 1.0)
|
238 |
+
|
239 |
+
self.force_shape_cut = cut_cfg.get('force_shape_cut', False)
|
240 |
+
force_shape_cut_anchors = cut_cfg.get('force_shape_cut_anchors', 'force_shape_cut_anchors')
|
241 |
+
|
242 |
+
|
243 |
+
self.add_global = cut_cfg.get('add_global', False)
|
244 |
+
|
245 |
+
# h,w
|
246 |
+
if isinstance(image_size, int):
|
247 |
+
image_size = (image_size, image_size)
|
248 |
+
self.image_size = image_size
|
249 |
+
|
250 |
+
if anchors in grid_dict:
|
251 |
+
anchors = grid_dict[anchors]
|
252 |
+
else:
|
253 |
+
anchors = eval(anchors)
|
254 |
+
self.anchors = [tuple(_) for _ in anchors]
|
255 |
+
self.anchor_max = max([max(_) for _ in self.anchors])
|
256 |
+
self.resizer = AnchorResize(image_size=image_size, anchors=anchors, interpolation=InterpolationMode.BICUBIC, anchor_strategy=anchor_strategy)
|
257 |
+
|
258 |
+
if force_shape_cut_anchors in grid_dict:
|
259 |
+
force_shape_cut_anchors = grid_dict[force_shape_cut_anchors]
|
260 |
+
else:
|
261 |
+
force_shape_cut_anchors = eval(force_shape_cut_anchors)
|
262 |
+
self.force_shape_cut_anchors = [tuple(_) for _ in force_shape_cut_anchors]
|
263 |
+
self.force_shape_cut_anchors_max = max([max(_) for _ in self.force_shape_cut_anchors])
|
264 |
+
|
265 |
+
|
266 |
+
|
267 |
+
self.old_resizer = transforms.Resize(image_size,interpolation=InterpolationMode.BICUBIC)
|
268 |
+
|
269 |
+
# 把image processor的缩放去掉 只保留后面的变换
|
270 |
+
self.image_transform = transforms.Compose(self.image_transform.transforms[1:])
|
271 |
+
if self.add_global:
|
272 |
+
self.cut_prompt_template = cut_prompt_template_dict[cut_prompt+'_global']
|
273 |
+
else:
|
274 |
+
self.cut_prompt_template = cut_prompt_template_dict[cut_prompt]
|
275 |
+
|
276 |
+
self.media_tokens = ["<|image|>", "<|video|>"]
|
277 |
+
|
278 |
+
|
279 |
+
|
280 |
+
def _process_image(self, images):
|
281 |
+
new_images = []
|
282 |
+
cut_shape = []
|
283 |
+
for image in images:
|
284 |
+
raw_image = image
|
285 |
+
|
286 |
+
image, selected_anchor = self.resizer(image)
|
287 |
+
image_input = self.image_transform(image) # h,w,3 -> 3,h,w
|
288 |
+
cut_shape.append((image_input.shape[1]//self.image_size[0], image_input.shape[2]//self.image_size[1])) # cut_h, cut_w
|
289 |
+
image_input = rearrange(image_input, 'C (num_h h) (num_w w) -> (num_h num_w) C h w', h=self.image_size[0], w=self.image_size[1])
|
290 |
+
|
291 |
+
new_images.append(image_input)
|
292 |
+
|
293 |
+
if self.add_global:
|
294 |
+
new_images.append(self.image_transform(self.resizer.resize_global(raw_image)).unsqueeze(0))
|
295 |
+
cut_shape.append((1,1))
|
296 |
+
|
297 |
+
new_images = torch.cat(new_images,dim=0)
|
298 |
+
cut_shape_indices = build_cut_shape_indices(cut_shape)
|
299 |
+
return new_images, cut_shape, cut_shape_indices
|
300 |
+
|
301 |
+
class mPLUGOwl3BatchFeature(BatchFeature):
|
302 |
+
r"""
|
303 |
+
Extend from BatchFeature for supporting various image size
|
304 |
+
"""
|
305 |
+
def __init__(self, data: Optional[Dict[str, Any]] = None, tensor_type: Union[None, str, TensorType] = None):
|
306 |
+
super().__init__(data)
|
307 |
+
self.convert_to_tensors(tensor_type=tensor_type)
|
308 |
+
|
309 |
+
def convert_to_tensors(self, tensor_type: Optional[Union[str, TensorType]] = None):
|
310 |
+
if tensor_type is None:
|
311 |
+
return self
|
312 |
+
|
313 |
+
is_tensor, as_tensor = self._get_is_as_tensor_fns(tensor_type)
|
314 |
+
|
315 |
+
def converter(value):
|
316 |
+
try:
|
317 |
+
if not is_tensor(value):
|
318 |
+
tensor = as_tensor(value)
|
319 |
+
return tensor
|
320 |
+
except: # noqa E722
|
321 |
+
if key == "overflowing_values":
|
322 |
+
raise ValueError("Unable to create tensor returning overflowing values of different lengths. ")
|
323 |
+
raise ValueError(
|
324 |
+
"Unable to create tensor, you should probably activate padding "
|
325 |
+
"with 'padding=True' to have batched tensors with the same length."
|
326 |
+
)
|
327 |
+
|
328 |
+
|
329 |
+
for key, value in self.items():
|
330 |
+
self[key] = recursive_converter(converter, value)
|
331 |
+
return self
|
332 |
+
|
333 |
+
def to(self, *args, **kwargs) -> "mPLUGOwl3BatchFeature":
|
334 |
+
requires_backends(self, ["torch"])
|
335 |
+
import torch
|
336 |
+
|
337 |
+
def cast_tensor(v):
|
338 |
+
# check if v is a floating point
|
339 |
+
if torch.is_floating_point(v):
|
340 |
+
# cast and send to device
|
341 |
+
return v.to(*args, **kwargs)
|
342 |
+
elif device is not None:
|
343 |
+
return v.to(device=device)
|
344 |
+
else:
|
345 |
+
return v
|
346 |
+
|
347 |
+
new_data = {}
|
348 |
+
device = kwargs.get("device")
|
349 |
+
# Check if the args are a device or a dtype
|
350 |
+
if device is None and len(args) > 0:
|
351 |
+
# device should be always the first argument
|
352 |
+
arg = args[0]
|
353 |
+
if is_torch_dtype(arg):
|
354 |
+
# The first argument is a dtype
|
355 |
+
pass
|
356 |
+
elif isinstance(arg, str) or is_torch_device(arg) or isinstance(arg, int):
|
357 |
+
device = arg
|
358 |
+
else:
|
359 |
+
# it's something else
|
360 |
+
raise ValueError(f"Attempting to cast a BatchFeature to type {str(arg)}. This is not supported.")
|
361 |
+
# We cast only floating point tensors to avoid issues with tokenizers casting `LongTensor` to `FloatTensor`
|
362 |
+
for k, v in self.items():
|
363 |
+
new_data[k] = recursive_converter(cast_tensor, v)
|
364 |
+
self.data = new_data
|
365 |
+
return self
|
366 |
+
|
367 |
+
|
368 |
+
class mPLUGOwl3ImageProcessor(BaseImageProcessor, CutMixin):
|
369 |
+
model_input_names = ["pixel_values"]
|
370 |
+
|
371 |
+
def __init__(
|
372 |
+
self,
|
373 |
+
image_size,
|
374 |
+
mean=[0.5, 0.5, 0.5],
|
375 |
+
std=[0.5, 0.5, 0.5],
|
376 |
+
**kwargs):
|
377 |
+
super().__init__(**kwargs)
|
378 |
+
self.image_size = image_size
|
379 |
+
self.image_transform = transforms.Compose([
|
380 |
+
transforms.Resize((image_size, image_size), interpolation=Image.BICUBIC),
|
381 |
+
transforms.ToTensor(),
|
382 |
+
transforms.Normalize(mean, std),
|
383 |
+
])
|
384 |
+
CutMixin.__init__(self)
|
385 |
+
|
386 |
+
def preprocess(
|
387 |
+
self,
|
388 |
+
images: Union[Image.Image, List[Image.Image]],
|
389 |
+
cut_enable=True,
|
390 |
+
**kwargs
|
391 |
+
) -> mPLUGOwl3BatchFeature:
|
392 |
+
if isinstance(images, Image.Image):
|
393 |
+
images_list = [images]
|
394 |
+
else:
|
395 |
+
images_list = images
|
396 |
+
|
397 |
+
if self.cut_enable and cut_enable:
|
398 |
+
image_data, cut_shape, cut_shape_indices = self._process_image(images_list)
|
399 |
+
else:
|
400 |
+
image_data = [self.image_transform(self.resizer.resize_global(image)) for image in images_list]
|
401 |
+
image_data = torch.stack(image_data, dim=0)
|
402 |
+
cut_shape = cut_shape_indices = None
|
403 |
+
|
404 |
+
return mPLUGOwl3BatchFeature(data={'pixel_values': image_data, 'cut_shape':cut_shape, 'cut_shape_indices':cut_shape_indices})
|
405 |
+
|
406 |
+
AutoImageProcessor.register("mPLUGOwl3ImageProcessor", mPLUGOwl3ImageProcessor)
|
merges.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c4b3da8a8a282946a57f6cb936ec231216f592c9be67de9539290d6dc24dc22d
|
3 |
+
size 16122498328
|
modeling_hyper_qwen2.py
ADDED
@@ -0,0 +1,1541 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
import inspect
|
22 |
+
import math
|
23 |
+
from typing import List, Optional, Tuple, Union
|
24 |
+
|
25 |
+
from einops import rearrange, repeat
|
26 |
+
import torch
|
27 |
+
import torch.nn.functional as F
|
28 |
+
import torch.utils.checkpoint
|
29 |
+
from torch import nn
|
30 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
31 |
+
from transformers.activations import ACT2FN
|
32 |
+
from transformers.cache_utils import Cache, DynamicCache
|
33 |
+
from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa
|
34 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
|
35 |
+
from transformers.modeling_utils import PreTrainedModel
|
36 |
+
from transformers.utils import (
|
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,
|
41 |
+
logging,
|
42 |
+
replace_return_docstrings,
|
43 |
+
)
|
44 |
+
from .configuration_hyper_qwen2 import HyperQwen2Config
|
45 |
+
|
46 |
+
|
47 |
+
if is_flash_attn_2_available():
|
48 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
49 |
+
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
|
50 |
+
|
51 |
+
_flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
|
52 |
+
from .x_sdpa import ScaleDotProductAttention
|
53 |
+
|
54 |
+
try:
|
55 |
+
from flash_attn.layers.rotary import apply_rotary_emb_func
|
56 |
+
from einops import rearrange
|
57 |
+
|
58 |
+
use_flash_rotary = True
|
59 |
+
print("use flash_attn rotary")
|
60 |
+
except ImportError:
|
61 |
+
use_flash_rotary = False
|
62 |
+
print("import flash_attn rotary fail")
|
63 |
+
|
64 |
+
logger = logging.get_logger(__name__)
|
65 |
+
|
66 |
+
|
67 |
+
_CHECKPOINT_FOR_DOC = "Qwen/Qwen2-7B-beta"
|
68 |
+
_CONFIG_FOR_DOC = "HyperQwen2Config"
|
69 |
+
|
70 |
+
|
71 |
+
# Copied from transformers.models.llama.modeling_llama._get_unpad_data
|
72 |
+
def _get_unpad_data(attention_mask):
|
73 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
74 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
75 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
76 |
+
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
|
77 |
+
return (
|
78 |
+
indices,
|
79 |
+
cu_seqlens,
|
80 |
+
max_seqlen_in_batch,
|
81 |
+
)
|
82 |
+
|
83 |
+
|
84 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Qwen2
|
85 |
+
class Qwen2RMSNorm(nn.Module):
|
86 |
+
def __init__(self, hidden_size, eps=1e-6):
|
87 |
+
"""
|
88 |
+
Qwen2RMSNorm is equivalent to T5LayerNorm
|
89 |
+
"""
|
90 |
+
super().__init__()
|
91 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
92 |
+
self.variance_epsilon = eps
|
93 |
+
|
94 |
+
def forward(self, hidden_states):
|
95 |
+
input_dtype = hidden_states.dtype
|
96 |
+
hidden_states = hidden_states.to(torch.float32)
|
97 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
98 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
99 |
+
return self.weight * hidden_states.to(input_dtype)
|
100 |
+
|
101 |
+
|
102 |
+
# Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->Qwen2
|
103 |
+
class Qwen2RotaryEmbedding(nn.Module):
|
104 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
105 |
+
super().__init__()
|
106 |
+
|
107 |
+
self.dim = dim
|
108 |
+
self.max_position_embeddings = max_position_embeddings
|
109 |
+
self.base = base
|
110 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
|
111 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
112 |
+
|
113 |
+
# Build here to make `torch.jit.trace` work.
|
114 |
+
self._set_cos_sin_cache(
|
115 |
+
seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
|
116 |
+
)
|
117 |
+
|
118 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
119 |
+
self.max_seq_len_cached = seq_len
|
120 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
|
121 |
+
|
122 |
+
freqs = torch.outer(t, self.inv_freq)
|
123 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
124 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
125 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
126 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
127 |
+
|
128 |
+
def forward(self, x, seq_len=None):
|
129 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
130 |
+
if seq_len > self.max_seq_len_cached:
|
131 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
132 |
+
|
133 |
+
return (
|
134 |
+
self.cos_cached[:seq_len].to(dtype=x.dtype),
|
135 |
+
self.sin_cached[:seq_len].to(dtype=x.dtype),
|
136 |
+
)
|
137 |
+
|
138 |
+
class RotaryEmbedding(torch.nn.Module):
|
139 |
+
def __init__(self, dim, base=10000, use_fp32=False, use_outer_in_rope=False):
|
140 |
+
super().__init__()
|
141 |
+
self.dim = dim
|
142 |
+
self.base = base
|
143 |
+
self.use_fp32 = use_fp32
|
144 |
+
if use_fp32:
|
145 |
+
self.inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
|
146 |
+
else:
|
147 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
|
148 |
+
self.register_buffer("inv_freq", inv_freq)
|
149 |
+
|
150 |
+
self._rotary_pos_emb_cache = None
|
151 |
+
self._seq_len_cached = 0
|
152 |
+
self.use_outer_in_rope = use_outer_in_rope
|
153 |
+
self._ntk_alpha_cached = 1.0
|
154 |
+
|
155 |
+
def update_rotary_pos_emb_cache(self, max_seq_len, offset=0, ntk_alpha=1.0):
|
156 |
+
seqlen = max_seq_len + offset
|
157 |
+
if seqlen > self._seq_len_cached or ntk_alpha != self._ntk_alpha_cached:
|
158 |
+
base = self.base * ntk_alpha ** (self.dim / (self.dim - 2))
|
159 |
+
self.inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2, device=self.inv_freq.device).float() / self.dim))
|
160 |
+
self._seq_len_cached = seqlen
|
161 |
+
self._ntk_alpha_cached = ntk_alpha
|
162 |
+
seq = torch.arange(seqlen, device=self.inv_freq.device)
|
163 |
+
# Don't do einsum, it converts fp32 to fp16 # TODO: CHECK this
|
164 |
+
if self.use_outer_in_rope:
|
165 |
+
freqs = torch.outer(seq.type_as(self.inv_freq), self.inv_freq)
|
166 |
+
else:
|
167 |
+
freqs = einsum('i , j -> i j', seq.type_as(self.inv_freq), self.inv_freq)
|
168 |
+
# first part even vector components, second part odd vector components,
|
169 |
+
# 2 * dim in dimension size
|
170 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
171 |
+
# emb [seq_length, .., dim]
|
172 |
+
from einops import rearrange
|
173 |
+
self._rotary_pos_emb_cache = rearrange(emb, 'n d -> n 1 1 d')
|
174 |
+
|
175 |
+
def forward(self, max_seq_len, offset=0, ntk_alpha=1.0):
|
176 |
+
self.update_rotary_pos_emb_cache(max_seq_len, offset, ntk_alpha)
|
177 |
+
return self._rotary_pos_emb_cache[offset:offset + max_seq_len]
|
178 |
+
|
179 |
+
# Copied from transformers.models.llama.modeling_llama.rotate_half
|
180 |
+
def rotate_half(x):
|
181 |
+
"""Rotates half the hidden dims of the input."""
|
182 |
+
x1 = x[..., : x.shape[-1] // 2]
|
183 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
184 |
+
return torch.cat((-x2, x1), dim=-1)
|
185 |
+
|
186 |
+
|
187 |
+
# Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
|
188 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
|
189 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
190 |
+
|
191 |
+
Args:
|
192 |
+
q (`torch.Tensor`): The query tensor.
|
193 |
+
k (`torch.Tensor`): The key tensor.
|
194 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
195 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
196 |
+
position_ids (`torch.Tensor`):
|
197 |
+
The position indices of the tokens corresponding to the query and key tensors. For example, this can be
|
198 |
+
used to pass offsetted position ids when working with a KV-cache.
|
199 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
200 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
201 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
202 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
203 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
204 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
205 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
206 |
+
Returns:
|
207 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
208 |
+
"""
|
209 |
+
cos = cos[position_ids].unsqueeze(unsqueeze_dim)
|
210 |
+
sin = sin[position_ids].unsqueeze(unsqueeze_dim)
|
211 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
212 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
213 |
+
return q_embed, k_embed
|
214 |
+
|
215 |
+
|
216 |
+
# Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Qwen2
|
217 |
+
class Qwen2MLP(nn.Module):
|
218 |
+
def __init__(self, config):
|
219 |
+
super().__init__()
|
220 |
+
self.config = config
|
221 |
+
self.hidden_size = config.hidden_size
|
222 |
+
self.intermediate_size = config.intermediate_size
|
223 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
224 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
225 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
226 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
227 |
+
|
228 |
+
def forward(self, x):
|
229 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
230 |
+
|
231 |
+
|
232 |
+
# Copied from transformers.models.llama.modeling_llama.repeat_kv
|
233 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
234 |
+
"""
|
235 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
236 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
237 |
+
"""
|
238 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
239 |
+
if n_rep == 1:
|
240 |
+
return hidden_states
|
241 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
242 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
243 |
+
|
244 |
+
|
245 |
+
|
246 |
+
|
247 |
+
|
248 |
+
def make_t2v_mask(media_offset_line, num_images):
|
249 |
+
assert len(media_offset_line.shape) == 1
|
250 |
+
media_offset_line = media_offset_line.view(-1,1)
|
251 |
+
# print_rank_0(media_offset_line)
|
252 |
+
visual_arange=torch.arange(num_images, device=media_offset_line.device).view(1,-1)
|
253 |
+
mask = (media_offset_line<=visual_arange)
|
254 |
+
# print_rank_0(mask)
|
255 |
+
return mask
|
256 |
+
|
257 |
+
def select_query(media_offset, num_queries=None):
|
258 |
+
query_indices = media_offset[:,:,1]>=0 # B L
|
259 |
+
assert query_indices.sum().item()%num_queries == 0, query_indices.sum().item()
|
260 |
+
query_indices = query_indices.nonzero()
|
261 |
+
ptr = 0
|
262 |
+
while ptr < query_indices.shape[0]:
|
263 |
+
first_query_index, last_query_index = query_indices[ptr], query_indices[ptr+num_queries-1]
|
264 |
+
assert (last_query_index[1] - first_query_index[1] + 1).item() == num_queries
|
265 |
+
assert last_query_index[0].item() == first_query_index[0].item()
|
266 |
+
batch_id, begin_i, end_i = first_query_index[0].item(), first_query_index[1].item(), first_query_index[1].item()+num_queries
|
267 |
+
yield batch_id, begin_i, end_i
|
268 |
+
|
269 |
+
ptr += num_queries
|
270 |
+
|
271 |
+
def _rotate_half(x):
|
272 |
+
"""
|
273 |
+
change sign so the last dimension becomes [-odd, +even]
|
274 |
+
"""
|
275 |
+
from einops import rearrange
|
276 |
+
x = rearrange(x, '... (j d) -> ... j d', j=2)
|
277 |
+
x1, x2 = x.unbind(dim=-2)
|
278 |
+
return torch.cat((-x2, x1), dim=-1)
|
279 |
+
|
280 |
+
def apply_rotary_pos_emb_core(t, freqs, use_fp32=False, debug=False):
|
281 |
+
"""
|
282 |
+
input tensor t is of shape [seq_length, ..., dim]
|
283 |
+
rotary positional embeding tensor freqs is of shape [seq_length, ..., dim]
|
284 |
+
check https://kexue.fm/archives/8265 for detailed formulas
|
285 |
+
"""
|
286 |
+
|
287 |
+
if use_flash_rotary and use_fp32:
|
288 |
+
t_ = rearrange(t, 's b ... -> b s ...').contiguous()
|
289 |
+
if use_fp32:
|
290 |
+
t_ = t_.float()
|
291 |
+
freqs = freqs.squeeze(1).squeeze(1)
|
292 |
+
cos = freqs[:, :freqs.shape[-1] // 2].cos()
|
293 |
+
sin = freqs[:, :freqs.shape[-1] // 2].sin()
|
294 |
+
output = apply_rotary_emb_func(t_, cos, sin).type_as(t)
|
295 |
+
if debug:
|
296 |
+
from icecream import ic
|
297 |
+
ic(t_.shape, freqs.shape, cos.shape)
|
298 |
+
return rearrange(output, 'b s ... -> s b ...')
|
299 |
+
|
300 |
+
rot_dim = freqs.shape[-1]
|
301 |
+
# ideally t_pass is empty so rotary pos embedding is applied to all tensor t
|
302 |
+
t_, t_pass_ = t[..., :rot_dim], t[..., rot_dim:]
|
303 |
+
|
304 |
+
if use_fp32:
|
305 |
+
t_ = t_.float()
|
306 |
+
t_pass_ = t_pass_.float()
|
307 |
+
# first part is cosine component
|
308 |
+
# second part is sine component, need to change signs with _rotate_half method
|
309 |
+
t_ = (t_ * freqs.cos()) + (_rotate_half(t_) * freqs.sin())
|
310 |
+
return torch.cat((t_, t_pass_), dim=-1).type_as(t)
|
311 |
+
|
312 |
+
class HyperQwen2Attention(nn.Module):
|
313 |
+
"""
|
314 |
+
Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
|
315 |
+
and "Generating Long Sequences with Sparse Transformers".
|
316 |
+
"""
|
317 |
+
|
318 |
+
def __init__(self, config: HyperQwen2Config, layer_idx: Optional[int] = None, is_hyper_enabed=False):
|
319 |
+
super().__init__()
|
320 |
+
self.config = config
|
321 |
+
self.layer_idx = layer_idx
|
322 |
+
if layer_idx is None:
|
323 |
+
logger.warning_once(
|
324 |
+
f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
|
325 |
+
"to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
326 |
+
"when creating this class."
|
327 |
+
)
|
328 |
+
|
329 |
+
self.hidden_size = config.hidden_size
|
330 |
+
self.num_heads = config.num_attention_heads
|
331 |
+
self.head_dim = self.hidden_size // self.num_heads
|
332 |
+
self.num_key_value_heads = config.num_key_value_heads
|
333 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
334 |
+
self.max_position_embeddings = config.max_position_embeddings
|
335 |
+
self.rope_theta = config.rope_theta
|
336 |
+
self.is_causal = True
|
337 |
+
self.attention_dropout = config.attention_dropout
|
338 |
+
|
339 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
340 |
+
raise ValueError(
|
341 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
342 |
+
f" and `num_heads`: {self.num_heads})."
|
343 |
+
)
|
344 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
|
345 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
|
346 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
|
347 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
348 |
+
|
349 |
+
self.rotary_emb = Qwen2RotaryEmbedding(
|
350 |
+
self.head_dim,
|
351 |
+
max_position_embeddings=self.max_position_embeddings,
|
352 |
+
base=self.rope_theta,
|
353 |
+
)
|
354 |
+
self.rotary_emb_core = RotaryEmbedding(
|
355 |
+
self.head_dim, base=self.rope_theta, use_fp32=True, use_outer_in_rope=True
|
356 |
+
)
|
357 |
+
# Hyper Attention Modules
|
358 |
+
self.is_hyper_enabed = is_hyper_enabed
|
359 |
+
if self.is_hyper_enabed:
|
360 |
+
self.v_kv_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim * 2, bias=True)
|
361 |
+
self.gate_proj = nn.Sequential(
|
362 |
+
nn.Linear(self.head_dim, self.head_dim),
|
363 |
+
nn.Sigmoid()
|
364 |
+
)
|
365 |
+
self.v_core_attention_sdpa = ScaleDotProductAttention(layer_number=-1,causal=False, attention_dropout=self.attention_dropout)
|
366 |
+
self.visual_cache={}
|
367 |
+
|
368 |
+
|
369 |
+
|
370 |
+
def apply_mi_rope(self, key_layer, media_offset_line, length_each_img):
|
371 |
+
# input shape should be [s b h d]
|
372 |
+
key_layer = rearrange(key_layer, 'b h s d -> s b h d')
|
373 |
+
if self.rotary_emb_core.inv_freq.device!=key_layer.device:
|
374 |
+
self.rotary_emb_core.inv_freq = self.rotary_emb_core.inv_freq.to(key_layer.device)
|
375 |
+
rotary_pos_emb_max_seq_len = self.config.max_position_embeddings
|
376 |
+
ntk_alpha = 1
|
377 |
+
rotary_pos_emb = self.rotary_emb_core(rotary_pos_emb_max_seq_len, ntk_alpha=ntk_alpha)
|
378 |
+
assert rotary_pos_emb is not None
|
379 |
+
|
380 |
+
if isinstance(rotary_pos_emb, tuple):
|
381 |
+
rotary_pos_emb = rotary_pos_emb
|
382 |
+
else:
|
383 |
+
rotary_pos_emb = ((rotary_pos_emb,) * 2)
|
384 |
+
|
385 |
+
|
386 |
+
if rotary_pos_emb is not None:
|
387 |
+
q_pos_emb, k_pos_emb = rotary_pos_emb
|
388 |
+
# ic(key_layer.shape, k_pos_emb.shape)
|
389 |
+
|
390 |
+
image_pos = (media_offset_line[1:] - media_offset_line[:-1]).nonzero().squeeze(1)+1
|
391 |
+
k_pos_emb = repeat(k_pos_emb[image_pos], 'N_img b h d -> (N_img L) b h d', L=length_each_img) # N_img, dim
|
392 |
+
|
393 |
+
key_layer = apply_rotary_pos_emb_core(key_layer, k_pos_emb, use_fp32=True) # TODO difference
|
394 |
+
key_layer = rearrange(key_layer, 's b h d -> b h s d')
|
395 |
+
return key_layer
|
396 |
+
|
397 |
+
def crossattention(self, query_layer, vision_features, media_offset, context_layer):
|
398 |
+
'''
|
399 |
+
query_layer: [s b h d]
|
400 |
+
vision_features: [b' lv d]
|
401 |
+
context_layer: s b d
|
402 |
+
'''
|
403 |
+
if vision_features is None or (self.is_hyper_enabed == False):
|
404 |
+
return context_layer
|
405 |
+
context_layer_clone = context_layer.clone()
|
406 |
+
# obtain dynamic gate value
|
407 |
+
L_c, B_c = context_layer.shape[:2]
|
408 |
+
D_head = self.head_dim
|
409 |
+
context_layer_gate = rearrange(
|
410 |
+
self.gate_proj(
|
411 |
+
rearrange(context_layer, 'L B (Head D) -> (L B Head) D', D=D_head)),
|
412 |
+
'(L B Head) D -> L B (Head D)', L=L_c, B=B_c)
|
413 |
+
|
414 |
+
vision_features = vision_features.contiguous()
|
415 |
+
vision_features = self.v_kv_proj(vision_features)
|
416 |
+
length_each_img = vision_features.shape[1]
|
417 |
+
sequence_length = query_layer.shape[0]
|
418 |
+
if sequence_length == 1:
|
419 |
+
# 此时处于生成模式
|
420 |
+
completion_flag=True
|
421 |
+
media_offset = media_offset[:,-1:]
|
422 |
+
else:
|
423 |
+
completion_flag=False
|
424 |
+
self.visual_cache['media_offset'] = media_offset
|
425 |
+
self.visual_cache['vision_features'] = vision_features
|
426 |
+
query_layer = rearrange(query_layer, 'L B H D -> B H L D') # [25, 2, 32, 128])
|
427 |
+
assert sequence_length == media_offset.shape[1], (sequence_length, media_offset.shape)
|
428 |
+
|
429 |
+
for batch_id, begin_i, end_i in select_query(media_offset, sequence_length):
|
430 |
+
# media_offset should be set to -100000 for samples without images.
|
431 |
+
|
432 |
+
assert begin_i == 0
|
433 |
+
assert end_i == sequence_length, (end_i, sequence_length)
|
434 |
+
curr_offset = media_offset[batch_id,end_i-1] # 当前数据序列的最后一个token拿到的media offset应该是当前数据的所有图
|
435 |
+
if (not completion_flag):
|
436 |
+
# 对于生成模式 query对视觉可见性应该是全部
|
437 |
+
# v2t mask只对prefill阶段有效
|
438 |
+
re_to_zero_media_offset = (media_offset[batch_id,:,1]-curr_offset[0]).to(query_layer.device)
|
439 |
+
query_shift = re_to_zero_media_offset.nonzero()[0].item() # 找��第一个非0位置
|
440 |
+
curr_mask = make_t2v_mask(
|
441 |
+
re_to_zero_media_offset[query_shift:], # 取end表示最多能看几张图
|
442 |
+
num_images=curr_offset[1]-curr_offset[0],
|
443 |
+
)
|
444 |
+
curr_mask = repeat(curr_mask, 's_q s_k -> B H s_q (s_k img_l)', B=1, H=1, img_l=length_each_img)
|
445 |
+
|
446 |
+
# print_rank_0(query_shift)
|
447 |
+
else:
|
448 |
+
curr_mask = None
|
449 |
+
query_shift = 0
|
450 |
+
|
451 |
+
curr_query_tokens = query_layer[batch_id,:,query_shift:].unsqueeze(0).clone().contiguous()
|
452 |
+
|
453 |
+
assert curr_offset[0]<vision_features.shape[0]
|
454 |
+
assert curr_offset[1]<=vision_features.shape[0]
|
455 |
+
|
456 |
+
curr_vision_kv: torch.Tensor = rearrange(vision_features[curr_offset[0]:curr_offset[1]].clone(), 'BL Lv (H KV D) -> KV 1 H (BL Lv) D', KV=2, H=self.num_key_value_heads)
|
457 |
+
key_layer = curr_vision_kv[0].contiguous() # [b h s d]
|
458 |
+
value_layer = curr_vision_kv[1].contiguous()
|
459 |
+
|
460 |
+
# Apply MI-Rope
|
461 |
+
key_layer = self.apply_mi_rope(key_layer, media_offset_line=self.visual_cache['media_offset'][batch_id,:,1]-curr_offset[0], length_each_img=length_each_img)
|
462 |
+
|
463 |
+
key_layer = repeat_kv(key_layer, self.num_key_value_groups)
|
464 |
+
value_layer = repeat_kv(value_layer, self.num_key_value_groups)
|
465 |
+
|
466 |
+
v_context_layer = self.v_core_attention_sdpa(curr_query_tokens, key_layer, value_layer, attn_mask=curr_mask, order='bhsd').squeeze(1)
|
467 |
+
|
468 |
+
# Apply dynamic gate
|
469 |
+
gate_value = context_layer_gate[query_shift:, batch_id]
|
470 |
+
context_layer_clone[query_shift:, batch_id] = context_layer[query_shift:, batch_id].clone() * (1-gate_value) + v_context_layer * gate_value
|
471 |
+
|
472 |
+
return context_layer_clone
|
473 |
+
|
474 |
+
def forward(
|
475 |
+
self,
|
476 |
+
hidden_states: torch.Tensor,
|
477 |
+
attention_mask: Optional[torch.Tensor] = None,
|
478 |
+
position_ids: Optional[torch.LongTensor] = None,
|
479 |
+
image_embeds=None,
|
480 |
+
media_offset=None,
|
481 |
+
past_key_value: Optional[Cache] = None,
|
482 |
+
output_attentions: bool = False,
|
483 |
+
use_cache: bool = False,
|
484 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
485 |
+
raise NotImplementError("We do not support eager model yet. Use attn_implementation == \"flash_attention_2\" or attn_implementation == \"sdpa\".")
|
486 |
+
bsz, q_len, _ = hidden_states.size()
|
487 |
+
|
488 |
+
query_states = self.q_proj(hidden_states)
|
489 |
+
key_states = self.k_proj(hidden_states)
|
490 |
+
value_states = self.v_proj(hidden_states)
|
491 |
+
|
492 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
493 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
494 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
495 |
+
|
496 |
+
kv_seq_len = key_states.shape[-2]
|
497 |
+
if past_key_value is not None:
|
498 |
+
if self.layer_idx is None:
|
499 |
+
raise ValueError(
|
500 |
+
f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
|
501 |
+
"for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
|
502 |
+
"with a layer index."
|
503 |
+
)
|
504 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
505 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
506 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
507 |
+
|
508 |
+
if past_key_value is not None:
|
509 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
510 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
511 |
+
|
512 |
+
# repeat k/v heads if n_kv_heads < n_heads
|
513 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
514 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
515 |
+
|
516 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
517 |
+
|
518 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
519 |
+
raise ValueError(
|
520 |
+
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
521 |
+
f" {attn_weights.size()}"
|
522 |
+
)
|
523 |
+
|
524 |
+
if attention_mask is not None:
|
525 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
526 |
+
raise ValueError(
|
527 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
528 |
+
)
|
529 |
+
|
530 |
+
attn_weights = attn_weights + attention_mask
|
531 |
+
|
532 |
+
# upcast attention to fp32
|
533 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
534 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
535 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
536 |
+
|
537 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
538 |
+
raise ValueError(
|
539 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
540 |
+
f" {attn_output.size()}"
|
541 |
+
)
|
542 |
+
|
543 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
544 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
545 |
+
|
546 |
+
# Hyper Attention
|
547 |
+
print(query_states.shape, attn_output.shape)
|
548 |
+
attn_output = self.crossattention(query_states.permute(1,0,1,3), image_embeds, media_offset, attn_output.permute(1,0,2))
|
549 |
+
attn_output = attn_output.permute(1,0,2)
|
550 |
+
#### End of Hyper Attention
|
551 |
+
|
552 |
+
attn_output = self.o_proj(attn_output)
|
553 |
+
|
554 |
+
if not output_attentions:
|
555 |
+
attn_weights = None
|
556 |
+
|
557 |
+
return attn_output, attn_weights, past_key_value
|
558 |
+
|
559 |
+
|
560 |
+
class HyperQwen2FlashAttention2(HyperQwen2Attention):
|
561 |
+
"""
|
562 |
+
Qwen2 flash attention module, following Qwen2 attention module. This module inherits from `Qwen2Attention`
|
563 |
+
as the weights of the module stays untouched. The only required change would be on the forward pass
|
564 |
+
where it needs to correctly call the public API of flash attention and deal with padding tokens
|
565 |
+
in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
|
566 |
+
config.max_window_layers layers.
|
567 |
+
"""
|
568 |
+
|
569 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
|
570 |
+
def __init__(self, *args, **kwargs):
|
571 |
+
super().__init__(*args, **kwargs)
|
572 |
+
|
573 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
574 |
+
# 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.
|
575 |
+
# 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).
|
576 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
577 |
+
|
578 |
+
def forward(
|
579 |
+
self,
|
580 |
+
hidden_states: torch.Tensor,
|
581 |
+
attention_mask: Optional[torch.Tensor] = None,
|
582 |
+
position_ids: Optional[torch.LongTensor] = None,
|
583 |
+
image_embeds=None,
|
584 |
+
media_offset=None,
|
585 |
+
past_key_value: Optional[Cache] = None,
|
586 |
+
output_attentions: bool = False,
|
587 |
+
use_cache: bool = False,
|
588 |
+
):
|
589 |
+
bsz, q_len, _ = hidden_states.size()
|
590 |
+
|
591 |
+
query_states = self.q_proj(hidden_states)
|
592 |
+
key_states = self.k_proj(hidden_states)
|
593 |
+
value_states = self.v_proj(hidden_states)
|
594 |
+
|
595 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
596 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
597 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
598 |
+
|
599 |
+
kv_seq_len = key_states.shape[-2]
|
600 |
+
if past_key_value is not None:
|
601 |
+
if self.layer_idx is None:
|
602 |
+
raise ValueError(
|
603 |
+
f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
|
604 |
+
"for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
|
605 |
+
"with a layer index."
|
606 |
+
)
|
607 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
608 |
+
|
609 |
+
# Because the input can be padded, the absolute sequence length depends on the max position id.
|
610 |
+
rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
|
611 |
+
cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
|
612 |
+
|
613 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
614 |
+
|
615 |
+
use_sliding_windows = (
|
616 |
+
_flash_supports_window_size
|
617 |
+
and getattr(self.config, "sliding_window", None) is not None
|
618 |
+
and kv_seq_len > self.config.sliding_window
|
619 |
+
and self.config.use_sliding_window
|
620 |
+
)
|
621 |
+
|
622 |
+
if not _flash_supports_window_size:
|
623 |
+
logger.warning_once(
|
624 |
+
"The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
|
625 |
+
" make sure to upgrade flash-attn library."
|
626 |
+
)
|
627 |
+
|
628 |
+
if past_key_value is not None:
|
629 |
+
# Activate slicing cache only if the config has a value `sliding_windows` attribute
|
630 |
+
cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
|
631 |
+
if (
|
632 |
+
getattr(self.config, "sliding_window", None) is not None
|
633 |
+
and kv_seq_len > self.config.sliding_window
|
634 |
+
and cache_has_contents
|
635 |
+
):
|
636 |
+
slicing_tokens = 1 - self.config.sliding_window
|
637 |
+
|
638 |
+
past_key = past_key_value[self.layer_idx][0]
|
639 |
+
past_value = past_key_value[self.layer_idx][1]
|
640 |
+
|
641 |
+
past_key = past_key[:, :, slicing_tokens:, :].contiguous()
|
642 |
+
past_value = past_value[:, :, slicing_tokens:, :].contiguous()
|
643 |
+
|
644 |
+
if past_key.shape[-2] != self.config.sliding_window - 1:
|
645 |
+
raise ValueError(
|
646 |
+
f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
|
647 |
+
f" {past_key.shape}"
|
648 |
+
)
|
649 |
+
|
650 |
+
if attention_mask is not None:
|
651 |
+
attention_mask = attention_mask[:, slicing_tokens:]
|
652 |
+
attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
|
653 |
+
|
654 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
655 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
656 |
+
|
657 |
+
# repeat k/v heads if n_kv_heads < n_heads
|
658 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
659 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
660 |
+
dropout_rate = 0.0 if not self.training else self.attention_dropout
|
661 |
+
|
662 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
663 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
664 |
+
# cast them back in float16 just to be sure everything works as expected.
|
665 |
+
input_dtype = query_states.dtype
|
666 |
+
if input_dtype == torch.float32:
|
667 |
+
if torch.is_autocast_enabled():
|
668 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
669 |
+
# Handle the case where the model is quantized
|
670 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
671 |
+
target_dtype = self.config._pre_quantization_dtype
|
672 |
+
else:
|
673 |
+
target_dtype = self.q_proj.weight.dtype
|
674 |
+
|
675 |
+
logger.warning_once(
|
676 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
677 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
678 |
+
f" {target_dtype}."
|
679 |
+
)
|
680 |
+
|
681 |
+
query_states = query_states.to(target_dtype)
|
682 |
+
key_states = key_states.to(target_dtype)
|
683 |
+
value_states = value_states.to(target_dtype)
|
684 |
+
|
685 |
+
# Reashape to the expected shape for Flash Attention
|
686 |
+
query_states = query_states.transpose(1, 2)
|
687 |
+
key_states = key_states.transpose(1, 2)
|
688 |
+
value_states = value_states.transpose(1, 2)
|
689 |
+
|
690 |
+
attn_output = self._flash_attention_forward(
|
691 |
+
query_states,
|
692 |
+
key_states,
|
693 |
+
value_states,
|
694 |
+
attention_mask,
|
695 |
+
q_len,
|
696 |
+
dropout=dropout_rate,
|
697 |
+
use_sliding_windows=use_sliding_windows,
|
698 |
+
)
|
699 |
+
|
700 |
+
|
701 |
+
|
702 |
+
|
703 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
704 |
+
|
705 |
+
# Hyper Attention
|
706 |
+
# (batch_size, seqlen, nheads, headdim) -> [s b h d]
|
707 |
+
attn_output = self.crossattention(query_states.permute(1,0,2,3), image_embeds, media_offset, attn_output.permute(1,0,2))
|
708 |
+
attn_output = attn_output.permute(1,0,2)
|
709 |
+
#### End of Hyper Attention
|
710 |
+
|
711 |
+
attn_output = self.o_proj(attn_output)
|
712 |
+
|
713 |
+
if not output_attentions:
|
714 |
+
attn_weights = None
|
715 |
+
|
716 |
+
return attn_output, attn_weights, past_key_value
|
717 |
+
|
718 |
+
def _flash_attention_forward(
|
719 |
+
self,
|
720 |
+
query_states,
|
721 |
+
key_states,
|
722 |
+
value_states,
|
723 |
+
attention_mask,
|
724 |
+
query_length,
|
725 |
+
dropout=0.0,
|
726 |
+
softmax_scale=None,
|
727 |
+
use_sliding_windows=False,
|
728 |
+
):
|
729 |
+
"""
|
730 |
+
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
731 |
+
first unpad the input, then computes the attention scores and pad the final attention scores.
|
732 |
+
|
733 |
+
Args:
|
734 |
+
query_states (`torch.Tensor`):
|
735 |
+
Input query states to be passed to Flash Attention API
|
736 |
+
key_states (`torch.Tensor`):
|
737 |
+
Input key states to be passed to Flash Attention API
|
738 |
+
value_states (`torch.Tensor`):
|
739 |
+
Input value states to be passed to Flash Attention API
|
740 |
+
attention_mask (`torch.Tensor`):
|
741 |
+
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
742 |
+
position of padding tokens and 1 for the position of non-padding tokens.
|
743 |
+
dropout (`float`):
|
744 |
+
Attention dropout
|
745 |
+
softmax_scale (`float`, *optional*):
|
746 |
+
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
747 |
+
use_sliding_windows (`bool`, *optional*):
|
748 |
+
Whether to activate sliding window attention.
|
749 |
+
"""
|
750 |
+
if not self._flash_attn_uses_top_left_mask:
|
751 |
+
causal = self.is_causal
|
752 |
+
else:
|
753 |
+
# 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__.
|
754 |
+
causal = self.is_causal and query_length != 1
|
755 |
+
|
756 |
+
# Decide whether to use SWA or not by layer index.
|
757 |
+
if use_sliding_windows and self.layer_idx >= self.config.max_window_layers:
|
758 |
+
use_sliding_windows = False
|
759 |
+
|
760 |
+
# Contains at least one padding token in the sequence
|
761 |
+
if attention_mask is not None:
|
762 |
+
batch_size = query_states.shape[0]
|
763 |
+
query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
|
764 |
+
query_states, key_states, value_states, attention_mask, query_length
|
765 |
+
)
|
766 |
+
|
767 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
768 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
769 |
+
|
770 |
+
if not use_sliding_windows:
|
771 |
+
attn_output_unpad = flash_attn_varlen_func(
|
772 |
+
query_states,
|
773 |
+
key_states,
|
774 |
+
value_states,
|
775 |
+
cu_seqlens_q=cu_seqlens_q,
|
776 |
+
cu_seqlens_k=cu_seqlens_k,
|
777 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
778 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
779 |
+
dropout_p=dropout,
|
780 |
+
softmax_scale=softmax_scale,
|
781 |
+
causal=causal,
|
782 |
+
)
|
783 |
+
else:
|
784 |
+
attn_output_unpad = flash_attn_varlen_func(
|
785 |
+
query_states,
|
786 |
+
key_states,
|
787 |
+
value_states,
|
788 |
+
cu_seqlens_q=cu_seqlens_q,
|
789 |
+
cu_seqlens_k=cu_seqlens_k,
|
790 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
791 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
792 |
+
dropout_p=dropout,
|
793 |
+
softmax_scale=softmax_scale,
|
794 |
+
causal=causal,
|
795 |
+
window_size=(self.config.sliding_window, self.config.sliding_window),
|
796 |
+
)
|
797 |
+
|
798 |
+
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
|
799 |
+
else:
|
800 |
+
if not use_sliding_windows:
|
801 |
+
attn_output = flash_attn_func(
|
802 |
+
query_states,
|
803 |
+
key_states,
|
804 |
+
value_states,
|
805 |
+
dropout,
|
806 |
+
softmax_scale=softmax_scale,
|
807 |
+
causal=causal,
|
808 |
+
)
|
809 |
+
else:
|
810 |
+
attn_output = flash_attn_func(
|
811 |
+
query_states,
|
812 |
+
key_states,
|
813 |
+
value_states,
|
814 |
+
dropout,
|
815 |
+
softmax_scale=softmax_scale,
|
816 |
+
causal=causal,
|
817 |
+
window_size=(self.config.sliding_window, self.config.sliding_window),
|
818 |
+
)
|
819 |
+
|
820 |
+
return attn_output
|
821 |
+
|
822 |
+
# Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
|
823 |
+
def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
|
824 |
+
batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
|
825 |
+
|
826 |
+
# On the first iteration we need to properly re-create the padding mask
|
827 |
+
# by slicing it on the proper place
|
828 |
+
if kv_seq_len != attention_mask.shape[-1]:
|
829 |
+
attention_mask_num_tokens = attention_mask.shape[-1]
|
830 |
+
attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
|
831 |
+
|
832 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
833 |
+
|
834 |
+
key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
|
835 |
+
value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
|
836 |
+
|
837 |
+
if query_length == kv_seq_len:
|
838 |
+
query_layer = index_first_axis(
|
839 |
+
query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
|
840 |
+
)
|
841 |
+
cu_seqlens_q = cu_seqlens_k
|
842 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
843 |
+
indices_q = indices_k
|
844 |
+
elif query_length == 1:
|
845 |
+
max_seqlen_in_batch_q = 1
|
846 |
+
cu_seqlens_q = torch.arange(
|
847 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
848 |
+
) # There is a memcpy here, that is very bad.
|
849 |
+
indices_q = cu_seqlens_q[:-1]
|
850 |
+
query_layer = query_layer.squeeze(1)
|
851 |
+
else:
|
852 |
+
# The -q_len: slice assumes left padding.
|
853 |
+
attention_mask = attention_mask[:, -query_length:]
|
854 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
|
855 |
+
|
856 |
+
return (
|
857 |
+
query_layer,
|
858 |
+
key_layer,
|
859 |
+
value_layer,
|
860 |
+
indices_q,
|
861 |
+
(cu_seqlens_q, cu_seqlens_k),
|
862 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
863 |
+
)
|
864 |
+
|
865 |
+
|
866 |
+
# Copied from transformers.models.mistral.modeling_mistral.MistralSdpaAttention with Mistral->Qwen2
|
867 |
+
class HyperQwen2SdpaAttention(HyperQwen2Attention):
|
868 |
+
"""
|
869 |
+
Qwen2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
|
870 |
+
`Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
|
871 |
+
SDPA API.
|
872 |
+
"""
|
873 |
+
|
874 |
+
# Adapted from Qwen2Attention.forward
|
875 |
+
def forward(
|
876 |
+
self,
|
877 |
+
hidden_states: torch.Tensor,
|
878 |
+
attention_mask: Optional[torch.Tensor] = None,
|
879 |
+
position_ids: Optional[torch.LongTensor] = None,
|
880 |
+
image_embeds=None,
|
881 |
+
media_offset=None,
|
882 |
+
past_key_value: Optional[Cache] = None,
|
883 |
+
output_attentions: bool = False,
|
884 |
+
use_cache: bool = False,
|
885 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
886 |
+
if output_attentions:
|
887 |
+
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
|
888 |
+
logger.warning_once(
|
889 |
+
"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, "
|
890 |
+
'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.'
|
891 |
+
)
|
892 |
+
return super().forward(
|
893 |
+
hidden_states=hidden_states,
|
894 |
+
attention_mask=attention_mask,
|
895 |
+
position_ids=position_ids,
|
896 |
+
past_key_value=past_key_value,
|
897 |
+
output_attentions=output_attentions,
|
898 |
+
use_cache=use_cache,
|
899 |
+
)
|
900 |
+
|
901 |
+
bsz, q_len, _ = hidden_states.size()
|
902 |
+
|
903 |
+
query_states = self.q_proj(hidden_states)
|
904 |
+
key_states = self.k_proj(hidden_states)
|
905 |
+
value_states = self.v_proj(hidden_states)
|
906 |
+
|
907 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
908 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
909 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
910 |
+
|
911 |
+
kv_seq_len = key_states.shape[-2]
|
912 |
+
if past_key_value is not None:
|
913 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
914 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
915 |
+
|
916 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
917 |
+
|
918 |
+
if past_key_value is not None:
|
919 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
920 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
921 |
+
|
922 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
923 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
924 |
+
|
925 |
+
if attention_mask is not None:
|
926 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
927 |
+
raise ValueError(
|
928 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
929 |
+
)
|
930 |
+
|
931 |
+
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
|
932 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577.
|
933 |
+
if query_states.device.type == "cuda" and attention_mask is not None:
|
934 |
+
query_states = query_states.contiguous()
|
935 |
+
key_states = key_states.contiguous()
|
936 |
+
value_states = value_states.contiguous()
|
937 |
+
|
938 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
939 |
+
query_states,
|
940 |
+
key_states,
|
941 |
+
value_states,
|
942 |
+
attn_mask=attention_mask,
|
943 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
944 |
+
# 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.
|
945 |
+
is_causal=self.is_causal and attention_mask is None and q_len > 1,
|
946 |
+
)
|
947 |
+
|
948 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
949 |
+
attn_output = attn_output.view(bsz, q_len, self.hidden_size)
|
950 |
+
|
951 |
+
# Hyper Attention
|
952 |
+
attn_output = self.crossattention(query_states.permute(2,0,1,3), image_embeds, media_offset, attn_output.permute(1,0,2))
|
953 |
+
attn_output = attn_output.permute(1,0,2)
|
954 |
+
#### End of Hyper Attention
|
955 |
+
|
956 |
+
attn_output = self.o_proj(attn_output)
|
957 |
+
|
958 |
+
return attn_output, None, past_key_value
|
959 |
+
|
960 |
+
|
961 |
+
QWEN2_ATTENTION_CLASSES = {
|
962 |
+
"eager": HyperQwen2Attention,
|
963 |
+
"flash_attention_2": HyperQwen2FlashAttention2,
|
964 |
+
"sdpa": HyperQwen2SdpaAttention,
|
965 |
+
}
|
966 |
+
|
967 |
+
|
968 |
+
class HyperQwen2DecoderLayer(nn.Module):
|
969 |
+
def __init__(self, config: HyperQwen2Config, layer_idx: int):
|
970 |
+
super().__init__()
|
971 |
+
self.hidden_size = config.hidden_size
|
972 |
+
|
973 |
+
if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
|
974 |
+
logger.warning_once(
|
975 |
+
f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
|
976 |
+
"unexpected results may be encountered."
|
977 |
+
)
|
978 |
+
self.is_hyper_enabled = (layer_idx+1) in config.hyper_layers
|
979 |
+
self.self_attn = QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx, is_hyper_enabed=self.is_hyper_enabled)
|
980 |
+
|
981 |
+
|
982 |
+
self.mlp = Qwen2MLP(config)
|
983 |
+
self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
984 |
+
self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
985 |
+
|
986 |
+
def forward(
|
987 |
+
self,
|
988 |
+
hidden_states: torch.Tensor,
|
989 |
+
attention_mask: Optional[torch.Tensor] = None,
|
990 |
+
position_ids: Optional[torch.LongTensor] = None,
|
991 |
+
image_embeds=None,
|
992 |
+
media_offset=None,
|
993 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
994 |
+
output_attentions: Optional[bool] = False,
|
995 |
+
use_cache: Optional[bool] = False,
|
996 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
997 |
+
"""
|
998 |
+
Args:
|
999 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
1000 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
1001 |
+
`(batch, sequence_length)` where padding elements are indicated by 0.
|
1002 |
+
output_attentions (`bool`, *optional*):
|
1003 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
1004 |
+
returned tensors for more detail.
|
1005 |
+
use_cache (`bool`, *optional*):
|
1006 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
1007 |
+
(see `past_key_values`).
|
1008 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
1009 |
+
"""
|
1010 |
+
|
1011 |
+
residual = hidden_states
|
1012 |
+
|
1013 |
+
hidden_states = self.input_layernorm(hidden_states)
|
1014 |
+
|
1015 |
+
# Shared LayerNorm
|
1016 |
+
if image_embeds is not None and self.is_hyper_enabled:
|
1017 |
+
image_embeds = self.input_layernorm(image_embeds)
|
1018 |
+
else:
|
1019 |
+
image_embeds = media_offset = None
|
1020 |
+
# Self Attention
|
1021 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
1022 |
+
hidden_states=hidden_states,
|
1023 |
+
attention_mask=attention_mask,
|
1024 |
+
position_ids=position_ids,
|
1025 |
+
image_embeds=image_embeds,
|
1026 |
+
media_offset=media_offset,
|
1027 |
+
past_key_value=past_key_value,
|
1028 |
+
output_attentions=output_attentions,
|
1029 |
+
use_cache=use_cache,
|
1030 |
+
)
|
1031 |
+
hidden_states = residual + hidden_states
|
1032 |
+
|
1033 |
+
# Fully Connected
|
1034 |
+
residual = hidden_states
|
1035 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
1036 |
+
hidden_states = self.mlp(hidden_states)
|
1037 |
+
hidden_states = residual + hidden_states
|
1038 |
+
|
1039 |
+
outputs = (hidden_states,)
|
1040 |
+
|
1041 |
+
if output_attentions:
|
1042 |
+
outputs += (self_attn_weights,)
|
1043 |
+
|
1044 |
+
if use_cache:
|
1045 |
+
outputs += (present_key_value,)
|
1046 |
+
|
1047 |
+
return outputs
|
1048 |
+
|
1049 |
+
|
1050 |
+
QWEN2_START_DOCSTRING = r"""
|
1051 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
1052 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
1053 |
+
etc.)
|
1054 |
+
|
1055 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
1056 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
1057 |
+
and behavior.
|
1058 |
+
|
1059 |
+
Parameters:
|
1060 |
+
config ([`HyperQwen2Config`]):
|
1061 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
1062 |
+
load the weights associated with the model, only the configuration. Check out the
|
1063 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
1064 |
+
"""
|
1065 |
+
|
1066 |
+
|
1067 |
+
@add_start_docstrings(
|
1068 |
+
"The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
|
1069 |
+
QWEN2_START_DOCSTRING,
|
1070 |
+
)
|
1071 |
+
class Qwen2PreTrainedModel(PreTrainedModel):
|
1072 |
+
config_class = HyperQwen2Config
|
1073 |
+
base_model_prefix = "model"
|
1074 |
+
supports_gradient_checkpointing = True
|
1075 |
+
_no_split_modules = ["HyperQwen2DecoderLayer"]
|
1076 |
+
_skip_keys_device_placement = "past_key_values"
|
1077 |
+
_supports_flash_attn_2 = True
|
1078 |
+
_supports_sdpa = True
|
1079 |
+
_supports_cache_class = True
|
1080 |
+
|
1081 |
+
def _init_weights(self, module):
|
1082 |
+
std = self.config.initializer_range
|
1083 |
+
if isinstance(module, nn.Linear):
|
1084 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
1085 |
+
if module.bias is not None:
|
1086 |
+
module.bias.data.zero_()
|
1087 |
+
elif isinstance(module, nn.Embedding):
|
1088 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
1089 |
+
if module.padding_idx is not None:
|
1090 |
+
module.weight.data[module.padding_idx].zero_()
|
1091 |
+
|
1092 |
+
|
1093 |
+
QWEN2_INPUTS_DOCSTRING = r"""
|
1094 |
+
Args:
|
1095 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
1096 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
1097 |
+
it.
|
1098 |
+
|
1099 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
1100 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
1101 |
+
|
1102 |
+
[What are input IDs?](../glossary#input-ids)
|
1103 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1104 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
1105 |
+
|
1106 |
+
- 1 for tokens that are **not masked**,
|
1107 |
+
- 0 for tokens that are **masked**.
|
1108 |
+
|
1109 |
+
[What are attention masks?](../glossary#attention-mask)
|
1110 |
+
|
1111 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
1112 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
1113 |
+
|
1114 |
+
If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
1115 |
+
`past_key_values`).
|
1116 |
+
|
1117 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
1118 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
1119 |
+
information on the default strategy.
|
1120 |
+
|
1121 |
+
- 1 indicates the head is **not masked**,
|
1122 |
+
- 0 indicates the head is **masked**.
|
1123 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1124 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
1125 |
+
config.n_positions - 1]`.
|
1126 |
+
|
1127 |
+
[What are position IDs?](../glossary#position-ids)
|
1128 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
1129 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
1130 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
1131 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
1132 |
+
|
1133 |
+
Two formats are allowed:
|
1134 |
+
- a [`~cache_utils.Cache`] instance;
|
1135 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
1136 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
1137 |
+
cache format.
|
1138 |
+
|
1139 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
1140 |
+
legacy cache format will be returned.
|
1141 |
+
|
1142 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
1143 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
1144 |
+
of shape `(batch_size, sequence_length)`.
|
1145 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
1146 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
1147 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
1148 |
+
model's internal embedding lookup matrix.
|
1149 |
+
use_cache (`bool`, *optional*):
|
1150 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
1151 |
+
`past_key_values`).
|
1152 |
+
output_attentions (`bool`, *optional*):
|
1153 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
1154 |
+
tensors for more detail.
|
1155 |
+
output_hidden_states (`bool`, *optional*):
|
1156 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
1157 |
+
more detail.
|
1158 |
+
return_dict (`bool`, *optional*):
|
1159 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
1160 |
+
"""
|
1161 |
+
|
1162 |
+
|
1163 |
+
@add_start_docstrings(
|
1164 |
+
"The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
|
1165 |
+
QWEN2_START_DOCSTRING,
|
1166 |
+
)
|
1167 |
+
class HyperQwen2Model(Qwen2PreTrainedModel):
|
1168 |
+
"""
|
1169 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
|
1170 |
+
|
1171 |
+
Args:
|
1172 |
+
config: HyperQwen2Config
|
1173 |
+
"""
|
1174 |
+
|
1175 |
+
def __init__(self, config: HyperQwen2Config):
|
1176 |
+
super().__init__(config)
|
1177 |
+
self.padding_idx = config.pad_token_id
|
1178 |
+
self.vocab_size = config.vocab_size
|
1179 |
+
|
1180 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
1181 |
+
self.layers = nn.ModuleList(
|
1182 |
+
[HyperQwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
1183 |
+
)
|
1184 |
+
self._attn_implementation = config._attn_implementation
|
1185 |
+
self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
1186 |
+
|
1187 |
+
self.gradient_checkpointing = False
|
1188 |
+
# Initialize weights and apply final processing
|
1189 |
+
self.post_init()
|
1190 |
+
|
1191 |
+
def get_input_embeddings(self):
|
1192 |
+
return self.embed_tokens
|
1193 |
+
|
1194 |
+
def set_input_embeddings(self, value):
|
1195 |
+
self.embed_tokens = value
|
1196 |
+
|
1197 |
+
@add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
|
1198 |
+
def forward(
|
1199 |
+
self,
|
1200 |
+
input_ids: torch.LongTensor = None,
|
1201 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1202 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1203 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1204 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1205 |
+
image_embeds=None,
|
1206 |
+
media_offset=None,
|
1207 |
+
use_cache: Optional[bool] = None,
|
1208 |
+
output_attentions: Optional[bool] = None,
|
1209 |
+
output_hidden_states: Optional[bool] = None,
|
1210 |
+
return_dict: Optional[bool] = None,
|
1211 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
1212 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1213 |
+
output_hidden_states = (
|
1214 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1215 |
+
)
|
1216 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
1217 |
+
|
1218 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1219 |
+
|
1220 |
+
# retrieve input_ids and inputs_embeds
|
1221 |
+
if input_ids is not None and inputs_embeds is not None:
|
1222 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
1223 |
+
elif input_ids is not None:
|
1224 |
+
batch_size, seq_length = input_ids.shape
|
1225 |
+
elif inputs_embeds is not None:
|
1226 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
1227 |
+
else:
|
1228 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
1229 |
+
|
1230 |
+
if self.gradient_checkpointing and self.training:
|
1231 |
+
if use_cache:
|
1232 |
+
logger.warning_once(
|
1233 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
1234 |
+
)
|
1235 |
+
use_cache = False
|
1236 |
+
|
1237 |
+
past_key_values_length = 0
|
1238 |
+
|
1239 |
+
if use_cache:
|
1240 |
+
use_legacy_cache = not isinstance(past_key_values, Cache)
|
1241 |
+
if use_legacy_cache:
|
1242 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
1243 |
+
past_key_values_length = past_key_values.get_usable_length(seq_length)
|
1244 |
+
|
1245 |
+
if position_ids is None:
|
1246 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
1247 |
+
position_ids = torch.arange(
|
1248 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
1249 |
+
)
|
1250 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
1251 |
+
else:
|
1252 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
1253 |
+
|
1254 |
+
if inputs_embeds is None:
|
1255 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
1256 |
+
|
1257 |
+
if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
|
1258 |
+
is_padding_right = attention_mask[:, -1].sum().item() != batch_size
|
1259 |
+
if is_padding_right:
|
1260 |
+
raise ValueError(
|
1261 |
+
"You are attempting to perform batched generation with padding_side='right'"
|
1262 |
+
" this may lead to unexpected behaviour for Flash Attention version of Qwen2. Make sure to "
|
1263 |
+
" call `tokenizer.padding_side = 'left'` before tokenizing the input. "
|
1264 |
+
)
|
1265 |
+
|
1266 |
+
if self._attn_implementation == "flash_attention_2":
|
1267 |
+
# 2d mask is passed through the layers
|
1268 |
+
attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
|
1269 |
+
elif self._attn_implementation == "sdpa" and not output_attentions:
|
1270 |
+
# output_attentions=True can not be supported when using SDPA, and we fall back on
|
1271 |
+
# the manual implementation that requires a 4D causal mask in all cases.
|
1272 |
+
attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
|
1273 |
+
attention_mask,
|
1274 |
+
(batch_size, seq_length),
|
1275 |
+
inputs_embeds,
|
1276 |
+
past_key_values_length,
|
1277 |
+
sliding_window=self.config.sliding_window,
|
1278 |
+
)
|
1279 |
+
else:
|
1280 |
+
# 4d mask is passed through the layers
|
1281 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
1282 |
+
attention_mask,
|
1283 |
+
(batch_size, seq_length),
|
1284 |
+
inputs_embeds,
|
1285 |
+
past_key_values_length,
|
1286 |
+
sliding_window=self.config.sliding_window,
|
1287 |
+
)
|
1288 |
+
|
1289 |
+
hidden_states = inputs_embeds
|
1290 |
+
|
1291 |
+
# decoder layers
|
1292 |
+
all_hidden_states = () if output_hidden_states else None
|
1293 |
+
all_self_attns = () if output_attentions else None
|
1294 |
+
next_decoder_cache = None
|
1295 |
+
|
1296 |
+
for decoder_layer in self.layers:
|
1297 |
+
if output_hidden_states:
|
1298 |
+
all_hidden_states += (hidden_states,)
|
1299 |
+
|
1300 |
+
if self.gradient_checkpointing and self.training:
|
1301 |
+
layer_outputs = self._gradient_checkpointing_func(
|
1302 |
+
decoder_layer.__call__,
|
1303 |
+
hidden_states,
|
1304 |
+
attention_mask,
|
1305 |
+
position_ids,
|
1306 |
+
image_embeds,
|
1307 |
+
media_offset,
|
1308 |
+
past_key_values,
|
1309 |
+
output_attentions,
|
1310 |
+
use_cache,
|
1311 |
+
)
|
1312 |
+
else:
|
1313 |
+
layer_outputs = decoder_layer(
|
1314 |
+
hidden_states,
|
1315 |
+
attention_mask=attention_mask,
|
1316 |
+
position_ids=position_ids,
|
1317 |
+
image_embeds=image_embeds,
|
1318 |
+
media_offset=media_offset,
|
1319 |
+
past_key_value=past_key_values,
|
1320 |
+
output_attentions=output_attentions,
|
1321 |
+
use_cache=use_cache,
|
1322 |
+
)
|
1323 |
+
|
1324 |
+
hidden_states = layer_outputs[0]
|
1325 |
+
|
1326 |
+
if use_cache:
|
1327 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
1328 |
+
|
1329 |
+
if output_attentions:
|
1330 |
+
all_self_attns += (layer_outputs[1],)
|
1331 |
+
|
1332 |
+
hidden_states = self.norm(hidden_states)
|
1333 |
+
|
1334 |
+
# add hidden states from the last decoder layer
|
1335 |
+
if output_hidden_states:
|
1336 |
+
all_hidden_states += (hidden_states,)
|
1337 |
+
|
1338 |
+
next_cache = None
|
1339 |
+
if use_cache:
|
1340 |
+
next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
|
1341 |
+
|
1342 |
+
if not return_dict:
|
1343 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
1344 |
+
return BaseModelOutputWithPast(
|
1345 |
+
last_hidden_state=hidden_states,
|
1346 |
+
past_key_values=next_cache,
|
1347 |
+
hidden_states=all_hidden_states,
|
1348 |
+
attentions=all_self_attns,
|
1349 |
+
)
|
1350 |
+
|
1351 |
+
|
1352 |
+
class HyperQwen2ForCausalLM(Qwen2PreTrainedModel):
|
1353 |
+
_tied_weights_keys = ["lm_head.weight"]
|
1354 |
+
|
1355 |
+
def __init__(self, config):
|
1356 |
+
super().__init__(config)
|
1357 |
+
self.model = HyperQwen2Model(config)
|
1358 |
+
self.vocab_size = config.vocab_size
|
1359 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
1360 |
+
|
1361 |
+
# Initialize weights and apply final processing
|
1362 |
+
self.post_init()
|
1363 |
+
|
1364 |
+
def get_input_embeddings(self):
|
1365 |
+
return self.model.embed_tokens
|
1366 |
+
|
1367 |
+
def set_input_embeddings(self, value):
|
1368 |
+
self.model.embed_tokens = value
|
1369 |
+
|
1370 |
+
def get_output_embeddings(self):
|
1371 |
+
return self.lm_head
|
1372 |
+
|
1373 |
+
def set_output_embeddings(self, new_embeddings):
|
1374 |
+
self.lm_head = new_embeddings
|
1375 |
+
|
1376 |
+
def set_decoder(self, decoder):
|
1377 |
+
self.model = decoder
|
1378 |
+
|
1379 |
+
def get_decoder(self):
|
1380 |
+
return self.model
|
1381 |
+
|
1382 |
+
@add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
|
1383 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
1384 |
+
def forward(
|
1385 |
+
self,
|
1386 |
+
input_ids: torch.LongTensor = None,
|
1387 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1388 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1389 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1390 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1391 |
+
image_embeds=None,
|
1392 |
+
media_offset=None,
|
1393 |
+
labels: Optional[torch.LongTensor] = None,
|
1394 |
+
use_cache: Optional[bool] = None,
|
1395 |
+
output_attentions: Optional[bool] = None,
|
1396 |
+
output_hidden_states: Optional[bool] = None,
|
1397 |
+
return_dict: Optional[bool] = None,
|
1398 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
1399 |
+
r"""
|
1400 |
+
Args:
|
1401 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1402 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
1403 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
1404 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
1405 |
+
|
1406 |
+
Returns:
|
1407 |
+
|
1408 |
+
Example:
|
1409 |
+
|
1410 |
+
```python
|
1411 |
+
>>> from transformers import AutoTokenizer, Qwen2ForCausalLM
|
1412 |
+
|
1413 |
+
>>> model = Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
|
1414 |
+
>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
|
1415 |
+
|
1416 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
1417 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
1418 |
+
|
1419 |
+
>>> # Generate
|
1420 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
1421 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
1422 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
1423 |
+
```"""
|
1424 |
+
|
1425 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1426 |
+
output_hidden_states = (
|
1427 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1428 |
+
)
|
1429 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1430 |
+
|
1431 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
1432 |
+
outputs = self.model(
|
1433 |
+
input_ids=input_ids,
|
1434 |
+
attention_mask=attention_mask,
|
1435 |
+
position_ids=position_ids,
|
1436 |
+
past_key_values=past_key_values,
|
1437 |
+
inputs_embeds=inputs_embeds,
|
1438 |
+
image_embeds=image_embeds,
|
1439 |
+
media_offset=media_offset,
|
1440 |
+
use_cache=use_cache,
|
1441 |
+
output_attentions=output_attentions,
|
1442 |
+
output_hidden_states=output_hidden_states,
|
1443 |
+
return_dict=return_dict,
|
1444 |
+
)
|
1445 |
+
|
1446 |
+
hidden_states = outputs[0]
|
1447 |
+
logits = self.lm_head(hidden_states)
|
1448 |
+
logits = logits.float()
|
1449 |
+
|
1450 |
+
loss = None
|
1451 |
+
if labels is not None:
|
1452 |
+
# Shift so that tokens < n predict n
|
1453 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
1454 |
+
shift_labels = labels[..., 1:].contiguous()
|
1455 |
+
# Flatten the tokens
|
1456 |
+
loss_fct = CrossEntropyLoss()
|
1457 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
1458 |
+
shift_labels = shift_labels.view(-1)
|
1459 |
+
# Enable model parallelism
|
1460 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
1461 |
+
loss = loss_fct(shift_logits, shift_labels)
|
1462 |
+
|
1463 |
+
if not return_dict:
|
1464 |
+
output = (logits,) + outputs[1:]
|
1465 |
+
return (loss,) + output if loss is not None else output
|
1466 |
+
|
1467 |
+
return CausalLMOutputWithPast(
|
1468 |
+
loss=loss,
|
1469 |
+
logits=logits,
|
1470 |
+
past_key_values=outputs.past_key_values,
|
1471 |
+
hidden_states=outputs.hidden_states,
|
1472 |
+
attentions=outputs.attentions,
|
1473 |
+
)
|
1474 |
+
|
1475 |
+
def prepare_inputs_for_generation(
|
1476 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
1477 |
+
):
|
1478 |
+
# Omit tokens covered by past_key_values
|
1479 |
+
if past_key_values is not None:
|
1480 |
+
if isinstance(past_key_values, Cache):
|
1481 |
+
cache_length = past_key_values.get_seq_length()
|
1482 |
+
past_length = past_key_values.seen_tokens
|
1483 |
+
max_cache_length = past_key_values.get_max_length()
|
1484 |
+
else:
|
1485 |
+
cache_length = past_length = past_key_values[0][0].shape[2]
|
1486 |
+
max_cache_length = None
|
1487 |
+
|
1488 |
+
# Keep only the unprocessed tokens:
|
1489 |
+
# 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
|
1490 |
+
# some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
|
1491 |
+
# input)
|
1492 |
+
if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
|
1493 |
+
input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
|
1494 |
+
# 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
|
1495 |
+
# input_ids based on the past_length.
|
1496 |
+
elif past_length < input_ids.shape[1]:
|
1497 |
+
input_ids = input_ids[:, past_length:]
|
1498 |
+
# 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
|
1499 |
+
|
1500 |
+
# If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
|
1501 |
+
if (
|
1502 |
+
max_cache_length is not None
|
1503 |
+
and attention_mask is not None
|
1504 |
+
and cache_length + input_ids.shape[1] > max_cache_length
|
1505 |
+
):
|
1506 |
+
attention_mask = attention_mask[:, -max_cache_length:]
|
1507 |
+
|
1508 |
+
position_ids = kwargs.get("position_ids", None)
|
1509 |
+
if attention_mask is not None and position_ids is None:
|
1510 |
+
# create position_ids on the fly for batch generation
|
1511 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
1512 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
1513 |
+
if past_key_values:
|
1514 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
1515 |
+
|
1516 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
1517 |
+
if inputs_embeds is not None and past_key_values is None:
|
1518 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
1519 |
+
else:
|
1520 |
+
model_inputs = {"input_ids": input_ids}
|
1521 |
+
|
1522 |
+
model_inputs.update(
|
1523 |
+
{
|
1524 |
+
"position_ids": position_ids,
|
1525 |
+
"past_key_values": past_key_values,
|
1526 |
+
"use_cache": kwargs.get("use_cache"),
|
1527 |
+
"attention_mask": attention_mask,
|
1528 |
+
'image_embeds': kwargs.get('image_embeds'),
|
1529 |
+
'media_offset': kwargs.get('media_offset'),
|
1530 |
+
}
|
1531 |
+
)
|
1532 |
+
return model_inputs
|
1533 |
+
|
1534 |
+
@staticmethod
|
1535 |
+
def _reorder_cache(past_key_values, beam_idx):
|
1536 |
+
reordered_past = ()
|
1537 |
+
for layer_past in past_key_values:
|
1538 |
+
reordered_past += (
|
1539 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
1540 |
+
)
|
1541 |
+
return reordered_past
|
modeling_mplugowl3.py
ADDED
@@ -0,0 +1,246 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
from typing import List, Optional
|
3 |
+
import json
|
4 |
+
import torch
|
5 |
+
import torchvision
|
6 |
+
|
7 |
+
from threading import Thread
|
8 |
+
from copy import deepcopy
|
9 |
+
from PIL import Image
|
10 |
+
from transformers import AutoProcessor, Qwen2PreTrainedModel, Qwen2ForCausalLM, TextIteratorStreamer
|
11 |
+
from .processing_mplugowl3 import mPLUGOwl3Processor
|
12 |
+
from .image_processing_mplugowl3 import mPLUGOwl3ImageProcessor
|
13 |
+
from .configuration_mplugowl3 import mPLUGOwl3Config
|
14 |
+
# from .modeling_navit_siglip import SiglipVisionTransformer
|
15 |
+
from transformers.models.siglip.modeling_siglip import SiglipVisionTransformer
|
16 |
+
from .x_sdpa import ScaleDotProductAttention
|
17 |
+
from .modeling_hyper_qwen2 import HyperQwen2ForCausalLM
|
18 |
+
from torch import nn
|
19 |
+
|
20 |
+
|
21 |
+
class mPLUGOwl3PreTrainedModel(Qwen2PreTrainedModel):
|
22 |
+
config_class = mPLUGOwl3Config
|
23 |
+
|
24 |
+
|
25 |
+
class mPLUGOwl3Model(mPLUGOwl3PreTrainedModel):
|
26 |
+
def __init__(self, config):
|
27 |
+
super().__init__(config)
|
28 |
+
self.language_model = HyperQwen2ForCausalLM(config)
|
29 |
+
self.vision_model = self.init_vision_module()
|
30 |
+
self.vision_dim = self.vision_model.embed_dim
|
31 |
+
self.embed_dim = self.language_model.config.hidden_size
|
32 |
+
self.vision2text_model = nn.Linear(self.vision_dim, self.embed_dim)
|
33 |
+
self.processor = None
|
34 |
+
|
35 |
+
self.terminators = ['<|im_end|>', '<|endoftext|>']
|
36 |
+
|
37 |
+
def init_vision_module(self):
|
38 |
+
|
39 |
+
self.config.vision_config._attn_implementation = self.config.vision_config._attn_implementation
|
40 |
+
model = SiglipVisionTransformer(self.config.vision_config)
|
41 |
+
|
42 |
+
setattr(model, 'embed_dim', model.embeddings.embed_dim)
|
43 |
+
setattr(model, 'patch_size', model.embeddings.patch_size)
|
44 |
+
return model
|
45 |
+
|
46 |
+
|
47 |
+
def get_input_embeddings(self):
|
48 |
+
return self.language_model.get_input_embeddings()
|
49 |
+
|
50 |
+
def set_input_embeddings(self, value):
|
51 |
+
self.language_model.embed_tokens = value
|
52 |
+
|
53 |
+
def get_output_embeddings(self):
|
54 |
+
return self.language_model.lm_head
|
55 |
+
|
56 |
+
def set_output_embeddings(self, new_embeddings):
|
57 |
+
self.language_model.lm_head = new_embeddings
|
58 |
+
|
59 |
+
def set_decoder(self, decoder):
|
60 |
+
self.language_model = decoder
|
61 |
+
|
62 |
+
def get_decoder(self):
|
63 |
+
return self.language_model
|
64 |
+
|
65 |
+
def forward_image(self, pixel_values):
|
66 |
+
if pixel_values is None:
|
67 |
+
return None
|
68 |
+
dtype = self.language_model.model.embed_tokens.weight.dtype
|
69 |
+
with torch.inference_mode():
|
70 |
+
image_embeds = self.vision_model(pixel_values.to(dtype), output_hidden_states=True).hidden_states[-2]
|
71 |
+
|
72 |
+
if self.vision2text_model is not None:
|
73 |
+
image_embeds = self.vision2text_model(image_embeds)
|
74 |
+
else:
|
75 |
+
pass
|
76 |
+
|
77 |
+
return image_embeds
|
78 |
+
|
79 |
+
def forward(self, pixel_values=None, **kwargs):
|
80 |
+
image_embeds = self.forward_image(pixel_values)
|
81 |
+
|
82 |
+
return self.language_model(
|
83 |
+
image_embeds=image_embeds,
|
84 |
+
**kwargs
|
85 |
+
)
|
86 |
+
|
87 |
+
def _decode(self, input_ids, image_embeds, media_offset, tokenizer, attention_mask, decode_text=False, **kwargs):
|
88 |
+
terminators = [tokenizer.convert_tokens_to_ids(i) for i in self.terminators]
|
89 |
+
output = self.language_model.generate(
|
90 |
+
input_ids=input_ids,
|
91 |
+
image_embeds=image_embeds,
|
92 |
+
media_offset=media_offset,
|
93 |
+
pad_token_id=0,
|
94 |
+
eos_token_id=terminators,
|
95 |
+
attention_mask=attention_mask,
|
96 |
+
**kwargs
|
97 |
+
)
|
98 |
+
|
99 |
+
output = output[:,input_ids.shape[1]:]
|
100 |
+
if decode_text:
|
101 |
+
return self._decode_text(output, tokenizer)
|
102 |
+
return output
|
103 |
+
|
104 |
+
def _decode_stream(self, input_ids, image_embeds, media_offset, tokenizer, **kwargs):
|
105 |
+
terminators = [tokenizer.convert_tokens_to_ids(i) for i in self.terminators]
|
106 |
+
streamer = TextIteratorStreamer(tokenizer=tokenizer)
|
107 |
+
generation_kwargs = {
|
108 |
+
'input_ids': input_ids,
|
109 |
+
'image_embeds': image_embeds,
|
110 |
+
'media_offset': media_offset,
|
111 |
+
'pad_token_id': 0,
|
112 |
+
'eos_token_id': terminators,
|
113 |
+
'streamer': streamer
|
114 |
+
}
|
115 |
+
generation_kwargs.update(kwargs)
|
116 |
+
|
117 |
+
thread = Thread(target=self.language_model.generate, kwargs=generation_kwargs)
|
118 |
+
thread.start()
|
119 |
+
|
120 |
+
return streamer
|
121 |
+
|
122 |
+
def _decode_text(self, result_ids, tokenizer):
|
123 |
+
terminators = [tokenizer.convert_tokens_to_ids(i) for i in self.terminators]
|
124 |
+
result_text = []
|
125 |
+
for result in result_ids:
|
126 |
+
result = result[result != 0]
|
127 |
+
if result[-1] in terminators:
|
128 |
+
result = result[:-1]
|
129 |
+
result_text.append(tokenizer.decode(result).strip())
|
130 |
+
return result_text
|
131 |
+
|
132 |
+
def init_processor(self, tokenizer):
|
133 |
+
ip = mPLUGOwl3ImageProcessor(image_size=384)
|
134 |
+
self.processor = mPLUGOwl3Processor(image_processor=ip, tokenizer=tokenizer)
|
135 |
+
processor = self.processor
|
136 |
+
return processor
|
137 |
+
|
138 |
+
def generate(
|
139 |
+
self,
|
140 |
+
input_ids=None,
|
141 |
+
pixel_values=None,
|
142 |
+
media_offset=None,
|
143 |
+
attention_mask=None,
|
144 |
+
tokenizer=None,
|
145 |
+
return_vision_hidden_states=False,
|
146 |
+
stream=False,
|
147 |
+
decode_text=False,
|
148 |
+
**kwargs
|
149 |
+
):
|
150 |
+
assert input_ids is not None
|
151 |
+
|
152 |
+
with torch.inference_mode():
|
153 |
+
image_embeds = self.forward_image(pixel_values)
|
154 |
+
|
155 |
+
if stream:
|
156 |
+
result = self._decode_stream(input_ids=input_ids, image_embeds=image_embeds, media_offset=media_offset, tokenizer=tokenizer, **kwargs)
|
157 |
+
else:
|
158 |
+
result = self._decode(input_ids=input_ids, image_embeds=image_embeds, media_offset=media_offset, tokenizer=tokenizer, attention_mask=attention_mask, decode_text=decode_text, **kwargs)
|
159 |
+
|
160 |
+
if return_vision_hidden_states:
|
161 |
+
return result, image_embeds
|
162 |
+
|
163 |
+
return result
|
164 |
+
|
165 |
+
def chat(
|
166 |
+
self,
|
167 |
+
images,
|
168 |
+
videos,
|
169 |
+
msgs,
|
170 |
+
tokenizer,
|
171 |
+
processor=None,
|
172 |
+
vision_hidden_states=None,
|
173 |
+
max_new_tokens=2048,
|
174 |
+
min_new_tokens=0,
|
175 |
+
sampling=True,
|
176 |
+
max_inp_length=8192,
|
177 |
+
system_prompt='',
|
178 |
+
stream=False,
|
179 |
+
max_slice_nums=None,
|
180 |
+
use_image_id=None,
|
181 |
+
**kwargs
|
182 |
+
):
|
183 |
+
print(msgs)
|
184 |
+
if processor is None:
|
185 |
+
if self.processor is None:
|
186 |
+
self.processor = AutoProcessor.from_pretrained(self.config._name_or_path, trust_remote_code=True)
|
187 |
+
processor = self.processor
|
188 |
+
|
189 |
+
|
190 |
+
inputs = processor(
|
191 |
+
prompts_lists,
|
192 |
+
input_images_lists,
|
193 |
+
max_slice_nums=max_slice_nums,
|
194 |
+
use_image_id=use_image_id,
|
195 |
+
return_tensors="pt",
|
196 |
+
max_length=max_inp_length
|
197 |
+
).to(self.device)
|
198 |
+
|
199 |
+
if sampling:
|
200 |
+
generation_config = {
|
201 |
+
"top_p": 0.8,
|
202 |
+
"top_k": 100,
|
203 |
+
"temperature": 0.7,
|
204 |
+
"do_sample": True,
|
205 |
+
"repetition_penalty": 1.05
|
206 |
+
}
|
207 |
+
else:
|
208 |
+
generation_config = {
|
209 |
+
"num_beams": 3,
|
210 |
+
"repetition_penalty": 1.2,
|
211 |
+
}
|
212 |
+
|
213 |
+
if min_new_tokens > 0:
|
214 |
+
generation_config['min_new_tokens'] = min_new_tokens
|
215 |
+
|
216 |
+
generation_config.update(
|
217 |
+
(k, kwargs[k]) for k in generation_config.keys() & kwargs.keys()
|
218 |
+
)
|
219 |
+
|
220 |
+
inputs.pop("image_sizes")
|
221 |
+
with torch.inference_mode():
|
222 |
+
res = self.generate(
|
223 |
+
**inputs,
|
224 |
+
tokenizer=tokenizer,
|
225 |
+
max_new_tokens=max_new_tokens,
|
226 |
+
vision_hidden_states=vision_hidden_states,
|
227 |
+
stream=stream,
|
228 |
+
decode_text=True,
|
229 |
+
**generation_config
|
230 |
+
)
|
231 |
+
|
232 |
+
if stream:
|
233 |
+
def stream_gen():
|
234 |
+
for text in res:
|
235 |
+
for term in self.terminators:
|
236 |
+
text = text.replace(term, '')
|
237 |
+
yield text
|
238 |
+
return stream_gen()
|
239 |
+
|
240 |
+
else:
|
241 |
+
if batched:
|
242 |
+
answer = res
|
243 |
+
else:
|
244 |
+
answer = res[0]
|
245 |
+
return answer
|
246 |
+
|
processing_mplugowl3.py
ADDED
@@ -0,0 +1,372 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2024 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 |
+
"""
|
16 |
+
Processor class for mPLUGOwl3.
|
17 |
+
"""
|
18 |
+
|
19 |
+
from typing import List, Optional, Union, Dict, Any
|
20 |
+
import warnings
|
21 |
+
import torch
|
22 |
+
import re
|
23 |
+
|
24 |
+
from transformers.image_processing_utils import BatchFeature
|
25 |
+
from transformers.image_utils import ImageInput
|
26 |
+
from transformers.processing_utils import ProcessorMixin
|
27 |
+
from transformers.tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
|
28 |
+
from transformers.utils import TensorType, requires_backends, is_torch_dtype, is_torch_device
|
29 |
+
|
30 |
+
from .image_processing_mplugowl3 import mPLUGOwl3BatchFeature, mPLUGOwl3ImageProcessor
|
31 |
+
|
32 |
+
OWL_MEDIA_TOKEN=['<|image|>']
|
33 |
+
|
34 |
+
class MediaIndicesHelper():
|
35 |
+
def __init__(self, tokenizer) -> None:
|
36 |
+
self.media_position = []
|
37 |
+
self.tokenizer = tokenizer
|
38 |
+
|
39 |
+
|
40 |
+
def has_media(self, text, media_tokens=None):
|
41 |
+
if media_tokens is None:
|
42 |
+
media_tokens = OWL_MEDIA_TOKEN
|
43 |
+
has_media_flag = any([media_token == text for media_token in media_tokens])
|
44 |
+
if any([media_token in text for media_token in media_tokens]):
|
45 |
+
# 不允许出现text中包含media token但是不仅仅是media token。 media token必须单独为一个chunk
|
46 |
+
assert has_media_flag, text
|
47 |
+
return has_media_flag
|
48 |
+
|
49 |
+
def add_media(self, text_chunk, text=None, tokenize_fn=None):
|
50 |
+
|
51 |
+
# cross
|
52 |
+
assert tokenize_fn is not None
|
53 |
+
assert text is not None
|
54 |
+
assert text in OWL_MEDIA_TOKEN
|
55 |
+
media_token_ids = tokenize_fn(text)
|
56 |
+
start = len(text_chunk)
|
57 |
+
end = start + len(media_token_ids)
|
58 |
+
self.media_position.append([start, end])
|
59 |
+
text_chunk.extend(media_token_ids)
|
60 |
+
return len(media_token_ids)
|
61 |
+
|
62 |
+
def cal_media_offset(self, input_ids):
|
63 |
+
if len(self.media_position) == 0:
|
64 |
+
return torch.ones_like(input_ids)*(-1000000)
|
65 |
+
|
66 |
+
media_starts = torch.tensor([_[0] for _ in self.media_position]).reshape(1,-1)
|
67 |
+
rng = torch.arange(input_ids.shape[0]).reshape(-1,1)
|
68 |
+
matrix = (rng > media_starts).sum(dim=1)
|
69 |
+
|
70 |
+
return matrix
|
71 |
+
|
72 |
+
def len_images(self,):
|
73 |
+
return len(self.media_position)
|
74 |
+
|
75 |
+
class mPLUGOwl3Processor(ProcessorMixin):
|
76 |
+
r"""
|
77 |
+
Args:
|
78 |
+
image_processor ([`mPLUGOwl3ImageProcessor`], *optional*):
|
79 |
+
The image processor is a required input.
|
80 |
+
tokenizer ([`LlamaTokenizerWrapper`], *optional*):
|
81 |
+
The tokenizer is a required input.
|
82 |
+
"""
|
83 |
+
attributes = ["image_processor", "tokenizer"]
|
84 |
+
image_processor_class = "AutoImageProcessor"
|
85 |
+
tokenizer_class = "AutoTokenizer"
|
86 |
+
|
87 |
+
def __init__(self, image_processor: mPLUGOwl3ImageProcessor = None, tokenizer=None, prompt_style='chatml', inference_mode=True, addition_eod="<|endoftext|>"):
|
88 |
+
super().__init__(image_processor, tokenizer)
|
89 |
+
self.image_processor: mPLUGOwl3ImageProcessor
|
90 |
+
self.prompt_style = prompt_style
|
91 |
+
self.inference_mode = inference_mode
|
92 |
+
self.media_tokens = ["<|image|>"]
|
93 |
+
self.addition_eod = addition_eod
|
94 |
+
|
95 |
+
def build_text_qwen(self, messages):
|
96 |
+
# role should be within ['system', 'user', 'assistant']
|
97 |
+
im_start, im_end = '<|im_start|>', '<|im_end|>'
|
98 |
+
|
99 |
+
text = []
|
100 |
+
for num_turn, message in enumerate(messages):
|
101 |
+
if num_turn == 0 and message['role'] != 'system':
|
102 |
+
if self.prompt_style != 'plain':
|
103 |
+
text.append({
|
104 |
+
"text": f"{im_start}system\n{im_end}",
|
105 |
+
"label": 0
|
106 |
+
})
|
107 |
+
if message['role'] == 'system':
|
108 |
+
if self.prompt_style != 'plain':
|
109 |
+
text.append({
|
110 |
+
"text": f"{im_start}system\n{message['content']}{im_end}",
|
111 |
+
"label": 0
|
112 |
+
})
|
113 |
+
elif message['role'] == 'user':
|
114 |
+
if self.prompt_style != 'plain':
|
115 |
+
content = f"\n{im_start}user\n{message['content']}{im_end}"
|
116 |
+
else:
|
117 |
+
content = message['content']
|
118 |
+
pattern = '|'.join(map(re.escape, self.media_tokens))
|
119 |
+
chunk_strs = re.split(f'({pattern})', content)
|
120 |
+
for chunk_str in chunk_strs:
|
121 |
+
text.append({
|
122 |
+
"text": chunk_str,
|
123 |
+
"label": 0
|
124 |
+
})
|
125 |
+
|
126 |
+
elif message['role'] == 'assistant':
|
127 |
+
if self.prompt_style != 'plain':
|
128 |
+
text.append({"text": f"\n{im_start}assistant\n", "label": 0})
|
129 |
+
text.append({"text": f"{message['content']}{im_end}", "label": 1})
|
130 |
+
else:
|
131 |
+
text.append({"text": f"{message['content']}", "label": 1})
|
132 |
+
text.append({"text": self.addition_eod, "label": 1})
|
133 |
+
else:
|
134 |
+
raise NotImplementedError
|
135 |
+
if self.inference_mode:
|
136 |
+
while text and text[-1]['label']==1: # 只要列表非空且最后一个元素满足条件
|
137 |
+
text.pop() # 就移除最后一个元素
|
138 |
+
return text
|
139 |
+
|
140 |
+
def wrapped_tokenize(self, text):
|
141 |
+
return self.tokenizer(text).input_ids
|
142 |
+
|
143 |
+
def encode_text_sft(self, texts):
|
144 |
+
# output enc_chunk
|
145 |
+
|
146 |
+
enc_chunk = []
|
147 |
+
label_chunk = []
|
148 |
+
enc_length = 0
|
149 |
+
|
150 |
+
num_images = 0
|
151 |
+
|
152 |
+
media_helper = MediaIndicesHelper(tokenizer=self.tokenizer)
|
153 |
+
for current_ti, text_chunk in enumerate(texts):
|
154 |
+
|
155 |
+
text = text_chunk["text"]
|
156 |
+
label = text_chunk["label"]
|
157 |
+
|
158 |
+
if not media_helper.has_media(text):
|
159 |
+
curr_chunk=self.wrapped_tokenize(text)
|
160 |
+
if label == 1:
|
161 |
+
enc_length += len(curr_chunk)
|
162 |
+
enc_chunk += curr_chunk
|
163 |
+
label_chunk += [label] * len(curr_chunk)
|
164 |
+
else:
|
165 |
+
|
166 |
+
enc_length += len(curr_chunk)
|
167 |
+
enc_chunk += curr_chunk
|
168 |
+
label_chunk += [label] * len(curr_chunk)
|
169 |
+
# For media tokens
|
170 |
+
else:
|
171 |
+
|
172 |
+
add_length = media_helper.add_media(
|
173 |
+
enc_chunk,
|
174 |
+
text=text,
|
175 |
+
tokenize_fn=self.wrapped_tokenize)
|
176 |
+
enc_length += add_length
|
177 |
+
label_chunk += [label] * add_length
|
178 |
+
# enc_chunk.extend([self.media_tokens[text]] * self.media_lengths[text])
|
179 |
+
# enc_length += self.media_lengths[text]
|
180 |
+
# label_chunk += [label] * self.media_lengths[text]
|
181 |
+
num_images += 1
|
182 |
+
|
183 |
+
enc_chunk = torch.tensor(enc_chunk).long()
|
184 |
+
media_offset = []
|
185 |
+
media_before = 0
|
186 |
+
for i,_ in enumerate([media_helper]):
|
187 |
+
mo = _.cal_media_offset(enc_chunk)
|
188 |
+
media_offset.append(torch.cat([(torch.ones(mo.shape[0],1)*media_before).long().to(mo.device), (mo+media_before).unsqueeze(1)], dim=1)) # L 2
|
189 |
+
|
190 |
+
media_before += _.len_images()
|
191 |
+
media_offset = torch.stack(media_offset, dim=0)
|
192 |
+
return {
|
193 |
+
'input_ids': enc_chunk.unsqueeze(0),
|
194 |
+
'media_offset': media_offset,
|
195 |
+
}
|
196 |
+
|
197 |
+
|
198 |
+
def __call__(
|
199 |
+
self,
|
200 |
+
messages,
|
201 |
+
images: ImageInput = None,
|
202 |
+
videos = None,
|
203 |
+
max_length: Optional[int] = None,
|
204 |
+
cut_enable=True,
|
205 |
+
return_tensors: Optional[Union[str, TensorType]] = TensorType.PYTORCH,
|
206 |
+
**kwargs
|
207 |
+
) -> mPLUGOwl3BatchFeature:
|
208 |
+
if videos is not None and len(videos)>0:
|
209 |
+
cut_enable=False
|
210 |
+
assert images is None or len(images)==0, "We do not support image video interleaved yet"
|
211 |
+
video_ptr = 0
|
212 |
+
for message in messages:
|
213 |
+
text_list = message['content'].split('<|video|>')
|
214 |
+
text = text_list[0]
|
215 |
+
for next_text in text_list[1:]:
|
216 |
+
text += '<|image|>'*len(videos[video_ptr])
|
217 |
+
text += next_text
|
218 |
+
video_ptr += 1
|
219 |
+
message['content'] = text
|
220 |
+
images = [frame for video in videos for frame in video ]
|
221 |
+
self.check_media(images, messages)
|
222 |
+
if images is not None:
|
223 |
+
image_inputs = self.image_processor(images, cut_enable=cut_enable, return_tensors=return_tensors)
|
224 |
+
|
225 |
+
if image_inputs.get('cut_shape',None) is not None:
|
226 |
+
cut_shape = image_inputs['cut_shape']
|
227 |
+
image_token_ptr = 0
|
228 |
+
for message in messages:
|
229 |
+
text_list = message['content'].split('<|image|>')
|
230 |
+
text = text_list[0]
|
231 |
+
for next_text in text_list[1:]:
|
232 |
+
text += self.image_processor.cut_prompt_template(img_token='<|image|>', h=cut_shape[image_token_ptr][0], w=cut_shape[image_token_ptr][1])
|
233 |
+
text += next_text
|
234 |
+
image_token_ptr += 1
|
235 |
+
message['content'] = text
|
236 |
+
|
237 |
+
|
238 |
+
# text = ''.join([_['text'] for _ in text])
|
239 |
+
text = self.build_text_qwen(messages)
|
240 |
+
model_inputs = self.encode_text_sft(text)
|
241 |
+
|
242 |
+
if images is not None:
|
243 |
+
model_inputs.update(image_inputs.data)
|
244 |
+
if 'cut_shape' in model_inputs:
|
245 |
+
model_inputs.pop('cut_shape')
|
246 |
+
if 'cut_shape_indices' in model_inputs:
|
247 |
+
model_inputs.pop('cut_shape_indices')
|
248 |
+
return mPLUGOwl3BatchFeature(model_inputs)
|
249 |
+
|
250 |
+
def check_media(self, images, messages):
|
251 |
+
media_num = 0 if images is None else len(images)
|
252 |
+
media_count = sum([message['content'].count('<|image|>') for message in messages])
|
253 |
+
assert media_num == media_count
|
254 |
+
|
255 |
+
|
256 |
+
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Llama
|
257 |
+
def batch_decode(self, *args, **kwargs):
|
258 |
+
"""
|
259 |
+
This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
|
260 |
+
refer to the docstring of this method for more information.
|
261 |
+
"""
|
262 |
+
output_ids = args[0]
|
263 |
+
result_text = []
|
264 |
+
for result in output_ids:
|
265 |
+
result = result[result != 0]
|
266 |
+
if result[0] == self.tokenizer.bos_id:
|
267 |
+
result = result[1:]
|
268 |
+
if result[-1] == self.tokenizer.eos_id:
|
269 |
+
result = result[:-1]
|
270 |
+
result_text.append(self.tokenizer.decode(result, *args[1:], **kwargs).strip())
|
271 |
+
return result_text
|
272 |
+
# return self.tokenizer.batch_decode(*args, **kwargs)
|
273 |
+
|
274 |
+
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Llama
|
275 |
+
def decode(self, *args, **kwargs):
|
276 |
+
"""
|
277 |
+
This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
|
278 |
+
the docstring of this method for more information.
|
279 |
+
"""
|
280 |
+
result = args[0]
|
281 |
+
result = result[result != 0]
|
282 |
+
if result[0] == self.tokenizer.bos_id:
|
283 |
+
result = result[1:]
|
284 |
+
if result[-1] == self.tokenizer.eos_id or (hasattr(self.tokenizer, "eot_id") and result[-1] == self.tokenizer.eot_id):
|
285 |
+
result = result[:-1]
|
286 |
+
return self.tokenizer.decode(result, *args[1:], **kwargs).strip()
|
287 |
+
|
288 |
+
def _convert(
|
289 |
+
self, input_str, max_inp_length: Optional[int] = None
|
290 |
+
):
|
291 |
+
if self.version > 2.5 or not getattr(self.tokenizer, "add_bos_token", False):
|
292 |
+
input_ids = self.tokenizer.encode(input_str)
|
293 |
+
else:
|
294 |
+
input_ids = [self.tokenizer.bos_id] + self.tokenizer.encode(input_str)
|
295 |
+
if max_inp_length is not None:
|
296 |
+
input_ids = input_ids[:max_inp_length]
|
297 |
+
input_ids = torch.tensor(input_ids, dtype=torch.int32)
|
298 |
+
|
299 |
+
start_cond = (input_ids == self.tokenizer.im_start_id) | (input_ids == self.tokenizer.slice_start_id)
|
300 |
+
end_cond = (input_ids == self.tokenizer.im_end_id) | (input_ids == self.tokenizer.slice_end_id)
|
301 |
+
|
302 |
+
image_start_tokens = torch.where(start_cond)[0]
|
303 |
+
image_start_tokens += 1
|
304 |
+
image_end_tokens = torch.where(end_cond)[0]
|
305 |
+
|
306 |
+
valid_image_nums = max(len(image_start_tokens), len(image_end_tokens))
|
307 |
+
|
308 |
+
image_bounds = torch.hstack(
|
309 |
+
[
|
310 |
+
image_start_tokens[:valid_image_nums].unsqueeze(-1),
|
311 |
+
image_end_tokens[:valid_image_nums].unsqueeze(-1),
|
312 |
+
]
|
313 |
+
)
|
314 |
+
return input_ids, image_bounds
|
315 |
+
|
316 |
+
|
317 |
+
@property
|
318 |
+
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names
|
319 |
+
def model_input_names(self):
|
320 |
+
tokenizer_input_names = self.tokenizer.model_input_names
|
321 |
+
image_processor_input_names = self.image_processor.model_input_names
|
322 |
+
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
|
323 |
+
|
324 |
+
|
325 |
+
def pad(self, inputs, max_length=None, padding_value=0, padding_side="left"):
|
326 |
+
items = []
|
327 |
+
if isinstance(inputs[0], list):
|
328 |
+
assert isinstance(inputs[0][0], torch.Tensor)
|
329 |
+
for it in inputs:
|
330 |
+
for tr in it:
|
331 |
+
items.append(tr)
|
332 |
+
else:
|
333 |
+
assert isinstance(inputs[0], torch.Tensor)
|
334 |
+
items = inputs
|
335 |
+
|
336 |
+
batch_size = len(items)
|
337 |
+
shape = items[0].shape
|
338 |
+
dim = len(shape)
|
339 |
+
assert dim <= 2
|
340 |
+
if max_length is None:
|
341 |
+
max_length = 0
|
342 |
+
max_length = max(max_length, max(item.shape[-1] for item in items))
|
343 |
+
min_length = min(item.shape[-1] for item in items)
|
344 |
+
dtype = items[0].dtype
|
345 |
+
|
346 |
+
if dim == 0:
|
347 |
+
return torch.stack([item for item in items], dim=0), [0]
|
348 |
+
elif dim == 1:
|
349 |
+
if max_length == min_length:
|
350 |
+
return torch.stack([item for item in items], dim=0), [0] * batch_size
|
351 |
+
tensor = torch.zeros((batch_size, max_length), dtype=dtype) + padding_value
|
352 |
+
else:
|
353 |
+
tensor = (
|
354 |
+
torch.zeros((batch_size, max_length, shape[-1]), dtype=dtype)
|
355 |
+
+ padding_value
|
356 |
+
)
|
357 |
+
|
358 |
+
padding_length = []
|
359 |
+
for i, item in enumerate(items):
|
360 |
+
if dim == 1:
|
361 |
+
if padding_side == "left":
|
362 |
+
tensor[i, -len(item) :] = item.clone()
|
363 |
+
else:
|
364 |
+
tensor[i, : len(item)] = item.clone()
|
365 |
+
elif dim == 2:
|
366 |
+
if padding_side == "left":
|
367 |
+
tensor[i, -len(item) :, :] = item.clone()
|
368 |
+
else:
|
369 |
+
tensor[i, : len(item), :] = item.clone()
|
370 |
+
padding_length.append(tensor.shape[-1] - len(item))
|
371 |
+
|
372 |
+
return tensor, padding_length
|
sdpa.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from torch import nn
|
2 |
+
from icecream import ic
|
3 |
+
from einops import rearrange
|
4 |
+
|
5 |
+
class ScaleDotProductAttention(nn.Module):
|
6 |
+
|
7 |
+
def __init__(self, layer_number, causal=False, softmax_scale=None, attention_dropout=0.0):
|
8 |
+
super().__init__()
|
9 |
+
self.layer_number = layer_number
|
10 |
+
self.causal = causal
|
11 |
+
self.softmax_scale = softmax_scale
|
12 |
+
self.dropout_p = attention_dropout
|
13 |
+
|
14 |
+
# Qwen 不需要scale
|
15 |
+
|
16 |
+
def forward(self, q, k, v, attn_mask=None, order='sbhd'):
|
17 |
+
"""Implements the multihead softmax attention.
|
18 |
+
Arguments
|
19 |
+
---------
|
20 |
+
q, k, v: The tensor containing the query, key, and value. (B, S, H, D)
|
21 |
+
"""
|
22 |
+
# (N,...,L,E)
|
23 |
+
import torch
|
24 |
+
import torch.nn as nn
|
25 |
+
import torch.nn.functional as F
|
26 |
+
if order == 'sbhd':
|
27 |
+
q, k, v = [rearrange(x, 's b h d -> b h s d').contiguous()
|
28 |
+
for x in (q, k, v)]
|
29 |
+
elif order == 'bhsd':
|
30 |
+
pass
|
31 |
+
|
32 |
+
if attn_mask is not None:
|
33 |
+
attn_mask = (~attn_mask.clone().bool()).contiguous()
|
34 |
+
else:
|
35 |
+
attn_mask = None
|
36 |
+
# attention mask, True means it will take part in attention B H s_q s_k
|
37 |
+
if self.training:
|
38 |
+
# during training q,k,v always have same seqlen
|
39 |
+
if self.causal:
|
40 |
+
assert q.shape[-2] == k.shape[-2]
|
41 |
+
is_causal = self.causal
|
42 |
+
dropout_p = self.dropout_p
|
43 |
+
else:
|
44 |
+
# turn off FA causal mask after first inference autoregressive iteration
|
45 |
+
# only on first autoregressive step q,k,v have same seqlen
|
46 |
+
if self.causal:
|
47 |
+
is_causal = q.shape[-2] == k.shape[-2]
|
48 |
+
else:
|
49 |
+
is_causal = self.causal
|
50 |
+
dropout_p = 0.0
|
51 |
+
|
52 |
+
# 如果is_causal则无视输入的mask 反之会使用输入的mask
|
53 |
+
o = F.scaled_dot_product_attention(q, k, v,
|
54 |
+
attn_mask=attn_mask,
|
55 |
+
dropout_p=dropout_p,
|
56 |
+
is_causal=is_causal,
|
57 |
+
scale=self.softmax_scale
|
58 |
+
)
|
59 |
+
# B Head L D -> L B (Head D)
|
60 |
+
o = rearrange(o, 'B Head L D -> L B (Head D)').contiguous()
|
61 |
+
return o
|
tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
tokenizer_config.json
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_prefix_space": false,
|
3 |
+
"added_tokens_decoder": {
|
4 |
+
"151643": {
|
5 |
+
"content": "<|endoftext|>",
|
6 |
+
"lstrip": false,
|
7 |
+
"normalized": false,
|
8 |
+
"rstrip": false,
|
9 |
+
"single_word": false,
|
10 |
+
"special": true
|
11 |
+
},
|
12 |
+
"151644": {
|
13 |
+
"content": "<|im_start|>",
|
14 |
+
"lstrip": false,
|
15 |
+
"normalized": false,
|
16 |
+
"rstrip": false,
|
17 |
+
"single_word": false,
|
18 |
+
"special": true
|
19 |
+
},
|
20 |
+
"151645": {
|
21 |
+
"content": "<|im_end|>",
|
22 |
+
"lstrip": false,
|
23 |
+
"normalized": false,
|
24 |
+
"rstrip": false,
|
25 |
+
"single_word": false,
|
26 |
+
"special": true
|
27 |
+
}
|
28 |
+
},
|
29 |
+
"additional_special_tokens": ["<|im_start|>", "<|im_end|>"],
|
30 |
+
"bos_token": null,
|
31 |
+
"chat_template": "{% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n' }}{% endif %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
|
32 |
+
"clean_up_tokenization_spaces": false,
|
33 |
+
"eos_token": "<|im_end|>",
|
34 |
+
"errors": "replace",
|
35 |
+
"model_max_length": 131072,
|
36 |
+
"pad_token": "<|endoftext|>",
|
37 |
+
"split_special_tokens": false,
|
38 |
+
"tokenizer_class": "Qwen2Tokenizer",
|
39 |
+
"unk_token": null
|
40 |
+
}
|
vocab.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
x_sdpa.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from torch import nn
|
2 |
+
from icecream import ic
|
3 |
+
from einops import rearrange
|
4 |
+
|
5 |
+
class ScaleDotProductAttention(nn.Module):
|
6 |
+
|
7 |
+
def __init__(self, layer_number, causal=False, softmax_scale=None, attention_dropout=0.0):
|
8 |
+
super().__init__()
|
9 |
+
self.layer_number = layer_number
|
10 |
+
self.causal = causal
|
11 |
+
self.softmax_scale = softmax_scale
|
12 |
+
self.dropout_p = attention_dropout
|
13 |
+
|
14 |
+
# Qwen 不需要scale
|
15 |
+
|
16 |
+
def forward(self, q, k, v, attn_mask=None, order='sbhd'):
|
17 |
+
"""Implements the multihead softmax attention.
|
18 |
+
Arguments
|
19 |
+
---------
|
20 |
+
q, k, v: The tensor containing the query, key, and value. (B, S, H, D)
|
21 |
+
"""
|
22 |
+
# (N,...,L,E)
|
23 |
+
import torch
|
24 |
+
import torch.nn as nn
|
25 |
+
import torch.nn.functional as F
|
26 |
+
if order == 'sbhd':
|
27 |
+
q, k, v = [rearrange(x, 's b h d -> b h s d').contiguous()
|
28 |
+
for x in (q, k, v)]
|
29 |
+
elif order == 'bhsd':
|
30 |
+
pass
|
31 |
+
|
32 |
+
if attn_mask is not None:
|
33 |
+
attn_mask = (~attn_mask.clone().bool()).contiguous()
|
34 |
+
else:
|
35 |
+
attn_mask = None
|
36 |
+
# attention mask, True means it will take part in attention B H s_q s_k
|
37 |
+
if self.training:
|
38 |
+
# during training q,k,v always have same seqlen
|
39 |
+
if self.causal:
|
40 |
+
assert q.shape[-2] == k.shape[-2]
|
41 |
+
is_causal = self.causal
|
42 |
+
dropout_p = self.dropout_p
|
43 |
+
else:
|
44 |
+
# turn off FA causal mask after first inference autoregressive iteration
|
45 |
+
# only on first autoregressive step q,k,v have same seqlen
|
46 |
+
if self.causal:
|
47 |
+
is_causal = q.shape[-2] == k.shape[-2]
|
48 |
+
else:
|
49 |
+
is_causal = self.causal
|
50 |
+
dropout_p = 0.0
|
51 |
+
|
52 |
+
# 如果is_causal则无视输入的mask 反之会使用输入的mask
|
53 |
+
o = F.scaled_dot_product_attention(q, k, v,
|
54 |
+
attn_mask=attn_mask,
|
55 |
+
dropout_p=dropout_p,
|
56 |
+
is_causal=is_causal,
|
57 |
+
scale=self.softmax_scale
|
58 |
+
)
|
59 |
+
# B Head L D -> L B (Head D)
|
60 |
+
o = rearrange(o, 'B Head L D -> L B (Head D)').contiguous()
|
61 |
+
return o
|