ryanzhangfan commited on
Commit
f6e699f
1 Parent(s): 97bb8d1

Upload 19 files

Browse files
config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Emu3ForCausalLM"
4
+ ],
5
+ "attention_dropout": 0.1,
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_emu3.Emu3Config",
8
+ "AutoModelForCausalLM": "modeling_emu3.Emu3ForCausalLM"
9
+ },
10
+ "boi_token_id": 151852,
11
+ "bos_token_id": 151849,
12
+ "eof_token_id": 151847,
13
+ "eoi_token_id": 151853,
14
+ "eol_token_id": 151846,
15
+ "eos_token_id": 151850,
16
+ "hidden_act": "silu",
17
+ "hidden_size": 4096,
18
+ "image_area": 262144,
19
+ "img_token_id": 151851,
20
+ "initializer_range": 0.02,
21
+ "intermediate_size": 14336,
22
+ "max_position_embeddings": 131072,
23
+ "model_type": "Emu3",
24
+ "num_attention_heads": 32,
25
+ "num_hidden_layers": 32,
26
+ "num_key_value_heads": 8,
27
+ "pad_token_id": 151643,
28
+ "pretraining_tp": 1,
29
+ "rms_norm_eps": 1e-05,
30
+ "rope_scaling": null,
31
+ "rope_theta": 1000000.0,
32
+ "tie_word_embeddings": false,
33
+ "torch_dtype": "float32",
34
+ "transformers_version": "4.44.0",
35
+ "use_cache": true,
36
+ "vocab_size": 184622
37
+ }
configuration_emu3.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Emu team, BAAI 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
+ """ Emu3 model configuration"""
21
+
22
+ from typing import Optional
23
+
24
+ from transformers.configuration_utils import PretrainedConfig
25
+ from transformers.utils import logging
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+ EMU3_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
31
+
32
+
33
+ class Emu3Config(PretrainedConfig):
34
+ r"""
35
+ This is the configuration class to store the configuration of a [`Emu3Model`]. It is used to instantiate an Emu3
36
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
37
+ defaults will yield a similar configuration to that of the Emu3-8B.
38
+
39
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
40
+ documentation from [`PretrainedConfig`] for more information.
41
+
42
+
43
+ Args:
44
+ vocab_size (`int`, *optional*, defaults to 184622):
45
+ Vocabulary size of the Emu3 model. Defines the number of different tokens that can be represented by the
46
+ `inputs_ids` passed when calling [`Emu3Model`]
47
+ hidden_size (`int`, *optional*, defaults to 4096):
48
+ Dimension of the hidden representations.
49
+ intermediate_size (`int`, *optional*, defaults to 14336):
50
+ Dimension of the MLP representations.
51
+ num_hidden_layers (`int`, *optional*, defaults to 32):
52
+ Number of hidden layers in the Transformer decoder.
53
+ num_attention_heads (`int`, *optional*, defaults to 32):
54
+ Number of attention heads for each attention layer in the Transformer decoder.
55
+ num_key_value_heads (`int`, *optional*, defaults to 8):
56
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
57
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
58
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
59
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
60
+ by meanpooling all the original heads within that group. For more details checkout [this
61
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
62
+ `num_attention_heads`.
63
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
64
+ The non-linear activation function (function or string) in the decoder.
65
+ max_position_embeddings (`int`, *optional*, defaults to 9216):
66
+ The maximum sequence length that this model might ever be used with. Emu supports up to 9216 tokens,
67
+ initializer_range (`float`, *optional*, defaults to 0.02):
68
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
69
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
70
+ The epsilon used by the rms normalization layers.
71
+ use_cache (`bool`, *optional*, defaults to `True`):
72
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
73
+ relevant if `config.is_decoder=True`.
74
+ pad_token_id (`int`, *optional*, 151643):
75
+ Padding token id.
76
+ bos_token_id (`int`, *optional*, defaults to 151849):
77
+ Beginning of stream token id.
78
+ eos_token_id (`int`, *optional*, defaults to 151850):
79
+ End of stream token id.
80
+ img_token_id (`int`, *optional*, defaults to 151851):
81
+ image token id.
82
+ boi_token_id (`int`, *optional*, defaults to 151852):
83
+ Beginning of image token id.
84
+ eoi_token_id (`int`, *optional*, defaults to 151853):
85
+ End of image token id.
86
+ eol_token_id (`int`, *optional*, defaults to 151846):
87
+ End of line token id.
88
+ eof_token_id (`int`, *optional*, defaults to 151847):
89
+ End of line token id.
90
+ image_area (`int`, *optional*, defaults to 720 * 720)
91
+ generated image area (image area used in training)
92
+ pretraining_tp (`int`, *optional*, defaults to 1):
93
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
94
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
95
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
96
+ issue](https://github.com/pytorch/pytorch/issues/76232).
97
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
98
+ Whether to tie weight embeddings
99
+ rope_theta (`float`, *optional*, defaults to 1_000_000.0):
100
+ The base period of the RoPE embeddings.
101
+ rope_scaling (`Dict`, *optional*):
102
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
103
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
104
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
105
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
106
+ these scaling strategies behave:
107
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
108
+ experimental feature, subject to breaking API changes in future versions.
109
+ attention_dropout (`float`, *optional*, defaults to 0.1):
110
+ The dropout ratio for the attention probabilities.
111
+
112
+ ```python
113
+ >>> from transformers import Emu3Model, Emu3Config
114
+
115
+ >>> # Initializing a Emu3-8b style configuration
116
+ >>> configuration = Emu3Config()
117
+
118
+ >>> # Initializing a model from the Emu3-8b style configuration
119
+ >>> model = Emu3Model(configuration)
120
+
121
+ >>> # Accessing the model configuration
122
+ >>> configuration = model.config
123
+ ```"""
124
+
125
+ model_type = "Emu3"
126
+ keys_to_ignore_at_inference = ["past_key_values"]
127
+
128
+ def __init__(
129
+ self,
130
+ vocab_size: int = 184622,
131
+ hidden_size: int = 4096,
132
+ intermediate_size: int = 14336,
133
+ num_hidden_layers: int = 32,
134
+ num_attention_heads: int = 32,
135
+ num_key_value_heads: Optional[int] = 8,
136
+ hidden_act: str = "silu",
137
+ max_position_embeddings: int = 9216,
138
+ initializer_range: float = 0.02,
139
+ rms_norm_eps: float = 1e-5,
140
+ use_cache: bool = True,
141
+ pad_token_id: int = 151643,
142
+ bos_token_id: int = 151849,
143
+ eos_token_id: int = 151850,
144
+ img_token_id: int = 151851,
145
+ boi_token_id: int = 151852,
146
+ eoi_token_id: int = 151853,
147
+ eol_token_id: int = 151846,
148
+ eof_token_id: int = 151847,
149
+ image_area: int = 720 * 720,
150
+ pretraining_tp: int = 1,
151
+ tie_word_embeddings: bool = False,
152
+ rope_theta: float = 1000000.0,
153
+ rope_scaling: Optional = None,
154
+ attention_dropout: float = 0.1,
155
+ **kwargs,
156
+ ):
157
+ self.vocab_size = vocab_size
158
+ self.max_position_embeddings = max_position_embeddings
159
+ self.hidden_size = hidden_size
160
+ self.intermediate_size = intermediate_size
161
+ self.num_hidden_layers = num_hidden_layers
162
+ self.num_attention_heads = num_attention_heads
163
+
164
+ # for backward compatibility
165
+ if num_key_value_heads is None:
166
+ num_key_value_heads = num_attention_heads
167
+
168
+ self.num_key_value_heads = num_key_value_heads
169
+ self.hidden_act = hidden_act
170
+ self.initializer_range = initializer_range
171
+ self.rms_norm_eps = rms_norm_eps
172
+ self.pretraining_tp = pretraining_tp
173
+ self.use_cache = use_cache
174
+ self.rope_theta = rope_theta
175
+ self.rope_scaling = rope_scaling
176
+ self._rope_scaling_validation()
177
+ self.attention_dropout = attention_dropout
178
+
179
+ self.img_token_id = img_token_id
180
+ self.boi_token_id = boi_token_id
181
+ self.eoi_token_id = eoi_token_id
182
+ self.eol_token_id = eol_token_id
183
+ self.eof_token_id = eof_token_id
184
+ self.image_area = image_area
185
+
186
+ super().__init__(
187
+ pad_token_id=pad_token_id,
188
+ bos_token_id=bos_token_id,
189
+ eos_token_id=eos_token_id,
190
+ tie_word_embeddings=tie_word_embeddings,
191
+ **kwargs,
192
+ )
193
+
194
+ def _rope_scaling_validation(self):
195
+ """
196
+ Validate the `rope_scaling` configuration.
197
+ """
198
+ if self.rope_scaling is None:
199
+ return
200
+
201
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
202
+ raise ValueError(
203
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
204
+ f"got {self.rope_scaling}"
205
+ )
206
+ rope_scaling_type = self.rope_scaling.get("type", None)
207
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
208
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
209
+ raise ValueError(
210
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
211
+ )
212
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
213
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
emu3.tiktoken ADDED
The diff for this file is too large to render. See raw diff
 
