rp-yu commited on
Commit
7c3bf61
·
verified ·
1 Parent(s): 38b26bc
config.json ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/local_home2/yurunpeng/DvD/output/DiM-v0.5.3-Instruct-7B-autoreg-instruct_llava_next_instruct_lr_5e-07_wd_0.0_bs_128_tt_dlm_9fe0af92_seed_0_autoreg-recovery",
3
+ "architectures": [
4
+ "DimpleModel"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_dimple.DimpleConfig",
9
+ "AutoModel": "modeling_dimple.DimpleModel"
10
+ },
11
+ "bos_token_id": 151643,
12
+ "eos_token_id": 151643,
13
+ "full_attn_mask": true,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 3584,
16
+ "image_token_id": 151655,
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 18944,
19
+ "mask_token_id": 151666,
20
+ "max_position_embeddings": 131072,
21
+ "max_window_layers": 28,
22
+ "model_type": "dimple",
23
+ "mrope_section": [
24
+ 16,
25
+ 24,
26
+ 24
27
+ ],
28
+ "num_attention_heads": 28,
29
+ "num_hidden_layers": 28,
30
+ "num_key_value_heads": 4,
31
+ "pad_token_id": 151643,
32
+ "rms_norm_eps": 1e-06,
33
+ "rope_scaling": null,
34
+ "rope_theta": 1000000.0,
35
+ "sliding_window": null,
36
+ "tie_word_embeddings": false,
37
+ "torch_dtype": "bfloat16",
38
+ "transformers_version": "4.46.2",
39
+ "use_cache": false,
40
+ "use_mrope": false,
41
+ "use_sliding_window": false,
42
+ "video_token_id": 151656,
43
+ "vision_config": {
44
+ "in_chans": 3,
45
+ "model_type": "dimple",
46
+ "spatial_patch_size": 14
47
+ },
48
+ "vision_end_token_id": 151653,
49
+ "vision_start_token_id": 151652,
50
+ "vision_token_id": 151654,
51
+ "vocab_size": 152064
52
+ }
configuration_dimple.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Dimple team and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Dimple model configuration"""
16
+
17
+ import os
18
+ from typing import Union
19
+
20
+ from transformers.configuration_utils import PretrainedConfig
21
+ from transformers.modeling_rope_utils import rope_config_validation
22
+ from transformers.utils import logging
23
+
24
+
25
+ logger = logging.get_logger("Dimple."+__name__)
26
+
27
+
28
+ class DimpleVisionConfig(PretrainedConfig):
29
+ model_type = "dimple"
30
+
31
+ def __init__(
32
+ self,
33
+ depth=32,
34
+ hidden_size=1280,
35
+ hidden_act="silu",
36
+ intermediate_size=3420,
37
+ num_heads=16,
38
+ in_channels=3,
39
+ patch_size=14,
40
+ spatial_merge_size=2,
41
+ temporal_patch_size=2,
42
+ tokens_per_second=2,
43
+ window_size=112,
44
+ out_hidden_size=3584,
45
+ fullatt_block_indexes=[7, 15, 23, 31],
46
+ **kwargs,
47
+ ):
48
+ super().__init__(**kwargs)
49
+
50
+ self.depth = depth
51
+ self.hidden_size = hidden_size
52
+ self.hidden_act = hidden_act
53
+ self.intermediate_size = intermediate_size
54
+ self.num_heads = num_heads
55
+ self.in_channels = in_channels
56
+ self.patch_size = patch_size
57
+ self.spatial_merge_size = spatial_merge_size
58
+ self.temporal_patch_size = temporal_patch_size
59
+ self.tokens_per_second = tokens_per_second
60
+ self.window_size = window_size
61
+ self.fullatt_block_indexes = fullatt_block_indexes
62
+ self.out_hidden_size = out_hidden_size
63
+
64
+
65
+ @classmethod
66
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
67
+ cls._set_token_in_kwargs(kwargs)
68
+
69
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
70
+
71
+ if config_dict.get("model_type") == "dimple":
72
+ config_dict = config_dict["vision_config"]
73
+
74
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
75
+ logger.warning(
76
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
77
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
78
+ )
79
+
80
+ return cls.from_dict(config_dict, **kwargs)
81
+
82
+
83
+ class DimpleConfig(PretrainedConfig):
84
+ model_type = "dimple"
85
+ keys_to_ignore_at_inference = ["past_key_values"]
86
+
87
+ def __init__(
88
+ self,
89
+ vocab_size=151936,
90
+ hidden_size=4096,
91
+ intermediate_size=22016,
92
+ num_hidden_layers=32,
93
+ num_attention_heads=32,
94
+ num_key_value_heads=32,
95
+ hidden_act="silu",
96
+ max_position_embeddings=32768,
97
+ initializer_range=0.02,
98
+ image_token_id = 151655,
99
+ video_token_id = 151656,
100
+ vision_end_token_id = 151653,
101
+ vision_start_token_id = 151652,
102
+ vision_token_id = 151654,
103
+ rms_norm_eps=1e-6,
104
+ use_cache=False, # cache not used in diffusion
105
+ tie_word_embeddings=False,
106
+ rope_theta=10000.0,
107
+ use_sliding_window=False,
108
+ sliding_window=4096,
109
+ max_window_layers=28,
110
+ attention_dropout=0.0,
111
+ mask_token_id=151666,
112
+ pad_token_id=151643,
113
+ vision_config=None,
114
+ rope_scaling=None,
115
+ mrope_section=[16,24,24],
116
+ full_attn_mask = True,
117
+ **kwargs,
118
+ ):
119
+ if isinstance(vision_config, dict):
120
+ self.vision_config = DimpleVisionConfig(**vision_config)
121
+ elif vision_config is None:
122
+ self.vision_config = DimpleVisionConfig()
123
+
124
+ self.vocab_size = vocab_size
125
+ self.max_position_embeddings = max_position_embeddings
126
+ self.hidden_size = hidden_size
127
+ self.intermediate_size = intermediate_size
128
+ self.num_hidden_layers = num_hidden_layers
129
+ self.num_attention_heads = num_attention_heads
130
+ self.use_sliding_window = use_sliding_window
131
+ self.sliding_window = sliding_window if use_sliding_window else None
132
+ self.max_window_layers = max_window_layers
133
+
134
+ # for backward compatibility
135
+ if num_key_value_heads is None:
136
+ num_key_value_heads = num_attention_heads
137
+
138
+ self.num_key_value_heads = num_key_value_heads
139
+ self.hidden_act = hidden_act
140
+ self.initializer_range = initializer_range
141
+ self.rms_norm_eps = rms_norm_eps
142
+ self.use_cache = use_cache
143
+ self.rope_theta = rope_theta
144
+ self.rope_scaling = rope_scaling
145
+ self.attention_dropout = attention_dropout
146
+ # Validate the correctness of rotary position embeddings parameters
147
+ # BC: if there is a 'type' field, move it to 'rope_type'.
148
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
149
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
150
+ rope_config_validation(self, ignore_keys={"mrope_section"})
151
+ self.mrope_section = mrope_section
152
+
153
+ super().__init__(
154
+ tie_word_embeddings=tie_word_embeddings,
155
+ **kwargs,
156
+ )
157
+ self.mask_token_id = mask_token_id
158
+ self.pad_token_id = pad_token_id
159
+ self.image_token_id = image_token_id
160
+ self.video_token_id = video_token_id
161
+ self.vision_end_token_id = vision_end_token_id
162
+ self.vision_start_token_id = vision_start_token_id
163
+ self.vision_token_id = vision_token_id
164
+ self.full_attn_mask = full_attn_mask
generation_config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "alg": "origin",
4
+ "alg_p_threshold": null,
5
+ "alg_temp": null,
6
+ "bos_token_id": 151643,
7
+ "decoding_pipeline": "dim",
8
+ "eos_token_id": 151643,
9
+ "eps": 0.001,
10
+ "mask_token_id": null,
11
+ "output_history": false,
12
+ "pad_token_id": 151643,
13
+ "steps": 512,
14
+ "temperature": 0.0,
15
+ "top_k": null,
16
+ "top_p": null,
17
+ "transformers_version": "4.46.2",
18
+ "use_cache": false,
19
+ "use_original_confidence": true
20
+ }
generation_utils.py ADDED
@@ -0,0 +1,707 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Dimple team and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import warnings
17
+ import copy
18
+ from dataclasses import dataclass
19
+ from typing import Any, Dict, Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.distributions as dists
23
+ from torch.nn import functional as F
24
+ from transformers import __version__
25
+ from transformers.generation.configuration_utils import (
26
+ GenerationConfig,
27
+ )
28
+ from transformers.utils import (
29
+ ModelOutput,
30
+ is_torchdynamo_compiling,
31
+ logging,
32
+ )
33
+ from transformers.cache_utils import (
34
+ Cache,
35
+ DynamicCache,
36
+ )
37
+ from transformers.generation.utils import GenerationMixin
38
+
39
+ logger = logging.get_logger("Dimple."+__name__)
40
+
41
+
42
+ def top_p_logits(logits, top_p=None):
43
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
44
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
45
+ sorted_indices_to_remove = cumulative_probs > top_p
46
+ # Shift the indices to the right to keep the first token above the threshold
47
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
48
+ sorted_indices_to_remove[..., 0] = 0
49
+
50
+ mask = torch.zeros_like(logits, dtype=torch.bool, device=logits.device)
51
+ mask = mask.scatter_(-1, sorted_indices, sorted_indices_to_remove)
52
+ logits = logits.masked_fill(mask, torch.finfo(logits.dtype).min)
53
+ return logits
54
+
55
+ def top_k_logits(logits, top_k=None):
56
+ top_k = min(top_k, logits.size(-1)) # Safety check
57
+ # Remove all tokens with a probability less than the last token of the top-k
58
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
59
+ logits = logits.masked_fill(indices_to_remove, torch.finfo(logits.dtype).min)
60
+ return logits
61
+
62
+
63
+ def sample_tokens(logits, temperature=0.0, top_p=None, top_k=None, margin_confidence=False, neg_entropy=False, use_original_confidence = True):
64
+
65
+ if use_original_confidence:
66
+ original_logits = logits.clone()
67
+ original_probs = torch.softmax(original_logits, dim=-1)
68
+
69
+ if temperature > 0:
70
+ logits = logits / temperature
71
+ if top_p is not None and top_p < 1:
72
+ logits = top_p_logits(logits, top_p)
73
+ if top_k is not None:
74
+ logits = top_k_logits(logits, top_k)
75
+ probs = torch.softmax(logits, dim=-1)
76
+
77
+ if temperature > 0:
78
+ try:
79
+ x0 = dists.Categorical(probs=probs).sample()
80
+ if use_original_confidence:
81
+ confidence = torch.gather(original_probs, -1, x0.unsqueeze(-1)).squeeze(-1)
82
+ else:
83
+ confidence = torch.gather(probs, -1, x0.unsqueeze(-1)).squeeze(-1)
84
+ except:
85
+ if use_original_confidence:
86
+ _, x0 = probs.max(dim=-1)
87
+ confidence = torch.gather(original_probs, -1, x0.unsqueeze(-1)).squeeze(-1)
88
+ else:
89
+ confidence, x0 = probs.max(dim=-1)
90
+ else:
91
+ if use_original_confidence:
92
+ _, x0 = probs.max(dim=-1)
93
+ confidence = torch.gather(original_probs, -1, x0.unsqueeze(-1)).squeeze(-1)
94
+ else:
95
+ confidence, x0 = probs.max(dim=-1)
96
+
97
+ if margin_confidence:
98
+ if use_original_confidence:
99
+ sorted_probs, _ = torch.sort(original_probs, dim=-1, descending=True)
100
+ # Extract top1 and top2 probabilities
101
+ top1_probs = sorted_probs[:, 0]
102
+ top2_probs = sorted_probs[:, 1]
103
+ # Calculate confidence as top1 - top2
104
+ confidence = top1_probs - top2_probs
105
+ else:
106
+ sorted_probs, _ = torch.sort(probs, dim=-1, descending=True)
107
+ # Extract top1 and top2 probabilities
108
+ top1_probs = sorted_probs[:, 0]
109
+ top2_probs = sorted_probs[:, 1]
110
+ # Calculate confidence as top1 - top2
111
+ confidence = top1_probs - top2_probs
112
+
113
+
114
+ if neg_entropy:
115
+ if use_original_confidence:
116
+ epsilon = 1e-10
117
+ log_probs = torch.log(original_probs + epsilon)
118
+ confidence = torch.sum(original_probs * log_probs, dim=-1)
119
+ else:
120
+ epsilon = 1e-10
121
+ log_probs = torch.log(probs + epsilon)
122
+ confidence = torch.sum(probs * log_probs, dim=-1)
123
+
124
+ return confidence, x0
125
+
126
+
127
+ @dataclass
128
+ class DimpleModelOutput(ModelOutput):
129
+ sequences: torch.LongTensor = None
130
+ history: Optional[Tuple[torch.FloatTensor]] = None
131
+
132
+
133
+ class DimpleGenerationConfig(GenerationConfig):
134
+ def __init__(self, **kwargs):
135
+ # cache parameter
136
+ self.use_cache: bool = kwargs.pop("use_cache", False)
137
+ # general generation parameter
138
+ self.temperature: float = kwargs.pop("temperature", 0.0)
139
+ self.top_p: Optional[float] = kwargs.pop("top_p", None)
140
+ self.top_k: Optional[int] = kwargs.pop("top_k", None)
141
+ self.max_length = kwargs.pop("max_length", 20)
142
+ self.max_new_tokens = kwargs.pop("max_new_tokens", None)
143
+ # diffusion specific params
144
+ self.eps: float = kwargs.pop("eps", 1e-3)
145
+ self.steps: int = kwargs.pop("steps", 512)
146
+ self.alg: str = kwargs.pop("alg", 'origin')
147
+ self.alg_temp: Optional[float] = kwargs.pop("alg_temp", None)
148
+ self.alg_p_threshold: Optional[float] = kwargs.pop("alg_p_threshold", None)
149
+ # highly recommended to be True!
150
+ self.use_original_confidence: Optional[bool] = kwargs.pop("use_original_confidence", True)
151
+ # dim or dream.
152
+ self.decoding_pipeline: Optional[str] = kwargs.pop("decoding_pipeline", "dim")
153
+
154
+ # Parameters that define the output variables of `generate`
155
+ self.num_return_sequences: int = kwargs.pop("num_return_sequences", 1)
156
+ self.return_dict_in_generate: bool = kwargs.pop("return_dict_in_generate", False)
157
+ self.output_history: bool = kwargs.pop("output_history", False)
158
+
159
+ # Special tokens that can be used at generation time
160
+ self.mask_token_id = kwargs.pop("mask_token_id", None)
161
+ self.pad_token_id = kwargs.pop("pad_token_id", None)
162
+ self.bos_token_id = kwargs.pop("bos_token_id", None)
163
+ self.eos_token_id = kwargs.pop("eos_token_id", None)
164
+
165
+ # Wild card
166
+ self.generation_kwargs = kwargs.pop("generation_kwargs", {})
167
+
168
+ # The remaining attributes do not parametrize `.generate()`, but are informative and/or used by the hub
169
+ # interface.
170
+ self._from_model_config = kwargs.pop("_from_model_config", False)
171
+ self._commit_hash = kwargs.pop("_commit_hash", None)
172
+ self.transformers_version = kwargs.pop("transformers_version", __version__)
173
+
174
+ # Additional attributes without default values
175
+ if not self._from_model_config:
176
+ # we don't want to copy values from the model config if we're initializing a `GenerationConfig` from a
177
+ # model's default configuration file
178
+ for key, value in kwargs.items():
179
+ try:
180
+ setattr(self, key, value)
181
+ except AttributeError as err:
182
+ logger.error(f"Can't set {key} with value {value} for {self}")
183
+ raise err
184
+
185
+ # Validate the values of the attributes
186
+ self.validate(is_init=True)
187
+
188
+ def validate(self, is_init=False):
189
+ pass
190
+
191
+ class DimpleGenerationMixin:
192
+ # in Dream
193
+
194
+ @staticmethod
195
+ def _expand_inputs_for_generation(
196
+ expand_size: int = 1,
197
+ is_encoder_decoder: bool = False,
198
+ input_ids: Optional[torch.LongTensor] = None,
199
+ **model_kwargs,
200
+ ) -> Tuple[torch.LongTensor, Dict[str, Any]]:
201
+ pixel_values = model_kwargs.get("pixel_values", None)
202
+ image_grid_thw = model_kwargs.get("image_grid_thw", None)
203
+ if expand_size == 1:
204
+ return GenerationMixin._expand_inputs_for_generation(
205
+ expand_size=expand_size,
206
+ is_encoder_decoder=is_encoder_decoder,
207
+ input_ids=input_ids,
208
+ **model_kwargs
209
+ )
210
+ elif pixel_values is None and image_grid_thw is None:
211
+ return GenerationMixin._expand_inputs_for_generation(
212
+ expand_size=expand_size,
213
+ is_encoder_decoder=is_encoder_decoder,
214
+ input_ids=input_ids,
215
+ **model_kwargs
216
+ )
217
+ else:
218
+ raise ValueError(
219
+ "Does not support expansion for image inputs. "
220
+ )
221
+
222
+ def _validate_generated_length(self, generation_config, input_ids_length, has_default_max_length):
223
+ """Performs validation related to the resulting generated length"""
224
+
225
+ # Can't throw warnings/exceptions during compilation
226
+ if is_torchdynamo_compiling():
227
+ return
228
+
229
+ # 1. Max length warnings related to poor parameterization
230
+ if has_default_max_length and generation_config.max_new_tokens is None and generation_config.max_length == 20:
231
+ # 20 is the default max_length of the generation config
232
+ logger.warning_once(
233
+ f"Using the model-agnostic default `max_length` (={generation_config.max_length}) to control the "
234
+ "generation length. We recommend setting `max_new_tokens` to control the maximum length of the "
235
+ "generation."
236
+ )
237
+ if input_ids_length >= generation_config.max_length:
238
+ input_ids_string = "input_ids"
239
+ raise ValueError(
240
+ f"Input length of {input_ids_string} is {input_ids_length}, but `max_length` is set to"
241
+ f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
242
+ " increasing `max_length` or, better yet, setting `max_new_tokens`."
243
+ )
244
+
245
+ def _prepare_generated_length(
246
+ self,
247
+ generation_config,
248
+ has_default_max_length,
249
+ input_ids_length,
250
+ ):
251
+ """Prepared max and min length in generation configs to avoid clashes between similar attributes"""
252
+
253
+ if generation_config.max_new_tokens is not None:
254
+ if not has_default_max_length and generation_config.max_length is not None:
255
+ logger.warning_once(
256
+ f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
257
+ f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
258
+ "Please refer to the documentation for more information. "
259
+ "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"
260
+ )
261
+ generation_config.max_length = generation_config.max_new_tokens + input_ids_length
262
+
263
+ elif has_default_max_length:
264
+ if generation_config.max_length == DimpleGenerationConfig().max_length:
265
+ generation_config.max_length = generation_config.max_length + input_ids_length
266
+ max_position_embeddings = getattr(self.config, "max_position_embeddings", None)
267
+ if max_position_embeddings is not None:
268
+ generation_config.max_length = min(generation_config.max_length, max_position_embeddings)
269
+
270
+ return generation_config
271
+
272
+ def _prepare_generation_config(
273
+ self, generation_config: Optional[DimpleGenerationConfig], **kwargs: Dict
274
+ ) -> DimpleGenerationConfig:
275
+ """
276
+ Prepares the base generation config, then applies any generation configuration options from kwargs. This
277
+ function handles retrocompatibility with respect to configuration files.
278
+ """
279
+ # priority: `generation_config` argument > `model.generation_config` (the default generation config)
280
+ using_model_generation_config = False
281
+ if generation_config is None:
282
+ generation_config = DimpleGenerationConfig.from_model_config(self.config)
283
+ using_model_generation_config = True
284
+
285
+ # `torch.compile` can't compile `copy.deepcopy`, arguments in `kwargs` that are part of `generation_config`
286
+ # will mutate the object with `.update`. As such, passing these arguments through `kwargs` is disabled -- an
287
+ # exception will be raised in `_validate_model_kwargs`
288
+ if not is_torchdynamo_compiling():
289
+ generation_config = copy.deepcopy(generation_config)
290
+ model_kwargs = generation_config.update(**kwargs)
291
+ # If `generation_config` is provided, let's fallback ALL special tokens to the default values for the model
292
+ if not using_model_generation_config:
293
+ if generation_config.bos_token_id is None:
294
+ generation_config.bos_token_id = self.generation_config.bos_token_id
295
+ if generation_config.eos_token_id is None:
296
+ generation_config.eos_token_id = self.generation_config.eos_token_id
297
+ if generation_config.pad_token_id is None:
298
+ generation_config.pad_token_id = self.generation_config.pad_token_id
299
+ if generation_config.mask_token_id is None:
300
+ generation_config.mask_token_id = self.generation_config.mask_token_id
301
+
302
+ return generation_config, model_kwargs
303
+
304
+ def _prepare_special_tokens(
305
+ self,
306
+ generation_config: DimpleGenerationConfig,
307
+ device: Optional[Union[torch.device, str]] = None,
308
+ ):
309
+ """
310
+ Prepares the special tokens for generation, overwriting the generation config with their processed versions
311
+ converted to tensor.
312
+
313
+ Note that `generation_config` is changed in place and stops being serializable after this method is called.
314
+ That is no problem if called within `generate` (`generation_config` is a local copy that doesn't leave the
315
+ function). However, if called outside `generate`, consider creating a copy of `generation_config` first.
316
+ """
317
+
318
+ # Convert special tokens to tensors
319
+ def _tensor_or_none(token, device=None):
320
+ if token is None:
321
+ return token
322
+
323
+ device = device if device is not None else self.device
324
+ if isinstance(token, torch.Tensor):
325
+ return token.to(device)
326
+ return torch.tensor(token, device=device, dtype=torch.long)
327
+
328
+ bos_token_tensor = _tensor_or_none(generation_config.bos_token_id, device=device)
329
+ eos_token_tensor = _tensor_or_none(generation_config.eos_token_id, device=device)
330
+ pad_token_tensor = _tensor_or_none(generation_config.pad_token_id, device=device)
331
+ mask_token_tensor = _tensor_or_none(generation_config.mask_token_id, device=device)
332
+
333
+ # We can have more than one eos token. Always treat it as a 1D tensor (when it exists).
334
+ if eos_token_tensor is not None and eos_token_tensor.ndim == 0:
335
+ eos_token_tensor = eos_token_tensor.unsqueeze(0)
336
+
337
+ # Set pad token if unset (and there are conditions to do so)
338
+ if pad_token_tensor is None and eos_token_tensor is not None:
339
+ pad_token_tensor = eos_token_tensor[0]
340
+ logger.warning_once(f"Setting `pad_token_id` to `eos_token_id`:{pad_token_tensor} for open-end generation.")
341
+
342
+ # Update generation config with the updated special tokens tensors
343
+ # NOTE: this must be written into a different attribute name than the one holding the original special tokens
344
+ # (in their non-tensor form), in order to enable end-to-end compilation. See
345
+ # https://pytorch.org/docs/stable/torch.compiler_cudagraph_trees.html#limitations
346
+ generation_config._bos_token_tensor = bos_token_tensor
347
+ generation_config._eos_token_tensor = eos_token_tensor
348
+ generation_config._pad_token_tensor = pad_token_tensor
349
+ generation_config._mask_token_tensor = mask_token_tensor
350
+ def _mask_pad_inputs_for_generation(
351
+ self,
352
+ input_ids: torch.LongTensor,
353
+ generation_config: DimpleGenerationConfig,
354
+ **model_kwargs,
355
+ ) -> Tuple[torch.LongTensor, Dict[str, Any]]:
356
+ """
357
+ pad tokens in the input ids and attentions for generation. This is used to insert mask tokens into the input_ids
358
+ """
359
+ max_length = generation_config.max_length
360
+ mask_token_id = generation_config.mask_token_id
361
+ attention_mask = model_kwargs.get("attention_mask", None)
362
+
363
+ # pad input_ids to max_length
364
+ input_ids = F.pad(input_ids, (0, max_length - input_ids.shape[1]), value=mask_token_id)
365
+ if attention_mask is not None:
366
+ attention_mask = F.pad(attention_mask, (0, max_length - attention_mask.shape[1]), value=1.0)
367
+ model_kwargs["attention_mask"] = attention_mask
368
+ else:
369
+ raise ValueError(
370
+ "attention_mask should be provided. "
371
+ )
372
+
373
+ return input_ids, model_kwargs
374
+
375
+ def compare_past_key_values(self, old, new):
376
+ if len(old) != len(new):
377
+ return False
378
+ for (k_old, v_old), (k_new, v_new) in zip(old, new):
379
+ if not (torch.equal(k_old, k_new) and torch.equal(v_old, v_new)):
380
+ return False
381
+ return True
382
+
383
+ def _update_model_kwargs_for_generation(
384
+ self,
385
+ outputs: ModelOutput,
386
+ model_kwargs: Dict[str, Any]
387
+ ) -> Dict[str, Any]:
388
+ # update past_key_values keeping its naming used in model code
389
+ if model_kwargs["use_cache"]:
390
+ assert outputs.past_key_values is not None, "Cache should not be None if use_cache is True"
391
+ assert outputs.past_key_values.get_seq_length() == model_kwargs["total_sequence_length"], \
392
+ f"Cache length {outputs.past_key_values.get_seq_length()} should be equal to the total sequence length {model_kwargs['total_sequence_length']}"
393
+ # The crop operation requires "left padding for batch processing"
394
+ outputs.past_key_values.crop(max_length = model_kwargs["prompt_length"])
395
+ # if model_kwargs["past_key_values"].get_seq_length() > 0:
396
+ # assert self.compare_past_key_values(model_kwargs["past_key_values"], outputs.past_key_values), \
397
+ # f"Cache {model_kwargs['past_key_values']} should be equal to the new cache {outputs.past_key_values}"
398
+ else:
399
+ assert outputs.past_key_values is None, "Cache should be None if use_cache is False"
400
+ model_kwargs["past_key_values"] = outputs.past_key_values
401
+
402
+ # update cache position
403
+ if model_kwargs["use_cache"]:
404
+ model_kwargs["cache_position"] = model_kwargs["cache_position"][-(model_kwargs["total_sequence_length"] - model_kwargs["prompt_length"]):]
405
+ else:
406
+ assert model_kwargs["cache_position"] is None, "Cache position should be None if use_cache is False"
407
+
408
+ if model_kwargs.get("rope_deltas", None) is not None:
409
+ assert torch.equal(
410
+ model_kwargs["rope_deltas"], outputs.rope_deltas), \
411
+ f"Rope deltas {model_kwargs['rope_deltas']} should be equal to the new rope deltas {outputs.rope_deltas}"
412
+ model_kwargs["rope_deltas"] = outputs.rope_deltas
413
+ return model_kwargs
414
+
415
+ @torch.no_grad()
416
+ def diffusion_generate(
417
+ self,
418
+ inputs: Optional[torch.Tensor] = None,
419
+ generation_config: Optional[DimpleGenerationConfig] = None,
420
+ # tokenizer=None, # only for debug, need to be removed !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
421
+ **kwargs,
422
+ ) -> Union[DimpleModelOutput, torch.LongTensor]:
423
+ # 1. Handle `generation_config` and kwargs that might update it, and validate the `.generate()` call
424
+ generation_config, model_kwargs = self._prepare_generation_config(generation_config, **kwargs)
425
+ generation_tokens_hook_func = model_kwargs.pop("generation_tokens_hook_func", lambda step, x, logits: x)
426
+ generation_logits_hook_func = model_kwargs.pop("generation_logits_hook_func", lambda step, x, logits: logits)
427
+
428
+ # 2. Define model inputs
429
+ assert inputs is not None
430
+ input_ids = inputs
431
+ device = input_ids.device
432
+ attention_mask = model_kwargs.get("attention_mask", None)
433
+ self._prepare_special_tokens(generation_config, device=device)
434
+
435
+ # 3. Prepare `max_length`.
436
+ input_ids_length = input_ids.shape[-1]
437
+ has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
438
+ generation_config = self._prepare_generated_length(
439
+ generation_config=generation_config,
440
+ has_default_max_length=has_default_max_length,
441
+ input_ids_length=input_ids_length,
442
+ )
443
+
444
+ self._validate_generated_length(generation_config, input_ids_length, has_default_max_length)
445
+
446
+ # 4. Check input_ids
447
+ if not is_torchdynamo_compiling() and self.device.type != input_ids.device.type:
448
+ logger.warning_once(
449
+ "You are calling .generate() with the `input_ids` being on a device type different"
450
+ f" than your model's device. `input_ids` is on {input_ids.device.type}, whereas the model"
451
+ f" is on {self.device.type}. You may experience unexpected behaviors or slower generation."
452
+ " Please make sure that you have put `input_ids` to the"
453
+ f" correct device by calling for example input_ids = input_ids.to('{self.device.type}') before"
454
+ " running `.generate()`."
455
+ )
456
+ if (
457
+ hasattr(generation_config, "pad_token_id") and
458
+ torch.any(input_ids == generation_config.pad_token_id) and
459
+ attention_mask is None
460
+ ):
461
+ logger.warning_once(
462
+ "Padding was detected but no attention mask is passed here. For correct "
463
+ "generation results, please set `attention_mask` when batch-padding inputs."
464
+ )
465
+
466
+ # 5. initialize kv cache
467
+ model_kwargs["use_cache"] = generation_config.use_cache
468
+ if model_kwargs["use_cache"]:
469
+ model_kwargs["past_key_values"] = DynamicCache()
470
+ model_kwargs["prompt_length"] = input_ids.shape[1] - 1
471
+ else:
472
+ model_kwargs["past_key_values"] = None
473
+ model_kwargs["prompt_length"] = input_ids.shape[1] - 1
474
+
475
+ # 6. Expand inputs for generation
476
+ input_ids, model_kwargs = self._expand_inputs_for_generation(
477
+ input_ids=input_ids,
478
+ expand_size=generation_config.num_return_sequences,
479
+ is_encoder_decoder=self.config.is_encoder_decoder,
480
+ **model_kwargs,
481
+ )
482
+
483
+ # 7. pad mask for generation
484
+ input_ids, model_kwargs = self._mask_pad_inputs_for_generation(
485
+ input_ids=input_ids,
486
+ generation_config=generation_config,
487
+ **model_kwargs,
488
+ )
489
+ model_kwargs["total_sequence_length"] = input_ids.shape[1]
490
+
491
+ # 8. initialize cache position
492
+ if model_kwargs["use_cache"]:
493
+ model_kwargs["cache_position"] = torch.ones_like(input_ids[0, :], dtype=torch.int64).cumsum(0) - 1
494
+ else:
495
+ model_kwargs["cache_position"] = None
496
+ # 9. Generate
497
+ result = self._sample(
498
+ input_ids,
499
+ generation_config=generation_config,
500
+ generation_tokens_hook_func=generation_tokens_hook_func,
501
+ generation_logits_hook_func=generation_logits_hook_func,
502
+ # tokenizer=tokenizer, # only for debug, need to be removed !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
503
+ **model_kwargs,
504
+ )
505
+ return result
506
+
507
+ def _sample(
508
+ self,
509
+ input_ids: torch.LongTensor,
510
+ generation_config: DimpleGenerationConfig,
511
+ generation_tokens_hook_func,
512
+ generation_logits_hook_func,
513
+ # tokenizer=None, # only for debug, need to be removed !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
514
+ **model_kwargs,
515
+ ) -> Union[DimpleModelOutput, torch.LongTensor]:
516
+ # init values
517
+ output_history = generation_config.output_history
518
+ return_dict_in_generate = generation_config.return_dict_in_generate
519
+ max_length = generation_config.max_length
520
+ mask_token_id = generation_config.mask_token_id
521
+ steps = generation_config.steps
522
+ eps = generation_config.eps
523
+ alg = generation_config.alg
524
+ alg_temp = generation_config.alg_temp
525
+ alg_p_threshold = generation_config.alg_p_threshold
526
+ decoding_pipeline = generation_config.decoding_pipeline
527
+ use_original_confidence = generation_config.use_original_confidence
528
+ temperature = generation_config.temperature
529
+ top_p = generation_config.top_p
530
+ top_k = generation_config.top_k
531
+ attention_mask = model_kwargs.get("attention_mask", None)
532
+ attention_mask_4d = model_kwargs.get("attention_mask_4d", None)
533
+
534
+ histories = [] if (return_dict_in_generate and output_history) else None
535
+
536
+ timesteps = torch.linspace(1, eps, steps + 1, device=input_ids.device)
537
+
538
+ input_ids = generation_tokens_hook_func(None, input_ids, None)
539
+
540
+ num_total_mask = (input_ids == mask_token_id).sum()
541
+
542
+ # this allows user-defined token control of the intermediate steps
543
+ for i in range(steps):
544
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
545
+ x = model_inputs.pop("input_ids").clone()
546
+ mask_index = (x == mask_token_id)
547
+ outputs = self(x, **model_inputs)
548
+
549
+ model_kwargs = self._update_model_kwargs_for_generation(outputs, model_kwargs)
550
+
551
+ logits = outputs.logits
552
+ assert torch.all(x[:,0] != mask_token_id), "The first token should not be a mask token"
553
+ logits = torch.cat([logits[:,:1], logits[:, :-1]], dim=1)
554
+
555
+ # this allows user-defined logits control of the intermediate steps
556
+ logits = generation_logits_hook_func(i, x, logits)
557
+
558
+ mask_logits = logits[mask_index]
559
+
560
+ if decoding_pipeline == 'dream':
561
+ # raise NotImplementedError("Dream decoding pipeline is copied from the original code.")
562
+ t = timesteps[i]
563
+ s = timesteps[i + 1]
564
+
565
+ if alg == 'origin':
566
+ p_transfer = 1 - s / t if i < steps - 1 else 1
567
+ x0 = torch.zeros_like(x[mask_index], device=self.device, dtype=torch.long) + mask_token_id
568
+ transfer_index_t_s = torch.rand(*x0.shape, device=self.device) < p_transfer
569
+ _, x0[transfer_index_t_s]= sample_tokens(mask_logits[transfer_index_t_s], temperature=temperature, top_p=top_p, top_k=top_k, use_original_confidence = False)
570
+ x[mask_index] = x0.clone()
571
+ elif alg == 'autoregressive':
572
+ x0 = torch.zeros_like(x[mask_index], device=self.device, dtype=torch.long) + mask_token_id
573
+ transfer_index_t_s = torch.zeros(*x.shape, device=self.device, dtype=torch.bool)
574
+ transfer_index_t_s[torch.arange(x.shape[0]), mask_index.max(dim = 1)[1]] = True
575
+ mask_transfer_index_t_s = transfer_index_t_s[mask_index]
576
+ _, x0[mask_transfer_index_t_s]= sample_tokens(mask_logits[mask_transfer_index_t_s], temperature=temperature, top_p=top_p, top_k=top_k, use_original_confidence = False)
577
+ x[mask_index] = x0.clone()
578
+ else:
579
+ if alg == 'maskgit_plus':
580
+ confidence, x0 = sample_tokens(mask_logits, temperature=temperature, top_p=top_p, top_k=top_k, use_original_confidence = False)
581
+ elif alg == 'topk_margin':
582
+ confidence, x0 = sample_tokens(mask_logits, temperature=temperature, top_p=top_p, top_k=top_k, margin_confidence=True, use_original_confidence = False)
583
+ elif alg == 'entropy':
584
+ confidence, x0 = sample_tokens(mask_logits, temperature, top_p=top_p, top_k=top_k, neg_entropy=True, use_original_confidence = False)
585
+ else:
586
+ raise RuntimeError(f"Unknown alg: {alg}")
587
+ num_mask_token = mask_index.sum()
588
+ number_transfer_tokens = int(num_mask_token * (1 - s / t)) if i < steps - 1 else num_mask_token
589
+ if number_transfer_tokens > 0:
590
+ if alg_temp is None or alg_temp == 0:
591
+ _, transfer_index = torch.topk(confidence, number_transfer_tokens)
592
+ else:
593
+ confidence = confidence / alg_temp
594
+ confidence = F.softmax(confidence, dim=-1)
595
+ transfer_index = torch.multinomial(confidence, num_samples=number_transfer_tokens)
596
+ x0_ = torch.zeros_like(x0, device=self.device, dtype=torch.long) + mask_token_id
597
+ x0_[transfer_index] = x0[transfer_index].clone()
598
+ x[mask_index] = x0_
599
+
600
+ elif decoding_pipeline == 'dim':
601
+
602
+ if alg == 'origin':
603
+ confidence, x0= sample_tokens(mask_logits, temperature=temperature, top_p=top_p, top_k=top_k, use_original_confidence = use_original_confidence)
604
+ elif alg == 'origin-ratio':
605
+ confidence, x0= sample_tokens(mask_logits, temperature=temperature, top_p=top_p, top_k=top_k, use_original_confidence = use_original_confidence)
606
+ elif alg == 'autoregressive':
607
+ confidence, x0= sample_tokens(mask_logits, temperature=temperature, top_p=top_p, top_k=top_k, use_original_confidence = use_original_confidence)
608
+ elif alg == 'maskgit_plus':
609
+ confidence, x0 = sample_tokens(mask_logits, temperature=temperature, top_p=top_p, top_k=top_k, use_original_confidence = use_original_confidence)
610
+ elif alg == 'topk_margin':
611
+ confidence, x0 = sample_tokens(mask_logits, temperature=temperature, top_p=top_p, top_k=top_k, margin_confidence=True, use_original_confidence = use_original_confidence)
612
+ elif alg == 'entropy':
613
+ confidence, x0 = sample_tokens(mask_logits, temperature, top_p=top_p, top_k=top_k, neg_entropy=True, use_original_confidence = use_original_confidence)
614
+ else:
615
+ raise RuntimeError(f"Unknown alg: {alg}")
616
+
617
+ p_threshold_transfer_index_sum = 0
618
+ if alg_p_threshold is not None and alg_p_threshold > 0:
619
+ if i == steps - 1:
620
+ # all tokens should be transfered
621
+ transfer_index = torch.ones_like(confidence, device=self.device, dtype=torch.bool)
622
+ else:
623
+ transfer_index = confidence > alg_p_threshold
624
+ p_threshold_transfer_index_sum = transfer_index.sum()
625
+ if p_threshold_transfer_index_sum == 0:
626
+ pass
627
+ else:
628
+ x0_ = torch.zeros_like(x0, device=self.device, dtype=torch.long) + mask_token_id
629
+ x0_[transfer_index] = x0[transfer_index].clone()
630
+ x[mask_index] = x0_.clone()
631
+ else:
632
+ pass
633
+
634
+ if p_threshold_transfer_index_sum == 0:
635
+
636
+ num_cur_mask = mask_index.sum()
637
+ ratio_cur_mask = num_cur_mask / num_total_mask
638
+ if ratio_cur_mask <= timesteps[-1]:
639
+ raise ValueError(f"ratio_cur_mask {ratio_cur_mask} should be larger than timesteps[-1] {timesteps[-1]}")
640
+
641
+ valid_s_indices = (timesteps < ratio_cur_mask).nonzero(as_tuple=True)[0]
642
+ s_idx_start = max(valid_s_indices.min().item(), i + 1)
643
+ t = ratio_cur_mask
644
+ for s_idx in range(s_idx_start, steps + 1):
645
+ s = timesteps[s_idx]
646
+ number_transfer_tokens = int(num_cur_mask * (1 - s / t)) if s > timesteps[-1] else num_cur_mask
647
+ if number_transfer_tokens >= 1:
648
+ break
649
+ else:
650
+ continue
651
+
652
+ if alg == 'origin':
653
+ x0_ = torch.zeros_like(x[mask_index], device=self.device, dtype=torch.long) + mask_token_id
654
+ transfer_index_t_s = torch.randperm(x0_.shape[0])[:number_transfer_tokens]
655
+ x0_[transfer_index_t_s]= x0[transfer_index_t_s].clone()
656
+ x[mask_index] = x0_.clone()
657
+ elif alg == 'origin-ratio':
658
+ p_transfer = 1 - s / t if s > timesteps[-1] else 1
659
+ x0_ = torch.zeros_like(x[mask_index], device=self.device, dtype=torch.long) + mask_token_id
660
+ transfer_index_t_s = torch.rand(*x0_.shape, device=self.device) < p_transfer
661
+ x0_[transfer_index_t_s]= x0[transfer_index_t_s].clone()
662
+ x[mask_index] = x0_.clone()
663
+ elif alg == 'autoregressive':
664
+ x0_ = torch.zeros_like(x[mask_index], device=self.device, dtype=torch.long) + mask_token_id
665
+ transfer_index_t_s = torch.zeros(*x.shape, device=self.device, dtype=torch.bool)
666
+ transfer_index_t_s[torch.arange(x.shape[0]), mask_index.max(dim = 1)[1]] = True
667
+ mask_transfer_index_t_s = transfer_index_t_s[mask_index]
668
+ x0_[mask_transfer_index_t_s]= x0[mask_transfer_index_t_s].clone()
669
+ x[mask_index] = x0_.clone()
670
+ elif alg in ['maskgit_plus', 'topk_margin', 'entropy']:
671
+ assert number_transfer_tokens > 0, f"number_transfer_tokens {number_transfer_tokens} should be larger than 0"
672
+ if alg_temp is None or alg_temp == 0:
673
+ _, transfer_index = torch.topk(confidence, number_transfer_tokens)
674
+ else:
675
+ confidence = confidence / alg_temp
676
+ confidence = F.softmax(confidence, dim=-1)
677
+ transfer_index = torch.multinomial(confidence, num_samples=number_transfer_tokens)
678
+ x0_ = torch.zeros_like(x0, device=self.device, dtype=torch.long) + mask_token_id
679
+ x0_[transfer_index] = x0[transfer_index].clone()
680
+ x[mask_index] = x0_.clone()
681
+ else:
682
+ raise ValueError(f"Unknown decoding pipeline: {decoding_pipeline}")
683
+
684
+ # this allows user-defined token control of the intermediate steps
685
+ x = generation_tokens_hook_func(i, x, logits)
686
+
687
+ answer_token_length = model_kwargs['total_sequence_length'] - model_kwargs['prompt_length']
688
+ if x.shape[1] == model_kwargs['total_sequence_length']:
689
+ assert torch.all(x[:,:model_kwargs['prompt_length']+1] == input_ids[:,:model_kwargs['prompt_length']+1]), "prompt tokens should not be changed"
690
+ elif x.shape[1] == answer_token_length:
691
+ assert torch.all(
692
+ x[:,0] == input_ids[:,-answer_token_length]), "The first token in x should be the same as the input_ids"
693
+ input_ids[:, -answer_token_length:] = x[:, -answer_token_length:].clone()
694
+
695
+ if histories is not None:
696
+ histories.append(input_ids.clone())
697
+
698
+ if decoding_pipeline == 'dim' and torch.all(input_ids != mask_token_id):
699
+ break
700
+
701
+ if return_dict_in_generate:
702
+ return DimpleModelOutput(
703
+ sequences=input_ids,
704
+ history=histories,
705
+ )
706
+ else:
707
+ return input_ids
model-00001-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:329fd943debbe8f1b03c3e369d73a93b242764029209fd2388e753e6bfbb1830
3
+ size 4968243304
model-00002-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0b89a4573508d322a95995debd730ab11f6ec7d0f3801e72bf8e6bedcc6767ce
3
+ size 4991495816
model-00003-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e8ddf4e01077c290e08a59d5d6b017b74e175cefff6194707ea0ba10437c2615
3
+ size 4932751040
model-00004-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d351f0dc11b8f913c5016b453ac3e2eb1b1603ce9b3650aec2666312f23e1dc1
3
+ size 1743319336
model.safetensors.index.json ADDED
@@ -0,0 +1,740 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 16635727872
4
+ },
5
+ "weight_map": {
6
+ "img_projector.linear_1.bias": "model-00004-of-00004.safetensors",
7
+ "img_projector.linear_1.weight": "model-00004-of-00004.safetensors",
8
+ "img_projector.linear_2.bias": "model-00004-of-00004.safetensors",
9
+ "img_projector.linear_2.weight": "model-00004-of-00004.safetensors",
10
+ "lm_head.weight": "model-00004-of-00004.safetensors",
11
+ "model.embed_tokens.weight": "model-00001-of-00004.safetensors",
12
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00004.safetensors",
13
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
14
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
15
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
16
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
17
+ "model.layers.0.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
18
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
19
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
20
+ "model.layers.0.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
21
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
22
+ "model.layers.0.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
23
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
24
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00004.safetensors",
25
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
26
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
27
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
28
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
29
+ "model.layers.1.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
30
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
31
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
32
+ "model.layers.1.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
33
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
34
+ "model.layers.1.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
35
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
36
+ "model.layers.10.input_layernorm.weight": "model-00002-of-00004.safetensors",
37
+ "model.layers.10.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
38
+ "model.layers.10.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
39
+ "model.layers.10.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
40
+ "model.layers.10.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
41
+ "model.layers.10.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
42
+ "model.layers.10.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
43
+ "model.layers.10.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
44
+ "model.layers.10.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
45
+ "model.layers.10.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
46
+ "model.layers.10.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
47
+ "model.layers.10.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
48
+ "model.layers.11.input_layernorm.weight": "model-00002-of-00004.safetensors",
49
+ "model.layers.11.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
50
+ "model.layers.11.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
51
+ "model.layers.11.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
52
+ "model.layers.11.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
53
+ "model.layers.11.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
54
+ "model.layers.11.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
55
+ "model.layers.11.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
56
+ "model.layers.11.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
57
+ "model.layers.11.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
58
+ "model.layers.11.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
59
+ "model.layers.11.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
60
+ "model.layers.12.input_layernorm.weight": "model-00002-of-00004.safetensors",
61
+ "model.layers.12.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
62
+ "model.layers.12.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
63
+ "model.layers.12.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
64
+ "model.layers.12.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
65
+ "model.layers.12.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
66
+ "model.layers.12.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
67
+ "model.layers.12.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
68
+ "model.layers.12.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
69
+ "model.layers.12.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
70
+ "model.layers.12.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
71
+ "model.layers.12.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
72
+ "model.layers.13.input_layernorm.weight": "model-00002-of-00004.safetensors",
73
+ "model.layers.13.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
74
+ "model.layers.13.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
75
+ "model.layers.13.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
76
+ "model.layers.13.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
77
+ "model.layers.13.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
78
+ "model.layers.13.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
79
+ "model.layers.13.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
80
+ "model.layers.13.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
81
+ "model.layers.13.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
82
+ "model.layers.13.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
83
+ "model.layers.13.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
84
+ "model.layers.14.input_layernorm.weight": "model-00002-of-00004.safetensors",
85
+ "model.layers.14.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
86
+ "model.layers.14.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
87
+ "model.layers.14.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
88
+ "model.layers.14.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
89
+ "model.layers.14.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
90
+ "model.layers.14.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
91
+ "model.layers.14.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
92
+ "model.layers.14.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
93
+ "model.layers.14.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
94
+ "model.layers.14.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
95
+ "model.layers.14.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
96
+ "model.layers.15.input_layernorm.weight": "model-00002-of-00004.safetensors",
97
+ "model.layers.15.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
98
+ "model.layers.15.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
99
+ "model.layers.15.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
100
+ "model.layers.15.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
101
+ "model.layers.15.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
102
+ "model.layers.15.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
103
+ "model.layers.15.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
104
+ "model.layers.15.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
105
+ "model.layers.15.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
106
+ "model.layers.15.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
107
+ "model.layers.15.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
108
+ "model.layers.16.input_layernorm.weight": "model-00003-of-00004.safetensors",
109
+ "model.layers.16.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
110
+ "model.layers.16.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
111
+ "model.layers.16.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
112
+ "model.layers.16.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
113
+ "model.layers.16.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
114
+ "model.layers.16.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
115
+ "model.layers.16.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
116
+ "model.layers.16.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
117
+ "model.layers.16.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
118
+ "model.layers.16.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
119
+ "model.layers.16.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
120
+ "model.layers.17.input_layernorm.weight": "model-00003-of-00004.safetensors",
121
+ "model.layers.17.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
122
+ "model.layers.17.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
123
+ "model.layers.17.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
124
+ "model.layers.17.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
125
+ "model.layers.17.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
126
+ "model.layers.17.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
127
+ "model.layers.17.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
128
+ "model.layers.17.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
129
+ "model.layers.17.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
130
+ "model.layers.17.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
131
+ "model.layers.17.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
132
+ "model.layers.18.input_layernorm.weight": "model-00003-of-00004.safetensors",
133
+ "model.layers.18.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
134
+ "model.layers.18.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
135
+ "model.layers.18.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
136
+ "model.layers.18.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
137
+ "model.layers.18.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
138
+ "model.layers.18.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
139
+ "model.layers.18.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
140
+ "model.layers.18.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
141
+ "model.layers.18.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
142
+ "model.layers.18.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
143
+ "model.layers.18.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
144
+ "model.layers.19.input_layernorm.weight": "model-00003-of-00004.safetensors",
145
+ "model.layers.19.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
146
+ "model.layers.19.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
147
+ "model.layers.19.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
148
+ "model.layers.19.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
149
+ "model.layers.19.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
150
+ "model.layers.19.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
151
+ "model.layers.19.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
152
+ "model.layers.19.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
153
+ "model.layers.19.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
154
+ "model.layers.19.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
155
+ "model.layers.19.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
156
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00004.safetensors",
157
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
158
+ "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
159
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
160
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
161
+ "model.layers.2.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
162
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
163
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
164
+ "model.layers.2.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
165
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
166
+ "model.layers.2.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
167
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
168
+ "model.layers.20.input_layernorm.weight": "model-00003-of-00004.safetensors",
169
+ "model.layers.20.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
170
+ "model.layers.20.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
171
+ "model.layers.20.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
172
+ "model.layers.20.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
173
+ "model.layers.20.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
174
+ "model.layers.20.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
175
+ "model.layers.20.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
176
+ "model.layers.20.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
177
+ "model.layers.20.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
178
+ "model.layers.20.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
179
+ "model.layers.20.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
180
+ "model.layers.21.input_layernorm.weight": "model-00003-of-00004.safetensors",
181
+ "model.layers.21.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
182
+ "model.layers.21.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
183
+ "model.layers.21.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
184
+ "model.layers.21.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
185
+ "model.layers.21.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
186
+ "model.layers.21.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
187
+ "model.layers.21.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
188
+ "model.layers.21.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
189
+ "model.layers.21.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
190
+ "model.layers.21.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
191
+ "model.layers.21.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
192
+ "model.layers.22.input_layernorm.weight": "model-00003-of-00004.safetensors",
193
+ "model.layers.22.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
194
+ "model.layers.22.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
195
+ "model.layers.22.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
196
+ "model.layers.22.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
197
+ "model.layers.22.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
198
+ "model.layers.22.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
199
+ "model.layers.22.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
200
+ "model.layers.22.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
201
+ "model.layers.22.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
202
+ "model.layers.22.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
203
+ "model.layers.22.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
204
+ "model.layers.23.input_layernorm.weight": "model-00003-of-00004.safetensors",
205
+ "model.layers.23.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
206
+ "model.layers.23.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
207
+ "model.layers.23.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
208
+ "model.layers.23.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
209
+ "model.layers.23.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
210
+ "model.layers.23.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
211
+ "model.layers.23.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
212
+ "model.layers.23.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
213
+ "model.layers.23.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
214
+ "model.layers.23.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
215
+ "model.layers.23.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
216
+ "model.layers.24.input_layernorm.weight": "model-00003-of-00004.safetensors",
217
+ "model.layers.24.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
218
+ "model.layers.24.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
219
+ "model.layers.24.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
220
+ "model.layers.24.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
221
+ "model.layers.24.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
222
+ "model.layers.24.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
223
+ "model.layers.24.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
224
+ "model.layers.24.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
225
+ "model.layers.24.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
226
+ "model.layers.24.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
227
+ "model.layers.24.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
228
+ "model.layers.25.input_layernorm.weight": "model-00003-of-00004.safetensors",
229
+ "model.layers.25.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
230
+ "model.layers.25.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
231
+ "model.layers.25.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
232
+ "model.layers.25.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
233
+ "model.layers.25.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
234
+ "model.layers.25.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
235
+ "model.layers.25.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
236
+ "model.layers.25.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
237
+ "model.layers.25.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
238
+ "model.layers.25.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
239
+ "model.layers.25.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
240
+ "model.layers.26.input_layernorm.weight": "model-00004-of-00004.safetensors",
241
+ "model.layers.26.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
242
+ "model.layers.26.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
243
+ "model.layers.26.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
244
+ "model.layers.26.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
245
+ "model.layers.26.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
246
+ "model.layers.26.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
247
+ "model.layers.26.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
248
+ "model.layers.26.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
249
+ "model.layers.26.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
250
+ "model.layers.26.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
251
+ "model.layers.26.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
252
+ "model.layers.27.input_layernorm.weight": "model-00004-of-00004.safetensors",
253
+ "model.layers.27.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
254
+ "model.layers.27.mlp.gate_proj.weight": "model-00004-of-00004.safetensors",
255
+ "model.layers.27.mlp.up_proj.weight": "model-00004-of-00004.safetensors",
256
+ "model.layers.27.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
257
+ "model.layers.27.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
258
+ "model.layers.27.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
259
+ "model.layers.27.self_attn.o_proj.weight": "model-00004-of-00004.safetensors",
260
+ "model.layers.27.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
261
+ "model.layers.27.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
262
+ "model.layers.27.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
263
+ "model.layers.27.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
264
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00004.safetensors",
265
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
266
+ "model.layers.3.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
267
+ "model.layers.3.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
268
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
269
+ "model.layers.3.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
270
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
271
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
272
+ "model.layers.3.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
273
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
274
+ "model.layers.3.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
275
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
276
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00004.safetensors",
277
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
278
+ "model.layers.4.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
279
+ "model.layers.4.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
280
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
281
+ "model.layers.4.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
282
+ "model.layers.4.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
283
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
284
+ "model.layers.4.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
285
+ "model.layers.4.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
286
+ "model.layers.4.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
287
+ "model.layers.4.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
288
+ "model.layers.5.input_layernorm.weight": "model-00002-of-00004.safetensors",
289
+ "model.layers.5.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
290
+ "model.layers.5.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
291
+ "model.layers.5.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
292
+ "model.layers.5.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
293
+ "model.layers.5.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
294
+ "model.layers.5.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
295
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
296
+ "model.layers.5.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
297
+ "model.layers.5.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
298
+ "model.layers.5.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
299
+ "model.layers.5.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
300
+ "model.layers.6.input_layernorm.weight": "model-00002-of-00004.safetensors",
301
+ "model.layers.6.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
302
+ "model.layers.6.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
303
+ "model.layers.6.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
304
+ "model.layers.6.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
305
+ "model.layers.6.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
306
+ "model.layers.6.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
307
+ "model.layers.6.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
308
+ "model.layers.6.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
309
+ "model.layers.6.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
310
+ "model.layers.6.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
311
+ "model.layers.6.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
312
+ "model.layers.7.input_layernorm.weight": "model-00002-of-00004.safetensors",
313
+ "model.layers.7.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
314
+ "model.layers.7.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
315
+ "model.layers.7.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
316
+ "model.layers.7.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
317
+ "model.layers.7.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
318
+ "model.layers.7.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
319
+ "model.layers.7.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
320
+ "model.layers.7.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
321
+ "model.layers.7.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
322
+ "model.layers.7.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
323
+ "model.layers.7.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
324
+ "model.layers.8.input_layernorm.weight": "model-00002-of-00004.safetensors",
325
+ "model.layers.8.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
326
+ "model.layers.8.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
327
+ "model.layers.8.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
328
+ "model.layers.8.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
329
+ "model.layers.8.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
330
+ "model.layers.8.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
331
+ "model.layers.8.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
332
+ "model.layers.8.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
333
+ "model.layers.8.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
334
+ "model.layers.8.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
335
+ "model.layers.8.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
336
+ "model.layers.9.input_layernorm.weight": "model-00002-of-00004.safetensors",
337
+ "model.layers.9.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
338
+ "model.layers.9.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
339
+ "model.layers.9.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
340
+ "model.layers.9.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
341
+ "model.layers.9.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
342
+ "model.layers.9.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
343
+ "model.layers.9.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
344
+ "model.layers.9.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
345
+ "model.layers.9.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
346
+ "model.layers.9.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
347
+ "model.layers.9.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
348
+ "model.norm.weight": "model-00004-of-00004.safetensors",
349
+ "visual.blocks.0.attn.proj.bias": "model-00001-of-00004.safetensors",
350
+ "visual.blocks.0.attn.proj.weight": "model-00001-of-00004.safetensors",
351
+ "visual.blocks.0.attn.qkv.bias": "model-00001-of-00004.safetensors",
352
+ "visual.blocks.0.attn.qkv.weight": "model-00001-of-00004.safetensors",
353
+ "visual.blocks.0.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
354
+ "visual.blocks.0.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
355
+ "visual.blocks.0.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
356
+ "visual.blocks.0.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
357
+ "visual.blocks.0.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
358
+ "visual.blocks.0.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
359
+ "visual.blocks.0.norm1.weight": "model-00001-of-00004.safetensors",
360
+ "visual.blocks.0.norm2.weight": "model-00001-of-00004.safetensors",
361
+ "visual.blocks.1.attn.proj.bias": "model-00001-of-00004.safetensors",
362
+ "visual.blocks.1.attn.proj.weight": "model-00001-of-00004.safetensors",
363
+ "visual.blocks.1.attn.qkv.bias": "model-00001-of-00004.safetensors",
364
+ "visual.blocks.1.attn.qkv.weight": "model-00001-of-00004.safetensors",
365
+ "visual.blocks.1.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
366
+ "visual.blocks.1.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
367
+ "visual.blocks.1.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
368
+ "visual.blocks.1.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
369
+ "visual.blocks.1.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
370
+ "visual.blocks.1.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
371
+ "visual.blocks.1.norm1.weight": "model-00001-of-00004.safetensors",
372
+ "visual.blocks.1.norm2.weight": "model-00001-of-00004.safetensors",
373
+ "visual.blocks.10.attn.proj.bias": "model-00001-of-00004.safetensors",
374
+ "visual.blocks.10.attn.proj.weight": "model-00001-of-00004.safetensors",
375
+ "visual.blocks.10.attn.qkv.bias": "model-00001-of-00004.safetensors",
376
+ "visual.blocks.10.attn.qkv.weight": "model-00001-of-00004.safetensors",
377
+ "visual.blocks.10.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
378
+ "visual.blocks.10.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
379
+ "visual.blocks.10.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
380
+ "visual.blocks.10.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
381
+ "visual.blocks.10.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
382
+ "visual.blocks.10.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
383
+ "visual.blocks.10.norm1.weight": "model-00001-of-00004.safetensors",
384
+ "visual.blocks.10.norm2.weight": "model-00001-of-00004.safetensors",
385
+ "visual.blocks.11.attn.proj.bias": "model-00001-of-00004.safetensors",
386
+ "visual.blocks.11.attn.proj.weight": "model-00001-of-00004.safetensors",
387
+ "visual.blocks.11.attn.qkv.bias": "model-00001-of-00004.safetensors",
388
+ "visual.blocks.11.attn.qkv.weight": "model-00001-of-00004.safetensors",
389
+ "visual.blocks.11.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
390
+ "visual.blocks.11.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
391
+ "visual.blocks.11.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
392
+ "visual.blocks.11.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
393
+ "visual.blocks.11.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
394
+ "visual.blocks.11.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
395
+ "visual.blocks.11.norm1.weight": "model-00001-of-00004.safetensors",
396
+ "visual.blocks.11.norm2.weight": "model-00001-of-00004.safetensors",
397
+ "visual.blocks.12.attn.proj.bias": "model-00001-of-00004.safetensors",
398
+ "visual.blocks.12.attn.proj.weight": "model-00001-of-00004.safetensors",
399
+ "visual.blocks.12.attn.qkv.bias": "model-00001-of-00004.safetensors",
400
+ "visual.blocks.12.attn.qkv.weight": "model-00001-of-00004.safetensors",
401
+ "visual.blocks.12.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
402
+ "visual.blocks.12.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
403
+ "visual.blocks.12.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
404
+ "visual.blocks.12.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
405
+ "visual.blocks.12.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
406
+ "visual.blocks.12.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
407
+ "visual.blocks.12.norm1.weight": "model-00001-of-00004.safetensors",
408
+ "visual.blocks.12.norm2.weight": "model-00001-of-00004.safetensors",
409
+ "visual.blocks.13.attn.proj.bias": "model-00001-of-00004.safetensors",
410
+ "visual.blocks.13.attn.proj.weight": "model-00001-of-00004.safetensors",
411
+ "visual.blocks.13.attn.qkv.bias": "model-00001-of-00004.safetensors",
412
+ "visual.blocks.13.attn.qkv.weight": "model-00001-of-00004.safetensors",
413
+ "visual.blocks.13.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
414
+ "visual.blocks.13.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
415
+ "visual.blocks.13.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
416
+ "visual.blocks.13.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
417
+ "visual.blocks.13.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
418
+ "visual.blocks.13.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
419
+ "visual.blocks.13.norm1.weight": "model-00001-of-00004.safetensors",
420
+ "visual.blocks.13.norm2.weight": "model-00001-of-00004.safetensors",
421
+ "visual.blocks.14.attn.proj.bias": "model-00001-of-00004.safetensors",
422
+ "visual.blocks.14.attn.proj.weight": "model-00001-of-00004.safetensors",
423
+ "visual.blocks.14.attn.qkv.bias": "model-00001-of-00004.safetensors",
424
+ "visual.blocks.14.attn.qkv.weight": "model-00001-of-00004.safetensors",
425
+ "visual.blocks.14.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
426
+ "visual.blocks.14.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
427
+ "visual.blocks.14.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
428
+ "visual.blocks.14.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
429
+ "visual.blocks.14.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
430
+ "visual.blocks.14.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
431
+ "visual.blocks.14.norm1.weight": "model-00001-of-00004.safetensors",
432
+ "visual.blocks.14.norm2.weight": "model-00001-of-00004.safetensors",
433
+ "visual.blocks.15.attn.proj.bias": "model-00001-of-00004.safetensors",
434
+ "visual.blocks.15.attn.proj.weight": "model-00001-of-00004.safetensors",
435
+ "visual.blocks.15.attn.qkv.bias": "model-00001-of-00004.safetensors",
436
+ "visual.blocks.15.attn.qkv.weight": "model-00001-of-00004.safetensors",
437
+ "visual.blocks.15.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
438
+ "visual.blocks.15.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
439
+ "visual.blocks.15.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
440
+ "visual.blocks.15.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
441
+ "visual.blocks.15.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
442
+ "visual.blocks.15.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
443
+ "visual.blocks.15.norm1.weight": "model-00001-of-00004.safetensors",
444
+ "visual.blocks.15.norm2.weight": "model-00001-of-00004.safetensors",
445
+ "visual.blocks.16.attn.proj.bias": "model-00001-of-00004.safetensors",
446
+ "visual.blocks.16.attn.proj.weight": "model-00001-of-00004.safetensors",
447
+ "visual.blocks.16.attn.qkv.bias": "model-00001-of-00004.safetensors",
448
+ "visual.blocks.16.attn.qkv.weight": "model-00001-of-00004.safetensors",
449
+ "visual.blocks.16.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
450
+ "visual.blocks.16.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
451
+ "visual.blocks.16.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
452
+ "visual.blocks.16.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
453
+ "visual.blocks.16.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
454
+ "visual.blocks.16.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
455
+ "visual.blocks.16.norm1.weight": "model-00001-of-00004.safetensors",
456
+ "visual.blocks.16.norm2.weight": "model-00001-of-00004.safetensors",
457
+ "visual.blocks.17.attn.proj.bias": "model-00001-of-00004.safetensors",
458
+ "visual.blocks.17.attn.proj.weight": "model-00001-of-00004.safetensors",
459
+ "visual.blocks.17.attn.qkv.bias": "model-00001-of-00004.safetensors",
460
+ "visual.blocks.17.attn.qkv.weight": "model-00001-of-00004.safetensors",
461
+ "visual.blocks.17.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
462
+ "visual.blocks.17.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
463
+ "visual.blocks.17.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
464
+ "visual.blocks.17.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
465
+ "visual.blocks.17.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
466
+ "visual.blocks.17.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
467
+ "visual.blocks.17.norm1.weight": "model-00001-of-00004.safetensors",
468
+ "visual.blocks.17.norm2.weight": "model-00001-of-00004.safetensors",
469
+ "visual.blocks.18.attn.proj.bias": "model-00001-of-00004.safetensors",
470
+ "visual.blocks.18.attn.proj.weight": "model-00001-of-00004.safetensors",
471
+ "visual.blocks.18.attn.qkv.bias": "model-00001-of-00004.safetensors",
472
+ "visual.blocks.18.attn.qkv.weight": "model-00001-of-00004.safetensors",
473
+ "visual.blocks.18.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
474
+ "visual.blocks.18.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
475
+ "visual.blocks.18.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
476
+ "visual.blocks.18.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
477
+ "visual.blocks.18.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
478
+ "visual.blocks.18.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
479
+ "visual.blocks.18.norm1.weight": "model-00001-of-00004.safetensors",
480
+ "visual.blocks.18.norm2.weight": "model-00001-of-00004.safetensors",
481
+ "visual.blocks.19.attn.proj.bias": "model-00001-of-00004.safetensors",
482
+ "visual.blocks.19.attn.proj.weight": "model-00001-of-00004.safetensors",
483
+ "visual.blocks.19.attn.qkv.bias": "model-00001-of-00004.safetensors",
484
+ "visual.blocks.19.attn.qkv.weight": "model-00001-of-00004.safetensors",
485
+ "visual.blocks.19.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
486
+ "visual.blocks.19.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
487
+ "visual.blocks.19.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
488
+ "visual.blocks.19.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
489
+ "visual.blocks.19.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
490
+ "visual.blocks.19.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
491
+ "visual.blocks.19.norm1.weight": "model-00001-of-00004.safetensors",
492
+ "visual.blocks.19.norm2.weight": "model-00001-of-00004.safetensors",
493
+ "visual.blocks.2.attn.proj.bias": "model-00001-of-00004.safetensors",
494
+ "visual.blocks.2.attn.proj.weight": "model-00001-of-00004.safetensors",
495
+ "visual.blocks.2.attn.qkv.bias": "model-00001-of-00004.safetensors",
496
+ "visual.blocks.2.attn.qkv.weight": "model-00001-of-00004.safetensors",
497
+ "visual.blocks.2.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
498
+ "visual.blocks.2.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
499
+ "visual.blocks.2.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
500
+ "visual.blocks.2.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
501
+ "visual.blocks.2.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
502
+ "visual.blocks.2.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
503
+ "visual.blocks.2.norm1.weight": "model-00001-of-00004.safetensors",
504
+ "visual.blocks.2.norm2.weight": "model-00001-of-00004.safetensors",
505
+ "visual.blocks.20.attn.proj.bias": "model-00001-of-00004.safetensors",
506
+ "visual.blocks.20.attn.proj.weight": "model-00001-of-00004.safetensors",
507
+ "visual.blocks.20.attn.qkv.bias": "model-00001-of-00004.safetensors",
508
+ "visual.blocks.20.attn.qkv.weight": "model-00001-of-00004.safetensors",
509
+ "visual.blocks.20.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
510
+ "visual.blocks.20.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
511
+ "visual.blocks.20.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
512
+ "visual.blocks.20.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
513
+ "visual.blocks.20.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
514
+ "visual.blocks.20.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
515
+ "visual.blocks.20.norm1.weight": "model-00001-of-00004.safetensors",
516
+ "visual.blocks.20.norm2.weight": "model-00001-of-00004.safetensors",
517
+ "visual.blocks.21.attn.proj.bias": "model-00001-of-00004.safetensors",
518
+ "visual.blocks.21.attn.proj.weight": "model-00001-of-00004.safetensors",
519
+ "visual.blocks.21.attn.qkv.bias": "model-00001-of-00004.safetensors",
520
+ "visual.blocks.21.attn.qkv.weight": "model-00001-of-00004.safetensors",
521
+ "visual.blocks.21.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
522
+ "visual.blocks.21.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
523
+ "visual.blocks.21.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
524
+ "visual.blocks.21.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
525
+ "visual.blocks.21.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
526
+ "visual.blocks.21.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
527
+ "visual.blocks.21.norm1.weight": "model-00001-of-00004.safetensors",
528
+ "visual.blocks.21.norm2.weight": "model-00001-of-00004.safetensors",
529
+ "visual.blocks.22.attn.proj.bias": "model-00001-of-00004.safetensors",
530
+ "visual.blocks.22.attn.proj.weight": "model-00001-of-00004.safetensors",
531
+ "visual.blocks.22.attn.qkv.bias": "model-00001-of-00004.safetensors",
532
+ "visual.blocks.22.attn.qkv.weight": "model-00001-of-00004.safetensors",
533
+ "visual.blocks.22.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
534
+ "visual.blocks.22.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
535
+ "visual.blocks.22.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
536
+ "visual.blocks.22.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
537
+ "visual.blocks.22.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
538
+ "visual.blocks.22.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
539
+ "visual.blocks.22.norm1.weight": "model-00001-of-00004.safetensors",
540
+ "visual.blocks.22.norm2.weight": "model-00001-of-00004.safetensors",
541
+ "visual.blocks.23.attn.proj.bias": "model-00001-of-00004.safetensors",
542
+ "visual.blocks.23.attn.proj.weight": "model-00001-of-00004.safetensors",
543
+ "visual.blocks.23.attn.qkv.bias": "model-00001-of-00004.safetensors",
544
+ "visual.blocks.23.attn.qkv.weight": "model-00001-of-00004.safetensors",
545
+ "visual.blocks.23.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
546
+ "visual.blocks.23.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
547
+ "visual.blocks.23.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
548
+ "visual.blocks.23.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
549
+ "visual.blocks.23.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
550
+ "visual.blocks.23.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
551
+ "visual.blocks.23.norm1.weight": "model-00001-of-00004.safetensors",
552
+ "visual.blocks.23.norm2.weight": "model-00001-of-00004.safetensors",
553
+ "visual.blocks.24.attn.proj.bias": "model-00001-of-00004.safetensors",
554
+ "visual.blocks.24.attn.proj.weight": "model-00001-of-00004.safetensors",
555
+ "visual.blocks.24.attn.qkv.bias": "model-00001-of-00004.safetensors",
556
+ "visual.blocks.24.attn.qkv.weight": "model-00001-of-00004.safetensors",
557
+ "visual.blocks.24.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
558
+ "visual.blocks.24.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
559
+ "visual.blocks.24.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
560
+ "visual.blocks.24.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
561
+ "visual.blocks.24.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
562
+ "visual.blocks.24.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
563
+ "visual.blocks.24.norm1.weight": "model-00001-of-00004.safetensors",
564
+ "visual.blocks.24.norm2.weight": "model-00001-of-00004.safetensors",
565
+ "visual.blocks.25.attn.proj.bias": "model-00001-of-00004.safetensors",
566
+ "visual.blocks.25.attn.proj.weight": "model-00001-of-00004.safetensors",
567
+ "visual.blocks.25.attn.qkv.bias": "model-00001-of-00004.safetensors",
568
+ "visual.blocks.25.attn.qkv.weight": "model-00001-of-00004.safetensors",
569
+ "visual.blocks.25.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
570
+ "visual.blocks.25.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
571
+ "visual.blocks.25.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
572
+ "visual.blocks.25.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
573
+ "visual.blocks.25.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
574
+ "visual.blocks.25.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
575
+ "visual.blocks.25.norm1.weight": "model-00001-of-00004.safetensors",
576
+ "visual.blocks.25.norm2.weight": "model-00001-of-00004.safetensors",
577
+ "visual.blocks.26.attn.proj.bias": "model-00001-of-00004.safetensors",
578
+ "visual.blocks.26.attn.proj.weight": "model-00001-of-00004.safetensors",
579
+ "visual.blocks.26.attn.qkv.bias": "model-00001-of-00004.safetensors",
580
+ "visual.blocks.26.attn.qkv.weight": "model-00001-of-00004.safetensors",
581
+ "visual.blocks.26.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
582
+ "visual.blocks.26.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
583
+ "visual.blocks.26.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
584
+ "visual.blocks.26.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
585
+ "visual.blocks.26.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
586
+ "visual.blocks.26.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
587
+ "visual.blocks.26.norm1.weight": "model-00001-of-00004.safetensors",
588
+ "visual.blocks.26.norm2.weight": "model-00001-of-00004.safetensors",
589
+ "visual.blocks.27.attn.proj.bias": "model-00001-of-00004.safetensors",
590
+ "visual.blocks.27.attn.proj.weight": "model-00001-of-00004.safetensors",
591
+ "visual.blocks.27.attn.qkv.bias": "model-00001-of-00004.safetensors",
592
+ "visual.blocks.27.attn.qkv.weight": "model-00001-of-00004.safetensors",
593
+ "visual.blocks.27.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
594
+ "visual.blocks.27.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
595
+ "visual.blocks.27.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
596
+ "visual.blocks.27.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
597
+ "visual.blocks.27.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
598
+ "visual.blocks.27.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
599
+ "visual.blocks.27.norm1.weight": "model-00001-of-00004.safetensors",
600
+ "visual.blocks.27.norm2.weight": "model-00001-of-00004.safetensors",
601
+ "visual.blocks.28.attn.proj.bias": "model-00001-of-00004.safetensors",
602
+ "visual.blocks.28.attn.proj.weight": "model-00001-of-00004.safetensors",
603
+ "visual.blocks.28.attn.qkv.bias": "model-00001-of-00004.safetensors",
604
+ "visual.blocks.28.attn.qkv.weight": "model-00001-of-00004.safetensors",
605
+ "visual.blocks.28.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
606
+ "visual.blocks.28.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
607
+ "visual.blocks.28.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
608
+ "visual.blocks.28.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
609
+ "visual.blocks.28.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
610
+ "visual.blocks.28.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
611
+ "visual.blocks.28.norm1.weight": "model-00001-of-00004.safetensors",
612
+ "visual.blocks.28.norm2.weight": "model-00001-of-00004.safetensors",
613
+ "visual.blocks.29.attn.proj.bias": "model-00001-of-00004.safetensors",
614
+ "visual.blocks.29.attn.proj.weight": "model-00001-of-00004.safetensors",
615
+ "visual.blocks.29.attn.qkv.bias": "model-00001-of-00004.safetensors",
616
+ "visual.blocks.29.attn.qkv.weight": "model-00001-of-00004.safetensors",
617
+ "visual.blocks.29.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
618
+ "visual.blocks.29.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
619
+ "visual.blocks.29.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
620
+ "visual.blocks.29.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
621
+ "visual.blocks.29.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
622
+ "visual.blocks.29.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
623
+ "visual.blocks.29.norm1.weight": "model-00001-of-00004.safetensors",
624
+ "visual.blocks.29.norm2.weight": "model-00001-of-00004.safetensors",
625
+ "visual.blocks.3.attn.proj.bias": "model-00001-of-00004.safetensors",
626
+ "visual.blocks.3.attn.proj.weight": "model-00001-of-00004.safetensors",
627
+ "visual.blocks.3.attn.qkv.bias": "model-00001-of-00004.safetensors",
628
+ "visual.blocks.3.attn.qkv.weight": "model-00001-of-00004.safetensors",
629
+ "visual.blocks.3.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
630
+ "visual.blocks.3.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
631
+ "visual.blocks.3.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
632
+ "visual.blocks.3.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
633
+ "visual.blocks.3.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
634
+ "visual.blocks.3.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
635
+ "visual.blocks.3.norm1.weight": "model-00001-of-00004.safetensors",
636
+ "visual.blocks.3.norm2.weight": "model-00001-of-00004.safetensors",
637
+ "visual.blocks.30.attn.proj.bias": "model-00001-of-00004.safetensors",
638
+ "visual.blocks.30.attn.proj.weight": "model-00001-of-00004.safetensors",
639
+ "visual.blocks.30.attn.qkv.bias": "model-00001-of-00004.safetensors",
640
+ "visual.blocks.30.attn.qkv.weight": "model-00001-of-00004.safetensors",
641
+ "visual.blocks.30.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
642
+ "visual.blocks.30.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
643
+ "visual.blocks.30.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
644
+ "visual.blocks.30.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
645
+ "visual.blocks.30.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
646
+ "visual.blocks.30.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
647
+ "visual.blocks.30.norm1.weight": "model-00001-of-00004.safetensors",
648
+ "visual.blocks.30.norm2.weight": "model-00001-of-00004.safetensors",
649
+ "visual.blocks.31.attn.proj.bias": "model-00001-of-00004.safetensors",
650
+ "visual.blocks.31.attn.proj.weight": "model-00001-of-00004.safetensors",
651
+ "visual.blocks.31.attn.qkv.bias": "model-00001-of-00004.safetensors",
652
+ "visual.blocks.31.attn.qkv.weight": "model-00001-of-00004.safetensors",
653
+ "visual.blocks.31.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
654
+ "visual.blocks.31.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
655
+ "visual.blocks.31.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
656
+ "visual.blocks.31.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
657
+ "visual.blocks.31.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
658
+ "visual.blocks.31.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
659
+ "visual.blocks.31.norm1.weight": "model-00001-of-00004.safetensors",
660
+ "visual.blocks.31.norm2.weight": "model-00001-of-00004.safetensors",
661
+ "visual.blocks.4.attn.proj.bias": "model-00001-of-00004.safetensors",
662
+ "visual.blocks.4.attn.proj.weight": "model-00001-of-00004.safetensors",
663
+ "visual.blocks.4.attn.qkv.bias": "model-00001-of-00004.safetensors",
664
+ "visual.blocks.4.attn.qkv.weight": "model-00001-of-00004.safetensors",
665
+ "visual.blocks.4.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
666
+ "visual.blocks.4.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
667
+ "visual.blocks.4.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
668
+ "visual.blocks.4.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
669
+ "visual.blocks.4.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
670
+ "visual.blocks.4.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
671
+ "visual.blocks.4.norm1.weight": "model-00001-of-00004.safetensors",
672
+ "visual.blocks.4.norm2.weight": "model-00001-of-00004.safetensors",
673
+ "visual.blocks.5.attn.proj.bias": "model-00001-of-00004.safetensors",
674
+ "visual.blocks.5.attn.proj.weight": "model-00001-of-00004.safetensors",
675
+ "visual.blocks.5.attn.qkv.bias": "model-00001-of-00004.safetensors",
676
+ "visual.blocks.5.attn.qkv.weight": "model-00001-of-00004.safetensors",
677
+ "visual.blocks.5.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
678
+ "visual.blocks.5.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
679
+ "visual.blocks.5.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
680
+ "visual.blocks.5.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
681
+ "visual.blocks.5.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
682
+ "visual.blocks.5.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
683
+ "visual.blocks.5.norm1.weight": "model-00001-of-00004.safetensors",
684
+ "visual.blocks.5.norm2.weight": "model-00001-of-00004.safetensors",
685
+ "visual.blocks.6.attn.proj.bias": "model-00001-of-00004.safetensors",
686
+ "visual.blocks.6.attn.proj.weight": "model-00001-of-00004.safetensors",
687
+ "visual.blocks.6.attn.qkv.bias": "model-00001-of-00004.safetensors",
688
+ "visual.blocks.6.attn.qkv.weight": "model-00001-of-00004.safetensors",
689
+ "visual.blocks.6.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
690
+ "visual.blocks.6.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
691
+ "visual.blocks.6.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
692
+ "visual.blocks.6.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
693
+ "visual.blocks.6.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
694
+ "visual.blocks.6.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
695
+ "visual.blocks.6.norm1.weight": "model-00001-of-00004.safetensors",
696
+ "visual.blocks.6.norm2.weight": "model-00001-of-00004.safetensors",
697
+ "visual.blocks.7.attn.proj.bias": "model-00001-of-00004.safetensors",
698
+ "visual.blocks.7.attn.proj.weight": "model-00001-of-00004.safetensors",
699
+ "visual.blocks.7.attn.qkv.bias": "model-00001-of-00004.safetensors",
700
+ "visual.blocks.7.attn.qkv.weight": "model-00001-of-00004.safetensors",
701
+ "visual.blocks.7.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
702
+ "visual.blocks.7.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
703
+ "visual.blocks.7.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
704
+ "visual.blocks.7.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
705
+ "visual.blocks.7.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
706
+ "visual.blocks.7.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
707
+ "visual.blocks.7.norm1.weight": "model-00001-of-00004.safetensors",
708
+ "visual.blocks.7.norm2.weight": "model-00001-of-00004.safetensors",
709
+ "visual.blocks.8.attn.proj.bias": "model-00001-of-00004.safetensors",
710
+ "visual.blocks.8.attn.proj.weight": "model-00001-of-00004.safetensors",
711
+ "visual.blocks.8.attn.qkv.bias": "model-00001-of-00004.safetensors",
712
+ "visual.blocks.8.attn.qkv.weight": "model-00001-of-00004.safetensors",
713
+ "visual.blocks.8.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
714
+ "visual.blocks.8.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
715
+ "visual.blocks.8.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
716
+ "visual.blocks.8.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
717
+ "visual.blocks.8.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
718
+ "visual.blocks.8.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
719
+ "visual.blocks.8.norm1.weight": "model-00001-of-00004.safetensors",
720
+ "visual.blocks.8.norm2.weight": "model-00001-of-00004.safetensors",
721
+ "visual.blocks.9.attn.proj.bias": "model-00001-of-00004.safetensors",
722
+ "visual.blocks.9.attn.proj.weight": "model-00001-of-00004.safetensors",
723
+ "visual.blocks.9.attn.qkv.bias": "model-00001-of-00004.safetensors",
724
+ "visual.blocks.9.attn.qkv.weight": "model-00001-of-00004.safetensors",
725
+ "visual.blocks.9.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
726
+ "visual.blocks.9.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
727
+ "visual.blocks.9.mlp.gate_proj.bias": "model-00001-of-00004.safetensors",
728
+ "visual.blocks.9.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
729
+ "visual.blocks.9.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
730
+ "visual.blocks.9.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
731
+ "visual.blocks.9.norm1.weight": "model-00001-of-00004.safetensors",
732
+ "visual.blocks.9.norm2.weight": "model-00001-of-00004.safetensors",
733
+ "visual.merger.ln_q.weight": "model-00001-of-00004.safetensors",
734
+ "visual.merger.mlp.0.bias": "model-00001-of-00004.safetensors",
735
+ "visual.merger.mlp.0.weight": "model-00001-of-00004.safetensors",
736
+ "visual.merger.mlp.2.bias": "model-00001-of-00004.safetensors",
737
+ "visual.merger.mlp.2.weight": "model-00001-of-00004.safetensors",
738
+ "visual.patch_embed.proj.weight": "model-00001-of-00004.safetensors"
739
+ }
740
+ }
modeling_dimple.py ADDED
@@ -0,0 +1,1872 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Dimple team 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 Dimple model."""
21
+
22
+ import math, os
23
+ from dataclasses import dataclass
24
+ from typing import Any, Dict, List, Optional, Tuple, Union
25
+
26
+ import torch
27
+ import torch.nn as nn
28
+ import torch.nn.functional as F
29
+ import torch.utils.checkpoint
30
+ from torch.nn import CrossEntropyLoss, LayerNorm
31
+
32
+ from transformers.activations import ACT2FN
33
+ from transformers.cache_utils import Cache, SlidingWindowCache, StaticCache, DynamicCache
34
+ from transformers.modeling_outputs import (
35
+ BaseModelOutputWithPast,
36
+ ModelOutput,
37
+ BaseModelOutput,
38
+ MaskedLMOutput,
39
+ )
40
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
41
+ from transformers.modeling_utils import PreTrainedModel
42
+ from transformers.utils import (
43
+ add_start_docstrings,
44
+ add_start_docstrings_to_model_forward,
45
+ is_flash_attn_2_available,
46
+ is_flash_attn_greater_or_equal_2_10,
47
+ logging,
48
+ replace_return_docstrings,
49
+ )
50
+ from transformers import PretrainedConfig
51
+
52
+ from transformers.modeling_attn_mask_utils import (
53
+ AttentionMaskConverter,
54
+ )
55
+
56
+ from .configuration_dimple import DimpleConfig, DimpleVisionConfig
57
+ from .generation_utils import DimpleGenerationMixin, DimpleGenerationConfig
58
+
59
+
60
+ if is_flash_attn_2_available():
61
+ from flash_attn import flash_attn_varlen_func
62
+
63
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
64
+ else:
65
+ flash_attn_varlen_func = None
66
+
67
+
68
+ logger = logging.get_logger("Dimple."+__name__)
69
+
70
+ _CHECKPOINT_FOR_DOC = "Dimple-7B"
71
+ _CONFIG_FOR_DOC = "DimpleConfig"
72
+
73
+ @dataclass
74
+ class DimpleModelOutput(ModelOutput):
75
+ """
76
+ Base class for Dimple outputs.
77
+
78
+ Args:
79
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
80
+ Language modeling loss (for next-token prediction).
81
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
82
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
83
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
84
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
85
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
86
+
87
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
88
+ `past_key_values` input) to speed up sequential decoding.
89
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
90
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
91
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
92
+
93
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
94
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
95
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
96
+ sequence_length)`.
97
+
98
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
99
+ heads.
100
+ rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
101
+ The rope index difference between sequence length and multimodal rope.
102
+ """
103
+
104
+ logits: torch.FloatTensor = None
105
+ loss: Optional[torch.FloatTensor] = None
106
+ past_key_values: Optional[List[torch.FloatTensor]] = None
107
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
108
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
109
+ rope_deltas: Optional[torch.LongTensor] = None
110
+
111
+
112
+ class DimpleRotaryEmbedding(nn.Module):
113
+ def __init__(
114
+ self,
115
+ dim=None,
116
+ max_position_embeddings=2048,
117
+ base=10000,
118
+ device=None,
119
+ scaling_factor=1.0,
120
+ rope_type="default",
121
+ config: Optional[DimpleConfig] = None,
122
+ ):
123
+ super().__init__()
124
+ # TODO (joao): remove the `if` below, only used for BC
125
+ self.rope_kwargs = {}
126
+ if config is None:
127
+ logger.warning_once(
128
+ "`DimpleRotaryEmbedding` can now be fully parameterized by passing the model config through the "
129
+ "`config` argument. All other arguments will be removed in v4.46"
130
+ )
131
+ self.rope_kwargs = {
132
+ "rope_type": rope_type,
133
+ "factor": scaling_factor,
134
+ "dim": dim,
135
+ "base": base,
136
+ "max_position_embeddings": max_position_embeddings,
137
+ }
138
+ self.rope_type = rope_type
139
+ self.max_seq_len_cached = max_position_embeddings
140
+ self.original_max_seq_len = max_position_embeddings
141
+ else:
142
+ # BC: "rope_type" was originally "type"
143
+ if config.rope_scaling is not None:
144
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
145
+ else:
146
+ self.rope_type = "default"
147
+ self.max_seq_len_cached = config.max_position_embeddings
148
+ self.original_max_seq_len = config.max_position_embeddings
149
+
150
+ self.config = config
151
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
152
+
153
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
154
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
155
+ self.original_inv_freq = self.inv_freq
156
+
157
+ def reset_parameters(self):
158
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, self.inv_freq.device, **self.rope_kwargs)
159
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
160
+ self.original_inv_freq = self.inv_freq
161
+
162
+
163
+ def _dynamic_frequency_update(self, position_ids, device):
164
+ """
165
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
166
+ 1 - growing beyond the cached sequence length (allow scaling)
167
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
168
+ """
169
+ seq_len = torch.max(position_ids) + 1
170
+ if seq_len > self.max_seq_len_cached: # growth
171
+ inv_freq, self.attention_scaling = self.rope_init_fn(
172
+ self.config, device, seq_len=seq_len, **self.rope_kwargs
173
+ )
174
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
175
+ self.max_seq_len_cached = seq_len
176
+
177
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
178
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
179
+ self.max_seq_len_cached = self.original_max_seq_len
180
+
181
+ @torch.no_grad()
182
+ def forward(self, x, position_ids):
183
+ if "dynamic" in self.rope_type:
184
+ self._dynamic_frequency_update(position_ids, device=x.device)
185
+
186
+ # Core RoPE block. In contrast to other models, Dimple has different position ids for thw grids
187
+ # So we expand the inv_freq to shape (3, ...)
188
+ inv_freq_expanded = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1)
189
+ position_ids_expanded = position_ids[:, :, None, :].float() # shape (3, bs, 1, positions)
190
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
191
+ device_type = x.device.type
192
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
193
+ with torch.autocast(device_type=device_type, enabled=False):
194
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3)
195
+ emb = torch.cat((freqs, freqs), dim=-1)
196
+ cos = emb.cos()
197
+ sin = emb.sin()
198
+
199
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
200
+ cos = cos * self.attention_scaling
201
+ sin = sin * self.attention_scaling
202
+
203
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
204
+
205
+ # Copied from transformers.models.qwen2.modeling_qwen2.Qwen2RMSNorm
206
+ class DimpleRMSNorm(nn.Module):
207
+ def __init__(self, hidden_size, eps=1e-6):
208
+ """
209
+ DimpleRMSNorm is equivalent to T5LayerNorm
210
+ """
211
+ super().__init__()
212
+ self.weight = nn.Parameter(torch.ones(hidden_size))
213
+ self.variance_epsilon = eps
214
+
215
+ def forward(self, hidden_states):
216
+ input_dtype = hidden_states.dtype
217
+ hidden_states = hidden_states.to(torch.float32)
218
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
219
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
220
+ return self.weight * hidden_states.to(input_dtype)
221
+
222
+ def extra_repr(self):
223
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
224
+
225
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
226
+ def rotate_half(x):
227
+ """Rotates half the hidden dims of the input."""
228
+ x1 = x[..., : x.shape[-1] // 2]
229
+ x2 = x[..., x.shape[-1] // 2 :]
230
+ return torch.cat((-x2, x1), dim=-1)
231
+
232
+
233
+ def apply_multimodal_rotary_pos_emb(q, k, cos, sin, mrope_section, unsqueeze_dim=1):
234
+ """Applies Rotary Position Embedding with Multimodal Sections to the query and key tensors (https://qwenlm.github.io/blog/qwen2-vl/).
235
+
236
+ Explanation:
237
+ Multimodal 3D rotary position embedding is an extension to 1D rotary position embedding. The input embedding
238
+ sequence contains vision (images / videos) embedding and text embedding or just contains text embedding. For
239
+ vision embedding part, we apply rotary position embedding on temporal, height and width dimension seperately.
240
+ Here we split the channel dimension to 3 chunks for the temporal, height and width rotary position embedding.
241
+ For text embedding part, we just apply 1D rotary position embedding. The three rotary position index (temporal,
242
+ height and width) of text embedding is always the same, so the text embedding rotary position embedding has no
243
+ difference with modern LLMs.
244
+
245
+ Args:
246
+ q (`torch.Tensor`): The query tensor.
247
+ k (`torch.Tensor`): The key tensor.
248
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
249
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
250
+ position_ids (`torch.Tensor`):
251
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
252
+ used to pass offsetted position ids when working with a KV-cache.
253
+ mrope_section(`List(int)`):
254
+ Multimodal rope section is for channel dimension of temporal, height and width in rope calculation.
255
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
256
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
257
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
258
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
259
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
260
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
261
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
262
+ Returns:
263
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
264
+ """
265
+ mrope_section = mrope_section * 2
266
+ cos = torch.cat([m[i % 3] for i, m in enumerate(cos.split(mrope_section, dim=-1))], dim=-1).unsqueeze(
267
+ unsqueeze_dim
268
+ )
269
+ sin = torch.cat([m[i % 3] for i, m in enumerate(sin.split(mrope_section, dim=-1))], dim=-1).unsqueeze(
270
+ unsqueeze_dim
271
+ )
272
+
273
+ q_embed = (q * cos) + (rotate_half(q) * sin)
274
+ k_embed = (k * cos) + (rotate_half(k) * sin)
275
+ return q_embed, k_embed
276
+
277
+
278
+ def apply_rotary_pos_emb_vision(
279
+ q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor
280
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
281
+ orig_q_dtype = q.dtype
282
+ orig_k_dtype = k.dtype
283
+ q, k = q.float(), k.float()
284
+ cos, sin = cos.unsqueeze(-2).float(), sin.unsqueeze(-2).float()
285
+ q_embed = (q * cos) + (rotate_half(q) * sin)
286
+ k_embed = (k * cos) + (rotate_half(k) * sin)
287
+ q_embed = q_embed.to(orig_q_dtype)
288
+ k_embed = k_embed.to(orig_k_dtype)
289
+ return q_embed, k_embed
290
+
291
+
292
+ class DimpleVisionRotaryEmbedding(nn.Module):
293
+ def __init__(self, dim: int, theta: float = 10000.0) -> None:
294
+ super().__init__()
295
+ inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim))
296
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
297
+
298
+ def forward(self, seqlen: int) -> torch.Tensor:
299
+ seq = torch.arange(seqlen, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
300
+ freqs = torch.outer(seq, self.inv_freq)
301
+ return freqs
302
+
303
+
304
+ class DimpleVisionPatchEmbed(nn.Module):
305
+ def __init__(
306
+ self,
307
+ patch_size: int = 14,
308
+ temporal_patch_size: int = 2,
309
+ in_channels: int = 3,
310
+ embed_dim: int = 1152,
311
+ ) -> None:
312
+ super().__init__()
313
+ self.patch_size = patch_size
314
+ self.temporal_patch_size = temporal_patch_size
315
+ self.in_channels = in_channels
316
+ self.embed_dim = embed_dim
317
+
318
+ kernel_size = [temporal_patch_size, patch_size, patch_size]
319
+ self.proj = nn.Conv3d(in_channels, embed_dim, kernel_size=kernel_size, stride=kernel_size, bias=False)
320
+
321
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
322
+ target_dtype = self.proj.weight.dtype
323
+ hidden_states = hidden_states.view(
324
+ -1, self.in_channels, self.temporal_patch_size, self.patch_size, self.patch_size
325
+ )
326
+ hidden_states = self.proj(hidden_states.to(dtype=target_dtype)).view(-1, self.embed_dim)
327
+ return hidden_states
328
+
329
+
330
+ class DimplePatchMerger(nn.Module):
331
+ def __init__(self, dim: int, context_dim: int, spatial_merge_size: int = 2) -> None:
332
+ super().__init__()
333
+ self.hidden_size = context_dim * (spatial_merge_size**2)
334
+ self.ln_q = DimpleRMSNorm(context_dim, eps=1e-6)
335
+ self.mlp = nn.Sequential(
336
+ nn.Linear(self.hidden_size, self.hidden_size),
337
+ nn.GELU(),
338
+ nn.Linear(self.hidden_size, dim),
339
+ )
340
+
341
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
342
+ x = self.mlp(self.ln_q(x).view(-1, self.hidden_size))
343
+ return x
344
+
345
+ class DimpleVisionMLP(nn.Module):
346
+ def __init__(self, config, bias: bool = False):
347
+ super().__init__()
348
+ self.hidden_size = config.hidden_size
349
+ self.intermediate_size = config.intermediate_size
350
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=bias)
351
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=bias)
352
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=bias)
353
+ self.act_fn = ACT2FN[config.hidden_act]
354
+
355
+ def forward(self, hidden_state):
356
+ return self.down_proj(self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state))
357
+
358
+ class DimpleVisionAttention(nn.Module):
359
+ def __init__(self, dim: int, num_heads: int = 16) -> None:
360
+ super().__init__()
361
+ self.num_heads = num_heads
362
+ self.head_dim = dim // num_heads
363
+ self.qkv = nn.Linear(dim, dim * 3, bias=True)
364
+ self.proj = nn.Linear(dim, dim)
365
+
366
+ def forward(
367
+ self,
368
+ hidden_states: torch.Tensor,
369
+ cu_seqlens: torch.Tensor,
370
+ rotary_pos_emb: Optional[torch.Tensor] = None,
371
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
372
+ ) -> torch.Tensor:
373
+ seq_length = hidden_states.shape[0]
374
+ q, k, v = self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
375
+ if position_embeddings is None:
376
+ logger.warning_once(
377
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
378
+ "through `rotary_pos_emb` (2D tensor of RoPE theta values), to using externally computed "
379
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.54 `rotary_pos_emb` will be "
380
+ "removed and `position_embeddings` will be mandatory."
381
+ )
382
+ emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1)
383
+ cos = emb.cos()
384
+ sin = emb.sin()
385
+ else:
386
+ cos, sin = position_embeddings
387
+ q, k = apply_rotary_pos_emb_vision(q, k, cos, sin)
388
+
389
+ attention_mask = torch.full(
390
+ [1, seq_length, seq_length], torch.finfo(q.dtype).min, device=q.device, dtype=q.dtype
391
+ )
392
+ for i in range(1, len(cu_seqlens)):
393
+ attention_mask[..., cu_seqlens[i - 1] : cu_seqlens[i], cu_seqlens[i - 1] : cu_seqlens[i]] = 0
394
+
395
+ q = q.transpose(0, 1)
396
+ k = k.transpose(0, 1)
397
+ v = v.transpose(0, 1)
398
+ attn_weights = torch.matmul(q, k.transpose(1, 2)) / math.sqrt(self.head_dim)
399
+ attn_weights = attn_weights + attention_mask
400
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(q.dtype)
401
+ attn_output = torch.matmul(attn_weights, v)
402
+ attn_output = attn_output.transpose(0, 1)
403
+ attn_output = attn_output.reshape(seq_length, -1)
404
+ attn_output = self.proj(attn_output)
405
+ return attn_output
406
+
407
+
408
+ class DimpleVisionFlashAttention2(nn.Module):
409
+ def __init__(self, dim: int, num_heads: int = 16) -> None:
410
+ raise NotImplementedError(
411
+ "FlashAttention2 is not supported in Dimple. Please use the `sdpa` implementation instead."
412
+ )
413
+
414
+
415
+ class DimpleVisionSdpaAttention(nn.Module):
416
+ def __init__(self, dim: int, num_heads: int = 16) -> None:
417
+ super().__init__()
418
+ self.num_heads = num_heads
419
+ self.qkv = nn.Linear(dim, dim * 3, bias=True)
420
+ self.proj = nn.Linear(dim, dim)
421
+
422
+ def forward(
423
+ self,
424
+ hidden_states: torch.Tensor,
425
+ cu_seqlens: torch.Tensor,
426
+ rotary_pos_emb: Optional[torch.Tensor] = None,
427
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
428
+ ) -> torch.Tensor:
429
+ seq_length = hidden_states.shape[0]
430
+ q, k, v = self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
431
+ if position_embeddings is None:
432
+ logger.warning_once(
433
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
434
+ "through `rotary_pos_emb` (2D tensor of RoPE theta values), to using externally computed "
435
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.54 `rotary_pos_emb` will be "
436
+ "removed and `position_embeddings` will be mandatory."
437
+ )
438
+ emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1)
439
+ cos = emb.cos()
440
+ sin = emb.sin()
441
+ else:
442
+ cos, sin = position_embeddings
443
+ q, k = apply_rotary_pos_emb_vision(q, k, cos, sin)
444
+
445
+ attention_mask = torch.zeros([1, seq_length, seq_length], device=q.device, dtype=torch.bool)
446
+ for i in range(1, len(cu_seqlens)):
447
+ attention_mask[..., cu_seqlens[i - 1] : cu_seqlens[i], cu_seqlens[i - 1] : cu_seqlens[i]] = True
448
+ q = q.transpose(0, 1)
449
+ k = k.transpose(0, 1)
450
+ v = v.transpose(0, 1)
451
+ attn_output = F.scaled_dot_product_attention(
452
+ q.unsqueeze(0), k.unsqueeze(0), v.unsqueeze(0), attention_mask, dropout_p=0.0
453
+ )
454
+ attn_output = attn_output.squeeze(0).transpose(0, 1)
455
+ attn_output = attn_output.reshape(seq_length, -1)
456
+ attn_output = self.proj(attn_output)
457
+ return attn_output
458
+
459
+
460
+ DIMPLE_VISION_ATTENTION_CLASSES = {
461
+ "eager": DimpleVisionAttention,
462
+ # "flash_attention_2": DimpleVisionFlashAttention2,
463
+ "sdpa": DimpleVisionSdpaAttention,
464
+ }
465
+
466
+
467
+ class DimpleVisionBlock(nn.Module):
468
+ def __init__(self, config, attn_implementation: str = "sdpa") -> None:
469
+ super().__init__()
470
+ self.norm1 = DimpleRMSNorm(config.hidden_size, eps=1e-6)
471
+ self.norm2 = DimpleRMSNorm(config.hidden_size, eps=1e-6)
472
+ self.attn = DIMPLE_VISION_ATTENTION_CLASSES[attn_implementation](
473
+ config.hidden_size, num_heads=config.num_heads
474
+ )
475
+ self.mlp = DimpleVisionMLP(config, bias=True)
476
+
477
+ def forward(
478
+ self,
479
+ hidden_states: torch.Tensor,
480
+ cu_seqlens: torch.Tensor,
481
+ rotary_pos_emb: Optional[torch.Tensor] = None,
482
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
483
+ ) -> torch.Tensor:
484
+ hidden_states = hidden_states + self.attn(
485
+ self.norm1(hidden_states),
486
+ cu_seqlens=cu_seqlens,
487
+ rotary_pos_emb=rotary_pos_emb,
488
+ position_embeddings=position_embeddings,
489
+ )
490
+ hidden_states = hidden_states + self.mlp(self.norm2(hidden_states))
491
+ return hidden_states
492
+
493
+
494
+ # Copied from transformers.models.qwen2.modeling_qwen2.Qwen2MLP
495
+ class DimpleMLP(nn.Module):
496
+ def __init__(self, config):
497
+ super().__init__()
498
+ self.hidden_size = config.hidden_size
499
+ self.intermediate_size = config.intermediate_size
500
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
501
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
502
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
503
+ self.act_fn = ACT2FN[config.hidden_act]
504
+
505
+ def forward(self, hidden_state):
506
+ return self.down_proj(self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state))
507
+
508
+
509
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
510
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
511
+ """
512
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
513
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
514
+ """
515
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
516
+ if n_rep == 1:
517
+ return hidden_states
518
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
519
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
520
+
521
+
522
+ class DimpleAttention(nn.Module):
523
+ """
524
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
525
+ and "Generating Long Sequences with Sparse Transformers".
526
+ """
527
+
528
+ def __init__(self, config: DimpleConfig, layer_idx: Optional[int] = None):
529
+ super().__init__()
530
+ self.config = config
531
+ self.layer_idx = layer_idx
532
+ if layer_idx is None:
533
+ logger.warning_once(
534
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
535
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
536
+ "when creating this class."
537
+ )
538
+
539
+ self.hidden_size = config.hidden_size
540
+ self.num_heads = config.num_attention_heads
541
+ self.head_dim = self.hidden_size // self.num_heads
542
+ self.num_key_value_heads = config.num_key_value_heads
543
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
544
+ self.max_position_embeddings = config.max_position_embeddings
545
+ self.rope_theta = config.rope_theta
546
+ self.is_causal = False # not used in Dream
547
+ self.attention_dropout = config.attention_dropout
548
+ self.rope_scaling = config.rope_scaling # in Dream rope scaling is None
549
+ self.mrope_section = config.mrope_section
550
+
551
+ if (self.head_dim * self.num_heads) != self.hidden_size:
552
+ raise ValueError(
553
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
554
+ f" and `num_heads`: {self.num_heads})."
555
+ )
556
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
557
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
558
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
559
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
560
+
561
+ # implementaion in Qwen
562
+ # self.rotary_emb = DimpleRotaryEmbedding(
563
+ # self.head_dim,
564
+ # max_position_embeddings=self.max_position_embeddings,
565
+ # base=self.rope_theta,
566
+ # )
567
+ # implementaion in dream, same if configs are same
568
+ self.rotary_emb = DimpleRotaryEmbedding(config=self.config)
569
+
570
+ def forward(
571
+ self,
572
+ hidden_states: torch.Tensor,
573
+ attention_mask: Optional[torch.Tensor] = None,
574
+ position_ids: Optional[torch.LongTensor] = None,
575
+ past_key_value: Optional[Cache] = None,
576
+ output_attentions: bool = False,
577
+ use_cache: bool = False,
578
+ cache_position: Optional[torch.LongTensor] = None,
579
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
580
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
581
+ bsz, q_len, _ = hidden_states.size()
582
+
583
+ query_states = self.q_proj(hidden_states)
584
+ key_states = self.k_proj(hidden_states)
585
+ value_states = self.v_proj(hidden_states)
586
+
587
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
588
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
589
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
590
+
591
+ # not used in Dream
592
+ # kv_seq_len = key_states.shape[-2]
593
+ # if past_key_value is not None:
594
+ # kv_seq_len += cache_position[0] + 1
595
+
596
+ if position_embeddings is None:
597
+ logger.warning_once(
598
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
599
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
600
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
601
+ "removed and `position_embeddings` will be mandatory."
602
+ )
603
+ cos, sin = self.rotary_emb(value_states, position_ids)
604
+ else:
605
+ cos, sin = position_embeddings
606
+ query_states, key_states = apply_multimodal_rotary_pos_emb(
607
+ query_states, key_states, cos, sin, self.mrope_section
608
+ )
609
+
610
+ if past_key_value is not None:
611
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
612
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
613
+
614
+ # repeat k/v heads if n_kv_heads < n_heads
615
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
616
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
617
+
618
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
619
+
620
+ if attention_mask is not None: # no matter the length, we just slice it
621
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
622
+ attn_weights = attn_weights + causal_mask
623
+
624
+ # Fix precision issues in Dimple float16 inference
625
+ # Replace inf values with zeros in attention weights to prevent NaN propagation
626
+ if query_states.dtype == torch.float16:
627
+ attn_weights = torch.where(torch.isinf(attn_weights), torch.zeros_like(attn_weights), attn_weights)
628
+
629
+ # upcast attention to fp32
630
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
631
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
632
+ attn_output = torch.matmul(attn_weights, value_states)
633
+
634
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
635
+ raise ValueError(
636
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
637
+ f" {attn_output.size()}"
638
+ )
639
+
640
+ attn_output = attn_output.transpose(1, 2).contiguous()
641
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
642
+
643
+ attn_output = self.o_proj(attn_output)
644
+
645
+ if not output_attentions:
646
+ attn_weights = None
647
+
648
+ return attn_output, attn_weights, past_key_value
649
+
650
+
651
+ class DimpleFlashAttention2(DimpleAttention):
652
+
653
+ def __init__(self, *args, **kwargs):
654
+ raise NotImplementedError(
655
+ "DimpleFlashAttention2 is not implemented yet. Please use DimpleSdpaAttention instead."
656
+ )
657
+
658
+
659
+ class DimpleSdpaAttention(DimpleAttention):
660
+ """
661
+ Dimple attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
662
+ `DimpleAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
663
+ SDPA API.
664
+ """
665
+
666
+ # Adapted from DimpleAttention.forward
667
+ def forward(
668
+ self,
669
+ hidden_states: torch.Tensor,
670
+ attention_mask: Optional[torch.Tensor] = None,
671
+ position_ids: Optional[torch.LongTensor] = None,
672
+ past_key_value: Optional[Cache] = None,
673
+ output_attentions: bool = False,
674
+ use_cache: bool = False,
675
+ cache_position: Optional[torch.LongTensor] = None,
676
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
677
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
678
+ if output_attentions:
679
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
680
+ Dimple.warning_once(
681
+ "DimpleModel is using DimpleSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
682
+ '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.'
683
+ )
684
+ return super().forward(
685
+ hidden_states=hidden_states,
686
+ attention_mask=attention_mask,
687
+ position_ids=position_ids,
688
+ past_key_value=past_key_value,
689
+ output_attentions=output_attentions,
690
+ use_cache=use_cache,
691
+ # cache_position=cache_position, # not used in Dream
692
+ )
693
+
694
+ bsz, q_len, _ = hidden_states.size()
695
+
696
+ query_states = self.q_proj(hidden_states)
697
+ key_states = self.k_proj(hidden_states)
698
+ value_states = self.v_proj(hidden_states)
699
+
700
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
701
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
702
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
703
+
704
+ # not used in Dream
705
+ # kv_seq_len = key_states.shape[-2]
706
+ # if past_key_value is not None:
707
+ # kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
708
+ if position_embeddings is None:
709
+ logger.warning_once(
710
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
711
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
712
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
713
+ "removed and `position_embeddings` will be mandatory."
714
+ )
715
+ cos, sin = self.rotary_emb(value_states, position_ids)
716
+ else:
717
+ cos, sin = position_embeddings
718
+ query_states, key_states = apply_multimodal_rotary_pos_emb(
719
+ query_states, key_states, cos, sin, self.mrope_section
720
+ )
721
+
722
+ if past_key_value is not None:
723
+ logger.warning_once(
724
+ f"In {self.__class__}, cache is used."
725
+ )
726
+ # print("cache is used")
727
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
728
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
729
+
730
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
731
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
732
+
733
+ # not used in Dream
734
+ # causal_mask = attention_mask
735
+ # if attention_mask is not None: # no matter the length, we just slice it
736
+ # causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
737
+
738
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
739
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
740
+ if query_states.device.type == "cuda" and attention_mask is not None:
741
+ query_states = query_states.contiguous()
742
+ key_states = key_states.contiguous()
743
+ value_states = value_states.contiguous()
744
+
745
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
746
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
747
+ # 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.
748
+ # is_causal = True if causal_mask is None and q_len > 1 else False # not used in Dream
749
+
750
+ assert attention_mask.dtype == torch.bool, (
751
+ f"Attention mask should be of type `torch.bool`, but is {attention_mask.dtype}."
752
+ )
753
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
754
+ query_states,
755
+ key_states,
756
+ value_states,
757
+ attn_mask=attention_mask if isinstance(attention_mask, torch.Tensor) else None,
758
+ dropout_p=self.attention_dropout if self.training else 0.0,
759
+ is_causal=False, # hard coded
760
+ )
761
+
762
+ attn_output = attn_output.transpose(1, 2).contiguous()
763
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
764
+
765
+ attn_output = self.o_proj(attn_output)
766
+
767
+ return attn_output, None, past_key_value
768
+
769
+
770
+ DIMPLE_ATTENTION_CLASSES = {
771
+ "eager": DimpleAttention,
772
+ # "flash_attention_2": DimpleFlashAttention2,
773
+ "sdpa": DimpleSdpaAttention,
774
+ }
775
+
776
+
777
+ class DimpleDecoderLayer(nn.Module):
778
+ def __init__(self, config: DimpleConfig, layer_idx: int):
779
+ super().__init__()
780
+ self.hidden_size = config.hidden_size
781
+
782
+ if config.sliding_window and config._attn_implementation != "flash_attention_2":
783
+ logger.warning_once(
784
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
785
+ "unexpected results may be encountered."
786
+ )
787
+ # self.self_attn = Dimple_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
788
+ self.self_attn = DimpleSdpaAttention(config, layer_idx)
789
+
790
+ self.mlp = DimpleMLP(config)
791
+ self.input_layernorm = DimpleRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
792
+ self.post_attention_layernorm = DimpleRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
793
+
794
+ def forward(
795
+ self,
796
+ hidden_states: torch.Tensor,
797
+ attention_mask: Optional[torch.Tensor] = None,
798
+ position_ids: Optional[torch.LongTensor] = None,
799
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
800
+ output_attentions: Optional[bool] = False,
801
+ use_cache: Optional[bool] = False,
802
+ cache_position: Optional[torch.LongTensor] = None,
803
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
804
+ **kwargs,
805
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
806
+ """
807
+ Args:
808
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
809
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
810
+ `(batch, sequence_length)` where padding elements are indicated by 0.
811
+ output_attentions (`bool`, *optional*):
812
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
813
+ returned tensors for more detail.
814
+ use_cache (`bool`, *optional*):
815
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
816
+ (see `past_key_values`).
817
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
818
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
819
+ Indices depicting the position of the input sequence tokens in the sequence.
820
+ position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
821
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
822
+ with `head_dim` being the embedding dimension of each attention head.
823
+ kwargs (`dict`, *optional*):
824
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
825
+ into the model
826
+ """
827
+
828
+ residual = hidden_states
829
+
830
+ hidden_states = self.input_layernorm(hidden_states)
831
+
832
+ # Self Attention
833
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
834
+ hidden_states=hidden_states,
835
+ attention_mask=attention_mask,
836
+ position_ids=position_ids,
837
+ past_key_value=past_key_value,
838
+ output_attentions=output_attentions,
839
+ use_cache=use_cache,
840
+ cache_position=cache_position,
841
+ position_embeddings=position_embeddings,
842
+ )
843
+ hidden_states = residual + hidden_states
844
+
845
+ # Fully Connected
846
+ residual = hidden_states
847
+ hidden_states = self.post_attention_layernorm(hidden_states)
848
+ hidden_states = self.mlp(hidden_states)
849
+ hidden_states = residual + hidden_states
850
+
851
+ outputs = (hidden_states,)
852
+
853
+ if output_attentions:
854
+ outputs += (self_attn_weights,)
855
+
856
+ if use_cache:
857
+ outputs += (present_key_value,)
858
+
859
+ return outputs
860
+
861
+
862
+ Dimple_START_DOCSTRING = r"""
863
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
864
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
865
+ etc.)
866
+
867
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
868
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
869
+ and behavior.
870
+
871
+ Parameters:
872
+ config ([`DimpleConfig`]):
873
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
874
+ load the weights associated with the model, only the configuration. Check out the
875
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
876
+ """
877
+
878
+
879
+ @add_start_docstrings(
880
+ "The bare Dimple Model outputting raw hidden-states without any specific head on top.",
881
+ Dimple_START_DOCSTRING,
882
+ )
883
+ class DimplePreTrainedModel(PreTrainedModel):
884
+ config_class = DimpleConfig
885
+ base_model_prefix = "model"
886
+ supports_gradient_checkpointing = True
887
+ _no_split_modules = ["DimpleDecoderLayer", "DimpleVisionBlock"]
888
+ _skip_keys_device_placement = "past_key_values"
889
+ _supports_flash_attn_2 = True
890
+ _supports_sdpa = True
891
+ _supports_cache_class = True
892
+ _supports_quantized_cache = True
893
+ _supports_static_cache = True
894
+
895
+ def _init_weights(self, module):
896
+ std = self.config.initializer_range
897
+ if isinstance(module, (nn.Linear, nn.Conv3d)):
898
+ module.weight.data.normal_(mean=0.0, std=std)
899
+ if module.bias is not None:
900
+ module.bias.data.zero_()
901
+ elif isinstance(module, nn.Embedding):
902
+ module.weight.data.normal_(mean=0.0, std=std)
903
+ if module.padding_idx is not None:
904
+ module.weight.data[module.padding_idx].zero_()
905
+
906
+ @classmethod
907
+ def from_pretrained(
908
+ cls,
909
+ pretrained_model_name_or_path: Optional[Union[str, os.PathLike]],
910
+ *model_args,
911
+ config: Optional[Union[PretrainedConfig, str, os.PathLike]] = None,
912
+ cache_dir: Optional[Union[str, os.PathLike]] = None,
913
+ ignore_mismatched_sizes: bool = False,
914
+ force_download: bool = False,
915
+ local_files_only: bool = False,
916
+ token: Optional[Union[str, bool]] = None,
917
+ revision: str = "main",
918
+ use_safetensors: Optional[bool] = None,
919
+ weights_only: bool = True,
920
+ **kwargs,
921
+ ):
922
+ _model = super().from_pretrained(
923
+ pretrained_model_name_or_path,
924
+ *model_args,
925
+ config=config,
926
+ cache_dir=cache_dir,
927
+ ignore_mismatched_sizes=ignore_mismatched_sizes,
928
+ force_download=force_download,
929
+ local_files_only=local_files_only,
930
+ token=token,
931
+ revision=revision,
932
+ use_safetensors=use_safetensors,
933
+ weights_only=weights_only,
934
+ **kwargs,
935
+ )
936
+ # NOTE(Lin): we need to override the generation config
937
+ # because the generation config loaded in `from_pretrained`
938
+ # does not include all the attributes of DimpleGenerationConfig
939
+ resume_download = kwargs.get("resume_download", None)
940
+ proxies = kwargs.get("proxies", None)
941
+ subfolder = kwargs.get("subfolder", "")
942
+ from_auto_class = kwargs.get("_from_auto", False)
943
+ from_pipeline = kwargs.get("_from_pipeline", None)
944
+ _model.generation_config = DimpleGenerationConfig.from_pretrained(
945
+ pretrained_model_name_or_path,
946
+ cache_dir=cache_dir,
947
+ force_download=force_download,
948
+ resume_download=resume_download,
949
+ proxies=proxies,
950
+ local_files_only=local_files_only,
951
+ token=token,
952
+ revision=revision,
953
+ subfolder=subfolder,
954
+ _from_auto=from_auto_class,
955
+ _from_pipeline=from_pipeline,
956
+ )
957
+ return _model
958
+
959
+
960
+ class DimpleVisionTransformerPretrainedModel(DimplePreTrainedModel):
961
+ config_class = DimpleVisionConfig
962
+ _no_split_modules = ["DimpleVisionBlock"]
963
+
964
+ def __init__(self, config, *inputs, **kwargs) -> None:
965
+ super().__init__(config, *inputs, **kwargs)
966
+ self.spatial_merge_size = config.spatial_merge_size
967
+ self.patch_size = config.patch_size
968
+ self.fullatt_block_indexes = config.fullatt_block_indexes
969
+ self.window_size = config.window_size
970
+ self.spatial_merge_unit = self.spatial_merge_size * self.spatial_merge_size
971
+
972
+ self.patch_embed = DimpleVisionPatchEmbed(
973
+ patch_size=config.patch_size,
974
+ temporal_patch_size=config.temporal_patch_size,
975
+ in_channels=config.in_channels,
976
+ embed_dim=config.hidden_size,
977
+ )
978
+
979
+ head_dim = config.hidden_size // config.num_heads
980
+ self.rotary_pos_emb = DimpleVisionRotaryEmbedding(head_dim // 2)
981
+
982
+ self.blocks = nn.ModuleList(
983
+ [DimpleVisionBlock(config, config._attn_implementation) for _ in range(config.depth)]
984
+ )
985
+ self.merger = DimplePatchMerger(
986
+ dim=config.out_hidden_size,
987
+ context_dim=config.hidden_size,
988
+ spatial_merge_size=config.spatial_merge_size,
989
+ )
990
+ self.gradient_checkpointing = False
991
+
992
+ def get_dtype(self) -> torch.dtype:
993
+ return self.blocks[0].mlp.down_proj.weight.dtype
994
+
995
+ def get_device(self) -> torch.device:
996
+ return self.blocks[0].mlp.down_proj.weight.device
997
+
998
+ def rot_pos_emb(self, grid_thw):
999
+ pos_ids = []
1000
+ for t, h, w in grid_thw:
1001
+ hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w)
1002
+ hpos_ids = hpos_ids.reshape(
1003
+ h // self.spatial_merge_size,
1004
+ self.spatial_merge_size,
1005
+ w // self.spatial_merge_size,
1006
+ self.spatial_merge_size,
1007
+ )
1008
+ hpos_ids = hpos_ids.permute(0, 2, 1, 3)
1009
+ hpos_ids = hpos_ids.flatten()
1010
+
1011
+ wpos_ids = torch.arange(w).unsqueeze(0).expand(h, -1)
1012
+ wpos_ids = wpos_ids.reshape(
1013
+ h // self.spatial_merge_size,
1014
+ self.spatial_merge_size,
1015
+ w // self.spatial_merge_size,
1016
+ self.spatial_merge_size,
1017
+ )
1018
+ wpos_ids = wpos_ids.permute(0, 2, 1, 3)
1019
+ wpos_ids = wpos_ids.flatten()
1020
+ pos_ids.append(torch.stack([hpos_ids, wpos_ids], dim=-1).repeat(t, 1))
1021
+ pos_ids = torch.cat(pos_ids, dim=0)
1022
+ max_grid_size = grid_thw[:, 1:].max()
1023
+ rotary_pos_emb_full = self.rotary_pos_emb(max_grid_size)
1024
+ rotary_pos_emb = rotary_pos_emb_full[pos_ids].flatten(1)
1025
+ return rotary_pos_emb
1026
+
1027
+ def get_window_index(self, grid_thw):
1028
+ window_index: list = []
1029
+ cu_window_seqlens: list = [0]
1030
+ window_index_id = 0
1031
+ vit_merger_window_size = self.window_size // self.spatial_merge_size // self.patch_size
1032
+
1033
+ for grid_t, grid_h, grid_w in grid_thw:
1034
+ llm_grid_h, llm_grid_w = (
1035
+ grid_h // self.spatial_merge_size,
1036
+ grid_w // self.spatial_merge_size,
1037
+ )
1038
+ index = torch.arange(grid_t * llm_grid_h * llm_grid_w).reshape(grid_t, llm_grid_h, llm_grid_w)
1039
+ pad_h = vit_merger_window_size - llm_grid_h % vit_merger_window_size
1040
+ pad_w = vit_merger_window_size - llm_grid_w % vit_merger_window_size
1041
+ num_windows_h = (llm_grid_h + pad_h) // vit_merger_window_size
1042
+ num_windows_w = (llm_grid_w + pad_w) // vit_merger_window_size
1043
+ index_padded = F.pad(index, (0, pad_w, 0, pad_h), "constant", -100)
1044
+ index_padded = index_padded.reshape(
1045
+ grid_t,
1046
+ num_windows_h,
1047
+ vit_merger_window_size,
1048
+ num_windows_w,
1049
+ vit_merger_window_size,
1050
+ )
1051
+ index_padded = index_padded.permute(0, 1, 3, 2, 4).reshape(
1052
+ grid_t,
1053
+ num_windows_h * num_windows_w,
1054
+ vit_merger_window_size,
1055
+ vit_merger_window_size,
1056
+ )
1057
+ seqlens = (index_padded != -100).sum([2, 3]).reshape(-1)
1058
+ index_padded = index_padded.reshape(-1)
1059
+ index_new = index_padded[index_padded != -100]
1060
+ window_index.append(index_new + window_index_id)
1061
+ cu_seqlens_tmp = seqlens.cumsum(0) * self.spatial_merge_unit + cu_window_seqlens[-1]
1062
+ cu_window_seqlens.extend(cu_seqlens_tmp.tolist())
1063
+ window_index_id += (grid_t * llm_grid_h * llm_grid_w).item()
1064
+ window_index = torch.cat(window_index, dim=0)
1065
+
1066
+ return window_index, cu_window_seqlens
1067
+
1068
+ def forward(self, hidden_states: torch.Tensor, grid_thw: torch.Tensor) -> torch.Tensor:
1069
+ """
1070
+ Args:
1071
+ hidden_states (`torch.Tensor` of shape `(seq_len, hidden_size)`):
1072
+ The final hidden states of the model.
1073
+ grid_thw (`torch.Tensor` of shape `(num_images_or_videos, 3)`):
1074
+ The temporal, height and width of feature shape of each image in LLM.
1075
+
1076
+ Returns:
1077
+ `torch.Tensor`: hidden_states.
1078
+ """
1079
+ hidden_states = self.patch_embed(hidden_states)
1080
+ rotary_pos_emb = self.rot_pos_emb(grid_thw)
1081
+ window_index, cu_window_seqlens = self.get_window_index(grid_thw)
1082
+ cu_window_seqlens = torch.tensor(
1083
+ cu_window_seqlens,
1084
+ device=hidden_states.device,
1085
+ dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32,
1086
+ )
1087
+ cu_window_seqlens = torch.unique_consecutive(cu_window_seqlens)
1088
+
1089
+ seq_len, _ = hidden_states.size()
1090
+ hidden_states = hidden_states.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1)
1091
+ hidden_states = hidden_states[window_index, :, :]
1092
+ hidden_states = hidden_states.reshape(seq_len, -1)
1093
+ rotary_pos_emb = rotary_pos_emb.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1)
1094
+ rotary_pos_emb = rotary_pos_emb[window_index, :, :]
1095
+ rotary_pos_emb = rotary_pos_emb.reshape(seq_len, -1)
1096
+ emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1)
1097
+ position_embeddings = (emb.cos(), emb.sin())
1098
+
1099
+ cu_seqlens = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]).cumsum(
1100
+ dim=0,
1101
+ # Select dtype based on the following factors:
1102
+ # - FA2 requires that cu_seqlens_q must have dtype int32
1103
+ # - torch.onnx.export requires that cu_seqlens_q must have same dtype as grid_thw
1104
+ # See https://github.com/huggingface/transformers/pull/34852 for more information
1105
+ dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32,
1106
+ )
1107
+ cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0)
1108
+
1109
+ for layer_num, blk in enumerate(self.blocks):
1110
+ if layer_num in self.fullatt_block_indexes:
1111
+ cu_seqlens_now = cu_seqlens
1112
+ else:
1113
+ cu_seqlens_now = cu_window_seqlens
1114
+ if self.gradient_checkpointing and self.training:
1115
+ hidden_states = self._gradient_checkpointing_func(
1116
+ blk.__call__, hidden_states, cu_seqlens_now, None, position_embeddings
1117
+ )
1118
+ else:
1119
+ hidden_states = blk(hidden_states, cu_seqlens=cu_seqlens_now, position_embeddings=position_embeddings)
1120
+
1121
+ hidden_states = self.merger(hidden_states)
1122
+ reverse_indices = torch.argsort(window_index)
1123
+ hidden_states = hidden_states[reverse_indices, :]
1124
+
1125
+ return hidden_states
1126
+
1127
+ # Copied from transformers.models.llava.modeling_llava.LlavaMultiModalProjector with Llava->Dimple
1128
+ class DimpleMultiModalProjector(nn.Module):
1129
+ def __init__(self, config: DimpleConfig):
1130
+ super().__init__()
1131
+
1132
+ self.linear_1 = nn.Linear(config.vision_config.out_hidden_size, config.hidden_size, bias=True)
1133
+ self.act = ACT2FN[config.hidden_act]
1134
+ self.linear_2 = nn.Linear(config.hidden_size, config.hidden_size, bias=True)
1135
+
1136
+ def forward(self, image_features):
1137
+ hidden_states = self.linear_1(image_features)
1138
+ hidden_states = self.act(hidden_states)
1139
+ hidden_states = self.linear_2(hidden_states)
1140
+ return hidden_states
1141
+
1142
+ @add_start_docstrings(
1143
+ "The bare Dimple Model outputting raw hidden-states without any specific head on top.",
1144
+ Dimple_START_DOCSTRING,
1145
+ )
1146
+ class DimpleBaseModel(DimplePreTrainedModel):
1147
+ def __init__(self, config: DimpleConfig):
1148
+ super().__init__(config)
1149
+ self.padding_idx = config.pad_token_id
1150
+ self.vocab_size = config.vocab_size
1151
+
1152
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1153
+ self.layers = nn.ModuleList(
1154
+ [DimpleDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1155
+ )
1156
+ self._attn_implementation = config._attn_implementation
1157
+ self.norm = DimpleRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1158
+ self.rotary_emb = DimpleRotaryEmbedding(config=config)
1159
+
1160
+ self.gradient_checkpointing = False
1161
+ # Initialize weights and apply final processing
1162
+ self.post_init()
1163
+
1164
+ def get_input_embeddings(self):
1165
+ return self.embed_tokens
1166
+
1167
+ def set_input_embeddings(self, value):
1168
+ self.embed_tokens = value
1169
+
1170
+ def forward(
1171
+ self,
1172
+ input_ids: torch.LongTensor = None,
1173
+ attention_mask: Optional[torch.Tensor] = None,
1174
+ position_ids: Optional[torch.LongTensor] = None,
1175
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1176
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1177
+ use_cache: Optional[bool] = None,
1178
+ output_attentions: Optional[bool] = None,
1179
+ output_hidden_states: Optional[bool] = None,
1180
+ return_dict: Optional[bool] = None,
1181
+ cache_position: Optional[torch.LongTensor] = None,
1182
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1183
+
1184
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1185
+ output_hidden_states = (
1186
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1187
+ )
1188
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1189
+
1190
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1191
+
1192
+ if (input_ids is None) ^ (inputs_embeds is not None):
1193
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
1194
+
1195
+ if self.gradient_checkpointing and self.training:
1196
+ if use_cache:
1197
+ use_cache = False
1198
+
1199
+ if inputs_embeds is None:
1200
+ inputs_embeds = self.embed_tokens(input_ids)
1201
+
1202
+ if use_cache and past_key_values is None:
1203
+ logger.warning_once(
1204
+ "This should not be triggered, in either training or inference, but if it is, please report it to us."
1205
+ )
1206
+ past_key_values = DynamicCache()
1207
+
1208
+ if cache_position is None:
1209
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1210
+ cache_position = torch.arange(
1211
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1212
+ )
1213
+
1214
+ # the hard coded `3` is for temporal, height and width.
1215
+ if position_ids is None:
1216
+ logger.warning_once(
1217
+ "This should not be triggered, in either training or inference, but if it is, please report it to us."
1218
+ )
1219
+ position_ids = cache_position.view(1, 1, -1).expand(3, inputs_embeds.shape[0], -1)
1220
+ elif position_ids.dim() == 2:
1221
+ logger.warning_once(
1222
+ "This should not be triggered, in either training or inference, but if it is, please report it to us."
1223
+ )
1224
+ position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1)
1225
+
1226
+ # generate 4d caucasl attention mask
1227
+ if len(attention_mask.shape) == 4 :
1228
+ logger.warning_once(
1229
+ f"4d Attention Mask is used."
1230
+ )
1231
+ if attention_mask.dtype != torch.bool:
1232
+ logger.warning_once(
1233
+ f"Attention mask should be of type `torch.bool`, but is {attention_mask.dtype}. Changes have been made to convert it to `torch.bool`."
1234
+ )
1235
+ attention_mask = attention_mask.to(torch.bool)
1236
+ pass
1237
+ elif len(attention_mask.shape) == 2:
1238
+ if not self.config.full_attn_mask:
1239
+ # not used in Dream
1240
+ diag_attention_mask = torch.arange(
1241
+ attention_mask.shape[1],
1242
+ device=attention_mask.device
1243
+ ).unsqueeze(0) <= torch.arange(
1244
+ attention_mask.shape[1],
1245
+ device=attention_mask.device
1246
+ ).unsqueeze(1)
1247
+ diag_attention_mask = diag_attention_mask[None, None, :, :] # [1, 1, S, S]
1248
+ pad_attention_mask = torch.logical_and(
1249
+ attention_mask.unsqueeze(1).unsqueeze(-2),
1250
+ attention_mask.unsqueeze(1).unsqueeze(-1),
1251
+ ) # bs, seq_len -> bs, 1, 1, seq_len; bs, 1, seq_len, 1 -> bs, 1, seq_len, seq_len
1252
+ attention_mask = torch.logical_and(diag_attention_mask, pad_attention_mask)
1253
+ attention_mask = attention_mask[:,:,cache_position] # [bs, 1, input_length, S]
1254
+ else:
1255
+ # used in Dream
1256
+ attention_mask = torch.logical_and(
1257
+ attention_mask.unsqueeze(1).unsqueeze(-2),
1258
+ attention_mask.unsqueeze(1).unsqueeze(-1),
1259
+ ) # bs, seq_len -> bs, 1, 1, seq_len; bs, 1, seq_len, 1 -> bs, 1, seq_len, seq_len
1260
+ eye = torch.eye(attention_mask.size(-1), dtype=torch.bool, device=attention_mask.device) # [S, S]
1261
+ attention_mask = torch.logical_or(attention_mask, eye.unsqueeze(0).unsqueeze(0)) # [bs, 1, S, S]
1262
+ attention_mask = attention_mask[:,:,cache_position] # [bs, 1, input_length, S]
1263
+ else:
1264
+ raise ValueError(f"Attention mask shape length must be 2 or 4, but got {len(attention_mask.shape)}")
1265
+
1266
+ hidden_states = inputs_embeds
1267
+
1268
+ # create position embeddings to be shared across the decoder layers
1269
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
1270
+
1271
+ # decoder layers
1272
+ all_hidden_states = () if output_hidden_states else None
1273
+ all_self_attns = () if output_attentions else None
1274
+ next_decoder_cache = None # not used in Dream
1275
+
1276
+ # Dimple.debug(
1277
+ # f"In {self.__class__}, before input into decoder layers, Cache is {use_cache}, past_key_values is {past_key_values}, cache position is {cache_position}."
1278
+ # )
1279
+
1280
+ for decoder_layer in self.layers:
1281
+ if output_hidden_states:
1282
+ all_hidden_states += (hidden_states,)
1283
+
1284
+ if self.gradient_checkpointing and self.training:
1285
+ layer_outputs = self._gradient_checkpointing_func(
1286
+ decoder_layer.__call__,
1287
+ hidden_states,
1288
+ attention_mask,
1289
+ position_ids,
1290
+ past_key_values,
1291
+ output_attentions,
1292
+ use_cache,
1293
+ cache_position,
1294
+ position_embeddings,
1295
+ )
1296
+ else:
1297
+ layer_outputs = decoder_layer(
1298
+ hidden_states,
1299
+ attention_mask=attention_mask,
1300
+ position_ids=position_ids,
1301
+ past_key_value=past_key_values,
1302
+ output_attentions=output_attentions,
1303
+ use_cache=use_cache,
1304
+ cache_position=cache_position,
1305
+ position_embeddings=position_embeddings,
1306
+ )
1307
+
1308
+ hidden_states = layer_outputs[0]
1309
+
1310
+ # not used in Dream
1311
+ if use_cache:
1312
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1313
+
1314
+ if output_attentions:
1315
+ all_self_attns += (layer_outputs[1],)
1316
+
1317
+ hidden_states = self.norm(hidden_states)
1318
+
1319
+ # add hidden states from the last decoder layer
1320
+ if output_hidden_states:
1321
+ all_hidden_states += (hidden_states,)
1322
+
1323
+ # not used in Dream
1324
+ next_cache = next_decoder_cache if use_cache else None
1325
+
1326
+ if not return_dict:
1327
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attns] if v is not None)
1328
+ return BaseModelOutputWithPast(
1329
+ last_hidden_state=hidden_states,
1330
+ past_key_values=next_cache,
1331
+ hidden_states=all_hidden_states,
1332
+ attentions=all_self_attns,
1333
+ )
1334
+
1335
+ Dimple_INPUTS_DOCSTRING = r"""
1336
+ Args:
1337
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1338
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1339
+ it.
1340
+
1341
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1342
+ [`PreTrainedTokenizer.__call__`] for details.
1343
+
1344
+ [What are input IDs?](../glossary#input-ids)
1345
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1346
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1347
+
1348
+ - 1 for tokens that are **not masked**,
1349
+ - 0 for tokens that are **masked**.
1350
+
1351
+ [What are attention masks?](../glossary#attention-mask)
1352
+
1353
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1354
+ [`PreTrainedTokenizer.__call__`] for details.
1355
+
1356
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
1357
+ `past_key_values`).
1358
+
1359
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1360
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1361
+ information on the default strategy.
1362
+
1363
+ - 1 indicates the head is **not masked**,
1364
+ - 0 indicates the head is **masked**.
1365
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1366
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1367
+ config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
1368
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
1369
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
1370
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
1371
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
1372
+
1373
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1374
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
1375
+
1376
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1377
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1378
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1379
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1380
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1381
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1382
+ model's internal embedding lookup matrix.
1383
+ use_cache (`bool`, *optional*):
1384
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1385
+ `past_key_values`).
1386
+ output_attentions (`bool`, *optional*):
1387
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1388
+ tensors for more detail.
1389
+ output_hidden_states (`bool`, *optional*):
1390
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1391
+ more detail.
1392
+ return_dict (`bool`, *optional*):
1393
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1394
+ pixel_values (`torch.FloatTensor` of shape `(seq_length, num_channels * image_size * image_size)):
1395
+ The tensors corresponding to the input images. Pixel values can be obtained using
1396
+ [`AutoImageProcessor`]. See [`DimpleImageProcessor.__call__`] for details. [`DimpleProcessor`] uses
1397
+ [`DimpleImageProcessor`] for processing images.
1398
+ pixel_values_videos (`torch.FloatTensor` of shape `(seq_length, num_channels * temporal_size * image_size * image_size)):
1399
+ The tensors corresponding to the input videos. Pixel values can be obtained using
1400
+ [`AutoImageProcessor`]. See [`DimpleImageProcessor.__call__`] for details. [`DimpleProcessor`] uses
1401
+ [`DimpleImageProcessor`] for processing videos.
1402
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
1403
+ The temporal, height and width of feature shape of each image in LLM.
1404
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
1405
+ The temporal, height and width of feature shape of each video in LLM.
1406
+ rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
1407
+ The rope index difference between sequence length and multimodal rope.
1408
+ """
1409
+
1410
+
1411
+ class DimpleModel(DimpleGenerationMixin, DimplePreTrainedModel):
1412
+ _tied_weights_keys = ["lm_head.weight"]
1413
+
1414
+ def __init__(self, config):
1415
+ super().__init__(config)
1416
+ self.visual = DimpleVisionTransformerPretrainedModel._from_config(config.vision_config)
1417
+ self.model = DimpleBaseModel(config)
1418
+ self.vocab_size = config.vocab_size
1419
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1420
+ self.img_projector = DimpleMultiModalProjector(config)
1421
+ # self.padding_side = "left" # set it to left by default, user can use setter to change padding_sides # not specified in dream
1422
+
1423
+ # Initialize weights and apply final processing
1424
+ self.post_init()
1425
+
1426
+ def reset_rope_parameters(self):
1427
+ self.model.rotary_emb.reset_parameters()
1428
+ for layer in self.model.layers:
1429
+ layer.self_attn.rotary_emb.reset_parameters()
1430
+
1431
+ def get_input_embeddings(self):
1432
+ return self.model.embed_tokens
1433
+
1434
+ def set_input_embeddings(self, value):
1435
+ self.model.embed_tokens = value
1436
+
1437
+ def get_output_embeddings(self):
1438
+ return self.lm_head
1439
+
1440
+ def set_output_embeddings(self, new_embeddings):
1441
+ self.lm_head = new_embeddings
1442
+
1443
+ def set_decoder(self, decoder):
1444
+ self.model = decoder
1445
+
1446
+ def get_decoder(self):
1447
+ return self.model
1448
+
1449
+ def get_rope_index(
1450
+ self,
1451
+ input_ids: torch.LongTensor,
1452
+ image_grid_thw: Optional[torch.LongTensor] = None,
1453
+ video_grid_thw: Optional[torch.LongTensor] = None,
1454
+ attention_mask: Optional[torch.Tensor] = None,
1455
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
1456
+ """
1457
+ Calculate the 3D rope index based on image and video's temporal, height and width in LLM.
1458
+
1459
+ Explanation:
1460
+ Each embedding sequence contains vision embedding and text embedding or just contains text embedding.
1461
+
1462
+ For pure text embedding sequence, the rotary position embedding has no difference with mordern LLMs.
1463
+ Examples:
1464
+ input_ids: [T T T T T], here T is for text.
1465
+ temporal position_ids: [0, 1, 2, 3, 4]
1466
+ height position_ids: [0, 1, 2, 3, 4]
1467
+ width position_ids: [0, 1, 2, 3, 4]
1468
+
1469
+ For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part
1470
+ and 1D rotary position embeddin for text part.
1471
+ Examples:
1472
+ Assume we have a video input with 3 temporal patches, 2 height patches and 2 width patches.
1473
+ input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision.
1474
+ vision temporal position_ids: [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2]
1475
+ vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1]
1476
+ vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
1477
+ text temporal position_ids: [3, 4, 5, 6, 7]
1478
+ text height position_ids: [3, 4, 5, 6, 7]
1479
+ text width position_ids: [3, 4, 5, 6, 7]
1480
+ Here we calculate the text start position_ids as the max vision position_ids plus 1.
1481
+
1482
+ Args:
1483
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1484
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1485
+ it.
1486
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
1487
+ The temporal, height and width of feature shape of each image in LLM.
1488
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
1489
+ The temporal, height and width of feature shape of each video in LLM.
1490
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1491
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1492
+
1493
+ - 1 for tokens that are **not masked**,
1494
+ - 0 for tokens that are **masked**.
1495
+
1496
+ Returns:
1497
+ position_ids (`torch.LongTensor` of shape `(3, batch_size, sequence_length)`)
1498
+ mrope_position_deltas (`torch.Tensor` of shape `(batch_size)`)
1499
+ """
1500
+ spatial_merge_size = self.config.vision_config.spatial_merge_size
1501
+ image_token_id = self.config.image_token_id
1502
+ video_token_id = self.config.video_token_id
1503
+ vision_start_token_id = self.config.vision_start_token_id
1504
+ mrope_position_deltas = []
1505
+ if image_grid_thw is not None or video_grid_thw is not None:
1506
+ total_input_ids = input_ids
1507
+ if attention_mask is None:
1508
+ attention_mask = torch.ones_like(total_input_ids)
1509
+ position_ids = torch.ones(
1510
+ 3, input_ids.shape[0], input_ids.shape[1], dtype=input_ids.dtype, device=input_ids.device
1511
+ )
1512
+ image_index, video_index = 0, 0
1513
+ for i, input_ids in enumerate(total_input_ids):
1514
+ input_ids = input_ids[attention_mask[i] == 1]
1515
+ image_nums, video_nums = 0, 0
1516
+ vision_start_indices = torch.argwhere(input_ids == vision_start_token_id).squeeze(1)
1517
+ vision_tokens = input_ids[vision_start_indices + 1]
1518
+ image_nums = (vision_tokens == image_token_id).sum()
1519
+ video_nums = (vision_tokens == video_token_id).sum()
1520
+ input_tokens = input_ids.tolist()
1521
+ llm_pos_ids_list: list = []
1522
+ st = 0
1523
+ remain_images, remain_videos = image_nums, video_nums
1524
+ for _ in range(image_nums + video_nums):
1525
+ if image_token_id in input_tokens and remain_images > 0:
1526
+ ed_image = input_tokens.index(image_token_id, st)
1527
+ else:
1528
+ ed_image = len(input_tokens) + 1
1529
+ if video_token_id in input_tokens and remain_videos > 0:
1530
+ ed_video = input_tokens.index(video_token_id, st)
1531
+ else:
1532
+ ed_video = len(input_tokens) + 1
1533
+ if ed_image < ed_video:
1534
+ t, h, w = (
1535
+ image_grid_thw[image_index][0],
1536
+ image_grid_thw[image_index][1],
1537
+ image_grid_thw[image_index][2],
1538
+ )
1539
+ image_index += 1
1540
+ remain_images -= 1
1541
+ ed = ed_image
1542
+ else:
1543
+ t, h, w = (
1544
+ video_grid_thw[video_index][0],
1545
+ video_grid_thw[video_index][1],
1546
+ video_grid_thw[video_index][2],
1547
+ )
1548
+ video_index += 1
1549
+ remain_videos -= 1
1550
+ ed = ed_video
1551
+ llm_grid_t, llm_grid_h, llm_grid_w = (
1552
+ t.item(),
1553
+ h.item() // spatial_merge_size,
1554
+ w.item() // spatial_merge_size,
1555
+ )
1556
+ text_len = ed - st
1557
+
1558
+ st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
1559
+ llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)
1560
+
1561
+ t_index = torch.arange(llm_grid_t).view(-1, 1).expand(-1, llm_grid_h * llm_grid_w).flatten()
1562
+ h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten()
1563
+ w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten()
1564
+ llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + text_len + st_idx)
1565
+ st = ed + llm_grid_t * llm_grid_h * llm_grid_w
1566
+
1567
+ if st < len(input_tokens):
1568
+ st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
1569
+ text_len = len(input_tokens) - st
1570
+ llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)
1571
+
1572
+ llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1)
1573
+ position_ids[..., i, attention_mask[i] == 1] = llm_positions.to(position_ids.device)
1574
+ mrope_position_deltas.append(llm_positions.max() + 1 - len(total_input_ids[i]))
1575
+ mrope_position_deltas = torch.tensor(mrope_position_deltas, device=input_ids.device).unsqueeze(1)
1576
+ return position_ids, mrope_position_deltas
1577
+ else:
1578
+ if attention_mask is not None:
1579
+ position_ids = attention_mask.long().cumsum(-1) - 1
1580
+ position_ids.masked_fill_(attention_mask == 0, 1)
1581
+ position_ids = position_ids.unsqueeze(0).expand(3, -1, -1).to(input_ids.device)
1582
+ max_position_ids = position_ids.max(0, keepdim=False)[0].max(-1, keepdim=True)[0]
1583
+ mrope_position_deltas = max_position_ids + 1 - attention_mask.shape[-1]
1584
+ else:
1585
+ position_ids = (
1586
+ torch.arange(input_ids.shape[1], device=input_ids.device)
1587
+ .view(1, 1, -1)
1588
+ .expand(3, input_ids.shape[0], -1)
1589
+ )
1590
+ mrope_position_deltas = torch.zeros(
1591
+ [input_ids.shape[0], 1],
1592
+ device=input_ids.device,
1593
+ dtype=input_ids.dtype,
1594
+ )
1595
+
1596
+ return position_ids, mrope_position_deltas
1597
+
1598
+ @add_start_docstrings_to_model_forward(Dimple_INPUTS_DOCSTRING)
1599
+ @replace_return_docstrings(output_type=DimpleModelOutput, config_class=_CONFIG_FOR_DOC)
1600
+ def forward(
1601
+ self,
1602
+ input_ids: torch.LongTensor = None,
1603
+ attention_mask: Optional[torch.Tensor] = None,
1604
+ position_ids: Optional[torch.LongTensor] = None,
1605
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1606
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1607
+ labels: Optional[torch.LongTensor] = None,
1608
+ use_cache: Optional[bool] = None,
1609
+ output_attentions: Optional[bool] = None,
1610
+ output_hidden_states: Optional[bool] = None,
1611
+ return_dict: Optional[bool] = None,
1612
+ pixel_values: Optional[torch.Tensor] = None,
1613
+ pixel_values_videos: Optional[torch.FloatTensor] = None,
1614
+ image_grid_thw: Optional[torch.LongTensor] = None,
1615
+ video_grid_thw: Optional[torch.LongTensor] = None,
1616
+ rope_deltas: Optional[torch.LongTensor] = None,
1617
+ cache_position: Optional[torch.LongTensor] = None,
1618
+ num_logits_to_keep: int = 0,
1619
+ **loss_kwargs,
1620
+ ) -> Union[Tuple, DimpleModelOutput]:
1621
+ r"""
1622
+ Args:
1623
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1624
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1625
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1626
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1627
+
1628
+ Returns:
1629
+
1630
+ Example:
1631
+
1632
+ ```python
1633
+ >>> from PIL import Image
1634
+ >>> import requests
1635
+ >>> from transformers import AutoProcessor, DimpleForConditionalGeneration
1636
+
1637
+ >>> model = DimpleForConditionalGeneration.from_pretrained(" ")
1638
+ >>> processor = AutoProcessor.from_pretrained(" ")
1639
+
1640
+ >>> messages = [
1641
+ {
1642
+ "role": "user",
1643
+ "content": [
1644
+ {"type": "image"},
1645
+ {"type": "text", "text": "What is shown in this image?"},
1646
+ ],
1647
+ },
1648
+ ]
1649
+ >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
1650
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1651
+
1652
+ >>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
1653
+ >>> inputs = processor(text=[text], images=[image], vision_infos=[vision_infos])
1654
+
1655
+ >>> # Generate
1656
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1657
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1658
+ "The image shows a street scene with a red stop sign in the foreground. In the background, there is a large red gate with Chinese characters ..."
1659
+ ```"""
1660
+ # logger.warning_once(
1661
+ # f"In {self.__class__}, Cache is {use_cache}, past_key_values is {past_key_values}, cache position is {cache_position}."
1662
+ # )
1663
+
1664
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1665
+ output_hidden_states = (
1666
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1667
+ )
1668
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1669
+
1670
+ if inputs_embeds is None:
1671
+ inputs_embeds = self.model.embed_tokens(input_ids)
1672
+ if pixel_values is not None:
1673
+ pixel_values = pixel_values.type(self.visual.get_dtype())
1674
+ image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw)
1675
+ n_image_tokens = (input_ids == self.config.image_token_id).sum().item()
1676
+ n_image_features = image_embeds.shape[0]
1677
+ if n_image_tokens != n_image_features:
1678
+ raise ValueError(
1679
+ f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
1680
+ )
1681
+ image_mask = (
1682
+ (input_ids == self.config.image_token_id)
1683
+ .unsqueeze(-1)
1684
+ .expand_as(inputs_embeds)
1685
+ .to(inputs_embeds.device)
1686
+ )
1687
+ image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
1688
+ image_embeds_projected = self.img_projector(image_embeds)
1689
+ inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds_projected)
1690
+
1691
+ if pixel_values_videos is not None:
1692
+ pixel_values_videos = pixel_values_videos.type(self.visual.get_dtype())
1693
+ video_embeds = self.visual(pixel_values_videos, grid_thw=video_grid_thw)
1694
+ n_video_tokens = (input_ids == self.config.video_token_id).sum().item()
1695
+ n_video_features = video_embeds.shape[0]
1696
+ if n_video_tokens != n_video_features:
1697
+ raise ValueError(
1698
+ f"Video features and video tokens do not match: tokens: {n_video_tokens}, features {n_video_features}"
1699
+ )
1700
+ video_mask = (
1701
+ (input_ids == self.config.video_token_id)
1702
+ .unsqueeze(-1)
1703
+ .expand_as(inputs_embeds)
1704
+ .to(inputs_embeds.device)
1705
+ )
1706
+ video_embeds = video_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
1707
+ raise NotImplementedError(
1708
+ "Video feature projector not implemented"
1709
+ )
1710
+ inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds)
1711
+
1712
+ if attention_mask is not None:
1713
+ attention_mask = attention_mask.to(inputs_embeds.device)
1714
+
1715
+ outputs = self.model(
1716
+ input_ids=None, # in Qwen
1717
+ # input_ids=input_ids,# in Dream
1718
+ attention_mask=attention_mask,
1719
+ position_ids=position_ids,
1720
+ past_key_values=past_key_values,
1721
+ inputs_embeds=inputs_embeds,
1722
+ use_cache=use_cache,
1723
+ output_attentions=output_attentions,
1724
+ output_hidden_states=output_hidden_states,
1725
+ return_dict=return_dict,
1726
+ cache_position=cache_position,
1727
+ )
1728
+
1729
+ hidden_states = outputs[0]
1730
+ # in Qwen
1731
+ logits = self.lm_head(hidden_states)
1732
+ # in Dream
1733
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1734
+ # logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
1735
+
1736
+
1737
+ loss = None
1738
+ if labels is not None:
1739
+ logger.warning_once(
1740
+ "Use the naive next token prediction loss for the model. This is not the same as the original Dimple model, which uses a different loss function."
1741
+ )
1742
+ # in Qwen
1743
+ # Upcast to float if we need to compute the loss to avoid potential precision issues
1744
+ logits = logits.float()
1745
+ # Shift so that tokens < n predict n
1746
+ shift_logits = logits[..., :-1, :].contiguous()
1747
+ shift_labels = labels[..., 1:].contiguous()
1748
+ # Flatten the tokens
1749
+ loss_fct = CrossEntropyLoss()
1750
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1751
+ shift_labels = shift_labels.view(-1)
1752
+ # Enable model parallelism
1753
+ shift_labels = shift_labels.to(shift_logits.device)
1754
+ loss = loss_fct(shift_logits, shift_labels)
1755
+ # in Dream
1756
+ # loss = self.loss_function(logits, labels, self.vocab_size, **loss_kwargs)
1757
+
1758
+ if not return_dict:
1759
+ output = (logits,) + outputs[1:]
1760
+ return (loss,) + output if loss is not None else output
1761
+
1762
+ return DimpleModelOutput(
1763
+ logits=logits,
1764
+ loss=loss,
1765
+ past_key_values=outputs.past_key_values,
1766
+ hidden_states=outputs.hidden_states,
1767
+ attentions=outputs.attentions,
1768
+ rope_deltas=rope_deltas,
1769
+ )
1770
+
1771
+ def prepare_inputs_for_generation(
1772
+ self,
1773
+ input_ids,
1774
+ past_key_values=None,
1775
+ attention_mask=None,
1776
+ inputs_embeds=None,
1777
+ cache_position=None,
1778
+ position_ids=None,
1779
+ use_cache=True,
1780
+ pixel_values=None,
1781
+ pixel_values_videos=None,
1782
+ image_grid_thw=None,
1783
+ video_grid_thw=None,
1784
+ rope_deltas = None,
1785
+ **kwargs,
1786
+ ):
1787
+ # never remove input ids
1788
+
1789
+ if use_cache:
1790
+ if past_key_values is None:
1791
+ raise ValueError(
1792
+ "If `use_cache=True`, `past_key_values` must be provided. Please make sure to pass `past_key_values` to the model."
1793
+ )
1794
+ else:
1795
+ pass
1796
+ else:
1797
+ past_key_values = None
1798
+
1799
+ if use_cache:
1800
+ if cache_position is None:
1801
+ raise ValueError(
1802
+ "If `use_cache=True`, `cache_position` must be provided. Please make sure to pass `cache_position` to the model."
1803
+ )
1804
+ else:
1805
+ pass
1806
+ else:
1807
+ cache_position = None
1808
+
1809
+ if use_cache:
1810
+ if input_ids.shape[1] != cache_position.shape[0]:
1811
+ input_ids = input_ids[:, cache_position]
1812
+ else:
1813
+ pass
1814
+ else:
1815
+ pass
1816
+
1817
+ if position_ids is None:
1818
+ if not use_cache:
1819
+ position_ids, rope_deltas = self.get_rope_index(
1820
+ input_ids, image_grid_thw, video_grid_thw, attention_mask
1821
+ )
1822
+ else:
1823
+ if cache_position[0] == 0:
1824
+ position_ids, rope_deltas = self.get_rope_index(
1825
+ input_ids, image_grid_thw, video_grid_thw, attention_mask
1826
+ )
1827
+ else:
1828
+ batch_size, seq_length = input_ids.shape
1829
+ delta = (
1830
+ cache_position[0] + rope_deltas if cache_position is not None and rope_deltas is not None else 0
1831
+ )
1832
+ position_ids = torch.arange(seq_length, device=input_ids.device)
1833
+ position_ids = position_ids.view(1, -1).expand(batch_size, -1)
1834
+ position_ids = position_ids.add(delta)
1835
+ position_ids = position_ids.unsqueeze(0).expand(3, -1, -1)
1836
+
1837
+ else:
1838
+ raise NotImplementedError(
1839
+ "position_ids is not None, please check the code in prepare_inputs_for_generation"
1840
+ )
1841
+
1842
+ if use_cache:
1843
+ if cache_position[0] != 0:
1844
+ pixel_values = None
1845
+ pixel_values_videos = None
1846
+ logger.debug(f"after prefill, the pixel_values and pixel_values_videos are None.")
1847
+ else:
1848
+ pass
1849
+
1850
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1851
+ if inputs_embeds is not None:
1852
+ raise NotImplementedError(
1853
+ "inputs_embeds is not None, please check the code in prepare_inputs_for_generation"
1854
+ )
1855
+ else:
1856
+ model_inputs = {"input_ids": input_ids, "inputs_embeds": None}
1857
+
1858
+ model_inputs.update(
1859
+ {
1860
+ "position_ids": position_ids,
1861
+ "past_key_values": past_key_values,
1862
+ "use_cache": use_cache,
1863
+ "attention_mask": attention_mask,
1864
+ "pixel_values": pixel_values,
1865
+ "pixel_values_videos": pixel_values_videos,
1866
+ "image_grid_thw": image_grid_thw,
1867
+ "video_grid_thw": video_grid_thw,
1868
+ "cache_position": cache_position,
1869
+ "rope_deltas": rope_deltas,
1870
+ }
1871
+ )
1872
+ return model_inputs