YuanLiuuuuuu commited on
Commit
e28b279
1 Parent(s): fcb41df

Add files using upload-large-folder tool

Browse files
catty.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import List, Tuple
3
+
4
+ from PIL import Image
5
+
6
+ from .dynamic_high_resolution import factorize_number
7
+
8
+
9
+ def construct_mapping_dict(max_splits: int = 12) -> dict:
10
+ """Construct a mapping dictionary for the given max_splits.
11
+
12
+ Args:
13
+ max_splits (int, optional): The maximum number of splits.
14
+ Defaults to 12.
15
+
16
+ Returns:
17
+ dict: A mapping dictionary for the given max_splits.
18
+ """
19
+ mapping_dict = {}
20
+ for i in range(1, max_splits + 1):
21
+ factor_list = factorize_number(i)
22
+ for factor in factor_list:
23
+ ratio = factor[0] / factor[1]
24
+ if ratio not in mapping_dict:
25
+ mapping_dict[ratio] = [factor]
26
+ else:
27
+ mapping_dict[ratio].append(factor)
28
+ return mapping_dict
29
+
30
+
31
+ def save_image_list(image_list: List[Image.Image], save_folder: str) -> None:
32
+ """Save a list of images to a folder.
33
+
34
+ Args:
35
+ image_list (List[Image.Image]): A list of images.
36
+ save_folder (str): The folder to save the images to.
37
+ """
38
+ os.makedirs(save_folder, exist_ok=True)
39
+ for i, image in enumerate(image_list):
40
+ image.save(os.path.join(save_folder, f'{i}.png'))
41
+
42
+
43
+ def resize_to_best_size(image: Image.Image, best_slices: tuple,
44
+ width_slices: int, height_slices: int,
45
+ sub_image_size: int) -> Image.Image:
46
+ """Resize an image to the best size for the given number of slices.
47
+
48
+ Args:
49
+ image (Image.Image): The image to resize.
50
+ best_slices (tuple): The best number of slices for the image.
51
+ width_slices (int): The number of horizontal slices.
52
+ height_slices (int): The number of vertical slices.
53
+ sub_image_size (int): The size of the sub-images.
54
+
55
+ Returns:
56
+ Image.Image: The resized image.
57
+ """
58
+ width, height = image.size
59
+ best_width_slices, best_height_slices = best_slices
60
+ if width_slices < height_slices:
61
+ new_image_width = best_width_slices * sub_image_size
62
+ new_image_height = int(height / width * new_image_width)
63
+ else:
64
+ new_image_height = best_height_slices * sub_image_size
65
+ new_image_width = int(width / height * new_image_height)
66
+ new_image = image.resize((new_image_width, new_image_height), resample=2)
67
+ return new_image
68
+
69
+
70
+ def compute_strides(height: int, width: int, sub_image_size: int,
71
+ slices: Tuple[int, int]) -> Tuple[int, int]:
72
+ """Compute the strides for the given image size and slices.
73
+
74
+ Args:
75
+ height (int): The height of the image.
76
+ width (int): The width of the image.
77
+ sub_image_size (int): The size of the sub-images.
78
+ slices (Tuple[int, int]): The number of horizontal and vertical slices.
79
+
80
+ Returns:
81
+ Tuple[int, int]: The strides for the given image size and slices.
82
+ """
83
+ slice_width, slice_height = slices
84
+ if slice_width > 1:
85
+ stride_x = (width - sub_image_size) // (slice_width - 1)
86
+ else:
87
+ stride_x = 0
88
+ if slice_height > 1:
89
+ stride_y = (height - sub_image_size) // (slice_height - 1)
90
+ else:
91
+ stride_y = 0
92
+ return stride_x, stride_y
93
+
94
+
95
+ def sliding_window_crop(image: Image.Image, window_size: int,
96
+ slices: Tuple[int, int]) -> List[Image.Image]:
97
+ """Crop an image into sub-images using a sliding window.
98
+
99
+ Args:
100
+ image (Image.Image): The image to crop.
101
+ window_size (int): The size of the sub-images.
102
+ slices (Tuple[int, int]): The number of horizontal and vertical slices.
103
+
104
+ Returns:
105
+ List[Image]: A list of cropped images.
106
+ """
107
+ width, height = image.size
108
+ stride_x, stride_y = compute_strides(height, width, window_size, slices)
109
+ sub_images = []
110
+ if stride_x == 0:
111
+ stride_x = window_size
112
+
113
+ if stride_y == 0:
114
+ stride_y = window_size
115
+ for y in range(0, height - window_size + 1, stride_y):
116
+ for x in range(0, width - window_size + 1, stride_x):
117
+ sub_image = image.crop((x, y, x + window_size, y + window_size))
118
+ sub_images.append(sub_image)
119
+ return sub_images
120
+
121
+
122
+ def find_best_slices(width_slices: int,
123
+ height_slices: int,
124
+ aspect_ratio: float,
125
+ max_splits: int = 12) -> list:
126
+ """Find the best slices for the given image size and aspect ratio.
127
+
128
+ Args:
129
+ width_slices (int): The number of horizontal slices.
130
+ height_slices (int): The number of vertical slices.
131
+ aspect_ratio (float): The aspect ratio of the image.
132
+ max_splits (int, optional): The maximum number of splits.
133
+ Defaults to 12.
134
+
135
+ Returns:
136
+ list: the best slices for the given image.
137
+ """
138
+ mapping_dict = construct_mapping_dict(max_splits)
139
+ if aspect_ratio < 1:
140
+ mapping_dict = {
141
+ k: v
142
+ for k, v in mapping_dict.items() if k <= aspect_ratio
143
+ }
144
+ elif aspect_ratio > 1:
145
+ mapping_dict = {
146
+ k: v
147
+ for k, v in mapping_dict.items() if k >= aspect_ratio
148
+ }
149
+ # find the value which key is the closest to the ratio
150
+ best_ratio = min(mapping_dict.keys(), key=lambda x: abs(x - aspect_ratio))
151
+ # best_image_sizes is a list of image sizes
152
+ best_image_sizes = mapping_dict[best_ratio]
153
+ # find the image_size whose area is closest to the current image size
154
+ best_slices = min(
155
+ best_image_sizes,
156
+ key=lambda x: abs(x[0] * x[1] - width_slices * height_slices))
157
+ return best_slices
158
+
159
+
160
+ def split_image_with_catty(pil_image: Image.Image,
161
+ image_size: int = 336,
162
+ max_crop_slices: int = 8,
163
+ save_folder: str = None,
164
+ add_thumbnail: bool = True,
165
+ do_resize: bool = False,
166
+ **kwargs) -> List[Image.Image]:
167
+ """Split an image into sub-images using Catty.
168
+
169
+ Args:
170
+ pil_image (Image.Image): The image to split.
171
+ image_size (int, optional): The size of the image.
172
+ Defaults to 336.
173
+ max_crop_slices (int, optional): The maximum number of slices.
174
+ Defaults to 8.
175
+ save_folder (str, optional): The folder to save the sub-images.
176
+ Defaults to None.
177
+ add_thumbnail (bool, optional): Whether to add a thumbnail.
178
+ Defaults to False.
179
+ do_resize (bool, optional): Whether to resize the image to fit the
180
+ maximum number of slices. Defaults to False.
181
+
182
+ Returns:
183
+ List[Image.Image]: A list of cropped images.
184
+ """
185
+ width, height = pil_image.size
186
+ ratio = width / height
187
+ if ratio > max_crop_slices or ratio < 1 / max_crop_slices:
188
+ if do_resize:
189
+ print(
190
+ f'Resizing image to fit maximum number of slices ({max_crop_slices})' # noqa
191
+ ) # noqa
192
+ if width > height:
193
+ new_width = max_crop_slices * height
194
+ new_height = height
195
+ else:
196
+ new_width = width
197
+ new_height = max_crop_slices * width
198
+ pil_image = pil_image.resize((new_width, new_height), resample=2)
199
+ width, height = pil_image.size
200
+ ratio = width / height
201
+ else:
202
+ print(
203
+ f'Image aspect ratio ({ratio:.2f}) is out of range: ({1/max_crop_slices:.2f}, {max_crop_slices:.2f})' # noqa
204
+ )
205
+ return None, None
206
+ width_slices = width / image_size
207
+ height_slices = height / image_size
208
+ best_slices = find_best_slices(width_slices, height_slices, ratio,
209
+ max_crop_slices)
210
+ pil_image = resize_to_best_size(pil_image, best_slices, width_slices,
211
+ height_slices, image_size)
212
+ width, height = pil_image.size
213
+ sub_images = sliding_window_crop(pil_image, image_size, best_slices)
214
+ if add_thumbnail:
215
+ thumbnail_image = pil_image.resize((image_size, image_size),
216
+ resample=2)
217
+ sub_images.append(thumbnail_image)
218
+ # save split images to folder for debugging
219
+ if save_folder is not None:
220
+ save_image_list(sub_images, save_folder)
221
+ return sub_images
config.json ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_commit_hash": null,
3
+ "_name_or_path": "/mnt/cephfs/bensenliu/wfs/weights/mm/mmq-llava-20240826e1-sft-points-hf",
4
+ "architectures": [
5
+ "POINTSChatModel"
6
+ ],
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_points_chat.POINTSChatConfig",
9
+ "AutoModelForCausalLM": "modeling_points_chat.POINTSChatModel"
10
+ },
11
+ "llm_config": {
12
+ "_name_or_path": "",
13
+ "add_cross_attention": false,
14
+ "architectures": null,
15
+ "auto_map": {
16
+ "AutoConfig": "configuration_llama.CustomLlamaConfig",
17
+ "AutoModelForCausalLM": "modeling_llama.CustomLlamaForCausalLM"
18
+ },
19
+ "bad_words_ids": null,
20
+ "begin_suppress_tokens": null,
21
+ "bos_token_id": 0,
22
+ "chunk_size_feed_forward": 0,
23
+ "cross_attention_hidden_size": null,
24
+ "decoder_start_token_id": null,
25
+ "diversity_penalty": 0.0,
26
+ "do_sample": false,
27
+ "early_stopping": false,
28
+ "encoder_no_repeat_ngram_size": 0,
29
+ "eos_token_id": [
30
+ 2,
31
+ 3
32
+ ],
33
+ "exponential_decay_length_penalty": null,
34
+ "ffn_hidden_size": 11008,
35
+ "finetuning_task": null,
36
+ "forced_bos_token_id": null,
37
+ "forced_eos_token_id": null,
38
+ "hidden_act": "swiglu",
39
+ "hidden_size": 4096,
40
+ "id2label": {
41
+ "0": "LABEL_0",
42
+ "1": "LABEL_1"
43
+ },
44
+ "initializer_range": 0.02,
45
+ "is_decoder": false,
46
+ "is_encoder_decoder": false,
47
+ "label2id": {
48
+ "LABEL_0": 0,
49
+ "LABEL_1": 1
50
+ },
51
+ "layernorm_epsilon": 1e-05,
52
+ "length_penalty": 1.0,
53
+ "max_length": 20,
54
+ "max_position_embeddings": 16384,
55
+ "min_length": 0,
56
+ "mlp_fc1_bias": false,
57
+ "mlp_fc2_bias": false,
58
+ "model_type": "custom_llama",
59
+ "no_repeat_ngram_size": 0,
60
+ "norm_type": "rms_norm",
61
+ "num_attention_heads": 32,
62
+ "num_beam_groups": 1,
63
+ "num_beams": 1,
64
+ "num_hidden_layers": 48,
65
+ "num_kv_heads": 4,
66
+ "num_layers": 48,
67
+ "num_return_sequences": 1,
68
+ "out_proj_bias": false,
69
+ "output_attentions": false,
70
+ "output_hidden_states": false,
71
+ "output_scores": false,
72
+ "pad_token_id": null,
73
+ "prefix": null,
74
+ "problem_type": null,
75
+ "pruned_heads": {},
76
+ "qkv_proj_bias": false,
77
+ "remove_invalid_values": false,
78
+ "repetition_penalty": 1.0,
79
+ "return_dict": true,
80
+ "return_dict_in_generate": false,
81
+ "rotary_compress": 1.0,
82
+ "rotary_emb_base": 5000000.0,
83
+ "rotary_pct": 1.0,
84
+ "sep_token_id": null,
85
+ "share_kv_num_layers": 1,
86
+ "sliding_window_size": -1,
87
+ "sliding_window_type": null,
88
+ "suppress_tokens": null,
89
+ "task_specific_params": null,
90
+ "temperature": 1.0,
91
+ "tf_legacy_loss": false,
92
+ "tie_encoder_decoder": false,
93
+ "tie_word_embeddings": false,
94
+ "tokenizer_class": null,
95
+ "top_k": 50,
96
+ "top_p": 1.0,
97
+ "torch_dtype": null,
98
+ "torchscript": false,
99
+ "transformers_version": "4.44.2",
100
+ "typical_p": 1.0,
101
+ "use_bfloat16": false,
102
+ "use_cache": true,
103
+ "use_gqa": true,
104
+ "vocab_size": 64000
105
+ },
106
+ "torch_dtype": "float32",
107
+ "transformers_version": null,
108
+ "vision_config": {
109
+ "_name_or_path": "/mnt/cephfs/bensenliu/exp_runs/weights/mm/CLIP-L-336/clip-vit-large-patch14-336",
110
+ "add_cross_attention": false,
111
+ "architectures": [
112
+ "CLIPVisionModel"
113
+ ],
114
+ "attention_dropout": 0.0,
115
+ "bad_words_ids": null,
116
+ "begin_suppress_tokens": null,
117
+ "bos_token_id": null,
118
+ "chunk_size_feed_forward": 0,
119
+ "cross_attention_hidden_size": null,
120
+ "decoder_start_token_id": null,
121
+ "diversity_penalty": 0.0,
122
+ "do_sample": false,
123
+ "dropout": 0.0,
124
+ "early_stopping": false,
125
+ "encoder_no_repeat_ngram_size": 0,
126
+ "eos_token_id": null,
127
+ "exponential_decay_length_penalty": null,
128
+ "finetuning_task": null,
129
+ "forced_bos_token_id": null,
130
+ "forced_eos_token_id": null,
131
+ "hidden_act": "quick_gelu",
132
+ "hidden_size": 1024,
133
+ "id2label": {
134
+ "0": "LABEL_0",
135
+ "1": "LABEL_1"
136
+ },
137
+ "image_size": 336,
138
+ "initializer_factor": 1.0,
139
+ "initializer_range": 0.02,
140
+ "intermediate_size": 4096,
141
+ "is_decoder": false,
142
+ "is_encoder_decoder": false,
143
+ "label2id": {
144
+ "LABEL_0": 0,
145
+ "LABEL_1": 1
146
+ },
147
+ "layer_norm_eps": 1e-05,
148
+ "length_penalty": 1.0,
149
+ "max_length": 20,
150
+ "min_length": 0,
151
+ "model_type": "clip_vision_model",
152
+ "no_repeat_ngram_size": 0,
153
+ "num_attention_heads": 16,
154
+ "num_beam_groups": 1,
155
+ "num_beams": 1,
156
+ "num_channels": 3,
157
+ "num_hidden_layers": 24,
158
+ "num_return_sequences": 1,
159
+ "output_attentions": false,
160
+ "output_hidden_states": false,
161
+ "output_scores": false,
162
+ "pad_token_id": null,
163
+ "patch_size": 14,
164
+ "prefix": null,
165
+ "problem_type": null,
166
+ "projection_dim": 768,
167
+ "pruned_heads": {},
168
+ "remove_invalid_values": false,
169
+ "repetition_penalty": 1.0,
170
+ "return_dict": true,
171
+ "return_dict_in_generate": false,
172
+ "sep_token_id": null,
173
+ "suppress_tokens": null,
174
+ "task_specific_params": null,
175
+ "temperature": 1.0,
176
+ "tf_legacy_loss": false,
177
+ "tie_encoder_decoder": false,
178
+ "tie_word_embeddings": true,
179
+ "tokenizer_class": null,
180
+ "top_k": 50,
181
+ "top_p": 1.0,
182
+ "torch_dtype": "float32",
183
+ "torchscript": false,
184
+ "transformers_version": "4.44.2",
185
+ "typical_p": 1.0,
186
+ "use_bfloat16": false
187
+ }
188
+ }
configuration_llama.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Modify the original configuration_llama.py to
2
+ # be compatiable with our training framework.
3
+
4
+
5
+ from transformers.configuration_utils import PretrainedConfig
6
+ from transformers.utils import logging
7
+
8
+ logger = logging.get_logger(__name__)
9
+
10
+
11
+ class CustomLlamaConfig(PretrainedConfig):
12
+ """
13
+ Args:
14
+ vocab_size (`int`, *optional*, defaults to 50432):
15
+ Vocabulary size of the WeLMV3 model. Defines the number of
16
+ different tokens that can be represented by the
17
+ `inputs_ids` passed when calling [`WeLMV3Model`].
18
+ hidden_size (`int`, *optional*, defaults to 6144):
19
+ Dimension of the encoder layers and the pooler layer.
20
+ num_hidden_layers (`int`, *optional*, defaults to 44):
21
+ Number of hidden layers in the Transformer encoder.
22
+ num_attention_heads (`int`, *optional*, defaults to 64):
23
+ Number of attention heads for each attention layer in the
24
+ Transformer encoder.
25
+ num_kv_heads (`int`, *optional*, defaults to 4):
26
+ Number of GQA groups.
27
+ intermediate_size (`int`, *optional*, defaults to 24576):
28
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the
29
+ Transformer encoder.
30
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
31
+ The non-linear activation function (function or string) in the
32
+ encoder and pooler. If string, `"gelu"`,
33
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
34
+ rotary_pct (`float`, *optional*, defaults to 0.25):
35
+ percentage of hidden dimensions to allocate to rotary embeddings
36
+ rotary_emb_base (`int`, *optional*, defaults to 10000)
37
+ base for computing rotary embeddings frequency
38
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
39
+ The maximum sequence length that this model might ever be used
40
+ with. Typically set this to something large just in case
41
+ (e.g., 512 or 1024 or 2048).
42
+ initializer_range (`float`, *optional*, defaults to 1e-5):
43
+ The standard deviation of the truncated_normal_initializer for
44
+ initializing all weight matrices.
45
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
46
+ The epsilon used by the layer normalization layers.
47
+ use_cache (`bool`, *optional*, defaults to `True`):
48
+ Whether or not the model should return the last key/values
49
+ attentions (not used by all models). Only relevant if
50
+ `config.is_decoder=True`.
51
+ """
52
+ model_type = "custom_llama"
53
+
54
+ def __init__(
55
+ self,
56
+ vocab_size=102400,
57
+ hidden_size=2560,
58
+ num_layers=32,
59
+ num_attention_heads=20,
60
+ num_kv_heads=4,
61
+ ffn_hidden_size=2560 * 4,
62
+ hidden_act="swiglu",
63
+ rotary_pct=1.0,
64
+ rotary_emb_base=10000,
65
+ rotary_compress=1.0,
66
+ max_position_embeddings=4096,
67
+ initializer_range=0.02,
68
+ layernorm_epsilon=1e-5,
69
+ use_cache=True,
70
+ bos_token_id=0,
71
+ eos_token_id=2,
72
+ rms_norm=None,
73
+ norm_type='layer_norm',
74
+ qkv_proj_bias=True,
75
+ out_proj_bias=True,
76
+ mlp_fc1_bias=True,
77
+ mlp_fc2_bias=True,
78
+ **kwargs,
79
+ ):
80
+ super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
81
+ self.vocab_size = vocab_size
82
+ self.max_position_embeddings = max_position_embeddings
83
+ self.hidden_size = hidden_size
84
+ self.num_layers = num_layers
85
+ self.num_attention_heads = num_attention_heads
86
+ self.num_kv_heads = num_kv_heads
87
+ self.ffn_hidden_size = ffn_hidden_size
88
+ self.hidden_act = hidden_act
89
+ self.rotary_pct = rotary_pct
90
+ self.rotary_emb_base = rotary_emb_base
91
+ self.rotary_compress = rotary_compress
92
+ self.initializer_range = initializer_range
93
+ self.layernorm_epsilon = layernorm_epsilon
94
+ self.use_cache = use_cache
95
+ if rms_norm is not None:
96
+ self.norm_type = 'rms_norm' if rms_norm else 'layer_norm'
97
+ else:
98
+ self.norm_type = norm_type
99
+ self.qkv_proj_bias = qkv_proj_bias
100
+ self.out_proj_bias = out_proj_bias
101
+ self.mlp_fc1_bias = mlp_fc1_bias
102
+ self.mlp_fc2_bias = mlp_fc2_bias
103
+ self.num_hidden_layers = num_layers
configuration_points_chat.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ from typing import Any, Dict, Union
3
+
4
+ from transformers import CLIPVisionConfig, PretrainedConfig
5
+
6
+ from .configuration_llama import CustomLlamaConfig
7
+
8
+
9
+ class POINTSChatConfig(PretrainedConfig):
10
+ model_type = "points_chat"
11
+ is_composition = True
12
+ """Configuration class for `POINTS`.
13
+
14
+ Args:
15
+ vision_config (Union[dict, CLIPVisionConfig]):
16
+ Configuration of the vision model.
17
+ llm_config (Union[dict, LlamaConfig]):
18
+ Configuration of the language model.
19
+ """
20
+
21
+ def __init__(self,
22
+ vision_config: Union[dict, CLIPVisionConfig],
23
+ llm_config: Union[dict, CustomLlamaConfig],
24
+ **kwargs) -> None:
25
+ super().__init__(**kwargs)
26
+ if isinstance(vision_config, dict):
27
+ self.vision_config = CLIPVisionConfig(**vision_config)
28
+ else:
29
+ self.vision_config = vision_config
30
+ if isinstance(llm_config, dict):
31
+ self.llm_config = CustomLlamaConfig(**llm_config)
32
+ else:
33
+ self.llm_config = llm_config
34
+
35
+ def to_dict(self) -> Dict[str, Any]:
36
+ output = copy.deepcopy(self.__dict__)
37
+ output["vision_config"] = self.vision_config.to_dict()
38
+ output["llm_config"] = self.llm_config.to_dict()
39
+ return output
dynamic_high_resolution.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+
3
+ from PIL import Image
4
+
5
+
6
+ def factorize_number(num: int) -> list:
7
+ """Factorize a number into its prime factors.
8
+
9
+ Args:
10
+ num (int): The number to factorize.
11
+
12
+ Returns:
13
+ list: A list of prime factors of the number.
14
+ """
15
+ factors = []
16
+ for i in range(1, int(num) + 1):
17
+ if num % i == 0:
18
+ factors.append([i, num // i])
19
+ return factors
20
+
21
+
22
+ def construct_mapping_dict(max_splits: int = 8, image_size: int = 336) -> dict:
23
+ """Construct a mapping dictionary for image size reduction.
24
+
25
+ Args:
26
+ max_splits (int, optional): The maximum number of splits for each
27
+ dimension. Defaults to 8.
28
+ image_size (int, optional): The original image size.
29
+ Defaults to 336.
30
+
31
+ Returns:
32
+ dict: A dictionary containing the mapping of image sizes to
33
+ the corresponding factors.
34
+ """
35
+ mapping_dict = {}
36
+ for i in range(1, max_splits + 1):
37
+ factor_list = factorize_number(i)
38
+ for factor in factor_list:
39
+ ratio = factor[0] / factor[1]
40
+ if ratio not in mapping_dict:
41
+ mapping_dict[ratio] = [[
42
+ factor[0] * image_size, factor[1] * image_size
43
+ ]]
44
+ else:
45
+ mapping_dict[ratio].append(
46
+ [factor[0] * image_size, factor[1] * image_size])
47
+ return mapping_dict
48
+
49
+
50
+ def find_best_image_size(cur_image_size: list,
51
+ max_splits: int = 8,
52
+ image_size: int = 336) -> list:
53
+ """Find the best image size for a given image size.
54
+
55
+ Args:
56
+ cur_image_size (list): The current image size.
57
+ max_splits (int, optional): The maximum number of splits for each
58
+ dimension. Defaults to 8.
59
+ image_size (int, optional): The original image size.
60
+ Defaults to 336.
61
+
62
+ Returns:
63
+ list: The best image size for the given image size.
64
+ """
65
+
66
+ mapping_dict = construct_mapping_dict(max_splits, image_size)
67
+ ratio = cur_image_size[0] / cur_image_size[1]
68
+ # find the value which key is the closest to the ratio
69
+ best_ratio = min(mapping_dict.keys(), key=lambda x: abs(x - ratio))
70
+ # best_image_sizes is a list of image sizes
71
+ best_image_sizes = mapping_dict[best_ratio]
72
+ # find the image_size whose area is closest to the current image size
73
+ best_image_size = min(
74
+ best_image_sizes,
75
+ key=lambda x: abs(x[0] * x[1] - cur_image_size[0] * cur_image_size[1]))
76
+ return best_image_size
77
+
78
+
79
+ def split_image(pil_image: Image.Image,
80
+ image_size: int = 336,
81
+ max_splits: int = 8) -> List[Image.Image]:
82
+ """Split an image into sub-image.
83
+
84
+ Similar to that used in InternVL2。
85
+
86
+ Args:
87
+ pil_image (Image.Image): The input image.
88
+ image_size (int, optional): The size of the image.
89
+ Defaults to 336.
90
+ max_splits (int, optional): The maximum number of splits for each
91
+ dimension. Defaults to 8.
92
+
93
+ Returns:
94
+ List[Image.Image]: A list of cropped images.
95
+ """
96
+ whole_sub_image = pil_image.resize((image_size, image_size), resample=2)
97
+ best_size = find_best_image_size(pil_image.size,
98
+ max_splits=max_splits,
99
+ image_size=image_size)
100
+ pil_image = pil_image.resize(best_size, resample=2)
101
+ num_sub_images = ((best_size[0] // image_size),
102
+ (best_size[1] // image_size))
103
+ # crop pil_image to sub_images
104
+ sub_images = []
105
+ for i in range(num_sub_images[1]):
106
+ for j in range(num_sub_images[0]):
107
+ sub_image = pil_image.crop(
108
+ (j * image_size, i * image_size, (j + 1) * image_size,
109
+ (i + 1) * image_size))
110
+ sub_images.append(sub_image)
111
+ sub_images.append(whole_sub_image)
112
+ return sub_images
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.44.2"
4
+ }
model-00001-of-00008.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6fdcbfe7161fec8ca6739668eab580d2fea670c806a359ecc38652ff9ed67ee9
3
+ size 4944846696
model-00002-of-00008.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c13b4cd61173d5c9dac009590af5ff1be0766562e8012e2934b4e302b3166b12
3
+ size 4911765320
model-00003-of-00008.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e2a286172bef94e6f97a06943d001ca39babdf3904dd6f47e4dbfc40534f9ada
3
+ size 4844656384
model-00004-of-00008.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bbd633c04c1210720cd837237bc72674edb687f8ed43ea27c9f75156bbf8e598
3
+ size 4844656400
model-00005-of-00008.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:73bbbcb548f36a373d7ce6de9b1ddf98a64d3f7c424a208dd2df2fb5e766d80f
3
+ size 4844656400
model-00006-of-00008.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:79adc627f384d0529bb53d069127c5c66ed4dcd5a86117e036f8fd5489c0c829
3
+ size 4844656400
model-00007-of-00008.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:87e85202b3e1443b1b82f1f2aef5bb41c19c179891d0c6d149c3483d83c445b9
3
+ size 4844656400
model-00008-of-00008.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2dd82377be059c8ee87d37b15a3eca0e11e05f515d459a8b6f0f9f768e357f49
3
+ size 3800190272
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_llama.py ADDED
@@ -0,0 +1,978 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import partial
2
+ from typing import Optional, Tuple, Union
3
+
4
+ import torch
5
+ import torch.nn.functional as F
6
+ import torch.utils.checkpoint
7
+ from packaging import version
8
+ from torch import nn
9
+ from torch.nn import CrossEntropyLoss
10
+ from transformers.activations import ACT2FN
11
+ from transformers.modeling_outputs import (
12
+ BaseModelOutputWithPast,
13
+ CausalLMOutputWithPast,
14
+ )
15
+ from transformers.modeling_utils import PreTrainedModel
16
+ from transformers.utils import logging
17
+
18
+ from .configuration_llama import CustomLlamaConfig
19
+
20
+ try:
21
+ from apex.megatron_layer_norm import MixedFusedLayerNorm as LayerNorm
22
+ except ImportError:
23
+ from torch.nn import LayerNorm
24
+
25
+ USE_FLASH_ATTN = False
26
+ try:
27
+ import flash_attn
28
+ if version.parse(flash_attn.__version__) >= version.parse("2.1.0"):
29
+ USE_FLASH_ATTN = True
30
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
31
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input
32
+ except ImportError:
33
+ pass
34
+
35
+ logger = logging.get_logger(__name__)
36
+
37
+
38
+ def _get_unpad_data(attention_mask):
39
+ seqlens_in_batch = (attention_mask).sum(dim=-1, dtype=torch.int32)
40
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
41
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
42
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0,
43
+ dtype=torch.torch.int32), (1, 0))
44
+ return (
45
+ indices,
46
+ cu_seqlens,
47
+ max_seqlen_in_batch,
48
+ )
49
+
50
+
51
+ class RMSNorm(torch.nn.Module):
52
+ def __init__(self, dim: int, eps: float = 1e-6):
53
+ """
54
+ Initialize the RMSNorm normalization layer.
55
+
56
+ Args:
57
+ dim (int): The dimension of the input tensor.
58
+ eps (float, optional): A small value added to the denominator for numerical stability. Default is 1e-6.
59
+
60
+ Attributes:
61
+ eps (float): A small value added to the denominator for numerical stability.
62
+ weight (nn.Parameter): Learnable scaling parameter.
63
+
64
+ """
65
+ super().__init__()
66
+ self.eps = eps
67
+ self.weight = nn.Parameter(torch.ones(dim))
68
+
69
+ def _norm(self, x):
70
+ """
71
+ Apply the RMSNorm normalization to the input tensor.
72
+
73
+ Args:
74
+ x (torch.Tensor): The input tensor.
75
+
76
+ Returns:
77
+ torch.Tensor: The normalized tensor.
78
+
79
+ """
80
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
81
+
82
+ def forward(self, x):
83
+ """
84
+ Forward pass through the RMSNorm layer.
85
+
86
+ Args:
87
+ x (torch.Tensor): The input tensor.
88
+
89
+ Returns:
90
+ torch.Tensor: The output tensor after applying RMSNorm.
91
+
92
+ """
93
+ output = self._norm(x.float()).type_as(x)
94
+ return output * self.weight
95
+
96
+
97
+ def get_norm(config: CustomLlamaConfig):
98
+ norm_type = config.norm_type
99
+ if norm_type == 'rms_norm':
100
+ return partial(RMSNorm, eps=config.layernorm_epsilon)
101
+ elif norm_type == 'layer_norm':
102
+ return partial(LayerNorm, eps=config.layernorm_epsilon)
103
+ else:
104
+ raise ValueError(f'Unsupported norm type: {norm_type}')
105
+
106
+
107
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
108
+ def _make_causal_mask(
109
+ input_ids_shape: torch.Size,
110
+ dtype: torch.dtype,
111
+ device: torch.device,
112
+ past_key_values_length: int = 0,
113
+ ):
114
+ """
115
+ Make causal mask used for bi-directional self-attention.
116
+ """
117
+ bsz, tgt_len = input_ids_shape
118
+ mask = torch.full((tgt_len, tgt_len),
119
+ torch.finfo(dtype).min, device=device)
120
+ mask_cond = torch.arange(mask.size(-1), device=device)
121
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
122
+ mask = mask.to(dtype)
123
+
124
+ if past_key_values_length > 0:
125
+ mask = torch.cat(
126
+ [
127
+ torch.zeros(
128
+ tgt_len, past_key_values_length, dtype=dtype, device=device
129
+ ),
130
+ mask,
131
+ ],
132
+ dim=-1,
133
+ )
134
+ return mask[None, None, :, :].expand(
135
+ bsz, 1, tgt_len, tgt_len + past_key_values_length
136
+ )
137
+
138
+
139
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
140
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
141
+ """
142
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
143
+ """
144
+ bsz, src_len = mask.size()
145
+ tgt_len = tgt_len if tgt_len is not None else src_len
146
+
147
+ expanded_mask = mask[:, None, None, :].expand(
148
+ bsz, 1, tgt_len, src_len).to(dtype)
149
+
150
+ inverted_mask = 1.0 - expanded_mask
151
+
152
+ return inverted_mask.masked_fill(
153
+ inverted_mask.to(torch.bool), torch.finfo(dtype).min
154
+ )
155
+
156
+
157
+ class RotaryEmbedding(torch.nn.Module):
158
+ def __init__(self, dim, base=10000, compress=1.0):
159
+ super().__init__()
160
+ self.inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
161
+ self.seq_len_cached = 0
162
+ self.cos_cached = None
163
+ self.sin_cached = None
164
+ self.compress = compress
165
+
166
+ def forward(self, x, seq_len):
167
+ if seq_len > self.seq_len_cached:
168
+ self.seq_len_cached = seq_len
169
+ self.inv_freq = self.inv_freq.to(x.device)
170
+ t = (
171
+ torch.arange(seq_len, device=self.inv_freq.device,
172
+ dtype=self.inv_freq.dtype)
173
+ * self.compress
174
+ )
175
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
176
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
177
+ self.cos_cached = emb.cos()[None, None, :, :]
178
+ self.sin_cached = emb.sin()[None, None, :, :]
179
+ return self.cos_cached[:seq_len, ...], self.sin_cached[:seq_len, ...]
180
+
181
+
182
+ # rotary pos emb helpers:
183
+
184
+
185
+ def rotate_half(x):
186
+ x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2:]
187
+ return torch.cat((-x2, x1), dim=-1)
188
+
189
+
190
+ @torch.jit.script
191
+ def apply_rotary_pos_emb(q, k, cos, sin, offset: int = 0):
192
+ cos, sin = (
193
+ cos[..., offset: q.shape[-2] + offset, :],
194
+ sin[..., offset: q.shape[-2] + offset, :],
195
+ )
196
+ q_embed = (q.float() * cos) + (rotate_half(q.float()) * sin)
197
+ k_embed = (k.float() * cos) + (rotate_half(k.float()) * sin)
198
+ return q_embed.to(q.dtype), k_embed.to(k.dtype)
199
+
200
+
201
+ def apply_rotary_pos_emb_torch(
202
+ q, k, cos, sin, offset: int = 0
203
+ ): # jitting fails with bf16
204
+ cos, sin = (
205
+ cos[..., offset: q.shape[-2] + offset, :],
206
+ sin[..., offset: q.shape[-2] + offset, :],
207
+ )
208
+ q_embed = (q.float() * cos) + (rotate_half(q.float()) * sin)
209
+ k_embed = (k.float() * cos) + (rotate_half(k.float()) * sin)
210
+ return q_embed.to(q.dtype), k_embed.to(k.dtype)
211
+
212
+
213
+ class CustomLlamaAttention(nn.Module):
214
+ def __init__(self, config: CustomLlamaConfig):
215
+ super().__init__()
216
+ self.num_attention_heads = config.num_attention_heads
217
+ self.num_kv_heads = config.num_kv_heads
218
+ self.hidden_size = config.hidden_size
219
+ self.head_size = self.hidden_size // self.num_attention_heads
220
+ self.rotary_ndims = int(self.head_size * config.rotary_pct)
221
+ self.max_positions = config.max_position_embeddings
222
+ self.rotary_emb = RotaryEmbedding(
223
+ self.rotary_ndims,
224
+ base=config.rotary_emb_base,
225
+ compress=config.rotary_compress,
226
+ )
227
+ self.norm_factor = torch.sqrt(
228
+ torch.tensor(self.head_size, dtype=torch.float32)
229
+ ).to(torch.get_default_dtype())
230
+
231
+ if self.use_gqa:
232
+ self.query_dense = nn.Linear(
233
+ config.hidden_size,
234
+ config.hidden_size,
235
+ bias=getattr(config, "qkv_proj_bias", True)
236
+ )
237
+ self.key_value_dense = nn.Linear(
238
+ config.hidden_size,
239
+ self.head_size * 2 * config.num_kv_heads,
240
+ bias=getattr(config, "qkv_proj_bias", True),
241
+ )
242
+ else:
243
+ self.query_key_value = nn.Linear(
244
+ config.hidden_size,
245
+ 3 * config.hidden_size,
246
+ bias=getattr(config, "qkv_proj_bias", True),
247
+ )
248
+
249
+ self.dense = nn.Linear(
250
+ config.hidden_size,
251
+ config.hidden_size,
252
+ bias=getattr(config, "out_proj_bias", True),
253
+ )
254
+ self.apply_rotary_fn = (
255
+ apply_rotary_pos_emb_torch
256
+ if config.torch_dtype == torch.bfloat16
257
+ else apply_rotary_pos_emb
258
+ )
259
+
260
+ @property
261
+ def use_gqa(self):
262
+ return self.num_kv_heads < self.num_attention_heads
263
+
264
+ def forward(
265
+ self,
266
+ hidden_states,
267
+ attention_mask,
268
+ head_mask=None,
269
+ layer_past=None,
270
+ use_cache=False,
271
+ output_attentions=False,
272
+ ):
273
+ has_layer_past = layer_past is not None
274
+
275
+ if self.use_gqa:
276
+ # Compute Q
277
+ # [batch, seq_len, hidden_size] --> [batch_size, seq_len, (num_heads * head_size)]
278
+ q = self.query_dense(hidden_states)
279
+
280
+ # [batch_size, seq_len, (num_heads * head_size)]
281
+ # --> [batch, seq_len, num_attention_heads, head_size]
282
+ new_q_shape = q.size()[:-1] + \
283
+ (self.num_attention_heads, self.head_size)
284
+ q = q.view(*new_q_shape)
285
+
286
+ # Compute KV
287
+ # [batch, seq_len, hidden_size] --> [batch_size, seq_len, (num_attention_groups * 2 * head_size)]
288
+ kv = self.key_value_dense(hidden_states)
289
+
290
+ # [batch, seq_len, (num_attention_groups * 2 * head_size)]
291
+ # --> [batch, seq_len, num_attention_groups, 2 * head_size]
292
+ new_kv_shape = kv.size()[:-1] + (
293
+ self.num_kv_heads,
294
+ 2 * self.head_size,
295
+ )
296
+ kv = kv.view(*new_kv_shape)
297
+
298
+ # [batch, num_attention_heads, seq_len, head_size]
299
+ query = q.permute(0, 2, 1, 3)
300
+ # [batch, num_attention_groups, seq_len, head_size]
301
+ key = kv[..., : self.head_size].permute(0, 2, 1, 3)
302
+ value = kv[..., self.head_size:].permute(0, 2, 1, 3)
303
+ else:
304
+ # Compute QKV
305
+ # Attention heads [batch, seq_len, hidden_size]
306
+ # --> [batch, seq_len, (np * 3 * head_size)]
307
+ qkv = self.query_key_value(hidden_states)
308
+
309
+ # [batch, seq_len, (num_heads * 3 * head_size)]
310
+ # --> [batch, seq_len, num_heads, 3 * head_size]
311
+ new_qkv_shape = qkv.size()[:-1] + (
312
+ self.num_attention_heads,
313
+ 3 * self.head_size,
314
+ )
315
+ qkv = qkv.view(*new_qkv_shape)
316
+
317
+ # [batch, seq_len, num_attention_heads, 3 * head_size] --> 3 [batch, num_attention_heads, seq_len, head_size]
318
+ query = qkv[..., : self.head_size].permute(0, 2, 1, 3)
319
+ key = qkv[..., self.head_size: 2 *
320
+ self.head_size].permute(0, 2, 1, 3)
321
+ value = qkv[..., 2 * self.head_size:].permute(0, 2, 1, 3)
322
+
323
+ # Compute rotary embeddings on rotary_ndims
324
+ query_rot = query[..., : self.rotary_ndims]
325
+ query_pass = query[..., self.rotary_ndims:]
326
+ key_rot = key[..., : self.rotary_ndims]
327
+ key_pass = key[..., self.rotary_ndims:]
328
+
329
+ # Compute token offset for rotary embeddings (when decoding)
330
+ seq_len = key.shape[-2]
331
+ offset = 0
332
+ if has_layer_past:
333
+ offset = layer_past[0].shape[-2]
334
+ seq_len += offset
335
+ cos, sin = self.rotary_emb(value, seq_len=seq_len)
336
+ query, key = self.apply_rotary_fn(
337
+ query_rot, key_rot, cos, sin, offset=offset)
338
+ query = torch.cat((query, query_pass), dim=-1)
339
+ key = torch.cat((key, key_pass), dim=-1)
340
+
341
+ # Cache QKV values
342
+ if has_layer_past:
343
+ past_key = layer_past[0]
344
+ past_value = layer_past[1]
345
+ key = torch.cat((past_key, key), dim=-2)
346
+ value = torch.cat((past_value, value), dim=-2)
347
+ present = (key, value) if use_cache else None
348
+
349
+ if USE_FLASH_ATTN:
350
+ # Compute attention
351
+ attn_output, attn_weights = self._flash_attn(
352
+ query, key, value, attention_mask, head_mask
353
+ )
354
+
355
+ # from [batch_size, ]
356
+ attn_output = attn_output.reshape(
357
+ attn_output.size(0), attn_output.size(1), self.hidden_size).contiguous()
358
+ else:
359
+ # Compute attention
360
+ attn_output, attn_weights = self._attn(
361
+ query, key, value, attention_mask, head_mask
362
+ )
363
+
364
+ # Reshape outputs
365
+ attn_output = self._merge_heads(
366
+ attn_output, self.num_attention_heads, self.head_size
367
+ )
368
+ attn_output = self.dense(attn_output)
369
+
370
+ outputs = (attn_output, present)
371
+ if output_attentions:
372
+ outputs += (attn_weights,)
373
+
374
+ return outputs
375
+
376
+ @classmethod
377
+ def _split_heads(cls, tensor, num_attention_heads, attn_head_size):
378
+ """
379
+ Splits hidden dim into attn_head_size and num_attention_heads
380
+ """
381
+ # tensor: [bs, seq_len, hidden_size]
382
+ new_shape = tensor.size()[:-1] + (num_attention_heads, attn_head_size)
383
+ # -> [bs, seq_len, num_attention_heads, attn_head_size]
384
+ tensor = tensor.view(new_shape)
385
+ # -> [bs, num_attention_heads, seq_len, attn_head_size]
386
+ tensor = tensor.permute(0, 2, 1, 3)
387
+ return tensor
388
+
389
+ @classmethod
390
+ def _merge_heads(cls, tensor, num_attention_heads, attn_head_size):
391
+ """
392
+ Merges attn_head_size dim and num_attn_heads dim into hidden dim
393
+ """
394
+ # tensor [bs, num_attention_heads, seq_len, attn_head_size]
395
+ tensor = tensor.permute(0, 2, 1, 3).contiguous()
396
+ # -> [bs, seq_len, num_attention_heads, attn_head_size]
397
+ tensor = tensor.view(
398
+ tensor.size(0), tensor.size(
399
+ 1), num_attention_heads * attn_head_size
400
+ )
401
+ # -> [bs, seq_len, hidden_size]
402
+ return tensor
403
+
404
+ def _attn(self, query, key, value, attention_mask=None, head_mask=None):
405
+ # q: [bs, num_attention_heads, seq_len, attn_head_size]
406
+ # k,v: [bs, num_attention_groups, seq_len, attn_head_size]
407
+ # compute causal mask from causal mask buffer
408
+ batch_size, num_attention_heads, query_length, attn_head_size = query.size()
409
+ _, num_attention_groups, key_length, _ = key.size()
410
+
411
+ group_size = num_attention_heads // num_attention_groups
412
+
413
+ if not self.use_gqa:
414
+ assert group_size == 1
415
+
416
+ # repeat key and value, so we can use normal MHA algorithm
417
+ key = (
418
+ key.view(batch_size, num_attention_groups,
419
+ 1, key_length, attn_head_size)
420
+ .repeat(1, 1, group_size, 1, 1)
421
+ .view(batch_size, num_attention_heads, key_length, attn_head_size)
422
+ )
423
+ value = (
424
+ value.view(batch_size, num_attention_groups,
425
+ 1, key_length, attn_head_size)
426
+ .repeat(1, 1, group_size, 1, 1)
427
+ .view(batch_size, num_attention_heads, key_length, attn_head_size)
428
+ )
429
+
430
+ query = query.view(
431
+ batch_size * num_attention_heads, query_length, attn_head_size
432
+ )
433
+ key = key.view(batch_size * num_attention_heads,
434
+ key_length, attn_head_size)
435
+ attn_scores = torch.zeros(
436
+ batch_size * num_attention_heads,
437
+ query_length,
438
+ key_length,
439
+ dtype=query.dtype,
440
+ device=key.device,
441
+ )
442
+ attn_scores = torch.baddbmm(
443
+ attn_scores,
444
+ query,
445
+ key.transpose(1, 2),
446
+ beta=1.0,
447
+ alpha=(
448
+ torch.tensor(
449
+ 1.0, dtype=self.norm_factor.dtype, device=self.norm_factor.device
450
+ )
451
+ / self.norm_factor
452
+ ),
453
+ )
454
+ attn_scores = attn_scores.view(
455
+ batch_size, num_attention_heads, query_length, key_length
456
+ )
457
+
458
+ mask_value = torch.finfo(attn_scores.dtype).min
459
+ # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
460
+ # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
461
+ mask_value = torch.tensor(mask_value, dtype=attn_scores.dtype).to(
462
+ attn_scores.device
463
+ )
464
+
465
+ if attention_mask is not None:
466
+ # Apply the attention mask
467
+ attn_scores = attn_scores + attention_mask
468
+
469
+ attn_weights = nn.functional.softmax(attn_scores, dim=-1)
470
+ attn_weights = attn_weights.to(value.dtype)
471
+
472
+ # Mask heads if we want to
473
+ if head_mask is not None:
474
+ attn_weights = attn_weights * head_mask
475
+
476
+ attn_output = torch.matmul(attn_weights, value)
477
+ return attn_output, attn_weights
478
+
479
+ def _flash_attn(self, query, key, value, attention_mask=None, head_mask=None):
480
+ assert head_mask is None, "head_mask is not supported in _flash_attn"
481
+ # q: [bs, num_attention_heads, seq_len, attn_head_size]
482
+ # k,v: [bs, num_attention_groups, seq_len, attn_head_size]
483
+
484
+ # flash_attn need the layout to be [batch_size, sequence_length, num_heads, head_dim]
485
+ query = query.transpose(1, 2)
486
+ key = key.transpose(1, 2)
487
+ value = value.transpose(1, 2)
488
+
489
+ query_length = query.size(1)
490
+ causal = query_length != 1
491
+
492
+ if attention_mask is not None:
493
+ batch_size = query.size(0)
494
+ query, key, value, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
495
+ query, key, value, attention_mask, query_length
496
+ )
497
+
498
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
499
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
500
+
501
+ attn_output_unpad = flash_attn_varlen_func(
502
+ query,
503
+ key,
504
+ value,
505
+ cu_seqlens_q=cu_seqlens_q,
506
+ cu_seqlens_k=cu_seqlens_k,
507
+ max_seqlen_q=max_seqlen_in_batch_q,
508
+ max_seqlen_k=max_seqlen_in_batch_k,
509
+ dropout_p=0,
510
+ causal=causal,
511
+ )
512
+
513
+ attn_output = pad_input(
514
+ attn_output_unpad, indices_q, batch_size, query_length)
515
+ else:
516
+ attn_output = flash_attn_func(
517
+ query, key, value, 0, causal=causal
518
+ )
519
+
520
+ return attn_output, None
521
+
522
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
523
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(
524
+ attention_mask)
525
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
526
+ num_attention_heads = query_layer.shape[2]
527
+
528
+ key_layer = index_first_axis(
529
+ key_layer.reshape(batch_size * kv_seq_len,
530
+ num_key_value_heads, head_dim), indices_k
531
+ )
532
+ value_layer = index_first_axis(
533
+ value_layer.reshape(batch_size * kv_seq_len,
534
+ num_key_value_heads, head_dim), indices_k
535
+ )
536
+ if query_length == kv_seq_len:
537
+ query_layer = index_first_axis(
538
+ query_layer.reshape(batch_size * kv_seq_len,
539
+ num_attention_heads, head_dim), indices_k
540
+ )
541
+ cu_seqlens_q = cu_seqlens_k
542
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
543
+ indices_q = indices_k
544
+ elif query_length == 1:
545
+ max_seqlen_in_batch_q = 1
546
+ cu_seqlens_q = torch.arange(
547
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
548
+ ) # There is a memcpy here, that is very bad.
549
+ indices_q = cu_seqlens_q[:-1]
550
+ query_layer = query_layer.squeeze(1)
551
+ else:
552
+ # The -q_len: slice assumes left padding.
553
+ attention_mask = attention_mask[:, -query_length:]
554
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
555
+ query_layer, attention_mask)
556
+
557
+ return (
558
+ query_layer,
559
+ key_layer,
560
+ value_layer,
561
+ indices_q,
562
+ (cu_seqlens_q, cu_seqlens_k),
563
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
564
+ )
565
+
566
+
567
+ def swiglu(x):
568
+ x1, x2 = x.chunk(2, dim=(x.ndim - 1))
569
+ return x1 * torch.nn.functional.silu(x2)
570
+
571
+
572
+ def get_activation(act_name: str):
573
+ if act_name == "gelu":
574
+ return ACT2FN["gelu_new"]
575
+ elif act_name == "swiglu":
576
+ return swiglu
577
+ else:
578
+ return ACT2FN[act_name]
579
+
580
+
581
+ class CustomLlamaMLP(nn.Module):
582
+ def __init__(self, config):
583
+ super().__init__()
584
+ h_to_4h_out_channels = (
585
+ config.ffn_hidden_size * 2
586
+ if config.hidden_act == "swiglu"
587
+ else config.ffn_hidden_size
588
+ )
589
+ self.dense_h_to_4h = nn.Linear(
590
+ config.hidden_size,
591
+ h_to_4h_out_channels,
592
+ bias=getattr(config, "mlp_fc1_bias", True)
593
+ )
594
+ self.dense_4h_to_h = nn.Linear(
595
+ config.ffn_hidden_size,
596
+ config.hidden_size,
597
+ bias=getattr(config, "mlp_fc2_bias", True)
598
+ )
599
+ self.act = get_activation(config.hidden_act)
600
+
601
+ def forward(self, hidden_states):
602
+ hidden_states = self.dense_h_to_4h(hidden_states)
603
+ hidden_states = self.act(hidden_states)
604
+ hidden_states = self.dense_4h_to_h(hidden_states)
605
+ return hidden_states
606
+
607
+
608
+ class CustomLlamaLayer(nn.Module):
609
+ def __init__(self, config):
610
+ super().__init__()
611
+
612
+ norm_func = get_norm(config)
613
+ self.input_layernorm = norm_func(config.hidden_size)
614
+ self.post_attention_layernorm = norm_func(config.hidden_size)
615
+ self.attention = CustomLlamaAttention(config)
616
+ self.mlp = CustomLlamaMLP(config)
617
+
618
+ def forward(
619
+ self,
620
+ hidden_states,
621
+ attention_mask=None,
622
+ head_mask=None,
623
+ use_cache=False,
624
+ layer_past=None,
625
+ output_attentions=False,
626
+ ):
627
+ attn_in = self.input_layernorm(hidden_states)
628
+ attention_layer_outputs = self.attention(
629
+ attn_in,
630
+ attention_mask=attention_mask,
631
+ layer_past=layer_past,
632
+ head_mask=head_mask,
633
+ use_cache=use_cache,
634
+ output_attentions=output_attentions,
635
+ )
636
+ attn_output = attention_layer_outputs[
637
+ 0
638
+ ] # output_attn: attn_output, present, (attn_weights)
639
+ outputs = attention_layer_outputs[1:]
640
+ # pseudocode:
641
+ # x = x + attn(ln1(x))
642
+ # x = x + mlp(ln2(x))
643
+ attn_output = attn_output + hidden_states
644
+ mlp_input = self.post_attention_layernorm(attn_output)
645
+ mlp_output = self.mlp(mlp_input)
646
+ hidden_states = mlp_output + attn_output
647
+
648
+ if use_cache:
649
+ outputs = (
650
+ hidden_states,
651
+ ) + outputs # hidden_states, present, (attn_weights)
652
+ else:
653
+ # hidden_states, (attn_weights)
654
+ outputs = (hidden_states,) + outputs[1:]
655
+
656
+ return outputs
657
+
658
+
659
+ class CustomLlamaPreTrainedModel(PreTrainedModel):
660
+ config_class = CustomLlamaConfig
661
+ base_model_prefix = "lm"
662
+ _no_split_modules = ["CustomLlamaLayer"]
663
+
664
+
665
+ class CustomLlamaModel(CustomLlamaPreTrainedModel):
666
+ def __init__(self, config):
667
+ super().__init__(config)
668
+ self.config = config
669
+
670
+ self.embed_in = nn.Embedding(config.vocab_size, config.hidden_size)
671
+ self.layers = nn.ModuleList(
672
+ [CustomLlamaLayer(config) for _ in range(config.num_layers)]
673
+ )
674
+
675
+ norm_func = get_norm(config)
676
+ self.final_layer_norm = norm_func(config.hidden_size)
677
+ # Initialize weights and apply final processing
678
+ self.post_init()
679
+
680
+ def get_input_embeddings(self):
681
+ return self.embed_in
682
+
683
+ def set_input_embeddings(self, value):
684
+ self.embed_in = value
685
+
686
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
687
+ def _prepare_decoder_attention_mask(
688
+ self, attention_mask, input_shape, inputs_embeds, past_key_values_length
689
+ ):
690
+ # create causal mask
691
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
692
+ combined_attention_mask = None
693
+ if input_shape[-1] > 1:
694
+ combined_attention_mask = _make_causal_mask(
695
+ input_shape,
696
+ inputs_embeds.dtype,
697
+ device=inputs_embeds.device,
698
+ past_key_values_length=past_key_values_length,
699
+ )
700
+
701
+ if attention_mask is not None:
702
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
703
+ expanded_attn_mask = _expand_mask(
704
+ attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
705
+ ).to(inputs_embeds.device)
706
+ combined_attention_mask = (
707
+ expanded_attn_mask
708
+ if combined_attention_mask is None
709
+ else expanded_attn_mask + combined_attention_mask
710
+ )
711
+
712
+ return combined_attention_mask
713
+
714
+ def forward(
715
+ self,
716
+ input_ids: Optional[torch.LongTensor] = None,
717
+ attention_mask: Optional[torch.FloatTensor] = None,
718
+ head_mask: Optional[torch.FloatTensor] = None,
719
+ inputs_embeds: Optional[torch.FloatTensor] = None,
720
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
721
+ use_cache: Optional[bool] = None,
722
+ output_attentions: Optional[bool] = None,
723
+ output_hidden_states: Optional[bool] = None,
724
+ return_dict: Optional[bool] = None,
725
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
726
+ r"""
727
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
728
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
729
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
730
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
731
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
732
+ use_cache (`bool`, *optional*):
733
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
734
+ `past_key_values`).
735
+ """
736
+ output_attentions = (
737
+ output_attentions
738
+ if output_attentions is not None
739
+ else self.config.output_attentions
740
+ )
741
+ output_hidden_states = (
742
+ output_hidden_states
743
+ if output_hidden_states is not None
744
+ else self.config.output_hidden_states
745
+ )
746
+ return_dict = (
747
+ return_dict if return_dict is not None else self.config.use_return_dict
748
+ )
749
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
750
+
751
+ if input_ids is not None and inputs_embeds is not None:
752
+ raise ValueError(
753
+ "You cannot specify both input_ids and inputs_embeds at the same time"
754
+ )
755
+ elif input_ids is not None:
756
+ input_shape = input_ids.size()
757
+ elif inputs_embeds is not None:
758
+ input_shape = inputs_embeds.size()[:-1]
759
+ else:
760
+ raise ValueError(
761
+ "You have to specify either input_ids or inputs_embeds")
762
+
763
+ batch_size, seq_length = input_shape
764
+ seq_length_with_past = seq_length
765
+ past_key_values_length = 0
766
+
767
+ if past_key_values is not None:
768
+ past_key_values_length = past_key_values[0][0].shape[2]
769
+ seq_length_with_past = seq_length_with_past + past_key_values_length
770
+ else:
771
+ past_key_values = tuple([None] * self.config.num_layers)
772
+
773
+ if inputs_embeds is None:
774
+ inputs_embeds = self.embed_in(input_ids)
775
+ # Attention mask.
776
+ if attention_mask is None:
777
+ attention_mask = torch.ones(
778
+ (batch_size, seq_length_with_past),
779
+ dtype=torch.bool,
780
+ device=inputs_embeds.device,
781
+ )
782
+
783
+ # Prepare head mask if needed
784
+ # 1.0 in head_mask indicate we keep the head
785
+ # attention_probs has shape bsz x n_heads x N x N
786
+ # input head_mask has shape [num_heads] or [num_layers x num_heads]
787
+ # and head_mask is converted to shape [num_layers x batch x num_heads x seq_length x seq_length]
788
+ head_mask = self.get_head_mask(head_mask, self.config.num_layers)
789
+
790
+ if USE_FLASH_ATTN:
791
+ attention_mask = attention_mask if (
792
+ attention_mask is not None and 0 in attention_mask) else None
793
+ else:
794
+ attention_mask = self._prepare_decoder_attention_mask(
795
+ attention_mask,
796
+ (batch_size, seq_length),
797
+ inputs_embeds,
798
+ past_key_values_length,
799
+ )
800
+
801
+ hidden_states = inputs_embeds
802
+ presents = () if use_cache else None
803
+ all_attentions = () if output_attentions else None
804
+ all_hidden_states = () if output_hidden_states else None
805
+ for i, (layer, layer_past) in enumerate(zip(self.layers, past_key_values)):
806
+ if output_hidden_states:
807
+ all_hidden_states = all_hidden_states + (hidden_states,)
808
+ outputs = layer(
809
+ hidden_states,
810
+ attention_mask=attention_mask,
811
+ head_mask=head_mask[i],
812
+ layer_past=layer_past,
813
+ use_cache=use_cache,
814
+ output_attentions=output_attentions,
815
+ )
816
+ hidden_states = outputs[0]
817
+ if use_cache is True:
818
+ presents = presents + (outputs[1],)
819
+ if output_attentions:
820
+ all_attentions = all_attentions + \
821
+ (outputs[2 if use_cache else 1],)
822
+
823
+ hidden_states = self.final_layer_norm(hidden_states)
824
+ # Add last hidden state
825
+ if output_hidden_states:
826
+ all_hidden_states = all_hidden_states + (hidden_states,)
827
+
828
+ if not return_dict:
829
+ return tuple(
830
+ v
831
+ for v in [hidden_states, presents, all_hidden_states, all_attentions]
832
+ if v is not None
833
+ )
834
+
835
+ return BaseModelOutputWithPast(
836
+ last_hidden_state=hidden_states,
837
+ past_key_values=presents,
838
+ hidden_states=all_hidden_states,
839
+ attentions=all_attentions,
840
+ )
841
+
842
+
843
+ class CustomLlamaForCausalLM(CustomLlamaPreTrainedModel):
844
+ _tied_weights_keys = ["embed_out.weight"]
845
+ _keys_to_ignore_on_load_unexpected = [
846
+ r"lm.layers.\d+.attention.rotary_emb.inv_freq"
847
+ ]
848
+
849
+ def __init__(self, config):
850
+ super().__init__(config)
851
+
852
+ self.lm = CustomLlamaModel(config)
853
+ self.embed_out = nn.Linear(
854
+ config.hidden_size, config.vocab_size, bias=False)
855
+
856
+ # Initialize weights and apply final processing
857
+ self.post_init()
858
+
859
+ def get_output_embeddings(self):
860
+ return self.embed_out
861
+
862
+ def set_output_embeddings(self, new_embeddings):
863
+ self.embed_out = new_embeddings
864
+
865
+ def forward(
866
+ self,
867
+ input_ids: Optional[torch.LongTensor] = None,
868
+ attention_mask: Optional[torch.FloatTensor] = None,
869
+ inputs_embeds: Optional[torch.FloatTensor] = None,
870
+ head_mask: Optional[torch.FloatTensor] = None,
871
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
872
+ labels: Optional[torch.LongTensor] = None,
873
+ use_cache: Optional[bool] = None,
874
+ output_attentions: Optional[bool] = None,
875
+ output_hidden_states: Optional[bool] = None,
876
+ return_dict: Optional[bool] = None,
877
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
878
+ r"""
879
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
880
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
881
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
882
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional tensors are
883
+ only required when the model is used as a decoder in a Sequence to Sequence model.
884
+
885
+ Contains pre-computed hidden-states (key and values in the self-attention blocks that can be used (see
886
+ `past_key_values` input) to speed up sequential decoding.
887
+
888
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
889
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
890
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
891
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
892
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
893
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
894
+ ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`.
895
+ use_cache (`bool`, *optional*):
896
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
897
+ `past_key_values`).
898
+
899
+ ```"""
900
+ return_dict = (
901
+ return_dict if return_dict is not None else self.config.use_return_dict
902
+ )
903
+
904
+ outputs = self.lm(
905
+ input_ids,
906
+ attention_mask=attention_mask,
907
+ head_mask=head_mask,
908
+ inputs_embeds=inputs_embeds,
909
+ past_key_values=past_key_values,
910
+ use_cache=use_cache,
911
+ output_attentions=output_attentions,
912
+ output_hidden_states=output_hidden_states,
913
+ return_dict=return_dict,
914
+ )
915
+
916
+ hidden_states = outputs[0]
917
+ lm_logits = self.embed_out(hidden_states)
918
+
919
+ lm_loss = None
920
+ if labels is not None:
921
+ # we are doing next-token prediction; shift prediction scores and input ids by one
922
+ shift_logits = lm_logits[:, :-1, :].contiguous()
923
+ labels = labels[:, 1:].contiguous()
924
+ loss_fct = CrossEntropyLoss()
925
+ lm_loss = loss_fct(
926
+ shift_logits.view(-1, shift_logits.size(-1)), labels.view(-1)
927
+ )
928
+
929
+ if not return_dict:
930
+ output = (lm_logits,) + outputs[1:]
931
+ return ((lm_loss,) + output) if lm_loss is not None else output
932
+
933
+ return CausalLMOutputWithPast(
934
+ loss=lm_loss,
935
+ logits=lm_logits,
936
+ past_key_values=outputs.past_key_values,
937
+ hidden_states=outputs.hidden_states,
938
+ attentions=outputs.attentions,
939
+ )
940
+
941
+ def prepare_inputs_for_generation(
942
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **model_kwargs
943
+ ):
944
+ input_shape = input_ids.shape
945
+
946
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
947
+ if attention_mask is None:
948
+ attention_mask = input_ids.new_ones(input_shape)
949
+
950
+ # cut decoder_input_ids if past is used
951
+ if past_key_values and past_key_values[0] is not None:
952
+ input_ids = input_ids[:, -1:]
953
+
954
+ if inputs_embeds is not None and past_key_values is None:
955
+ model_inputs = {"inputs_embeds": inputs_embeds}
956
+ else:
957
+ model_inputs = {"input_ids": input_ids}
958
+
959
+ model_inputs.update(
960
+ {
961
+ "attention_mask": attention_mask,
962
+ "past_key_values": past_key_values
963
+ }
964
+ )
965
+
966
+ return model_inputs
967
+
968
+ def _reorder_cache(self, past_key_values, beam_idx):
969
+ reordered_past = ()
970
+ for layer_past in past_key_values:
971
+ reordered_past += (
972
+ tuple(
973
+ past_state.index_select(0, beam_idx)
974
+ for past_state in layer_past[:2]
975
+ )
976
+ + layer_past[2:],
977
+ )
978
+ return reordered_past
modeling_points_chat.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional, Tuple
2
+
3
+ import torch
4
+ from PIL import Image
5
+ from torch import nn
6
+ from transformers import (
7
+ CLIPVisionModel,
8
+ GenerationMixin,
9
+ PreTrainedModel,
10
+ PreTrainedTokenizer,
11
+ )
12
+
13
+ from .catty import split_image_with_catty
14
+ from .configuration_points_chat import POINTSChatConfig
15
+ from .dynamic_high_resolution import split_image
16
+ from .modeling_llama import CustomLlamaForCausalLM
17
+
18
+
19
+ class POINTSChatModel(PreTrainedModel, GenerationMixin):
20
+ config_class = POINTSChatConfig
21
+ _no_split_modules = ["CLIPVisionModel", "LLamaDecoderLayer"]
22
+ """Chat model for POINTS.
23
+
24
+ Official implementation of the paper "POINTS: Improving Your Vision-language Model with Affordable Strategies" # noqa: E501
25
+ paper: https://huggingface.co/papers/2409.04828
26
+
27
+ Args:
28
+ config (PretrainedConfig): The model config.
29
+ """
30
+
31
+ def __init__(self, config: POINTSChatConfig) -> None:
32
+ super().__init__(config)
33
+ self.general_vit = CLIPVisionModel(config.vision_config)
34
+ self.ocr_vit = CLIPVisionModel(config.vision_config)
35
+ self.llm = CustomLlamaForCausalLM(config.llm_config)
36
+ self.vision_projector = nn.Sequential(
37
+ nn.Linear(config.vision_config.hidden_size *
38
+ 4, config.llm_config.hidden_size),
39
+ nn.GELU(),
40
+ nn.Linear(config.llm_config.hidden_size,
41
+ config.llm_config.hidden_size)
42
+
43
+ )
44
+
45
+ def apply_chat_template(self, prompt: str, image_num: int) -> str:
46
+ """Apply the Yi-1.5-Chat template to the prompt.
47
+
48
+ Args:
49
+ prompt (str): The prompt to apply the template to.
50
+ image_num (int): The number of the image in the prompt.
51
+ Returns:
52
+ str: The prompt with the template applied.
53
+ """
54
+ image_tokens = ('<|endoftext|>' * 144) * image_num
55
+ prompt = f'<|im_start|>user\n{image_tokens}{prompt}<|im_end|>\n<|im_start|>assistant\n' # noqa: E501
56
+ return prompt
57
+
58
+ def pixel_shuffle(self, feature_map: torch.Tensor,
59
+ scale_factor: float = 0.5) -> torch.Tensor:
60
+ """Implementation of pixel shuffle.
61
+
62
+ Merge several patches into a single patch by concatenating
63
+ them across the channel dimension. Therefore, we can reduce
64
+ the image sequence length. In POINTS, we merge 2x2 adjacent
65
+ patches into a single patch.
66
+
67
+ Args:
68
+ feature_map (torch.Tensor): The feature map to be pixel
69
+ shuffled.
70
+ scale_factor (float, optional): The scale factor for the
71
+ """
72
+
73
+ # taken from https://huggingface.co/OpenGVLab/InternVL-Chat-V1-5/blob/main/modeling_internvl_chat.py#L187 # noqa
74
+ n, w, h, c = feature_map.size()
75
+ # N, W, H, C --> N, W, H * scale, C // scale
76
+ feature_map = feature_map.view(
77
+ n, w, int(h * scale_factor), int(c / scale_factor))
78
+ # N, W, H * scale, C // scale --> N, H * scale, W, C // scale
79
+ feature_map = feature_map.permute(0, 2, 1, 3).contiguous()
80
+ # N, H * scale, W, C // scale --> N, H * scale, W * scale, C // (scale ** 2)
81
+ feature_map = feature_map.view(
82
+ n,
83
+ int(h * scale_factor),
84
+ int(w * scale_factor),
85
+ int(c / (scale_factor * scale_factor)),
86
+ )
87
+ feature_map = feature_map.permute(0, 2, 1, 3).contiguous()
88
+ return feature_map
89
+
90
+ def extract_image_features(self, images: torch.Tensor,
91
+ vision_encoder: str = 'general_vit') -> torch.Tensor: # noqa: E501
92
+ """Extract the image features from the vision encoder.
93
+
94
+ Args:
95
+ images (torch.Tensor): The images to extract the features from.
96
+ vision_encoder (str, optional): The vision encoder to use.
97
+ Defaults to 'general_vit'.
98
+
99
+ Returns:
100
+ torch.Tensor: The extracted image features.
101
+ """
102
+ if vision_encoder == 'general_vit':
103
+ image_features = self.general_vit(
104
+ images, output_hidden_states=True
105
+ )
106
+ else:
107
+ image_features = self.ocr_vit(
108
+ images, output_hidden_states=True
109
+ )
110
+ image_features = image_features.hidden_states[-2]
111
+ image_features = image_features[:, 1:]
112
+ image_features = image_features.reshape(-1, 24, 24, 1024)
113
+ image_features = self.pixel_shuffle(image_features, 0.5)
114
+ image_features = image_features.view(-1, 144, 4096)
115
+ image_features = self.vision_projector(image_features)
116
+ return image_features
117
+
118
+ def get_pos_mapping(self, pos: List[list]) -> Tuple[dict, int]:
119
+ """Get the position mapping for the images.
120
+
121
+ Args:
122
+ pos (List[list]): The position of the images in the prompt.
123
+
124
+ Returns:
125
+ Tuple[dict, int]: The position mapping and the
126
+ total number of images.
127
+ """
128
+ mapping = {}
129
+ total_images = 0
130
+ for i, (start, end) in enumerate(pos):
131
+ num_image = int((end - start) / 144)
132
+ mapping[i] = num_image
133
+ total_images += num_image
134
+ return mapping, total_images
135
+
136
+ @torch.no_grad()
137
+ def chat(self, pixel_values: Image, prompt: str,
138
+ tokenizer: PreTrainedTokenizer,
139
+ image_processor, catty: bool = True,
140
+ generation_config: dict = None,
141
+ max_splits: int = 8) -> str:
142
+ """Generate a response to the input prompt.
143
+
144
+ Args:
145
+ pixel_values (Image): The input image.
146
+ prompt (str): The input prompt.
147
+ tokenizer (PreTrainedTokenizer): The tokenizer to use.
148
+ image_processor: The image processor to use.
149
+ catty (bool, optional): Whether to use catty. Defaults to True.
150
+ generation_config (dict, optional): The generation config.
151
+ Defaults to None.
152
+ max_splits (int, optional): The maximum number of splits.
153
+ Defaults to 8.
154
+ Returns:
155
+ str: The generated response.
156
+ """
157
+ if catty:
158
+ cropped_images = split_image_with_catty(pixel_values,
159
+ do_resize=True,
160
+ max_crop_slices=max_splits)
161
+ else:
162
+ cropped_images = split_image(pixel_values, max_splits=max_splits)
163
+ prompt = self.apply_chat_template(prompt, len(cropped_images))
164
+ cropped_images = image_processor.preprocess(
165
+ cropped_images, return_tensors='pt')['pixel_values']
166
+ cropped_images = cropped_images.to(self.device)
167
+ # extract features with general_vit
168
+ general_vit_features = self.extract_image_features(
169
+ cropped_images, vision_encoder='general_vit')
170
+ # extract features with ocr_vit
171
+ ocr_vit_features = self.extract_image_features(
172
+ cropped_images, vision_encoder='ocr_vit')
173
+ image_features = 0.5 * general_vit_features + 0.5 * ocr_vit_features
174
+ model_inputs = tokenizer(prompt, return_tensors='pt')
175
+ input_ids = model_inputs['input_ids'].to(self.device)
176
+ attention_mask = model_inputs['attention_mask'].to(self.device)
177
+ # stop token
178
+ eos_token_id = tokenizer.convert_tokens_to_ids("<|im_end|>")
179
+ # image token
180
+ image_token_id = tokenizer.convert_tokens_to_ids("<|endoftext|>")
181
+ generation_config.update(
182
+ {
183
+ 'eos_token_id': eos_token_id,
184
+ }
185
+ )
186
+ outputs = self.generate(
187
+ input_ids=input_ids,
188
+ attention_mask=attention_mask,
189
+ image_features=[image_features],
190
+ image_token_id=image_token_id,
191
+ **generation_config
192
+ )
193
+ response = tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]
194
+ return response
195
+
196
+ def generate(self,
197
+ input_ids: torch.LongTensor,
198
+ attention_mask: torch.LongTensor,
199
+ image_features: List[torch.Tensor],
200
+ image_token_id: int,
201
+ generation_config: Optional[dict] = None,
202
+ output_hidden_states: Optional[bool] = None,
203
+ return_dict: Optional[bool] = None,
204
+ **generate_kwargs) -> torch.LongTensor:
205
+ input_embeddings = self.llm.lm.embed_in(input_ids)
206
+ batch_size = input_ids.shape[0]
207
+ assert len(image_features) == batch_size
208
+ for i in range(batch_size):
209
+ special_pos = input_ids[i] == image_token_id
210
+ pos = (special_pos[:-1] != special_pos[1:]).nonzero() + 1
211
+ if pos.shape[0] % 2 != 0:
212
+ # when the sequence is <image><caption>
213
+ # we need to add a dummy token
214
+ pos = torch.cat([torch.tensor([[0]]).to(pos.device), pos])
215
+ pos = pos.reshape(-1, 2).tolist()
216
+ pos_mapping, total_images = self.get_pos_mapping(pos)
217
+ assert total_images == len(image_features[i])
218
+ img_offset = 0
219
+ for j, (start, end) in enumerate(pos):
220
+ num_images = pos_mapping[j]
221
+ input_embeddings[i, start:end] = torch.cat(
222
+ [image_features[i][img_offset+k]
223
+ for k in range(num_images)],
224
+ dim=0
225
+ )
226
+ img_offset += num_images
227
+ outputs = self.llm.generate(
228
+ inputs_embeds=input_embeddings,
229
+ attention_mask=attention_mask,
230
+ generation_config=generation_config,
231
+ output_hidden_states=output_hidden_states,
232
+ return_dict=return_dict,
233
+ use_cache=True,
234
+ **generate_kwargs
235
+ )
236
+ return outputs
preprocessor_config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "crop_size": {
3
+ "height": 336,
4
+ "width": 336
5
+ },
6
+ "do_center_crop": true,
7
+ "do_convert_rgb": true,
8
+ "do_normalize": true,
9
+ "do_rescale": true,
10
+ "do_resize": true,
11
+ "image_mean": [
12
+ 0.48145466,
13
+ 0.4578275,
14
+ 0.40821073
15
+ ],
16
+ "image_processor_type": "CLIPImageProcessor",
17
+ "image_std": [
18
+ 0.26862954,
19
+ 0.26130258,
20
+ 0.27577711
21
+ ],
22
+ "resample": 3,
23
+ "rescale_factor": 0.00392156862745098,
24
+ "size": {
25
+ "shortest_edge": 336
26
+ }
27
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|startoftext|>",
4
+ "lstrip": false,
5
+ "normalized": true,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|im_end|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<unk>",
18
+ "lstrip": false,
19
+ "normalized": true,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "unk_token": {
24
+ "content": "<unk>",
25
+ "lstrip": false,
26
+ "normalized": true,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ }
30
+ }
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:386c49cf943d71aa110361135338c50e38beeff0a66593480421f37b319e1a39
3
+ size 1033105
tokenizer_config.json ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": true,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<unk>",
8
+ "lstrip": false,
9
+ "normalized": true,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<|startoftext|>",
16
+ "lstrip": false,
17
+ "normalized": true,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "<|endoftext|>",
24
+ "lstrip": false,
25
+ "normalized": true,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": true
29
+ },
30
+ "7": {
31
+ "content": "<|im_end|>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ }
38
+ },
39
+ "bos_token": "<|startoftext|>",
40
+ "chat_template": "{% if messages[0]['role'] == 'system' %}{% set system_message = messages[0]['content'] %}{% endif %}{% if system_message is defined %}{{ system_message }}{% endif %}{% for message in messages %}{% set content = message['content'] %}{% if message['role'] == 'user' %}{{ '<|im_start|>user\\n' + content + '<|im_end|>\\n<|im_start|>assistant\\n' }}{% elif message['role'] == 'assistant' %}{{ content + '<|im_end|>' + '\\n' }}{% endif %}{% endfor %}",
41
+ "clean_up_tokenization_spaces": false,
42
+ "eos_token": "<|im_end|>",
43
+ "legacy": true,
44
+ "model_max_length": 4096,
45
+ "pad_token": "<unk>",
46
+ "padding_side": "right",
47
+ "sp_model_kwargs": {},
48
+ "spaces_between_special_tokens": false,
49
+ "split_special_tokens": false,
50
+ "tokenizer_class": "LlamaTokenizer",
51
+ "unk_token": "<unk>",
52
+ "use_default_system_prompt": false
53
+ }