emu3_vision_tokens.txt ADDED
The diff for this file is too large to render. See raw diff
 
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 151849,
4
+ "eos_token_id": 151850,
5
+ "pad_token_id": 151643,
6
+ "transformers_version": "4.44.0"
7
+ }
model-00001-of-00007.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:28d546200fc398c80e3cf40c980730e1d4822342cb46883d185473833a4649fd
3
+ size 4937517680
model-00002-of-00007.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:823be6493ea6ac05e16c3e5eb10c8d8995831407b068a97f9e7495dd286baefd
3
+ size 4832007448
model-00003-of-00007.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5270b83bafa7e41bfd48b04fba337e202eb470b14c41fc28f982be84ba7d4550
3
+ size 4999813104
model-00004-of-00007.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0d7d7eb5f0f3e88175ed1d018f9fccd57b84f9cf364253f8417662c5cd21aa8d
3
+ size 4999813128
model-00005-of-00007.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:db39fe4a3f9226359a87a0fcb7b25c601a1f9dff15a7bf5b0bc2cb571708cc25
3
+ size 4832007496
model-00006-of-00007.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d1596fc937a34257ddab522d7e6fad0438e43a717605c35b73e527937b135dde
3
+ size 4999813120
model-00007-of-00007.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0259dc22fadbea3720bbfd43b4693aaa97f5b3ada840c4a06da91fb2d58667c6
3
+ size 4367107768
model.safetensors.index.json ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 33968046080
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00007-of-00007.safetensors",
7
+ "model.embed_tokens.weight": "model-00001-of-00007.safetensors",
8
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00007.safetensors",
9
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00007.safetensors",
10
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00007.safetensors",
11
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00007.safetensors",
12
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00007.safetensors",
13
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00007.safetensors",
14
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00007.safetensors",
15
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00007.safetensors",
16
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00007.safetensors",
17
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00007.safetensors",
18
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00007.safetensors",
19
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00007.safetensors",
20
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00007.safetensors",
21
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00007.safetensors",
22
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00007.safetensors",
23
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00007.safetensors",
24
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00007.safetensors",
25
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00007.safetensors",
26
+ "model.layers.10.input_layernorm.weight": "model-00003-of-00007.safetensors",
27
+ "model.layers.10.mlp.down_proj.weight": "model-00003-of-00007.safetensors",
28
+ "model.layers.10.mlp.gate_proj.weight": "model-00003-of-00007.safetensors",
29
+ "model.layers.10.mlp.up_proj.weight": "model-00003-of-00007.safetensors",
30
+ "model.layers.10.post_attention_layernorm.weight": "model-00003-of-00007.safetensors",
31
+ "model.layers.10.self_attn.k_proj.weight": "model-00003-of-00007.safetensors",
32
+ "model.layers.10.self_attn.o_proj.weight": "model-00003-of-00007.safetensors",
33
+ "model.layers.10.self_attn.q_proj.weight": "model-00003-of-00007.safetensors",
34
+ "model.layers.10.self_attn.v_proj.weight": "model-00003-of-00007.safetensors",
35
+ "model.layers.11.input_layernorm.weight": "model-00003-of-00007.safetensors",
36
+ "model.layers.11.mlp.down_proj.weight": "model-00003-of-00007.safetensors",
37
+ "model.layers.11.mlp.gate_proj.weight": "model-00003-of-00007.safetensors",
38
+ "model.layers.11.mlp.up_proj.weight": "model-00003-of-00007.safetensors",
39
+ "model.layers.11.post_attention_layernorm.weight": "model-00003-of-00007.safetensors",
40
+ "model.layers.11.self_attn.k_proj.weight": "model-00003-of-00007.safetensors",
41
+ "model.layers.11.self_attn.o_proj.weight": "model-00003-of-00007.safetensors",
42
+ "model.layers.11.self_attn.q_proj.weight": "model-00003-of-00007.safetensors",
43
+ "model.layers.11.self_attn.v_proj.weight": "model-00003-of-00007.safetensors",
44
+ "model.layers.12.input_layernorm.weight": "model-00003-of-00007.safetensors",
45
+ "model.layers.12.mlp.down_proj.weight": "model-00003-of-00007.safetensors",
46
+ "model.layers.12.mlp.gate_proj.weight": "model-00003-of-00007.safetensors",
47
+ "model.layers.12.mlp.up_proj.weight": "model-00003-of-00007.safetensors",
48
+ "model.layers.12.post_attention_layernorm.weight": "model-00003-of-00007.safetensors",
49
+ "model.layers.12.self_attn.k_proj.weight": "model-00003-of-00007.safetensors",
50
+ "model.layers.12.self_attn.o_proj.weight": "model-00003-of-00007.safetensors",
51
+ "model.layers.12.self_attn.q_proj.weight": "model-00003-of-00007.safetensors",
52
+ "model.layers.12.self_attn.v_proj.weight": "model-00003-of-00007.safetensors",
53
+ "model.layers.13.input_layernorm.weight": "model-00004-of-00007.safetensors",
54
+ "model.layers.13.mlp.down_proj.weight": "model-00004-of-00007.safetensors",
55
+ "model.layers.13.mlp.gate_proj.weight": "model-00003-of-00007.safetensors",
56
+ "model.layers.13.mlp.up_proj.weight": "model-00004-of-00007.safetensors",
57
+ "model.layers.13.post_attention_layernorm.weight": "model-00004-of-00007.safetensors",
58
+ "model.layers.13.self_attn.k_proj.weight": "model-00003-of-00007.safetensors",
59
+ "model.layers.13.self_attn.o_proj.weight": "model-00003-of-00007.safetensors",
60
+ "model.layers.13.self_attn.q_proj.weight": "model-00003-of-00007.safetensors",
61
+ "model.layers.13.self_attn.v_proj.weight": "model-00003-of-00007.safetensors",
62
+ "model.layers.14.input_layernorm.weight": "model-00004-of-00007.safetensors",
63
+ "model.layers.14.mlp.down_proj.weight": "model-00004-of-00007.safetensors",
64
+ "model.layers.14.mlp.gate_proj.weight": "model-00004-of-00007.safetensors",
65
+ "model.layers.14.mlp.up_proj.weight": "model-00004-of-00007.safetensors",
66
+ "model.layers.14.post_attention_layernorm.weight": "model-00004-of-00007.safetensors",
67
+ "model.layers.14.self_attn.k_proj.weight": "model-00004-of-00007.safetensors",
68
+ "model.layers.14.self_attn.o_proj.weight": "model-00004-of-00007.safetensors",
69
+ "model.layers.14.self_attn.q_proj.weight": "model-00004-of-00007.safetensors",
70
+ "model.layers.14.self_attn.v_proj.weight": "model-00004-of-00007.safetensors",
71
+ "model.layers.15.input_layernorm.weight": "model-00004-of-00007.safetensors",
72
+ "model.layers.15.mlp.down_proj.weight": "model-00004-of-00007.safetensors",
73
+ "model.layers.15.mlp.gate_proj.weight": "model-00004-of-00007.safetensors",
74
+ "model.layers.15.mlp.up_proj.weight": "model-00004-of-00007.safetensors",
75
+ "model.layers.15.post_attention_layernorm.weight": "model-00004-of-00007.safetensors",
76
+ "model.layers.15.self_attn.k_proj.weight": "model-00004-of-00007.safetensors",
77
+ "model.layers.15.self_attn.o_proj.weight": "model-00004-of-00007.safetensors",
78
+ "model.layers.15.self_attn.q_proj.weight": "model-00004-of-00007.safetensors",
79
+ "model.layers.15.self_attn.v_proj.weight": "model-00004-of-00007.safetensors",
80
+ "model.layers.16.input_layernorm.weight": "model-00004-of-00007.safetensors",
81
+ "model.layers.16.mlp.down_proj.weight": "model-00004-of-00007.safetensors",
82
+ "model.layers.16.mlp.gate_proj.weight": "model-00004-of-00007.safetensors",
83
+ "model.layers.16.mlp.up_proj.weight": "model-00004-of-00007.safetensors",
84
+ "model.layers.16.post_attention_layernorm.weight": "model-00004-of-00007.safetensors",
85
+ "model.layers.16.self_attn.k_proj.weight": "model-00004-of-00007.safetensors",
86
+ "model.layers.16.self_attn.o_proj.weight": "model-00004-of-00007.safetensors",
87
+ "model.layers.16.self_attn.q_proj.weight": "model-00004-of-00007.safetensors",
88
+ "model.layers.16.self_attn.v_proj.weight": "model-00004-of-00007.safetensors",
89
+ "model.layers.17.input_layernorm.weight": "model-00004-of-00007.safetensors",
90
+ "model.layers.17.mlp.down_proj.weight": "model-00004-of-00007.safetensors",
91
+ "model.layers.17.mlp.gate_proj.weight": "model-00004-of-00007.safetensors",
92
+ "model.layers.17.mlp.up_proj.weight": "model-00004-of-00007.safetensors",
93
+ "model.layers.17.post_attention_layernorm.weight": "model-00004-of-00007.safetensors",
94
+ "model.layers.17.self_attn.k_proj.weight": "model-00004-of-00007.safetensors",
95
+ "model.layers.17.self_attn.o_proj.weight": "model-00004-of-00007.safetensors",
96
+ "model.layers.17.self_attn.q_proj.weight": "model-00004-of-00007.safetensors",
97
+ "model.layers.17.self_attn.v_proj.weight": "model-00004-of-00007.safetensors",
98
+ "model.layers.18.input_layernorm.weight": "model-00004-of-00007.safetensors",
99
+ "model.layers.18.mlp.down_proj.weight": "model-00004-of-00007.safetensors",
100
+ "model.layers.18.mlp.gate_proj.weight": "model-00004-of-00007.safetensors",
101
+ "model.layers.18.mlp.up_proj.weight": "model-00004-of-00007.safetensors",
102
+ "model.layers.18.post_attention_layernorm.weight": "model-00004-of-00007.safetensors",
103
+ "model.layers.18.self_attn.k_proj.weight": "model-00004-of-00007.safetensors",
104
+ "model.layers.18.self_attn.o_proj.weight": "model-00004-of-00007.safetensors",
105
+ "model.layers.18.self_attn.q_proj.weight": "model-00004-of-00007.safetensors",
106
+ "model.layers.18.self_attn.v_proj.weight": "model-00004-of-00007.safetensors",
107
+ "model.layers.19.input_layernorm.weight": "model-00005-of-00007.safetensors",
108
+ "model.layers.19.mlp.down_proj.weight": "model-00005-of-00007.safetensors",
109
+ "model.layers.19.mlp.gate_proj.weight": "model-00005-of-00007.safetensors",
110
+ "model.layers.19.mlp.up_proj.weight": "model-00005-of-00007.safetensors",
111
+ "model.layers.19.post_attention_layernorm.weight": "model-00005-of-00007.safetensors",
112
+ "model.layers.19.self_attn.k_proj.weight": "model-00004-of-00007.safetensors",
113
+ "model.layers.19.self_attn.o_proj.weight": "model-00004-of-00007.safetensors",
114
+ "model.layers.19.self_attn.q_proj.weight": "model-00004-of-00007.safetensors",
115
+ "model.layers.19.self_attn.v_proj.weight": "model-00004-of-00007.safetensors",
116
+ "model.layers.2.input_layernorm.weight": "model-00002-of-00007.safetensors",
117
+ "model.layers.2.mlp.down_proj.weight": "model-00002-of-00007.safetensors",
118
+ "model.layers.2.mlp.gate_proj.weight": "model-00002-of-00007.safetensors",
119
+ "model.layers.2.mlp.up_proj.weight": "model-00002-of-00007.safetensors",
120
+ "model.layers.2.post_attention_layernorm.weight": "model-00002-of-00007.safetensors",
121
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00007.safetensors",
122
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00007.safetensors",
123
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00007.safetensors",
124
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00007.safetensors",
125
+ "model.layers.20.input_layernorm.weight": "model-00005-of-00007.safetensors",
126
+ "model.layers.20.mlp.down_proj.weight": "model-00005-of-00007.safetensors",
127
+ "model.layers.20.mlp.gate_proj.weight": "model-00005-of-00007.safetensors",
128
+ "model.layers.20.mlp.up_proj.weight": "model-00005-of-00007.safetensors",
129
+ "model.layers.20.post_attention_layernorm.weight": "model-00005-of-00007.safetensors",
130
+ "model.layers.20.self_attn.k_proj.weight": "model-00005-of-00007.safetensors",
131
+ "model.layers.20.self_attn.o_proj.weight": "model-00005-of-00007.safetensors",
132
+ "model.layers.20.self_attn.q_proj.weight": "model-00005-of-00007.safetensors",
133
+ "model.layers.20.self_attn.v_proj.weight": "model-00005-of-00007.safetensors",
134
+ "model.layers.21.input_layernorm.weight": "model-00005-of-00007.safetensors",
135
+ "model.layers.21.mlp.down_proj.weight": "model-00005-of-00007.safetensors",
136
+ "model.layers.21.mlp.gate_proj.weight": "model-00005-of-00007.safetensors",
137
+ "model.layers.21.mlp.up_proj.weight": "model-00005-of-00007.safetensors",
138
+ "model.layers.21.post_attention_layernorm.weight": "model-00005-of-00007.safetensors",
139
+ "model.layers.21.self_attn.k_proj.weight": "model-00005-of-00007.safetensors",
140
+ "model.layers.21.self_attn.o_proj.weight": "model-00005-of-00007.safetensors",
141
+ "model.layers.21.self_attn.q_proj.weight": "model-00005-of-00007.safetensors",
142
+ "model.layers.21.self_attn.v_proj.weight": "model-00005-of-00007.safetensors",
143
+ "model.layers.22.input_layernorm.weight": "model-00005-of-00007.safetensors",
144
+ "model.layers.22.mlp.down_proj.weight": "model-00005-of-00007.safetensors",
145
+ "model.layers.22.mlp.gate_proj.weight": "model-00005-of-00007.safetensors",
146
+ "model.layers.22.mlp.up_proj.weight": "model-00005-of-00007.safetensors",
147
+ "model.layers.22.post_attention_layernorm.weight": "model-00005-of-00007.safetensors",
148
+ "model.layers.22.self_attn.k_proj.weight": "model-00005-of-00007.safetensors",
149
+ "model.layers.22.self_attn.o_proj.weight": "model-00005-of-00007.safetensors",
150
+ "model.layers.22.self_attn.q_proj.weight": "model-00005-of-00007.safetensors",
151
+ "model.layers.22.self_attn.v_proj.weight": "model-00005-of-00007.safetensors",
152
+ "model.layers.23.input_layernorm.weight": "model-00005-of-00007.safetensors",
153
+ "model.layers.23.mlp.down_proj.weight": "model-00005-of-00007.safetensors",
154
+ "model.layers.23.mlp.gate_proj.weight": "model-00005-of-00007.safetensors",
155
+ "model.layers.23.mlp.up_proj.weight": "model-00005-of-00007.safetensors",
156
+ "model.layers.23.post_attention_layernorm.weight": "model-00005-of-00007.safetensors",
157
+ "model.layers.23.self_attn.k_proj.weight": "model-00005-of-00007.safetensors",
158
+ "model.layers.23.self_attn.o_proj.weight": "model-00005-of-00007.safetensors",
159
+ "model.layers.23.self_attn.q_proj.weight": "model-00005-of-00007.safetensors",
160
+ "model.layers.23.self_attn.v_proj.weight": "model-00005-of-00007.safetensors",
161
+ "model.layers.24.input_layernorm.weight": "model-00006-of-00007.safetensors",
162
+ "model.layers.24.mlp.down_proj.weight": "model-00006-of-00007.safetensors",
163
+ "model.layers.24.mlp.gate_proj.weight": "model-00005-of-00007.safetensors",
164
+ "model.layers.24.mlp.up_proj.weight": "model-00005-of-00007.safetensors",
165
+ "model.layers.24.post_attention_layernorm.weight": "model-00006-of-00007.safetensors",
166
+ "model.layers.24.self_attn.k_proj.weight": "model-00005-of-00007.safetensors",
167
+ "model.layers.24.self_attn.o_proj.weight": "model-00005-of-00007.safetensors",
168
+ "model.layers.24.self_attn.q_proj.weight": "model-00005-of-00007.safetensors",
169
+ "model.layers.24.self_attn.v_proj.weight": "model-00005-of-00007.safetensors",
170
+ "model.layers.25.input_layernorm.weight": "model-00006-of-00007.safetensors",
171
+ "model.layers.25.mlp.down_proj.weight": "model-00006-of-00007.safetensors",
172
+ "model.layers.25.mlp.gate_proj.weight": "model-00006-of-00007.safetensors",
173
+ "model.layers.25.mlp.up_proj.weight": "model-00006-of-00007.safetensors",
174
+ "model.layers.25.post_attention_layernorm.weight": "model-00006-of-00007.safetensors",
175
+ "model.layers.25.self_attn.k_proj.weight": "model-00006-of-00007.safetensors",
176
+ "model.layers.25.self_attn.o_proj.weight": "model-00006-of-00007.safetensors",
177
+ "model.layers.25.self_attn.q_proj.weight": "model-00006-of-00007.safetensors",
178
+ "model.layers.25.self_attn.v_proj.weight": "model-00006-of-00007.safetensors",
179
+ "model.layers.26.input_layernorm.weight": "model-00006-of-00007.safetensors",
180
+ "model.layers.26.mlp.down_proj.weight": "model-00006-of-00007.safetensors",
181
+ "model.layers.26.mlp.gate_proj.weight": "model-00006-of-00007.safetensors",
182
+ "model.layers.26.mlp.up_proj.weight": "model-00006-of-00007.safetensors",
183
+ "model.layers.26.post_attention_layernorm.weight": "model-00006-of-00007.safetensors",
184
+ "model.layers.26.self_attn.k_proj.weight": "model-00006-of-00007.safetensors",
185
+ "model.layers.26.self_attn.o_proj.weight": "model-00006-of-00007.safetensors",
186
+ "model.layers.26.self_attn.q_proj.weight": "model-00006-of-00007.safetensors",
187
+ "model.layers.26.self_attn.v_proj.weight": "model-00006-of-00007.safetensors",
188
+ "model.layers.27.input_layernorm.weight": "model-00006-of-00007.safetensors",
189
+ "model.layers.27.mlp.down_proj.weight": "model-00006-of-00007.safetensors",
190
+ "model.layers.27.mlp.gate_proj.weight": "model-00006-of-00007.safetensors",
191
+ "model.layers.27.mlp.up_proj.weight": "model-00006-of-00007.safetensors",
192
+ "model.layers.27.post_attention_layernorm.weight": "model-00006-of-00007.safetensors",
193
+ "model.layers.27.self_attn.k_proj.weight": "model-00006-of-00007.safetensors",
194
+ "model.layers.27.self_attn.o_proj.weight": "model-00006-of-00007.safetensors",
195
+ "model.layers.27.self_attn.q_proj.weight": "model-00006-of-00007.safetensors",
196
+ "model.layers.27.self_attn.v_proj.weight": "model-00006-of-00007.safetensors",
197
+ "model.layers.28.input_layernorm.weight": "model-00006-of-00007.safetensors",
198
+ "model.layers.28.mlp.down_proj.weight": "model-00006-of-00007.safetensors",
199
+ "model.layers.28.mlp.gate_proj.weight": "model-00006-of-00007.safetensors",
200
+ "model.layers.28.mlp.up_proj.weight": "model-00006-of-00007.safetensors",
201
+ "model.layers.28.post_attention_layernorm.weight": "model-00006-of-00007.safetensors",
202
+ "model.layers.28.self_attn.k_proj.weight": "model-00006-of-00007.safetensors",
203
+ "model.layers.28.self_attn.o_proj.weight": "model-00006-of-00007.safetensors",
204
+ "model.layers.28.self_attn.q_proj.weight": "model-00006-of-00007.safetensors",
205
+ "model.layers.28.self_attn.v_proj.weight": "model-00006-of-00007.safetensors",
206
+ "model.layers.29.input_layernorm.weight": "model-00006-of-00007.safetensors",
207
+ "model.layers.29.mlp.down_proj.weight": "model-00006-of-00007.safetensors",
208
+ "model.layers.29.mlp.gate_proj.weight": "model-00006-of-00007.safetensors",
209
+ "model.layers.29.mlp.up_proj.weight": "model-00006-of-00007.safetensors",
210
+ "model.layers.29.post_attention_layernorm.weight": "model-00006-of-00007.safetensors",
211
+ "model.layers.29.self_attn.k_proj.weight": "model-00006-of-00007.safetensors",
212
+ "model.layers.29.self_attn.o_proj.weight": "model-00006-of-00007.safetensors",
213
+ "model.layers.29.self_attn.q_proj.weight": "model-00006-of-00007.safetensors",
214
+ "model.layers.29.self_attn.v_proj.weight": "model-00006-of-00007.safetensors",
215
+ "model.layers.3.input_layernorm.weight": "model-00002-of-00007.safetensors",
216
+ "model.layers.3.mlp.down_proj.weight": "model-00002-of-00007.safetensors",
217
+ "model.layers.3.mlp.gate_proj.weight": "model-00002-of-00007.safetensors",
218
+ "model.layers.3.mlp.up_proj.weight": "model-00002-of-00007.safetensors",
219
+ "model.layers.3.post_attention_layernorm.weight": "model-00002-of-00007.safetensors",
220
+ "model.layers.3.self_attn.k_proj.weight": "model-00002-of-00007.safetensors",
221
+ "model.layers.3.self_attn.o_proj.weight": "model-00002-of-00007.safetensors",
222
+ "model.layers.3.self_attn.q_proj.weight": "model-00002-of-00007.safetensors",
223
+ "model.layers.3.self_attn.v_proj.weight": "model-00002-of-00007.safetensors",
224
+ "model.layers.30.input_layernorm.weight": "model-00007-of-00007.safetensors",
225
+ "model.layers.30.mlp.down_proj.weight": "model-00007-of-00007.safetensors",
226
+ "model.layers.30.mlp.gate_proj.weight": "model-00006-of-00007.safetensors",
227
+ "model.layers.30.mlp.up_proj.weight": "model-00007-of-00007.safetensors",
228
+ "model.layers.30.post_attention_layernorm.weight": "model-00007-of-00007.safetensors",
229
+ "model.layers.30.self_attn.k_proj.weight": "model-00006-of-00007.safetensors",
230
+ "model.layers.30.self_attn.o_proj.weight": "model-00006-of-00007.safetensors",
231
+ "model.layers.30.self_attn.q_proj.weight": "model-00006-of-00007.safetensors",
232
+ "model.layers.30.self_attn.v_proj.weight": "model-00006-of-00007.safetensors",
233
+ "model.layers.31.input_layernorm.weight": "model-00007-of-00007.safetensors",
234
+ "model.layers.31.mlp.down_proj.weight": "model-00007-of-00007.safetensors",
235
+ "model.layers.31.mlp.gate_proj.weight": "model-00007-of-00007.safetensors",
236
+ "model.layers.31.mlp.up_proj.weight": "model-00007-of-00007.safetensors",
237
+ "model.layers.31.post_attention_layernorm.weight": "model-00007-of-00007.safetensors",
238
+ "model.layers.31.self_attn.k_proj.weight": "model-00007-of-00007.safetensors",
239
+ "model.layers.31.self_attn.o_proj.weight": "model-00007-of-00007.safetensors",
240
+ "model.layers.31.self_attn.q_proj.weight": "model-00007-of-00007.safetensors",
241
+ "model.layers.31.self_attn.v_proj.weight": "model-00007-of-00007.safetensors",
242
+ "model.layers.4.input_layernorm.weight": "model-00002-of-00007.safetensors",
243
+ "model.layers.4.mlp.down_proj.weight": "model-00002-of-00007.safetensors",
244
+ "model.layers.4.mlp.gate_proj.weight": "model-00002-of-00007.safetensors",
245
+ "model.layers.4.mlp.up_proj.weight": "model-00002-of-00007.safetensors",
246
+ "model.layers.4.post_attention_layernorm.weight": "model-00002-of-00007.safetensors",
247
+ "model.layers.4.self_attn.k_proj.weight": "model-00002-of-00007.safetensors",
248
+ "model.layers.4.self_attn.o_proj.weight": "model-00002-of-00007.safetensors",
249
+ "model.layers.4.self_attn.q_proj.weight": "model-00002-of-00007.safetensors",
250
+ "model.layers.4.self_attn.v_proj.weight": "model-00002-of-00007.safetensors",
251
+ "model.layers.5.input_layernorm.weight": "model-00002-of-00007.safetensors",
252
+ "model.layers.5.mlp.down_proj.weight": "model-00002-of-00007.safetensors",
253
+ "model.layers.5.mlp.gate_proj.weight": "model-00002-of-00007.safetensors",
254
+ "model.layers.5.mlp.up_proj.weight": "model-00002-of-00007.safetensors",
255
+ "model.layers.5.post_attention_layernorm.weight": "model-00002-of-00007.safetensors",
256
+ "model.layers.5.self_attn.k_proj.weight": "model-00002-of-00007.safetensors",
257
+ "model.layers.5.self_attn.o_proj.weight": "model-00002-of-00007.safetensors",
258
+ "model.layers.5.self_attn.q_proj.weight": "model-00002-of-00007.safetensors",
259
+ "model.layers.5.self_attn.v_proj.weight": "model-00002-of-00007.safetensors",
260
+ "model.layers.6.input_layernorm.weight": "model-00002-of-00007.safetensors",
261
+ "model.layers.6.mlp.down_proj.weight": "model-00002-of-00007.safetensors",
262
+ "model.layers.6.mlp.gate_proj.weight": "model-00002-of-00007.safetensors",
263
+ "model.layers.6.mlp.up_proj.weight": "model-00002-of-00007.safetensors",
264
+ "model.layers.6.post_attention_layernorm.weight": "model-00002-of-00007.safetensors",
265
+ "model.layers.6.self_attn.k_proj.weight": "model-00002-of-00007.safetensors",
266
+ "model.layers.6.self_attn.o_proj.weight": "model-00002-of-00007.safetensors",
267
+ "model.layers.6.self_attn.q_proj.weight": "model-00002-of-00007.safetensors",
268
+ "model.layers.6.self_attn.v_proj.weight": "model-00002-of-00007.safetensors",
269
+ "model.layers.7.input_layernorm.weight": "model-00003-of-00007.safetensors",
270
+ "model.layers.7.mlp.down_proj.weight": "model-00003-of-00007.safetensors",
271
+ "model.layers.7.mlp.gate_proj.weight": "model-00002-of-00007.safetensors",
272
+ "model.layers.7.mlp.up_proj.weight": "model-00002-of-00007.safetensors",
273
+ "model.layers.7.post_attention_layernorm.weight": "model-00003-of-00007.safetensors",
274
+ "model.layers.7.self_attn.k_proj.weight": "model-00002-of-00007.safetensors",
275
+ "model.layers.7.self_attn.o_proj.weight": "model-00002-of-00007.safetensors",
276
+ "model.layers.7.self_attn.q_proj.weight": "model-00002-of-00007.safetensors",
277
+ "model.layers.7.self_attn.v_proj.weight": "model-00002-of-00007.safetensors",
278
+ "model.layers.8.input_layernorm.weight": "model-00003-of-00007.safetensors",
279
+ "model.layers.8.mlp.down_proj.weight": "model-00003-of-00007.safetensors",
280
+ "model.layers.8.mlp.gate_proj.weight": "model-00003-of-00007.safetensors",
281
+ "model.layers.8.mlp.up_proj.weight": "model-00003-of-00007.safetensors",
282
+ "model.layers.8.post_attention_layernorm.weight": "model-00003-of-00007.safetensors",
283
+ "model.layers.8.self_attn.k_proj.weight": "model-00003-of-00007.safetensors",
284
+ "model.layers.8.self_attn.o_proj.weight": "model-00003-of-00007.safetensors",
285
+ "model.layers.8.self_attn.q_proj.weight": "model-00003-of-00007.safetensors",
286
+ "model.layers.8.self_attn.v_proj.weight": "model-00003-of-00007.safetensors",
287
+ "model.layers.9.input_layernorm.weight": "model-00003-of-00007.safetensors",
288
+ "model.layers.9.mlp.down_proj.weight": "model-00003-of-00007.safetensors",
289
+ "model.layers.9.mlp.gate_proj.weight": "model-00003-of-00007.safetensors",
290
+ "model.layers.9.mlp.up_proj.weight": "model-00003-of-00007.safetensors",
291
+ "model.layers.9.post_attention_layernorm.weight": "model-00003-of-00007.safetensors",
292
+ "model.layers.9.self_attn.k_proj.weight": "model-00003-of-00007.safetensors",
293
+ "model.layers.9.self_attn.o_proj.weight": "model-00003-of-00007.safetensors",
294
+ "model.layers.9.self_attn.q_proj.weight": "model-00003-of-00007.safetensors",
295
+ "model.layers.9.self_attn.v_proj.weight": "model-00003-of-00007.safetensors",
296
+ "model.norm.weight": "model-00007-of-00007.safetensors"
297
+ }
298
+ }
modeling_emu3.py ADDED
@@ -0,0 +1,1343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Emu team, BAAI and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ #
21
+ # Adapted from https://github.com/huggingface/transformers/blob/52daf4ec768fb9ffe84a0c373834172a7c54aecc/src/transformers/models/llama/modeling_llama.py
22
+ #
23
+ """ PyTorch Emu3 model."""
24
+ import math
25
+ import warnings
26
+ from typing import List, Optional, Tuple, Union
27
+
28
+ import torch
29
+ import torch.nn.functional as F
30
+ import torch.utils.checkpoint
31
+ from torch import nn
32
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
33
+
34
+ from transformers.activations import ACT2FN
35
+ from transformers.cache_utils import Cache, DynamicCache
36
+ from transformers.modeling_attn_mask_utils import (
37
+ AttentionMaskConverter,
38
+ _prepare_4d_attention_mask,
39
+ _prepare_4d_causal_attention_mask,
40
+ _prepare_4d_causal_attention_mask_for_sdpa,
41
+ )
42
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
43
+ from transformers.modeling_utils import PreTrainedModel
44
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
45
+ from transformers.utils import (
46
+ add_start_docstrings,
47
+ add_start_docstrings_to_model_forward,
48
+ is_flash_attn_2_available,
49
+ is_flash_attn_greater_or_equal_2_10,
50
+ logging,
51
+ replace_return_docstrings,
52
+ )
53
+ from transformers.utils.import_utils import is_torch_fx_available
54
+ from .configuration_emu3 import Emu3Config
55
+
56
+
57
+ if is_flash_attn_2_available():
58
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
59
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
60
+
61
+
62
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
63
+ # It means that the function will not be traced through and simply appear as a node in the graph.
64
+ if is_torch_fx_available():
65
+ if not is_torch_greater_or_equal_than_1_13:
66
+ import torch.fx
67
+
68
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
69
+
70
+
71
+ logger = logging.get_logger(__name__)
72
+
73
+ _CONFIG_FOR_DOC = "Emu3Config"
74
+
75
+
76
+ def _get_unpad_data(attention_mask):
77
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
78
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
79
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
80
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
81
+ return (
82
+ indices,
83
+ cu_seqlens,
84
+ max_seqlen_in_batch,
85
+ )
86
+
87
+
88
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
89
+ warnings.warn(
90
+ "Calling `transformers.models.emu3.modeling_emu3._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask"
91
+ )
92
+ return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
93
+
94
+
95
+ def _make_causal_mask(
96
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
97
+ ):
98
+ warnings.warn(
99
+ "Calling `transformers.models.emu3.modeling_emu3._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.emu3.modeling_emu3.AttentionMaskConverter._make_causal_mask"
100
+ )
101
+ return AttentionMaskConverter._make_causal_mask(
102
+ input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
103
+ )
104
+
105
+
106
+ class Emu3RMSNorm(nn.Module):
107
+ def __init__(self, hidden_size, eps=1e-6):
108
+ """
109
+ Emu3RMSNorm is equivalent to T5LayerNorm
110
+ """
111
+ super().__init__()
112
+ self.weight = nn.Parameter(torch.ones(hidden_size))
113
+ self.variance_epsilon = eps
114
+
115
+ def forward(self, hidden_states):
116
+ input_dtype = hidden_states.dtype
117
+ hidden_states = hidden_states.to(torch.float32)
118
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
119
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
120
+ return self.weight * hidden_states.to(input_dtype)
121
+
122
+
123
+ ALL_LAYERNORM_LAYERS.append(Emu3RMSNorm)
124
+
125
+
126
+ class Emu3RotaryEmbedding(nn.Module):
127
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
128
+ super().__init__()
129
+
130
+ self.dim = dim
131
+ self.max_position_embeddings = max_position_embeddings
132
+ self.base = base
133
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
134
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
135
+
136
+ # Build here to make `torch.jit.trace` work.
137
+ self._set_cos_sin_cache(
138
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
139
+ )
140
+
141
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
142
+ self.max_seq_len_cached = seq_len
143
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
144
+
145
+ freqs = torch.outer(t, self.inv_freq)
146
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
147
+ emb = torch.cat((freqs, freqs), dim=-1)
148
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
149
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
150
+
151
+ def forward(self, x, seq_len=None):
152
+ # x: [bs, num_attention_heads, seq_len, head_size]
153
+ if seq_len > self.max_seq_len_cached:
154
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
155
+
156
+ return (
157
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
158
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
159
+ )
160
+
161
+
162
+ class Emu3LinearScalingRotaryEmbedding(Emu3RotaryEmbedding):
163
+ """Emu3RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
164
+
165
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
166
+ self.scaling_factor = scaling_factor
167
+ super().__init__(dim, max_position_embeddings, base, device)
168
+
169
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
170
+ self.max_seq_len_cached = seq_len
171
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
172
+ t = t / self.scaling_factor
173
+
174
+ freqs = torch.outer(t, self.inv_freq)
175
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
176
+ emb = torch.cat((freqs, freqs), dim=-1)
177
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
178
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
179
+
180
+
181
+ class Emu3DynamicNTKScalingRotaryEmbedding(Emu3RotaryEmbedding):
182
+ """Emu3RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
183
+
184
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
185
+ self.scaling_factor = scaling_factor
186
+ super().__init__(dim, max_position_embeddings, base, device)
187
+
188
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
189
+ self.max_seq_len_cached = seq_len
190
+
191
+ if seq_len > self.max_position_embeddings:
192
+ base = self.base * (
193
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
194
+ ) ** (self.dim / (self.dim - 2))
195
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
196
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
197
+
198
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
199
+
200
+ freqs = torch.outer(t, self.inv_freq)
201
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
202
+ emb = torch.cat((freqs, freqs), dim=-1)
203
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
204
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
205
+
206
+
207
+ def rotate_half(x):
208
+ """Rotates half the hidden dims of the input."""
209
+ x1 = x[..., : x.shape[-1] // 2]
210
+ x2 = x[..., x.shape[-1] // 2 :]
211
+ return torch.cat((-x2, x1), dim=-1)
212
+
213
+
214
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
215
+ """Applies Rotary Position Embedding to the query and key tensors.
216
+
217
+ Args:
218
+ q (`torch.Tensor`): The query tensor.
219
+ k (`torch.Tensor`): The key tensor.
220
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
221
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
222
+ position_ids (`torch.Tensor`):
223
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
224
+ used to pass offsetted position ids when working with a KV-cache.
225
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
226
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
227
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
228
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
229
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
230
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
231
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
232
+ Returns:
233
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
234
+ """
235
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
236
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
237
+ q_embed = (q * cos) + (rotate_half(q) * sin)
238
+ k_embed = (k * cos) + (rotate_half(k) * sin)
239
+ return q_embed, k_embed
240
+
241
+
242
+ class Emu3MLP(nn.Module):
243
+ def __init__(self, config):
244
+ super().__init__()
245
+ self.config = config
246
+ self.hidden_size = config.hidden_size
247
+ self.intermediate_size = config.intermediate_size
248
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
249
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
250
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
251
+ self.act_fn = ACT2FN[config.hidden_act]
252
+
253
+ def forward(self, x):
254
+ if self.config.pretraining_tp > 1:
255
+ slice = self.intermediate_size // self.config.pretraining_tp
256
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
257
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
258
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
259
+
260
+ gate_proj = torch.cat(
261
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
262
+ )
263
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
264
+
265
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
266
+ down_proj = [
267
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
268
+ ]
269
+ down_proj = sum(down_proj)
270
+ else:
271
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
272
+
273
+ return down_proj
274
+
275
+
276
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
277
+ """
278
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
279
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
280
+ """
281
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
282
+ if n_rep == 1:
283
+ return hidden_states
284
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
285
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
286
+
287
+
288
+ class Emu3Attention(nn.Module):
289
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
290
+
291
+ def __init__(self, config: Emu3Config, layer_idx: Optional[int] = None):
292
+ super().__init__()
293
+ self.config = config
294
+ self.layer_idx = layer_idx
295
+ if layer_idx is None:
296
+ logger.warning_once(
297
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
298
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
299
+ "when creating this class."
300
+ )
301
+
302
+ self.attention_dropout = config.attention_dropout
303
+ self.hidden_size = config.hidden_size
304
+ self.num_heads = config.num_attention_heads
305
+ self.head_dim = self.hidden_size // self.num_heads
306
+ self.num_key_value_heads = config.num_key_value_heads
307
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
308
+ self.max_position_embeddings = config.max_position_embeddings
309
+ self.rope_theta = config.rope_theta
310
+ self.is_causal = True
311
+
312
+ if (self.head_dim * self.num_heads) != self.hidden_size:
313
+ raise ValueError(
314
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
315
+ f" and `num_heads`: {self.num_heads})."
316
+ )
317
+
318
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
319
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
320
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
321
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
322
+ self._init_rope()
323
+
324
+ def _init_rope(self):
325
+ if self.config.rope_scaling is None:
326
+ self.rotary_emb = Emu3RotaryEmbedding(
327
+ self.head_dim,
328
+ max_position_embeddings=self.max_position_embeddings,
329
+ base=self.rope_theta,
330
+ )
331
+ else:
332
+ scaling_type = self.config.rope_scaling["type"]
333
+ scaling_factor = self.config.rope_scaling["factor"]
334
+ if scaling_type == "linear":
335
+ self.rotary_emb = Emu3LinearScalingRotaryEmbedding(
336
+ self.head_dim,
337
+ max_position_embeddings=self.max_position_embeddings,
338
+ scaling_factor=scaling_factor,
339
+ base=self.rope_theta,
340
+ )
341
+ elif scaling_type == "dynamic":
342
+ self.rotary_emb = Emu3DynamicNTKScalingRotaryEmbedding(
343
+ self.head_dim,
344
+ max_position_embeddings=self.max_position_embeddings,
345
+ scaling_factor=scaling_factor,
346
+ base=self.rope_theta,
347
+ )
348
+ else:
349
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
350
+
351
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
352
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
353
+
354
+ def forward(
355
+ self,
356
+ hidden_states: torch.Tensor,
357
+ attention_mask: Optional[torch.Tensor] = None,
358
+ position_ids: Optional[torch.LongTensor] = None,
359
+ past_key_value: Optional[Cache] = None,
360
+ output_attentions: bool = False,
361
+ use_cache: bool = False,
362
+ **kwargs,
363
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
364
+ if "padding_mask" in kwargs:
365
+ warnings.warn(
366
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
367
+ )
368
+
369
+ bsz, q_len, _ = hidden_states.size()
370
+
371
+ if self.config.pretraining_tp > 1:
372
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
373
+ query_slices = self.q_proj.weight.split(
374
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
375
+ )
376
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
377
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
378
+
379
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
380
+ query_states = torch.cat(query_states, dim=-1)
381
+
382
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
383
+ key_states = torch.cat(key_states, dim=-1)
384
+
385
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
386
+ value_states = torch.cat(value_states, dim=-1)
387
+
388
+ else:
389
+ query_states = self.q_proj(hidden_states)
390
+ key_states = self.k_proj(hidden_states)
391
+ value_states = self.v_proj(hidden_states)
392
+
393
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
394
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
395
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
396
+
397
+ kv_seq_len = key_states.shape[-2]
398
+ if past_key_value is not None:
399
+ if self.layer_idx is None:
400
+ raise ValueError(
401
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
402
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
403
+ "with a layer index."
404
+ )
405
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
406
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
407
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
408
+
409
+ if past_key_value is not None:
410
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
411
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
412
+
413
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
414
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
415
+
416
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
417
+
418
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
419
+ raise ValueError(
420
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
421
+ f" {attn_weights.size()}"
422
+ )
423
+
424
+ if attention_mask is not None:
425
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
426
+ raise ValueError(
427
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
428
+ )
429
+ attn_weights = attn_weights + attention_mask
430
+
431
+ # upcast attention to fp32
432
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
433
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
434
+ attn_output = torch.matmul(attn_weights, value_states)
435
+
436
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
437
+ raise ValueError(
438
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
439
+ f" {attn_output.size()}"
440
+ )
441
+
442
+ attn_output = attn_output.transpose(1, 2).contiguous()
443
+
444
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
445
+
446
+ if self.config.pretraining_tp > 1:
447
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
448
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
449
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
450
+ else:
451
+ attn_output = self.o_proj(attn_output)
452
+
453
+ if not output_attentions:
454
+ attn_weights = None
455
+
456
+ return attn_output, attn_weights, past_key_value
457
+
458
+
459
+ class Emu3FlashAttention2(Emu3Attention):
460
+ """
461
+ Emu3 flash attention module. This module inherits from `Emu3Attention` as the weights of the module stays
462
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
463
+ flash attention and deal with padding tokens in case the input contains any of them.
464
+ """
465
+
466
+ def __init__(self, *args, **kwargs):
467
+ super().__init__(*args, **kwargs)
468
+
469
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
470
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
471
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
472
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
473
+
474
+ def forward(
475
+ self,
476
+ hidden_states: torch.Tensor,
477
+ attention_mask: Optional[torch.LongTensor] = None,
478
+ position_ids: Optional[torch.LongTensor] = None,
479
+ past_key_value: Optional[Cache] = None,
480
+ output_attentions: bool = False,
481
+ use_cache: bool = False,
482
+ **kwargs,
483
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
484
+ # Emu3FlashAttention2 attention does not support output_attentions
485
+ if "padding_mask" in kwargs:
486
+ warnings.warn(
487
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
488
+ )
489
+
490
+ # overwrite attention_mask with padding_mask
491
+ attention_mask = kwargs.pop("padding_mask")
492
+
493
+ output_attentions = False
494
+
495
+ bsz, q_len, _ = hidden_states.size()
496
+
497
+ query_states = self.q_proj(hidden_states)
498
+ key_states = self.k_proj(hidden_states)
499
+ value_states = self.v_proj(hidden_states)
500
+
501
+ # Flash attention requires the input to have the shape
502
+ # batch_size x seq_length x head_dim x hidden_dim
503
+ # therefore we just need to keep the original shape
504
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
505
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
506
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
507
+
508
+ kv_seq_len = key_states.shape[-2]
509
+ if past_key_value is not None:
510
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
511
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
512
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
513
+
514
+ if past_key_value is not None:
515
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
516
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
517
+
518
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
519
+ # to be able to avoid many of these transpose/reshape/view.
520
+ query_states = query_states.transpose(1, 2)
521
+ key_states = key_states.transpose(1, 2)
522
+ value_states = value_states.transpose(1, 2)
523
+
524
+ dropout_rate = self.attention_dropout if self.training else 0.0
525
+
526
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
527
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
528
+ # cast them back in the correct dtype just to be sure everything works as expected.
529
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
530
+ # in fp32. (Emu3RMSNorm handles it correctly)
531
+
532
+ input_dtype = query_states.dtype
533
+ if input_dtype == torch.float32:
534
+ # Handle the case where the model is quantized
535
+ if hasattr(self.config, "_pre_quantization_dtype"):
536
+ target_dtype = self.config._pre_quantization_dtype
537
+ else:
538
+ target_dtype = self.q_proj.weight.dtype
539
+
540
+ logger.warning_once(
541
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
542
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
543
+ f" {target_dtype}."
544
+ )
545
+
546
+ query_states = query_states.to(target_dtype)
547
+ key_states = key_states.to(target_dtype)
548
+ value_states = value_states.to(target_dtype)
549
+
550
+ attn_output = self._flash_attention_forward(
551
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
552
+ )
553
+
554
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
555
+ attn_output = self.o_proj(attn_output)
556
+
557
+ if not output_attentions:
558
+ attn_weights = None
559
+
560
+ return attn_output, attn_weights, past_key_value
561
+
562
+ def _flash_attention_forward(
563
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
564
+ ):
565
+ """
566
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
567
+ first unpad the input, then computes the attention scores and pad the final attention scores.
568
+
569
+ Args:
570
+ query_states (`torch.Tensor`):
571
+ Input query states to be passed to Flash Attention API
572
+ key_states (`torch.Tensor`):
573
+ Input key states to be passed to Flash Attention API
574
+ value_states (`torch.Tensor`):
575
+ Input value states to be passed to Flash Attention API
576
+ attention_mask (`torch.Tensor`):
577
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
578
+ position of padding tokens and 1 for the position of non-padding tokens.
579
+ dropout (`int`, *optional*):
580
+ Attention dropout
581
+ softmax_scale (`float`, *optional*):
582
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
583
+ """
584
+ if not self._flash_attn_uses_top_left_mask:
585
+ causal = self.is_causal
586
+ else:
587
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in Emu3FlashAttention2 __init__.
588
+ causal = self.is_causal and query_length != 1
589
+
590
+ # Contains at least one padding token in the sequence
591
+ if attention_mask is not None:
592
+ batch_size = query_states.shape[0]
593
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
594
+ query_states, key_states, value_states, attention_mask, query_length
595
+ )
596
+
597
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
598
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
599
+
600
+ attn_output_unpad = flash_attn_varlen_func(
601
+ query_states,
602
+ key_states,
603
+ value_states,
604
+ cu_seqlens_q=cu_seqlens_q,
605
+ cu_seqlens_k=cu_seqlens_k,
606
+ max_seqlen_q=max_seqlen_in_batch_q,
607
+ max_seqlen_k=max_seqlen_in_batch_k,
608
+ dropout_p=dropout,
609
+ softmax_scale=softmax_scale,
610
+ causal=causal,
611
+ )
612
+
613
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
614
+ else:
615
+ attn_output = flash_attn_func(
616
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
617
+ )
618
+
619
+ return attn_output
620
+
621
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
622
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
623
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
624
+
625
+ key_layer = index_first_axis(
626
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
627
+ )
628
+ value_layer = index_first_axis(
629
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
630
+ )
631
+ if query_length == kv_seq_len:
632
+ query_layer = index_first_axis(
633
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
634
+ )
635
+ cu_seqlens_q = cu_seqlens_k
636
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
637
+ indices_q = indices_k
638
+ elif query_length == 1:
639
+ max_seqlen_in_batch_q = 1
640
+ cu_seqlens_q = torch.arange(
641
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
642
+ ) # There is a memcpy here, that is very bad.
643
+ indices_q = cu_seqlens_q[:-1]
644
+ query_layer = query_layer.squeeze(1)
645
+ else:
646
+ # The -q_len: slice assumes left padding.
647
+ attention_mask = attention_mask[:, -query_length:]
648
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
649
+
650
+ return (
651
+ query_layer,
652
+ key_layer,
653
+ value_layer,
654
+ indices_q,
655
+ (cu_seqlens_q, cu_seqlens_k),
656
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
657
+ )
658
+
659
+
660
+ class Emu3SdpaAttention(Emu3Attention):
661
+ """
662
+ Emu3 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
663
+ `Emu3Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
664
+ SDPA API.
665
+ """
666
+
667
+ # Adapted from Emu3Attention.forward
668
+ def forward(
669
+ self,
670
+ hidden_states: torch.Tensor,
671
+ attention_mask: Optional[torch.Tensor] = None,
672
+ position_ids: Optional[torch.LongTensor] = None,
673
+ past_key_value: Optional[Cache] = None,
674
+ output_attentions: bool = False,
675
+ use_cache: bool = False,
676
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
677
+ if output_attentions:
678
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
679
+ logger.warning_once(
680
+ "Emu3Model is using Emu3SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
681
+ '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.'
682
+ )
683
+ return super().forward(
684
+ hidden_states=hidden_states,
685
+ attention_mask=attention_mask,
686
+ position_ids=position_ids,
687
+ past_key_value=past_key_value,
688
+ output_attentions=output_attentions,
689
+ use_cache=use_cache,
690
+ )
691
+
692
+ bsz, q_len, _ = hidden_states.size()
693
+
694
+ query_states = self.q_proj(hidden_states)
695
+ key_states = self.k_proj(hidden_states)
696
+ value_states = self.v_proj(hidden_states)
697
+
698
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
699
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
700
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
701
+
702
+ kv_seq_len = key_states.shape[-2]
703
+ if past_key_value is not None:
704
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
705
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
706
+
707
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
708
+
709
+ if past_key_value is not None:
710
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
711
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
712
+
713
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
714
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
715
+
716
+ if attention_mask is not None:
717
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
718
+ raise ValueError(
719
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
720
+ )
721
+
722
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
723
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
724
+ if query_states.device.type == "cuda" and attention_mask is not None:
725
+ query_states = query_states.contiguous()
726
+ key_states = key_states.contiguous()
727
+ value_states = value_states.contiguous()
728
+
729
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
730
+ query_states,
731
+ key_states,
732
+ value_states,
733
+ attn_mask=attention_mask,
734
+ dropout_p=self.attention_dropout if self.training else 0.0,
735
+ # 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.
736
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
737
+ )
738
+
739
+ attn_output = attn_output.transpose(1, 2).contiguous()
740
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
741
+
742
+ attn_output = self.o_proj(attn_output)
743
+
744
+ return attn_output, None, past_key_value
745
+
746
+
747
+ EMU3_ATTENTION_CLASSES = {
748
+ "eager": Emu3Attention,
749
+ "flash_attention_2": Emu3FlashAttention2,
750
+ "sdpa": Emu3SdpaAttention,
751
+ }
752
+
753
+
754
+ class Emu3DecoderLayer(nn.Module):
755
+ def __init__(self, config: Emu3Config, layer_idx: int):
756
+ super().__init__()
757
+ self.hidden_size = config.hidden_size
758
+ self.dropout = nn.Dropout(config.attention_dropout)
759
+ self.self_attn = EMU3_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
760
+
761
+ self.mlp = Emu3MLP(config)
762
+ self.input_layernorm = Emu3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
763
+ self.post_attention_layernorm = Emu3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
764
+
765
+ def forward(
766
+ self,
767
+ hidden_states: torch.Tensor,
768
+ attention_mask: Optional[torch.Tensor] = None,
769
+ position_ids: Optional[torch.LongTensor] = None,
770
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
771
+ output_attentions: Optional[bool] = False,
772
+ use_cache: Optional[bool] = False,
773
+ **kwargs,
774
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
775
+ """
776
+ Args:
777
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
778
+ attention_mask (`torch.FloatTensor`, *optional*):
779
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
780
+ query_sequence_length, key_sequence_length)` if default attention is used.
781
+ output_attentions (`bool`, *optional*):
782
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
783
+ returned tensors for more detail.
784
+ use_cache (`bool`, *optional*):
785
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
786
+ (see `past_key_values`).
787
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
788
+ """
789
+ if "padding_mask" in kwargs:
790
+ warnings.warn(
791
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
792
+ )
793
+
794
+ residual = hidden_states
795
+
796
+ hidden_states = self.input_layernorm(hidden_states)
797
+
798
+ # Self Attention
799
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
800
+ hidden_states=hidden_states,
801
+ attention_mask=attention_mask,
802
+ position_ids=position_ids,
803
+ past_key_value=past_key_value,
804
+ output_attentions=output_attentions,
805
+ use_cache=use_cache,
806
+ **kwargs,
807
+ )
808
+ hidden_states = residual + self.dropout(hidden_states)
809
+
810
+ # Fully Connected
811
+ residual = hidden_states
812
+ hidden_states = self.post_attention_layernorm(hidden_states)
813
+ hidden_states = self.mlp(hidden_states)
814
+ hidden_states = residual + self.dropout(hidden_states)
815
+
816
+ outputs = (hidden_states,)
817
+
818
+ if output_attentions:
819
+ outputs += (self_attn_weights,)
820
+
821
+ if use_cache:
822
+ outputs += (present_key_value,)
823
+
824
+ return outputs
825
+
826
+
827
+ EMU3_START_DOCSTRING = r"""
828
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
829
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
830
+ etc.)
831
+
832
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
833
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
834
+ and behavior.
835
+
836
+ Parameters:
837
+ config ([`Emu3Config`]):
838
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
839
+ load the weights associated with the model, only the configuration. Check out the
840
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
841
+ """
842
+
843
+
844
+ @add_start_docstrings(
845
+ "The bare Emu3 Model outputting raw hidden-states without any specific head on top.",
846
+ EMU3_START_DOCSTRING,
847
+ )
848
+ class Emu3PreTrainedModel(PreTrainedModel):
849
+ config_class = Emu3Config
850
+ base_model_prefix = "model"
851
+ supports_gradient_checkpointing = True
852
+ _no_split_modules = ["Emu3DecoderLayer"]
853
+ _skip_keys_device_placement = "past_key_values"
854
+ _supports_flash_attn_2 = True
855
+ _supports_sdpa = True
856
+ _supports_cache_class = True
857
+
858
+ def _init_weights(self, module):
859
+ std = self.config.initializer_range
860
+ if isinstance(module, nn.Linear):
861
+ module.weight.data.normal_(mean=0.0, std=std)
862
+ if module.bias is not None:
863
+ module.bias.data.zero_()
864
+ elif isinstance(module, nn.Embedding):
865
+ module.weight.data.normal_(mean=0.0, std=std)
866
+ if module.padding_idx is not None:
867
+ module.weight.data[module.padding_idx].zero_()
868
+
869
+
870
+ EMU3_INPUTS_DOCSTRING = r"""
871
+ Args:
872
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
873
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
874
+ it.
875
+
876
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
877
+ [`PreTrainedTokenizer.__call__`] for details.
878
+
879
+ [What are input IDs?](../glossary#input-ids)
880
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
881
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
882
+
883
+ - 1 for tokens that are **not masked**,
884
+ - 0 for tokens that are **masked**.
885
+
886
+ [What are attention masks?](../glossary#attention-mask)
887
+
888
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
889
+ [`PreTrainedTokenizer.__call__`] for details.
890
+
891
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
892
+ `past_key_values`).
893
+
894
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
895
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
896
+ information on the default strategy.
897
+
898
+ - 1 indicates the head is **not masked**,
899
+ - 0 indicates the head is **masked**.
900
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
901
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
902
+ config.n_positions - 1]`.
903
+
904
+ [What are position IDs?](../glossary#position-ids)
905
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
906
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
907
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
908
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
909
+
910
+ Two formats are allowed:
911
+ - a [`~cache_utils.Cache`] instance;
912
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
913
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
914
+ cache format.
915
+
916
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
917
+ legacy cache format will be returned.
918
+
919
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
920
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
921
+ of shape `(batch_size, sequence_length)`.
922
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
923
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
924
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
925
+ model's internal embedding lookup matrix.
926
+ use_cache (`bool`, *optional*):
927
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
928
+ `past_key_values`).
929
+ output_attentions (`bool`, *optional*):
930
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
931
+ tensors for more detail.
932
+ output_hidden_states (`bool`, *optional*):
933
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
934
+ more detail.
935
+ return_dict (`bool`, *optional*):
936
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
937
+ """
938
+
939
+
940
+ @add_start_docstrings(
941
+ "The bare Emu3 Model outputting raw hidden-states without any specific head on top.",
942
+ EMU3_START_DOCSTRING,
943
+ )
944
+ class Emu3Model(Emu3PreTrainedModel):
945
+ """
946
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Emu3DecoderLayer`]
947
+
948
+ Args:
949
+ config: Emu3Config
950
+ """
951
+
952
+ def __init__(self, config: Emu3Config):
953
+ super().__init__(config)
954
+ self.padding_idx = config.pad_token_id
955
+ self.vocab_size = config.vocab_size
956
+
957
+ self.dropout = nn.Dropout(config.attention_dropout)
958
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
959
+ self.layers = nn.ModuleList(
960
+ [Emu3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
961
+ )
962
+ self._use_sdpa = config._attn_implementation == "sdpa"
963
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
964
+ self.norm = Emu3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
965
+
966
+ self.gradient_checkpointing = False
967
+ # Initialize weights and apply final processing
968
+ self.post_init()
969
+
970
+ def get_input_embeddings(self):
971
+ return self.embed_tokens
972
+
973
+ def set_input_embeddings(self, value):
974
+ self.embed_tokens = value
975
+
976
+ @add_start_docstrings_to_model_forward(EMU3_INPUTS_DOCSTRING)
977
+ def forward(
978
+ self,
979
+ input_ids: torch.LongTensor = None,
980
+ attention_mask: Optional[torch.Tensor] = None,
981
+ position_ids: Optional[torch.LongTensor] = None,
982
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
983
+ inputs_embeds: Optional[torch.FloatTensor] = None,
984
+ use_cache: Optional[bool] = None,
985
+ output_attentions: Optional[bool] = None,
986
+ output_hidden_states: Optional[bool] = None,
987
+ return_dict: Optional[bool] = None,
988
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
989
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
990
+ output_hidden_states = (
991
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
992
+ )
993
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
994
+
995
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
996
+
997
+ # retrieve input_ids and inputs_embeds
998
+ if input_ids is not None and inputs_embeds is not None:
999
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1000
+ elif input_ids is not None:
1001
+ batch_size, seq_length = input_ids.shape[:2]
1002
+ elif inputs_embeds is not None:
1003
+ batch_size, seq_length = inputs_embeds.shape[:2]
1004
+ else:
1005
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1006
+
1007
+ if self.gradient_checkpointing and self.training:
1008
+ if use_cache:
1009
+ logger.warning_once(
1010
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1011
+ )
1012
+ use_cache = False
1013
+
1014
+ past_key_values_length = 0
1015
+ if use_cache:
1016
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1017
+ if use_legacy_cache:
1018
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1019
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1020
+
1021
+ if position_ids is None:
1022
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1023
+ position_ids = torch.arange(
1024
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1025
+ )
1026
+ position_ids = position_ids.unsqueeze(0)
1027
+
1028
+ if inputs_embeds is None:
1029
+ inputs_embeds = self.embed_tokens(input_ids)
1030
+
1031
+ if self._use_flash_attention_2:
1032
+ # 2d mask is passed through the layers
1033
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1034
+ elif self._use_sdpa and not output_attentions:
1035
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1036
+ # the manual implementation that requires a 4D causal mask in all cases.
1037
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1038
+ attention_mask,
1039
+ (batch_size, seq_length),
1040
+ inputs_embeds,
1041
+ past_key_values_length,
1042
+ )
1043
+ else:
1044
+ # 4d mask is passed through the layers
1045
+ attention_mask = _prepare_4d_causal_attention_mask(
1046
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1047
+ )
1048
+
1049
+ # embed positions
1050
+ hidden_states = self.dropout(inputs_embeds)
1051
+
1052
+ # decoder layers
1053
+ all_hidden_states = () if output_hidden_states else None
1054
+ all_self_attns = () if output_attentions else None
1055
+ next_decoder_cache = None
1056
+
1057
+ for decoder_layer in self.layers:
1058
+ if output_hidden_states:
1059
+ all_hidden_states += (hidden_states,)
1060
+
1061
+ if self.gradient_checkpointing and self.training:
1062
+ layer_outputs = self._gradient_checkpointing_func(
1063
+ decoder_layer.__call__,
1064
+ hidden_states,
1065
+ attention_mask,
1066
+ position_ids,
1067
+ past_key_values,
1068
+ output_attentions,
1069
+ use_cache,
1070
+ )
1071
+ else:
1072
+ layer_outputs = decoder_layer(
1073
+ hidden_states,
1074
+ attention_mask=attention_mask,
1075
+ position_ids=position_ids,
1076
+ past_key_value=past_key_values,
1077
+ output_attentions=output_attentions,
1078
+ use_cache=use_cache,
1079
+ )
1080
+
1081
+ hidden_states = layer_outputs[0]
1082
+
1083
+ if use_cache:
1084
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1085
+
1086
+ if output_attentions:
1087
+ all_self_attns += (layer_outputs[1],)
1088
+
1089
+ hidden_states = self.norm(hidden_states)
1090
+
1091
+ # add hidden states from the last decoder layer
1092
+ if output_hidden_states:
1093
+ all_hidden_states += (hidden_states,)
1094
+
1095
+ next_cache = None
1096
+ if use_cache:
1097
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1098
+ if not return_dict:
1099
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1100
+ return BaseModelOutputWithPast(
1101
+ last_hidden_state=hidden_states,
1102
+ past_key_values=next_cache,
1103
+ hidden_states=all_hidden_states,
1104
+ attentions=all_self_attns,
1105
+ )
1106
+
1107
+
1108
+ class Emu3ForCausalLM(Emu3PreTrainedModel):
1109
+ _tied_weights_keys = ["lm_head.weight"]
1110
+
1111
+ def __init__(self, config):
1112
+ super().__init__(config)
1113
+ self.model = Emu3Model(config)
1114
+ self.vocab_size = config.vocab_size
1115
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1116
+
1117
+ # Initialize weights and apply final processing
1118
+ self.post_init()
1119
+
1120
+ def get_input_embeddings(self):
1121
+ return self.model.embed_tokens
1122
+
1123
+ def set_input_embeddings(self, value):
1124
+ self.model.embed_tokens = value
1125
+
1126
+ def get_output_embeddings(self):
1127
+ return self.lm_head
1128
+
1129
+ def set_output_embeddings(self, new_embeddings):
1130
+ self.lm_head = new_embeddings
1131
+
1132
+ def set_decoder(self, decoder):
1133
+ self.model = decoder
1134
+
1135
+ def get_decoder(self):
1136
+ return self.model
1137
+
1138
+ @add_start_docstrings_to_model_forward(EMU3_INPUTS_DOCSTRING)
1139
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1140
+ def forward(
1141
+ self,
1142
+ input_ids: torch.LongTensor = None,
1143
+ attention_mask: Optional[torch.Tensor] = None,
1144
+ position_ids: Optional[torch.LongTensor] = None,
1145
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1146
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1147
+ labels: Optional[torch.LongTensor] = None,
1148
+ use_cache: Optional[bool] = None,
1149
+ output_attentions: Optional[bool] = None,
1150
+ output_hidden_states: Optional[bool] = None,
1151
+ return_dict: Optional[bool] = None,
1152
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1153
+ r"""
1154
+ Args:
1155
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1156
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1157
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1158
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1159
+
1160
+ Returns:
1161
+
1162
+ Example:
1163
+
1164
+ ```python
1165
+ >>> from transformers import AutoTokenizer, AutoModel, AutoImageProcessor, AutoModelForCausalLM
1166
+ >>> from transformers.generation.configuration_utils import GenerationConfig
1167
+ >>> from transformers.generation import LogitsProcessorList, PrefixConstrainedLogitsProcessor, UnbatchedClassifierFreeGuidanceLogitsProcessor
1168
+ >>> from transformers import Emu3Processor
1169
+ >>> from PIL import Image
1170
+
1171
+ >>> model = AutoModelForCausalLM.from_pretrained(PATH_TO_CONVERTED_EMU3_WEIGHTS)
1172
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1173
+ >>> image_processor = AutoImageProcessor.from_pretrained(PATH_TO_CONVERTED_IMAGE_PROCESSER)
1174
+ >>> image_tokenizer = AutoModel.from_pretrained(PATH_TO_CONVERTED_TOKENIZER_WEIGHTS).eval()
1175
+ >>> processor = Emu3Processor(image_processor, image_tokenizer, tokenizer)
1176
+
1177
+ >>> # Generation
1178
+ >>> prompt = "An Emu in cartoon style, it is wearing sunglasses."
1179
+
1180
+ >>> pos_inputs = processor(text=prompt, mode='G', ratio="4:3", image_area=model.config.image_area, return_tensors="pt")
1181
+ >>> neg_inputs = processor(text="", mode='G', ratio="4:3", image_area=model.config.image_area, return_tensors="pt")
1182
+
1183
+ >>> GENERATION_CONFIG = GenerationConfig(
1184
+ >>> use_cache=True,
1185
+ >>> eos_token_id=model.config.eos_token_id,
1186
+ >>> pad_token_id=model.config.pad_token_id,
1187
+ >>> max_new_tokens=40960,
1188
+ >>> do_sample=True,
1189
+ >>> top_k=2048,
1190
+ >>> )
1191
+
1192
+ >>> h, w = pos_inputs.image_size[0]
1193
+ >>> constrained_fn = processor.build_prefix_constrained_fn(h, w)
1194
+ >>> logits_processor = LogitsProcessorList([
1195
+ >>> UnbatchedClassifierFreeGuidanceLogitsProcessor(
1196
+ >>> classifier_free_guidance,
1197
+ >>> model,
1198
+ >>> unconditional_ids=neg_inputs.input_ids.to("cuda:0"),
1199
+ >>> ),
1200
+ >>> PrefixConstrainedLogitsProcessor(
1201
+ >>> constrained_fn,
1202
+ >>> num_beams=1,
1203
+ >>> ),
1204
+ >>> ])
1205
+
1206
+ >>> outputs = model.generate(pos_inputs.input_ids.to("cuda:0"), GENERATION_CONFIG, logits_processor=logits_processor)
1207
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1208
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1209
+ >>> mm_list = processor.decode(outputs[0])
1210
+
1211
+ >>> # Understanding
1212
+ >>> prompt = "Provide a one-sentence caption for the provided image."
1213
+ >>> image = Image.open(TEST_IMAGE_PATH)
1214
+
1215
+ >>> inputs = processor(text=text, image=image, mode='U', padding_side="left", padding="longest", return_tensors="pt")
1216
+ >>> input_ids = inputs.input_ids.to("cuda:0")
1217
+ >>> GENERATION_CONFIG = GenerationConfig(
1218
+ >>> pad_token_id=tokenizer.pad_token_id,
1219
+ >>> bos_token_id=tokenizer.bos_token_id,
1220
+ >>> eos_token_id=tokenizer.eos_token_id,
1221
+ >>> )
1222
+
1223
+ >>> outputs = model.generate(input_ids, GENERATION_CONFIG, max_new_tokens=100)
1224
+ >>> outputs = outputs[:, input_ids.shape[-1]:]
1225
+ >>> answer = processor.batch_decode(outputs, skip_special_tokens=True)
1226
+ ```"""
1227
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1228
+ output_hidden_states = (
1229
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1230
+ )
1231
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1232
+
1233
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1234
+ outputs = self.model(
1235
+ input_ids=input_ids,
1236
+ attention_mask=attention_mask,
1237
+ position_ids=position_ids,
1238
+ past_key_values=past_key_values,
1239
+ inputs_embeds=inputs_embeds,
1240
+ use_cache=use_cache,
1241
+ output_attentions=output_attentions,
1242
+ output_hidden_states=output_hidden_states,
1243
+ return_dict=return_dict,
1244
+ )
1245
+
1246
+ hidden_states = outputs[0]
1247
+ if self.config.pretraining_tp > 1:
1248
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1249
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1250
+ logits = torch.cat(logits, dim=-1)
1251
+ else:
1252
+ logits = self.lm_head(hidden_states)
1253
+ logits = logits.float()
1254
+
1255
+ loss = None
1256
+ if labels is not None:
1257
+ # Shift so that tokens < n predict n
1258
+ shift_logits = logits[..., :-1, :].contiguous()
1259
+ shift_labels = labels[..., 1:].contiguous()
1260
+ # Flatten the tokens
1261
+ loss_fct = CrossEntropyLoss()
1262
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1263
+ shift_labels = shift_labels.view(-1)
1264
+ # Enable model parallelism
1265
+ shift_labels = shift_labels.to(shift_logits.device)
1266
+ loss = loss_fct(shift_logits, shift_labels)
1267
+
1268
+ if not return_dict:
1269
+ output = (logits,) + outputs[1:]
1270
+ return (loss,) + output if loss is not None else output
1271
+
1272
+ return CausalLMOutputWithPast(
1273
+ loss=loss,
1274
+ logits=logits,
1275
+ past_key_values=outputs.past_key_values,
1276
+ hidden_states=outputs.hidden_states,
1277
+ attentions=outputs.attentions,
1278
+ )
1279
+
1280
+ def prepare_inputs_for_generation(
1281
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1282
+ ):
1283
+ if past_key_values is not None:
1284
+ if isinstance(past_key_values, Cache):
1285
+ cache_length = past_key_values.get_seq_length()
1286
+ past_length = past_key_values.seen_tokens
1287
+ max_cache_length = past_key_values.get_max_length()
1288
+ else:
1289
+ cache_length = past_length = past_key_values[0][0].shape[2]
1290
+ max_cache_length = None
1291
+
1292
+ # Keep only the unprocessed tokens:
1293
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1294
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1295
+ # input)
1296
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1297
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1298
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1299
+ # input_ids based on the past_length.
1300
+ elif past_length < input_ids.shape[1]:
1301
+ input_ids = input_ids[:, past_length:]
1302
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1303
+
1304
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1305
+ if (
1306
+ max_cache_length is not None
1307
+ and attention_mask is not None
1308
+ and cache_length + input_ids.shape[1] > max_cache_length
1309
+ ):
1310
+ attention_mask = attention_mask[:, -max_cache_length:]
1311
+
1312
+ position_ids = kwargs.get("position_ids", None)
1313
+ if attention_mask is not None and position_ids is None:
1314
+ # create position_ids on the fly for batch generation
1315
+ position_ids = attention_mask.long().cumsum(-1) - 1
1316
+ position_ids.masked_fill_(attention_mask == 0, 1)
1317
+ if past_key_values:
1318
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1319
+
1320
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1321
+ if inputs_embeds is not None and past_key_values is None:
1322
+ model_inputs = {"inputs_embeds": inputs_embeds}
1323
+ else:
1324
+ model_inputs = {"input_ids": input_ids}
1325
+
1326
+ model_inputs.update(
1327
+ {
1328
+ "position_ids": position_ids,
1329
+ "past_key_values": past_key_values,
1330
+ "use_cache": kwargs.get("use_cache"),
1331
+ "attention_mask": attention_mask,
1332
+ }
1333
+ )
1334
+ return model_inputs
1335
+
1336
+ @staticmethod
1337
+ def _reorder_cache(past_key_values, beam_idx):
1338
+ reordered_past = ()
1339
+ for layer_past in past_key_values:
1340
+ reordered_past += (
1341
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1342
+ )
1343
+ return reordered_past
processing_emu3.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Emu team, BAAI 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
+ """ Processor class for Emu3. """
16
+
17
+ import re
18
+ from typing import List, Optional, Sequence, Union
19
+ from functools import partial
20
+
21
+ from PIL import Image
22
+ import torch
23
+ from transformers.feature_extraction_utils import BatchFeature
24
+ from transformers.image_utils import ImageInput, get_image_size, to_numpy_array
25
+ from transformers.processing_utils import ProcessingKwargs, ProcessorMixin
26
+ from transformers.tokenization_utils_base import TextInput, PreTokenizedInput
27
+ from transformers.utils import logging
28
+
29
+ from .utils_emu3 import Emu3PrefixConstrainedLogitsHelper
30
+
31
+
32
+ logger = logging.get_logger(__name__)
33
+
34
+
35
+ class Emu3Processor(ProcessorMixin):
36
+ r"""
37
+ Constructs an Emu3 processor which wraps an Emu3 image processor and an Emu3 vision vq model and an Emu3 tokenizer into a single processor.
38
+
39
+ [`Emu3Processor`] offers all the functionalities of [`Emu3VisionVQModel`] and [`Emu3Tokenizer`]. See the
40
+ [`~Emu3Processor.__call__`], [`~Emu3Processor.decode`], [`~Emu3Processor.vision_encode`], [`~Emu3Processor.vision_decode`]
41
+ for more information.
42
+
43
+ Args:
44
+ image_processor ([`Emu3VisionVQImageProcessor`]):
45
+ The image processor is a required input.
46
+ vision_tokenizer ([`Emu3VisionVQModel`]):
47
+ The vision tokenizer is a required input.
48
+ tokenizer ([`Emu3Tokenizer`]):
49
+ The tokenizer is a required input.
50
+ prefix_template(`str`, *optional*):
51
+ The prefix template for image tokens
52
+ visual_template(`Tuple[str, ...]`, *optional*):
53
+ The visual token template for image tokens
54
+ """
55
+
56
+ attributes = ["image_processor", "tokenizer"]
57
+ valid_kwargs = ["vision_tokenizer", "prefix_template", "visual_template"]
58
+ image_processor_class = "AutoImageProcessor"
59
+ tokenizer_class = "AutoTokenizer"
60
+
61
+ def __init__(
62
+ self,
63
+ image_processor=None,
64
+ vision_tokenizer=None,
65
+ tokenizer=None,
66
+ chat_template="You are a helpful assistant. USER: {image_prompt}{text_prompt}. ASSISTANT:",
67
+ prefix_template="{H}*{W}",
68
+ visual_template=("<|visual token {token_id:0>6d}|>", r"<\|visual token (\d+)\|>"),
69
+ **kwargs,
70
+ ):
71
+ assert vision_tokenizer is not None, "image tokenizer can not be None"
72
+
73
+ self.vision_tokenizer = vision_tokenizer
74
+ self.prefix_template = prefix_template
75
+ self.visual_template = visual_template
76
+
77
+ super().__init__(image_processor, tokenizer, chat_template=chat_template)
78
+ self.const_helper = self.build_const_helper()
79
+
80
+ @torch.no_grad()
81
+ def __call__(
82
+ self,
83
+ text: Optional[TextInput | PreTokenizedInput] = None,
84
+ image: Optional[Image.Image | List[Image.Image]] = None,
85
+ *,
86
+ mode: str = "G",
87
+ ratio: str = "1:1",
88
+ image_area: int = 518400,
89
+ **kwargs,
90
+ ) -> BatchFeature:
91
+ """
92
+ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
93
+ and `kwargs` arguments to Emu3Tokenizer's [`~Emu3Tokenizer.__call__`] to encode the text.
94
+ To prepare the image(s), this method forwards the `image` argument to
95
+ Emu3VisionVQImageProcessor's [`~Emu3VisionVQImageProcessor.__call__`] and Emu3VisionVQModel's [`~EmuVideoVQModel.encode`]
96
+ if `image` is not `None`. Please refer to the doctsring of the above two methods for more information.
97
+
98
+ Args:
99
+ text (`str` or `List[str]`):
100
+ The sequence or a batch of sequence to be encoded. A sequence is a string.
101
+ image (`PIL.Image.Image` or `List[PIL.Image.Image]`, *optional*):
102
+ The image or a batch of images to be prepared. An image is a PIL image.
103
+ mode (`str`, *optional*, in `G` or `U`):
104
+ task mode, `G` for generation and `U` for understanding
105
+ ratio (`str`, *optional*):
106
+ the image width-height ratio for generation
107
+ image_area (`int`, *optional*):
108
+ image area used to calcualte the generated image height and width
109
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
110
+ If set, will return tensors of a particular framework. Acceptable values are:
111
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
112
+ - `'np'`: Return NumPy `np.ndarray` objects.
113
+
114
+ Returns:
115
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
116
+
117
+ - **input_ids** -- List of token ids to be fed to a model.
118
+ - **image_size** -- List of image size of input images or generated images.
119
+ """
120
+ assert mode in ('G', 'U'), "mode must be 'G' or 'U'."
121
+ if isinstance(text, str):
122
+ text = [text]
123
+
124
+ if not isinstance(text[0], str):
125
+ raise ValueError("`text` must be string or list of string")
126
+
127
+ image_inputs = None
128
+ if mode == 'G':
129
+ if image is not None:
130
+ raise ValueError("You have to specify only `text` in generation mode")
131
+
132
+ if len(text) > 1:
133
+ raise ValueError("`text` can only be `str` in generation mode")
134
+ else:
135
+ if image is None:
136
+ raise ValueError("Invalid input image. Please provide exactly one PIL.Image.Image per text.")
137
+
138
+ if not isinstance(image, Sequence) and not isinstance(image, Image.Image):
139
+ raise ValueError("Invalid input image. Please provide PIL.Image.Image or List[PIL.Image.Image].")
140
+
141
+ if isinstance(image, Sequence) and not isinstance(image[0], Image.Image):
142
+ raise ValueError("Invalid input image. Please provide PIL.Image.Image or List[PIL.Image.Image].")
143
+
144
+ image_inputs = self.image_processor(image, return_tensors="pt")["pixel_values"]
145
+ image_inputs = image_inputs.to(self.vision_tokenizer.device, self.vision_tokenizer.dtype)
146
+ image_tokens = self.vision_tokenizer.encode(image_inputs)
147
+
148
+ if len(text) != len(image_tokens):
149
+ raise ValueError("number of image must match number of text prompt")
150
+
151
+ prompt_list, size_list = [], []
152
+ for idx, text_prompt in enumerate(text):
153
+ prompt = self.tokenizer.bos_token
154
+ if mode == 'U':
155
+ h, w = image_tokens[idx].shape
156
+ imgstr = self.to_imgstr(image_tokens[idx])
157
+ image_prompt = (
158
+ self.tokenizer.boi_token +
159
+ self.prefix_template.format(H=h, W=w) +
160
+ self.tokenizer.img_token +
161
+ imgstr +
162
+ self.tokenizer.eol_token +
163
+ self.tokenizer.eof_token +
164
+ self.tokenizer.eoi_token
165
+ )
166
+ prompt += self.chat_template.format(image_prompt=image_prompt, text_prompt=text_prompt)
167
+ else:
168
+ h, w = self.calculate_generate_size(ratio, image_area, self.vision_tokenizer.spatial_scale_factor)
169
+ image_prompt = (
170
+ self.tokenizer.boi_token +
171
+ self.prefix_template.format(H=h, W=w) +
172
+ self.tokenizer.img_token
173
+ )
174
+ prompt += (text_prompt + image_prompt)
175
+
176
+ prompt_list.append(prompt)
177
+ size_list.append([h, w])
178
+
179
+ text_inputs = self.tokenizer(prompt_list, **kwargs)
180
+ return BatchFeature(data={**text_inputs, "image_size": size_list}, tensor_type=kwargs.get("return_tensors"))
181
+
182
+ @torch.no_grad()
183
+ def batch_decode(self, *args, **kwargs):
184
+ docs = self.tokenizer.batch_decode(*args, **kwargs)
185
+ return [self.multimodal_decode(d) for d in docs]
186
+
187
+ @torch.no_grad()
188
+ def decode(self, *args, **kwargs):
189
+ doc = self.tokenizer.decode(*args, **kwargs)
190
+ return self.multimodal_decode(doc)
191
+
192
+ @torch.no_grad()
193
+ def vision_encode(self, *args, **kwargs):
194
+ return self.vision_tokenizer.encode(*args, **kwargs)
195
+
196
+ @torch.no_grad()
197
+ def vision_decode(self, *args, **kwargs):
198
+ return self.vision_tokenizer.decode(*args, **kwargs)
199
+
200
+ @torch.no_grad()
201
+ def multimodal_decode(self, doc):
202
+ multimodal_output = []
203
+ pattern = rf'({re.escape(self.tokenizer.boi_token)}.*?{re.escape(self.tokenizer.eoi_token)})'
204
+ chunks = re.split(pattern, doc)
205
+ for c in chunks:
206
+ if len(c) == 0:
207
+ continue
208
+
209
+ if self.tokenizer.boi_token in c:
210
+ image = []
211
+ image_rows = re.split(re.escape(self.tokenizer.eol_token), c)
212
+ for r in image_rows:
213
+ token_ids = re.findall(self.visual_template[1], r)
214
+ if len(token_ids) > 0:
215
+ row_token = [int(m) for m in token_ids]
216
+ image.append(row_token)
217
+ image = torch.tensor(image, dtype=torch.long, device=self.vision_tokenizer.device)
218
+ image = self.vision_tokenizer.decode(image[None]).float()
219
+ image = self.image_processor.postprocess(image)["pixel_values"][0]
220
+ multimodal_output.append(image)
221
+ else:
222
+ multimodal_output.append(c)
223
+
224
+ return multimodal_output if len(multimodal_output) > 1 else multimodal_output[0]
225
+
226
+ @property
227
+ def model_input_names(self):
228
+ tokenizer_input_names = self.tokenizer.model_input_names
229
+ image_processor_input_names = self.image_processor.model_input_names
230
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
231
+
232
+ def to_imgstr(self, image_tokens):
233
+ image_tokens = image_tokens.cpu().numpy().tolist()
234
+ image_token_str = [
235
+ [
236
+ self.visual_template[0].format(token_id=token_id)
237
+ for token_id in token_row
238
+ ]
239
+ for token_row in image_tokens
240
+ ]
241
+ image_row_str = ["".join(token_row) for token_row in image_token_str]
242
+ imgstr = self.tokenizer.eol_token.join(image_row_str)
243
+ return imgstr
244
+
245
+ def calculate_generate_size(self, ratio, image_area, spatial_scale_factor):
246
+ w, h = map(int, ratio.split(":"))
247
+ current_area = h * w
248
+ target_ratio = (image_area / current_area) ** 0.5
249
+
250
+ th = int(round(h * target_ratio / spatial_scale_factor))
251
+ tw = int(round(w * target_ratio / spatial_scale_factor))
252
+ return th, tw
253
+
254
+ def build_const_helper(self):
255
+ (
256
+ img_token,
257
+ eoi_token,
258
+ eos_token,
259
+ eol_token,
260
+ eof_token,
261
+ pad_token,
262
+ vis_start,
263
+ vis_end,
264
+ ) = self.tokenizer.encode([
265
+ self.tokenizer.img_token,
266
+ self.tokenizer.eoi_token,
267
+ self.tokenizer.eos_token,
268
+ self.tokenizer.eol_token,
269
+ self.tokenizer.eof_token,
270
+ self.tokenizer.pad_token,
271
+ self.visual_template[0].format(token_id=0),
272
+ self.visual_template[0].format(token_id=self.vision_tokenizer.config.codebook_size - 1),
273
+ ])
274
+
275
+ const_helper = partial(
276
+ Emu3PrefixConstrainedLogitsHelper,
277
+ img_token=img_token,
278
+ eoi_token=eoi_token,
279
+ eos_token=eos_token,
280
+ eol_token=eol_token,
281
+ eof_token=eof_token,
282
+ pad_token=pad_token,
283
+ visual_tokens=list(range(vis_start, vis_end + 1)),
284
+ )
285
+ return const_helper
286
+
287
+ def build_prefix_constrained_fn(self, height, width):
288
+ helper = self.const_helper(height=height, width=width)
289
+ return helper
special_tokens_map.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<|extra_203|>",
3
+ "eos_token": "<|extra_204|>",
4
+ "pad_token": "<|endoftext|>"
5
+ }
tokenization_emu3.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Emu team, BAAI and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization classes for Emu3."""
16
+
17
+ import base64
18
+ import logging
19
+ import os
20
+ import unicodedata
21
+ from typing import Collection, Dict, List, Optional, Set, Tuple, Union
22
+
23
+ import tiktoken
24
+ from transformers import PreTrainedTokenizer, AddedToken
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ VOCAB_FILES_NAMES = {
30
+ "vocab_file": "emu3.tiktoken",
31
+ "special_tokens_file": "emu3_vision_tokens.txt",
32
+ }
33
+
34
+ PAT_STR = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
35
+ ENDOFTEXT = "<|endoftext|>"
36
+ IMSTART = "<|im_start|>"
37
+ IMEND = "<|im_end|>"
38
+ # as the default behavior is changed to allow special tokens in
39
+ # regular texts, the surface forms of special tokens need to be
40
+ # as different as possible to minimize the impact
41
+ EXTRAS = tuple((f"<|extra_{i}|>" for i in range(205)))
42
+ # changed to use actual index to avoid misconfiguration with vocabulary expansion
43
+ SPECIAL_START_ID = 151643
44
+
45
+
46
+ def _load_tiktoken_bpe(tiktoken_bpe_file: str) -> Dict[bytes, int]:
47
+ with open(tiktoken_bpe_file, "rb") as f:
48
+ contents = f.read()
49
+ return {
50
+ base64.b64decode(token): int(rank)
51
+ for token, rank in (line.split() for line in contents.splitlines() if line)
52
+ }
53
+
54
+
55
+ class Emu3Tokenizer(PreTrainedTokenizer):
56
+ """Emu3 tokenizer."""
57
+
58
+ vocab_files_names = VOCAB_FILES_NAMES
59
+
60
+ def __init__(
61
+ self,
62
+ vocab_file,
63
+ special_tokens_file,
64
+ errors="replace",
65
+ bos_token = "<|extra_203|>",
66
+ eos_token = "<|extra_204|>",
67
+ pad_token = "<|endoftext|>",
68
+ img_token = "<|image token|>",
69
+ boi_token = "<|image start|>",
70
+ eoi_token = "<|image end|>",
71
+ eol_token = "<|extra_200|>",
72
+ eof_token = "<|extra_201|>",
73
+ **kwargs,
74
+ ):
75
+ super().__init__(**kwargs)
76
+
77
+ # how to handle errors in decoding UTF-8 byte sequences
78
+ # use ignore if you are in streaming inference
79
+ self.errors = errors
80
+
81
+ self.mergeable_ranks = _load_tiktoken_bpe(vocab_file)
82
+
83
+ vision_tokens = [t.strip() for t in open(special_tokens_file).readlines() if len(t.strip()) > 0]
84
+ SPECIAL_TOKENS = tuple(
85
+ enumerate(
86
+ (
87
+ (
88
+ ENDOFTEXT,
89
+ IMSTART,
90
+ IMEND,
91
+ )
92
+ + EXTRAS
93
+ + tuple(vision_tokens)
94
+ ),
95
+ start=SPECIAL_START_ID,
96
+ )
97
+ )
98
+ self.special_tokens = {token: index for index, token in SPECIAL_TOKENS}
99
+ self.special_tokens_set = set(t for _, t in SPECIAL_TOKENS)
100
+
101
+ enc = tiktoken.Encoding(
102
+ "Emu3",
103
+ pat_str=PAT_STR,
104
+ mergeable_ranks=self.mergeable_ranks,
105
+ special_tokens=self.special_tokens,
106
+ )
107
+
108
+ assert (
109
+ len(self.mergeable_ranks) + len(self.special_tokens) == enc.n_vocab
110
+ ), f"{len(self.mergeable_ranks) + len(self.special_tokens)} != {enc.n_vocab} in encoding"
111
+
112
+ self.decoder = {
113
+ v: k for k, v in self.mergeable_ranks.items()
114
+ }
115
+ self.decoder.update({v: k for k, v in self.special_tokens.items()})
116
+
117
+ self.tokenizer = enc
118
+
119
+ self.eod_id = self.tokenizer.eot_token
120
+ self.bos_token = bos_token
121
+ self.eos_token = eos_token
122
+ self.pad_token = pad_token
123
+ self.img_token = img_token
124
+ self.boi_token = boi_token
125
+ self.eoi_token = eoi_token
126
+ self.eol_token = eol_token
127
+ self.eof_token = eof_token
128
+
129
+ def __getstate__(self):
130
+ # for pickle lovers
131
+ state = self.__dict__.copy()
132
+ del state["tokenizer"]
133
+ return state
134
+
135
+ def __setstate__(self, state):
136
+ # tokenizer is not python native; don't pass it; rebuild it
137
+ self.__dict__.update(state)
138
+ enc = tiktoken.Encoding(
139
+ "Emu3",
140
+ pat_str=PAT_STR,
141
+ mergeable_ranks=self.mergeable_ranks,
142
+ special_tokens=self.special_tokens,
143
+ )
144
+ self.tokenizer = enc
145
+
146
+ def __len__(self) -> int:
147
+ return self.tokenizer.n_vocab
148
+
149
+ def get_vocab(self) -> Dict[bytes, int]:
150
+ return self.mergeable_ranks
151
+
152
+ def convert_tokens_to_ids(
153
+ self, tokens: Union[bytes, str, List[Union[bytes, str]]]
154
+ ) -> List[int]:
155
+ if isinstance(tokens, (str, bytes)):
156
+ if tokens in self.special_tokens:
157
+ return self.special_tokens[tokens]
158
+ else:
159
+ return self.mergeable_ranks.get(tokens)
160
+
161
+ ids = []
162
+ for token in tokens:
163
+ if token in self.special_tokens:
164
+ ids.append(self.special_tokens[token])
165
+ else:
166
+ ids.append(self.mergeable_ranks.get(token))
167
+ return ids
168
+
169
+ def _add_tokens(
170
+ self,
171
+ new_tokens: Union[List[str], List[AddedToken]],
172
+ special_tokens: bool = False,
173
+ ) -> int:
174
+ if not special_tokens and new_tokens:
175
+ raise ValueError("Adding regular tokens is not supported")
176
+
177
+ for token in new_tokens:
178
+ surface_form = token.content if isinstance(token, AddedToken) else token
179
+ if surface_form not in self.special_tokens_set:
180
+ raise ValueError("Adding unknown special tokens is not supported")
181
+
182
+ return 0
183
+
184
+ def save_vocabulary(self, save_directory: str, **kwargs) -> Tuple[str]:
185
+ """
186
+ Save only the vocabulary of the tokenizer (vocabulary).
187
+
188
+ Returns:
189
+ `Tuple(str)`: Paths to the files saved.
190
+ """
191
+ regular_file_path = os.path.join(save_directory, self.vocab_files_names["vocab_file"])
192
+ with open(regular_file_path,'w', encoding="utf8") as w:
193
+ for k, v in self.mergeable_ranks.items():
194
+ line = base64.b64encode(k).decode("utf8") + " " + str(v) + "\n"
195
+ w.write(line)
196
+
197
+ excluded_special_tokens = set((ENDOFTEXT, IMSTART, IMEND,) + EXTRAS)
198
+ special_file_path = os.path.join(save_directory, self.vocab_files_names["special_tokens_file"])
199
+ with open(special_file_path, 'w', encoding="utf8") as w:
200
+ for k in self.special_tokens:
201
+ if k not in excluded_special_tokens:
202
+ print(k, file=w)
203
+
204
+ return (regular_file_path, special_file_path)
205
+
206
+ def tokenize(
207
+ self,
208
+ text: str,
209
+ allowed_special: Union[Set, str] = "all",
210
+ disallowed_special: Union[Collection, str] = (),
211
+ **kwargs,
212
+ ) -> List[Union[bytes, str]]:
213
+ """
214
+ Converts a string in a sequence of tokens.
215
+
216
+ Args:
217
+ text (`str`):
218
+ The sequence to be encoded.
219
+ allowed_special (`Literal["all"]` or `set`):
220
+ The surface forms of the tokens to be encoded as special tokens in regular texts.
221
+ Default to "all".
222
+ disallowed_special (`Literal["all"]` or `Collection`):
223
+ The surface forms of the tokens that should not be in regular texts and trigger errors.
224
+ Default to an empty tuple.
225
+
226
+ kwargs (additional keyword arguments, *optional*):
227
+ Will be passed to the underlying model specific encode method.
228
+
229
+ Returns:
230
+ `List[bytes|str]`: The list of tokens.
231
+ """
232
+ tokens = []
233
+ text = unicodedata.normalize("NFC", text)
234
+
235
+ # this implementation takes a detour: text -> token id -> token surface forms
236
+ for t in self.tokenizer.encode(
237
+ text, allowed_special=allowed_special, disallowed_special=disallowed_special
238
+ ):
239
+ tokens.append(self.decoder[t])
240
+
241
+ return tokens
242
+
243
+ def convert_tokens_to_string(self, tokens: List[Union[bytes, str]]) -> str:
244
+ """
245
+ Converts a sequence of tokens in a single string.
246
+ """
247
+ text = ""
248
+ temp = b""
249
+ for t in tokens:
250
+ if isinstance(t, str):
251
+ if temp:
252
+ text += temp.decode("utf-8", errors=self.errors)
253
+ temp = b""
254
+ text += t
255
+ elif isinstance(t, bytes):
256
+ temp += t
257
+ else:
258
+ raise TypeError("token should only be of type types or str")
259
+ if temp:
260
+ text += temp.decode("utf-8", errors=self.errors)
261
+ return text
262
+
263
+ @property
264
+ def vocab_size(self):
265
+ return self.tokenizer.n_vocab
266
+
267
+ def _convert_id_to_token(self, index: int) -> Union[bytes, str]:
268
+ """Converts an id to a token, special tokens included"""
269
+ if index in self.decoder:
270
+ return self.decoder[index]
271
+ raise ValueError("unknown ids")
272
+
273
+ def _convert_token_to_id(self, token: Union[bytes, str]) -> int:
274
+ """Converts a token to an id using the vocab, special tokens included"""
275
+ if token in self.special_tokens:
276
+ return self.special_tokens[token]
277
+ if token in self.mergeable_ranks:
278
+ return self.mergeable_ranks[token]
279
+ raise ValueError("unknown token")
280
+
281
+ def _decode(
282
+ self,
283
+ token_ids: Union[int, List[int]],
284
+ skip_special_tokens: bool = False,
285
+ errors: Optional[str] = None,
286
+ **kwargs,
287
+ ) -> str:
288
+ if isinstance(token_ids, int):
289
+ token_ids = [token_ids]
290
+
291
+ if skip_special_tokens:
292
+ token_ids = [i for i in token_ids if i < self.eod_id]
293
+
294
+ return self.tokenizer.decode(token_ids, errors=errors or self.errors)
tokenizer_config.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {},
3
+ "auto_map": {
4
+ "AutoTokenizer": [
5
+ "tokenization_emu3.Emu3Tokenizer",
6
+ null
7
+ ]
8
+ },
9
+ "bos_token": "<|extra_203|>",
10
+ "clean_up_tokenization_spaces": true,
11
+ "eos_token": "<|extra_204|>",
12
+ "model_max_length": 1000000000000000019884624838656,
13
+ "pad_token": "<|endoftext|>",
14
+ "tokenizer_class": "Emu3Tokenizer"
15
+ }
utils_emu3.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Emu team, BAAI 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
+ """ Logits Processor Helper class for Emu3. """
16
+
17
+ import torch
18
+
19
+ class Emu3PrefixConstrainedLogitsHelper:
20
+
21
+ def __init__(
22
+ self,
23
+ height,
24
+ width,
25
+ img_token,
26
+ eoi_token,
27
+ eos_token,
28
+ eol_token,
29
+ eof_token,
30
+ pad_token,
31
+ visual_tokens,
32
+ ):
33
+ self.height = height
34
+ self.width = width
35
+ self.img_token = img_token
36
+ self.eoi_token = eoi_token
37
+ self.eos_token = eos_token
38
+ self.eol_token = eol_token
39
+ self.eof_token = eof_token
40
+ self.pad_token = pad_token
41
+ self.visual_tokens = visual_tokens
42
+
43
+ self.offset_cache = {}
44
+
45
+ def __call__(self, batch_id, input_ids):
46
+ if batch_id not in self.offset_cache:
47
+ position = torch.nonzero(input_ids == self.img_token, as_tuple=True)[0][0]
48
+ self.offset_cache[batch_id] = position
49
+
50
+ offset = input_ids.shape[0] - self.offset_cache[batch_id]
51
+ if offset % (self.width + 1) == 0:
52
+ return (self.eol_token, )
53
+ elif offset == (self.width + 1) * self.height + 1:
54
+ return (self.eof_token, )
55
+ elif offset == (self.width + 1) * self.height + 2:
56
+ return (self.eoi_token, )
57
+ elif offset == (self.width + 1) * self.height + 3:
58
+ return (self.eos_token, )
59
+ elif offset > (self.width + 1) * self.height + 3:
60
+ return (self.pad_token, )
61
+ else:
62
+ return self.visual_tokens