Mizukiluke commited on
Commit
b51625d
1 Parent(s): 605b727

Upload 16 files

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