TokenWang commited on
Commit
2316ab4
·
verified ·
1 Parent(s): ec22ee4

Upload folder using huggingface_hub

Browse files
__init__.py ADDED
File without changes
__pycache__/conversation.cpython-311.pyc ADDED
Binary file (15.3 kB). View file
 
added_tokens.json ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</box>": 151677,
3
+ "</img>": 151671,
4
+ "</quad>": 151673,
5
+ "</ref>": 151675,
6
+ "</think>": 151668,
7
+ "</tool_call>": 151658,
8
+ "</tool_response>": 151666,
9
+ "<FAKE_PAD_0>": 151682,
10
+ "<FAKE_PAD_100>": 151782,
11
+ "<FAKE_PAD_101>": 151783,
12
+ "<FAKE_PAD_102>": 151784,
13
+ "<FAKE_PAD_103>": 151785,
14
+ "<FAKE_PAD_104>": 151786,
15
+ "<FAKE_PAD_105>": 151787,
16
+ "<FAKE_PAD_106>": 151788,
17
+ "<FAKE_PAD_107>": 151789,
18
+ "<FAKE_PAD_108>": 151790,
19
+ "<FAKE_PAD_109>": 151791,
20
+ "<FAKE_PAD_10>": 151692,
21
+ "<FAKE_PAD_110>": 151792,
22
+ "<FAKE_PAD_111>": 151793,
23
+ "<FAKE_PAD_112>": 151794,
24
+ "<FAKE_PAD_113>": 151795,
25
+ "<FAKE_PAD_114>": 151796,
26
+ "<FAKE_PAD_115>": 151797,
27
+ "<FAKE_PAD_116>": 151798,
28
+ "<FAKE_PAD_117>": 151799,
29
+ "<FAKE_PAD_118>": 151800,
30
+ "<FAKE_PAD_119>": 151801,
31
+ "<FAKE_PAD_11>": 151693,
32
+ "<FAKE_PAD_120>": 151802,
33
+ "<FAKE_PAD_121>": 151803,
34
+ "<FAKE_PAD_122>": 151804,
35
+ "<FAKE_PAD_123>": 151805,
36
+ "<FAKE_PAD_124>": 151806,
37
+ "<FAKE_PAD_125>": 151807,
38
+ "<FAKE_PAD_126>": 151808,
39
+ "<FAKE_PAD_127>": 151809,
40
+ "<FAKE_PAD_128>": 151810,
41
+ "<FAKE_PAD_129>": 151811,
42
+ "<FAKE_PAD_12>": 151694,
43
+ "<FAKE_PAD_130>": 151812,
44
+ "<FAKE_PAD_131>": 151813,
45
+ "<FAKE_PAD_132>": 151814,
46
+ "<FAKE_PAD_133>": 151815,
47
+ "<FAKE_PAD_134>": 151816,
48
+ "<FAKE_PAD_135>": 151817,
49
+ "<FAKE_PAD_136>": 151818,
50
+ "<FAKE_PAD_137>": 151819,
51
+ "<FAKE_PAD_138>": 151820,
52
+ "<FAKE_PAD_139>": 151821,
53
+ "<FAKE_PAD_13>": 151695,
54
+ "<FAKE_PAD_140>": 151822,
55
+ "<FAKE_PAD_141>": 151823,
56
+ "<FAKE_PAD_142>": 151824,
57
+ "<FAKE_PAD_143>": 151825,
58
+ "<FAKE_PAD_144>": 151826,
59
+ "<FAKE_PAD_145>": 151827,
60
+ "<FAKE_PAD_146>": 151828,
61
+ "<FAKE_PAD_147>": 151829,
62
+ "<FAKE_PAD_148>": 151830,
63
+ "<FAKE_PAD_149>": 151831,
64
+ "<FAKE_PAD_14>": 151696,
65
+ "<FAKE_PAD_150>": 151832,
66
+ "<FAKE_PAD_151>": 151833,
67
+ "<FAKE_PAD_152>": 151834,
68
+ "<FAKE_PAD_153>": 151835,
69
+ "<FAKE_PAD_154>": 151836,
70
+ "<FAKE_PAD_155>": 151837,
71
+ "<FAKE_PAD_156>": 151838,
72
+ "<FAKE_PAD_157>": 151839,
73
+ "<FAKE_PAD_158>": 151840,
74
+ "<FAKE_PAD_159>": 151841,
75
+ "<FAKE_PAD_15>": 151697,
76
+ "<FAKE_PAD_160>": 151842,
77
+ "<FAKE_PAD_161>": 151843,
78
+ "<FAKE_PAD_162>": 151844,
79
+ "<FAKE_PAD_163>": 151845,
80
+ "<FAKE_PAD_164>": 151846,
81
+ "<FAKE_PAD_165>": 151847,
82
+ "<FAKE_PAD_166>": 151848,
83
+ "<FAKE_PAD_167>": 151849,
84
+ "<FAKE_PAD_168>": 151850,
85
+ "<FAKE_PAD_169>": 151851,
86
+ "<FAKE_PAD_16>": 151698,
87
+ "<FAKE_PAD_170>": 151852,
88
+ "<FAKE_PAD_171>": 151853,
89
+ "<FAKE_PAD_172>": 151854,
90
+ "<FAKE_PAD_173>": 151855,
91
+ "<FAKE_PAD_174>": 151856,
92
+ "<FAKE_PAD_175>": 151857,
93
+ "<FAKE_PAD_176>": 151858,
94
+ "<FAKE_PAD_177>": 151859,
95
+ "<FAKE_PAD_178>": 151860,
96
+ "<FAKE_PAD_179>": 151861,
97
+ "<FAKE_PAD_17>": 151699,
98
+ "<FAKE_PAD_180>": 151862,
99
+ "<FAKE_PAD_181>": 151863,
100
+ "<FAKE_PAD_182>": 151864,
101
+ "<FAKE_PAD_183>": 151865,
102
+ "<FAKE_PAD_184>": 151866,
103
+ "<FAKE_PAD_185>": 151867,
104
+ "<FAKE_PAD_186>": 151868,
105
+ "<FAKE_PAD_187>": 151869,
106
+ "<FAKE_PAD_188>": 151870,
107
+ "<FAKE_PAD_189>": 151871,
108
+ "<FAKE_PAD_18>": 151700,
109
+ "<FAKE_PAD_190>": 151872,
110
+ "<FAKE_PAD_191>": 151873,
111
+ "<FAKE_PAD_192>": 151874,
112
+ "<FAKE_PAD_193>": 151875,
113
+ "<FAKE_PAD_194>": 151876,
114
+ "<FAKE_PAD_195>": 151877,
115
+ "<FAKE_PAD_196>": 151878,
116
+ "<FAKE_PAD_197>": 151879,
117
+ "<FAKE_PAD_198>": 151880,
118
+ "<FAKE_PAD_199>": 151881,
119
+ "<FAKE_PAD_19>": 151701,
120
+ "<FAKE_PAD_1>": 151683,
121
+ "<FAKE_PAD_200>": 151882,
122
+ "<FAKE_PAD_201>": 151883,
123
+ "<FAKE_PAD_202>": 151884,
124
+ "<FAKE_PAD_203>": 151885,
125
+ "<FAKE_PAD_204>": 151886,
126
+ "<FAKE_PAD_205>": 151887,
127
+ "<FAKE_PAD_206>": 151888,
128
+ "<FAKE_PAD_207>": 151889,
129
+ "<FAKE_PAD_208>": 151890,
130
+ "<FAKE_PAD_209>": 151891,
131
+ "<FAKE_PAD_20>": 151702,
132
+ "<FAKE_PAD_210>": 151892,
133
+ "<FAKE_PAD_211>": 151893,
134
+ "<FAKE_PAD_212>": 151894,
135
+ "<FAKE_PAD_213>": 151895,
136
+ "<FAKE_PAD_214>": 151896,
137
+ "<FAKE_PAD_215>": 151897,
138
+ "<FAKE_PAD_216>": 151898,
139
+ "<FAKE_PAD_217>": 151899,
140
+ "<FAKE_PAD_218>": 151900,
141
+ "<FAKE_PAD_219>": 151901,
142
+ "<FAKE_PAD_21>": 151703,
143
+ "<FAKE_PAD_220>": 151902,
144
+ "<FAKE_PAD_221>": 151903,
145
+ "<FAKE_PAD_222>": 151904,
146
+ "<FAKE_PAD_223>": 151905,
147
+ "<FAKE_PAD_224>": 151906,
148
+ "<FAKE_PAD_225>": 151907,
149
+ "<FAKE_PAD_226>": 151908,
150
+ "<FAKE_PAD_227>": 151909,
151
+ "<FAKE_PAD_228>": 151910,
152
+ "<FAKE_PAD_229>": 151911,
153
+ "<FAKE_PAD_22>": 151704,
154
+ "<FAKE_PAD_230>": 151912,
155
+ "<FAKE_PAD_231>": 151913,
156
+ "<FAKE_PAD_232>": 151914,
157
+ "<FAKE_PAD_233>": 151915,
158
+ "<FAKE_PAD_234>": 151916,
159
+ "<FAKE_PAD_235>": 151917,
160
+ "<FAKE_PAD_236>": 151918,
161
+ "<FAKE_PAD_237>": 151919,
162
+ "<FAKE_PAD_238>": 151920,
163
+ "<FAKE_PAD_239>": 151921,
164
+ "<FAKE_PAD_23>": 151705,
165
+ "<FAKE_PAD_240>": 151922,
166
+ "<FAKE_PAD_241>": 151923,
167
+ "<FAKE_PAD_242>": 151924,
168
+ "<FAKE_PAD_243>": 151925,
169
+ "<FAKE_PAD_244>": 151926,
170
+ "<FAKE_PAD_245>": 151927,
171
+ "<FAKE_PAD_246>": 151928,
172
+ "<FAKE_PAD_247>": 151929,
173
+ "<FAKE_PAD_248>": 151930,
174
+ "<FAKE_PAD_249>": 151931,
175
+ "<FAKE_PAD_24>": 151706,
176
+ "<FAKE_PAD_250>": 151932,
177
+ "<FAKE_PAD_251>": 151933,
178
+ "<FAKE_PAD_252>": 151934,
179
+ "<FAKE_PAD_253>": 151935,
180
+ "<FAKE_PAD_25>": 151707,
181
+ "<FAKE_PAD_26>": 151708,
182
+ "<FAKE_PAD_27>": 151709,
183
+ "<FAKE_PAD_28>": 151710,
184
+ "<FAKE_PAD_29>": 151711,
185
+ "<FAKE_PAD_2>": 151684,
186
+ "<FAKE_PAD_30>": 151712,
187
+ "<FAKE_PAD_31>": 151713,
188
+ "<FAKE_PAD_32>": 151714,
189
+ "<FAKE_PAD_33>": 151715,
190
+ "<FAKE_PAD_34>": 151716,
191
+ "<FAKE_PAD_35>": 151717,
192
+ "<FAKE_PAD_36>": 151718,
193
+ "<FAKE_PAD_37>": 151719,
194
+ "<FAKE_PAD_38>": 151720,
195
+ "<FAKE_PAD_39>": 151721,
196
+ "<FAKE_PAD_3>": 151685,
197
+ "<FAKE_PAD_40>": 151722,
198
+ "<FAKE_PAD_41>": 151723,
199
+ "<FAKE_PAD_42>": 151724,
200
+ "<FAKE_PAD_43>": 151725,
201
+ "<FAKE_PAD_44>": 151726,
202
+ "<FAKE_PAD_45>": 151727,
203
+ "<FAKE_PAD_46>": 151728,
204
+ "<FAKE_PAD_47>": 151729,
205
+ "<FAKE_PAD_48>": 151730,
206
+ "<FAKE_PAD_49>": 151731,
207
+ "<FAKE_PAD_4>": 151686,
208
+ "<FAKE_PAD_50>": 151732,
209
+ "<FAKE_PAD_51>": 151733,
210
+ "<FAKE_PAD_52>": 151734,
211
+ "<FAKE_PAD_53>": 151735,
212
+ "<FAKE_PAD_54>": 151736,
213
+ "<FAKE_PAD_55>": 151737,
214
+ "<FAKE_PAD_56>": 151738,
215
+ "<FAKE_PAD_57>": 151739,
216
+ "<FAKE_PAD_58>": 151740,
217
+ "<FAKE_PAD_59>": 151741,
218
+ "<FAKE_PAD_5>": 151687,
219
+ "<FAKE_PAD_60>": 151742,
220
+ "<FAKE_PAD_61>": 151743,
221
+ "<FAKE_PAD_62>": 151744,
222
+ "<FAKE_PAD_63>": 151745,
223
+ "<FAKE_PAD_64>": 151746,
224
+ "<FAKE_PAD_65>": 151747,
225
+ "<FAKE_PAD_66>": 151748,
226
+ "<FAKE_PAD_67>": 151749,
227
+ "<FAKE_PAD_68>": 151750,
228
+ "<FAKE_PAD_69>": 151751,
229
+ "<FAKE_PAD_6>": 151688,
230
+ "<FAKE_PAD_70>": 151752,
231
+ "<FAKE_PAD_71>": 151753,
232
+ "<FAKE_PAD_72>": 151754,
233
+ "<FAKE_PAD_73>": 151755,
234
+ "<FAKE_PAD_74>": 151756,
235
+ "<FAKE_PAD_75>": 151757,
236
+ "<FAKE_PAD_76>": 151758,
237
+ "<FAKE_PAD_77>": 151759,
238
+ "<FAKE_PAD_78>": 151760,
239
+ "<FAKE_PAD_79>": 151761,
240
+ "<FAKE_PAD_7>": 151689,
241
+ "<FAKE_PAD_80>": 151762,
242
+ "<FAKE_PAD_81>": 151763,
243
+ "<FAKE_PAD_82>": 151764,
244
+ "<FAKE_PAD_83>": 151765,
245
+ "<FAKE_PAD_84>": 151766,
246
+ "<FAKE_PAD_85>": 151767,
247
+ "<FAKE_PAD_86>": 151768,
248
+ "<FAKE_PAD_87>": 151769,
249
+ "<FAKE_PAD_88>": 151770,
250
+ "<FAKE_PAD_89>": 151771,
251
+ "<FAKE_PAD_8>": 151690,
252
+ "<FAKE_PAD_90>": 151772,
253
+ "<FAKE_PAD_91>": 151773,
254
+ "<FAKE_PAD_92>": 151774,
255
+ "<FAKE_PAD_93>": 151775,
256
+ "<FAKE_PAD_94>": 151776,
257
+ "<FAKE_PAD_95>": 151777,
258
+ "<FAKE_PAD_96>": 151778,
259
+ "<FAKE_PAD_97>": 151779,
260
+ "<FAKE_PAD_98>": 151780,
261
+ "<FAKE_PAD_99>": 151781,
262
+ "<FAKE_PAD_9>": 151691,
263
+ "<IMG_CONTEXT>": 151669,
264
+ "<box>": 151676,
265
+ "<img>": 151670,
266
+ "<quad>": 151672,
267
+ "<ref>": 151674,
268
+ "<think>": 151667,
269
+ "<tool_call>": 151657,
270
+ "<tool_response>": 151665,
271
+ "<|action_end|>": 151679,
272
+ "<|action_start|>": 151678,
273
+ "<|box_end|>": 151649,
274
+ "<|box_start|>": 151648,
275
+ "<|endoftext|>": 151643,
276
+ "<|file_sep|>": 151664,
277
+ "<|fim_middle|>": 151660,
278
+ "<|fim_pad|>": 151662,
279
+ "<|fim_prefix|>": 151659,
280
+ "<|fim_suffix|>": 151661,
281
+ "<|im_end|>": 151645,
282
+ "<|im_start|>": 151644,
283
+ "<|image_pad|>": 151655,
284
+ "<|interpreter|>": 151681,
285
+ "<|object_ref_end|>": 151647,
286
+ "<|object_ref_start|>": 151646,
287
+ "<|plugin|>": 151680,
288
+ "<|quad_end|>": 151651,
289
+ "<|quad_start|>": 151650,
290
+ "<|repo_name|>": 151663,
291
+ "<|video_pad|>": 151656,
292
+ "<|vision_end|>": 151653,
293
+ "<|vision_pad|>": 151654,
294
+ "<|vision_start|>": 151652
295
+ }
config.json ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "NEOChatModel"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_neo_chat.NEOChatConfig",
7
+ "AutoModel": "modeling_neo_chat.NEOChatModel",
8
+ "AutoModelForCausalLM": "modeling_neo_chat.NEOChatModel"
9
+ },
10
+ "downsample_ratio": 0.5,
11
+ "eos_token_id": 151645,
12
+ "llm_config": {
13
+ "_name_or_path": null,
14
+ "architectures": [
15
+ "Qwen3ForCausalLM"
16
+ ],
17
+ "attention_bias": false,
18
+ "attention_dropout": 0.0,
19
+ "bos_token_id": 151643,
20
+ "eos_token_id": 151645,
21
+ "head_dim": 128,
22
+ "hidden_act": "silu",
23
+ "hidden_size": 4096,
24
+ "intermediate_size": 12288,
25
+ "max_position_embeddings": 262144,
26
+ "max_position_embeddings_hw": 10000,
27
+ "max_window_layers": 42,
28
+ "model_type": "qwen3",
29
+ "num_attention_heads": 32,
30
+ "num_hidden_layers": 42,
31
+ "num_key_value_heads": 8,
32
+ "rms_norm_eps": 1e-06,
33
+ "rope_scaling": null,
34
+ "rope_theta": 5000000.0,
35
+ "rope_theta_hw": 10000.0,
36
+ "sliding_window": null,
37
+ "torch_dtype": "bfloat16",
38
+ "use_cache": false,
39
+ "use_deepep": false,
40
+ "use_sliding_window": false,
41
+ "vocab_size": 151936,
42
+ "pure_llm": false
43
+ },
44
+ "model_type": "neo_chat",
45
+ "pad_token_id": 151643,
46
+ "template": "neo1_0",
47
+ "tie_word_embeddings": false,
48
+ "torch_dtype": "bfloat16",
49
+ "transformers_version": "4.37.2",
50
+ "use_backbone_lora": 0,
51
+ "use_llm_lora": 0,
52
+ "min_pixels": 65536,
53
+ "max_pixels": 16777216,
54
+ "patch_size": 16,
55
+ "timestep_shift": 1.0,
56
+ "time_schedule": "standard",
57
+ "time_shift_type": "exponential",
58
+ "base_shift": 0.5,
59
+ "max_shift": 1.15,
60
+ "base_image_seq_len": 64,
61
+ "max_image_seq_len": 4096,
62
+ "noise_scale_mode": "resolution",
63
+ "noise_scale_base_image_seq_len": 64,
64
+ "add_noise_scale_embedding": true,
65
+ "noise_scale_max_value": 8.0,
66
+ "noise_scale": 1.0,
67
+ "P_mean": -0.8,
68
+ "P_std": 0.8,
69
+ "t_eps": 0.05,
70
+ "fm_head_dim": 1536,
71
+ "fm_head_layers": 2,
72
+ "fm_head_mlp_ratio": 1,
73
+ "extra_num_layers_post": 0,
74
+ "concat_time_token_num": 0,
75
+ "use_pixel_head": false,
76
+ "use_adaLN": false,
77
+ "vision_config": {
78
+ "architectures": [
79
+ "NEOVisionModel"
80
+ ],
81
+ "attention_dropout": 0.0,
82
+ "auto_map": {
83
+ "AutoConfig": "configuration_neo_vit.NEOVisionConfig",
84
+ "AutoModel": "modeling_neo_vit.NEOVisionModel"
85
+ },
86
+ "llm_hidden_size": 4096,
87
+ "downsample_ratio": 0.5,
88
+ "hidden_size": 1024,
89
+ "model_type": "neo_vision",
90
+ "rope_theta_vision": 10000.0,
91
+ "max_position_embeddings_vision": 10000,
92
+ "num_channels": 3,
93
+ "patch_size": 16,
94
+ "torch_dtype": "bfloat16",
95
+ "transformers_version": "4.37.2",
96
+ "min_pixels": 65536,
97
+ "max_pixels": 16777216
98
+ }
99
+ }
configuration_neo_chat.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+
3
+ from transformers import Qwen3Config
4
+ from transformers.utils import logging
5
+ from transformers.configuration_utils import PretrainedConfig
6
+
7
+ from .configuration_neo_vit import NEOVisionConfig
8
+
9
+
10
+ logger = logging.get_logger(__name__)
11
+
12
+
13
+ class NEOLLMConfig(Qwen3Config):
14
+ def __init__(self, rope_theta_hw=10000.0, max_position_embeddings_hw=10000, **kwargs):
15
+ super().__init__(**kwargs)
16
+ self.rope_theta_hw = rope_theta_hw
17
+ self.max_position_embeddings_hw = max_position_embeddings_hw
18
+
19
+
20
+ class NEOChatConfig(PretrainedConfig):
21
+ model_type = 'neo_chat'
22
+ is_composition = True
23
+
24
+ def __init__(
25
+ self,
26
+ vision_config=None,
27
+ llm_config=None,
28
+ use_backbone_lora=0,
29
+ use_llm_lora=0,
30
+ downsample_ratio=0.5,
31
+ template=None,
32
+ **kwargs,
33
+ ):
34
+ super().__init__(**kwargs)
35
+
36
+ if vision_config is None:
37
+ vision_config = {'architectures': ['NEOVisionModel']}
38
+ logger.info('vision_config is None. Initializing the NEOVisionConfig with default values.')
39
+
40
+ if llm_config is None:
41
+ llm_config = {'architectures': ['Qwen3ForCausalLM']}
42
+ logger.info('llm_config is None. Initializing the LlamaConfig config with default values (`LlamaConfig`).')
43
+ assert 'architectures' in llm_config, "Should specify architecture in llm_config"
44
+
45
+ if isinstance(vision_config, dict):
46
+ self.vision_config = NEOVisionConfig(**vision_config)
47
+ else:
48
+ self.vision_config = vision_config
49
+
50
+ if isinstance(llm_config, dict):
51
+ self.llm_config = NEOLLMConfig(**llm_config)
52
+ else:
53
+ self.llm_config = llm_config
54
+
55
+ self.use_backbone_lora = use_backbone_lora
56
+ self.use_llm_lora = use_llm_lora
57
+ self.downsample_ratio = downsample_ratio
58
+ self.template = template
59
+ self.tie_word_embeddings = self.llm_config.tie_word_embeddings
60
+
61
+ def to_dict(self):
62
+ """
63
+ Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
64
+
65
+ Returns:
66
+ `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
67
+ """
68
+ output = copy.deepcopy(self.__dict__)
69
+ output['vision_config'] = self.vision_config.to_dict()
70
+ output['llm_config'] = self.llm_config.to_dict()
71
+ output['model_type'] = self.__class__.model_type
72
+ output['use_backbone_lora'] = self.use_backbone_lora
73
+ output['use_llm_lora'] = self.use_llm_lora
74
+ output['downsample_ratio'] = self.downsample_ratio
75
+ output['template'] = self.template
76
+
77
+ return output
configuration_neo_vit.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Union
3
+
4
+ from transformers.configuration_utils import PretrainedConfig
5
+ from transformers.utils import logging
6
+
7
+ logger = logging.get_logger(__name__)
8
+
9
+
10
+ class NEOVisionConfig(PretrainedConfig):
11
+
12
+ model_type = 'neo_vision'
13
+
14
+ def __init__(
15
+ self,
16
+ num_channels=3,
17
+ patch_size=16,
18
+ hidden_size=1024,
19
+ llm_hidden_size=2048,
20
+ downsample_ratio=0.5,
21
+ rope_theta_vision=10000.0,
22
+ max_position_embeddings_vision=10000,
23
+ min_pixels=65536,
24
+ max_pixels=4194304,
25
+ **kwargs,
26
+ ):
27
+ super().__init__(**kwargs)
28
+
29
+ self.hidden_size = hidden_size
30
+ self.llm_hidden_size = llm_hidden_size,
31
+ self.downsample_ratio = downsample_ratio,
32
+ self.rope_theta_vision = rope_theta_vision
33
+ self.max_position_embeddings_vision = max_position_embeddings_vision
34
+ self.num_channels = num_channels
35
+ self.patch_size = patch_size
36
+ self.min_pixels = min_pixels
37
+ self.max_pixels = max_pixels
38
+
39
+ @classmethod
40
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> 'PretrainedConfig':
41
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
42
+
43
+ if 'vision_config' in config_dict:
44
+ config_dict = config_dict['vision_config']
45
+
46
+ if 'model_type' in config_dict and hasattr(cls, 'model_type') and config_dict['model_type'] != cls.model_type:
47
+ logger.warning(
48
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
49
+ f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'
50
+ )
51
+
52
+ return cls.from_dict(config_dict, **kwargs)
conversation.py ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Conversation prompt templates.
3
+
4
+ We kindly request that you import fastchat instead of copying this file if you wish to use it.
5
+ If you have changes in mind, please contribute back so the community can benefit collectively and continue to maintain these valuable templates.
6
+
7
+ Modified from https://github.com/lm-sys/FastChat/blob/main/fastchat/conversation.py
8
+ """
9
+
10
+ import dataclasses
11
+ from enum import IntEnum, auto
12
+ from typing import Dict, List, Tuple, Union
13
+
14
+
15
+ class SeparatorStyle(IntEnum):
16
+ """Separator styles."""
17
+
18
+ ADD_COLON_SINGLE = auto()
19
+ ADD_COLON_TWO = auto()
20
+ ADD_COLON_SPACE_SINGLE = auto()
21
+ NO_COLON_SINGLE = auto()
22
+ NO_COLON_TWO = auto()
23
+ ADD_NEW_LINE_SINGLE = auto()
24
+ LLAMA2 = auto()
25
+ CHATGLM = auto()
26
+ CHATML = auto()
27
+ CHATINTERN = auto()
28
+ DOLLY = auto()
29
+ RWKV = auto()
30
+ PHOENIX = auto()
31
+ ROBIN = auto()
32
+ FALCON_CHAT = auto()
33
+ CHATGLM3 = auto()
34
+ INTERNVL_ZH = auto()
35
+ MPT = auto()
36
+
37
+
38
+ @dataclasses.dataclass
39
+ class Conversation:
40
+ """A class that manages prompt templates and keeps all conversation history."""
41
+
42
+ # The name of this template
43
+ name: str
44
+ # The template of the system prompt
45
+ system_template: str = '{system_message}'
46
+ # The system message
47
+ system_message: str = ''
48
+ # The names of two roles
49
+ roles: Tuple[str] = ('USER', 'ASSISTANT')
50
+ # All messages. Each item is (role, message).
51
+ messages: List[List[str]] = ()
52
+ # The number of few shot examples
53
+ offset: int = 0
54
+ # The separator style and configurations
55
+ sep_style: SeparatorStyle = SeparatorStyle.ADD_COLON_SINGLE
56
+ sep: str = '\n'
57
+ sep2: str = None
58
+ # Stop criteria (the default one is EOS token)
59
+ stop_str: Union[str, List[str]] = None
60
+ # Stops generation if meeting any token in this list
61
+ stop_token_ids: List[int] = None
62
+
63
+ def get_prompt(self) -> str:
64
+ """Get the prompt for generation."""
65
+ if self.system_message is not None and self.system_message != '':
66
+ system_prompt = self.system_template.format(system_message=self.system_message)
67
+ else:
68
+ system_prompt = ''
69
+
70
+ if self.sep_style == SeparatorStyle.ADD_COLON_SINGLE:
71
+ ret = '' if system_prompt == '' else system_prompt + self.sep
72
+ for role, message in self.messages:
73
+ if message:
74
+ ret += role + ': ' + message + self.sep
75
+ else:
76
+ ret += role + ':'
77
+ return ret
78
+ elif self.sep_style == SeparatorStyle.ADD_COLON_TWO:
79
+ seps = [self.sep, self.sep2]
80
+ ret = '' if system_prompt == '' else system_prompt + seps[0]
81
+ for i, (role, message) in enumerate(self.messages):
82
+ if message:
83
+ ret += role + ': ' + message + seps[i % 2]
84
+ else:
85
+ ret += role + ':'
86
+ return ret
87
+ elif self.sep_style == SeparatorStyle.ADD_COLON_SPACE_SINGLE:
88
+ ret = '' if system_prompt == '' else system_prompt + self.sep
89
+ for role, message in self.messages:
90
+ if message:
91
+ ret += role + ': ' + message + self.sep
92
+ else:
93
+ ret += role + ': ' # must be end with a space
94
+ return ret
95
+ elif self.sep_style == SeparatorStyle.ADD_NEW_LINE_SINGLE:
96
+ ret = '' if system_prompt == '' else system_prompt + self.sep
97
+ for role, message in self.messages:
98
+ if message:
99
+ ret += role + '\n' + message + self.sep
100
+ else:
101
+ ret += role + '\n'
102
+ return ret
103
+ elif self.sep_style == SeparatorStyle.NO_COLON_SINGLE:
104
+ ret = system_prompt
105
+ for role, message in self.messages:
106
+ if message:
107
+ ret += role + message + self.sep
108
+ else:
109
+ ret += role
110
+ return ret
111
+ elif self.sep_style == SeparatorStyle.NO_COLON_TWO:
112
+ seps = [self.sep, self.sep2]
113
+ ret = system_prompt
114
+ for i, (role, message) in enumerate(self.messages):
115
+ if message:
116
+ ret += role + message + seps[i % 2]
117
+ else:
118
+ ret += role
119
+ return ret
120
+ elif self.sep_style == SeparatorStyle.RWKV:
121
+ ret = system_prompt
122
+ for i, (role, message) in enumerate(self.messages):
123
+ if message:
124
+ ret += (
125
+ role
126
+ + ': '
127
+ + message.replace('\r\n', '\n').replace('\n\n', '\n')
128
+ )
129
+ ret += '\n\n'
130
+ else:
131
+ ret += role + ':'
132
+ return ret
133
+ elif self.sep_style == SeparatorStyle.LLAMA2:
134
+ seps = [self.sep, self.sep2]
135
+ ret = system_prompt if system_prompt != '' else '[INST] '
136
+ for i, (role, message) in enumerate(self.messages):
137
+ tag = self.roles[i % 2]
138
+ if message:
139
+ if i == 0:
140
+ ret += message + ' '
141
+ else:
142
+ ret += tag + ' ' + message + seps[i % 2]
143
+ else:
144
+ ret += tag
145
+ return ret
146
+ elif self.sep_style == SeparatorStyle.CHATGLM:
147
+ # source: https://huggingface.co/THUDM/chatglm-6b/blob/1d240ba371910e9282298d4592532d7f0f3e9f3e/modeling_chatglm.py#L1302-L1308
148
+ # source2: https://huggingface.co/THUDM/chatglm2-6b/blob/e186c891cf64310ac66ef10a87e6635fa6c2a579/modeling_chatglm.py#L926
149
+ round_add_n = 1 if self.name == 'chatglm2' else 0
150
+ ret = '' if system_prompt == '' else system_prompt + self.sep
151
+
152
+ for i, (role, message) in enumerate(self.messages):
153
+ if i % 2 == 0:
154
+ ret += f'[Round {i//2 + round_add_n}]{self.sep}'
155
+
156
+ if message:
157
+ ret += f'{role}:{message}{self.sep}'
158
+ else:
159
+ ret += f'{role}:'
160
+ return ret
161
+ elif self.sep_style == SeparatorStyle.CHATML:
162
+ ret = '' if system_prompt == '' else system_prompt + self.sep + '\n'
163
+ for role, message in self.messages:
164
+ if message:
165
+ ret += role + '\n' + message + self.sep + '\n'
166
+ else:
167
+ ret += role + '\n'
168
+ return ret
169
+ elif self.sep_style == SeparatorStyle.CHATGLM3:
170
+ ret = system_prompt
171
+ for role, message in self.messages:
172
+ if message:
173
+ ret += role + '\n' + ' ' + message
174
+ else:
175
+ ret += role
176
+ return ret
177
+ elif self.sep_style == SeparatorStyle.CHATINTERN:
178
+ # source: https://huggingface.co/internlm/internlm-chat-7b-8k/blob/bd546fa984b4b0b86958f56bf37f94aa75ab8831/modeling_internlm.py#L771
179
+ seps = [self.sep, self.sep2]
180
+ ret = system_prompt
181
+ for i, (role, message) in enumerate(self.messages):
182
+ # if i % 2 == 0:
183
+ # ret += "<s>"
184
+ if message:
185
+ ret += role + ':' + message + seps[i % 2] + '\n'
186
+ else:
187
+ ret += role + ':'
188
+ return ret
189
+ elif self.sep_style == SeparatorStyle.DOLLY:
190
+ seps = [self.sep, self.sep2]
191
+ ret = system_prompt
192
+ for i, (role, message) in enumerate(self.messages):
193
+ if message:
194
+ ret += role + ':\n' + message + seps[i % 2]
195
+ if i % 2 == 1:
196
+ ret += '\n\n'
197
+ else:
198
+ ret += role + ':\n'
199
+ return ret
200
+ elif self.sep_style == SeparatorStyle.PHOENIX:
201
+ ret = system_prompt
202
+ for role, message in self.messages:
203
+ if message:
204
+ ret += role + ': ' + '<s>' + message + '</s>'
205
+ else:
206
+ ret += role + ': ' + '<s>'
207
+ return ret
208
+ elif self.sep_style == SeparatorStyle.ROBIN:
209
+ ret = '' if system_prompt == '' else system_prompt + self.sep
210
+ for role, message in self.messages:
211
+ if message:
212
+ ret += role + ':\n' + message + self.sep
213
+ else:
214
+ ret += role + ':\n'
215
+ return ret
216
+ elif self.sep_style == SeparatorStyle.FALCON_CHAT:
217
+ ret = '' if system_prompt == '' else system_prompt + self.sep
218
+ for role, message in self.messages:
219
+ if message:
220
+ ret += role + ': ' + message + self.sep
221
+ else:
222
+ ret += role + ':'
223
+
224
+ return ret
225
+ elif self.sep_style == SeparatorStyle.INTERNVL_ZH:
226
+ seps = [self.sep, self.sep2]
227
+ ret = '' if system_prompt == '' else self.system_message + seps[0]
228
+ for i, (role, message) in enumerate(self.messages):
229
+ if message:
230
+ ret += role + ': ' + message + seps[i % 2]
231
+ else:
232
+ ret += role + ':'
233
+ return ret
234
+ elif self.sep_style == SeparatorStyle.MPT:
235
+ ret = '' if system_prompt == '' else system_prompt + self.sep
236
+ for i, (role, message) in enumerate(self.messages):
237
+ if message:
238
+ if type(message) is tuple:
239
+ message, _, _ = message
240
+ ret += role + message + self.sep
241
+ else:
242
+ if i != len(self.messages) - 1 and message is not None:
243
+ ret += role + self.sep
244
+ else:
245
+ ret += role
246
+ return ret
247
+ else:
248
+ raise ValueError(f'Invalid style: {self.sep_style}')
249
+
250
+ def set_system_message(self, system_message: str):
251
+ """Set the system message."""
252
+ self.system_message = system_message
253
+
254
+ def append_message(self, role: str, message: str):
255
+ """Append a new message."""
256
+ self.messages.append([role, message])
257
+
258
+ def update_last_message(self, message: str):
259
+ """Update the last output.
260
+
261
+ The last message is typically set to be None when constructing the prompt,
262
+ so we need to update it in-place after getting the response from a model.
263
+ """
264
+ self.messages[-1][1] = message
265
+
266
+ def to_gradio_chatbot(self):
267
+ """Convert the conversation to gradio chatbot format."""
268
+ ret = []
269
+ for i, (role, msg) in enumerate(self.messages[self.offset :]):
270
+ if i % 2 == 0:
271
+ ret.append([msg, None])
272
+ else:
273
+ ret[-1][-1] = msg
274
+ return ret
275
+
276
+ def to_openai_api_messages(self):
277
+ """Convert the conversation to OpenAI chat completion format."""
278
+ ret = [{'role': 'system', 'content': self.system_message}]
279
+
280
+ for i, (_, msg) in enumerate(self.messages[self.offset :]):
281
+ if i % 2 == 0:
282
+ ret.append({'role': 'user', 'content': msg})
283
+ else:
284
+ if msg is not None:
285
+ ret.append({'role': 'assistant', 'content': msg})
286
+ return ret
287
+
288
+ def copy(self):
289
+ return Conversation(
290
+ name=self.name,
291
+ system_template=self.system_template,
292
+ system_message=self.system_message,
293
+ roles=self.roles,
294
+ messages=[[x, y] for x, y in self.messages],
295
+ offset=self.offset,
296
+ sep_style=self.sep_style,
297
+ sep=self.sep,
298
+ sep2=self.sep2,
299
+ stop_str=self.stop_str,
300
+ stop_token_ids=self.stop_token_ids,
301
+ )
302
+
303
+ def dict(self):
304
+ return {
305
+ 'template_name': self.name,
306
+ 'system_message': self.system_message,
307
+ 'roles': self.roles,
308
+ 'messages': self.messages,
309
+ 'offset': self.offset,
310
+ }
311
+
312
+
313
+ # A global registry for all conversation templates
314
+ conv_templates: Dict[str, Conversation] = {}
315
+
316
+
317
+ def register_conv_template(template: Conversation, override: bool = False):
318
+ """Register a new conversation template."""
319
+ if not override:
320
+ assert (
321
+ template.name not in conv_templates
322
+ ), f'{template.name} has been registered.'
323
+
324
+ conv_templates[template.name] = template
325
+
326
+
327
+ def get_conv_template(name: str) -> Conversation:
328
+ """Get a conversation template."""
329
+ return conv_templates[name].copy()
330
+
331
+
332
+ # Both Hermes-2 and neo1_0-chat are chatml-format conversation templates. The difference
333
+ # is that during training, the preprocessing function for the Hermes-2 template doesn't add
334
+ # <s> at the beginning of the tokenized sequence, while the neo1_0-chat template does.
335
+ # Therefore, they are completely equivalent during inference.
336
+
337
+ register_conv_template(
338
+ Conversation(
339
+ name='Hermes-2',
340
+ system_template='<|im_start|>system\n{system_message}',
341
+ # note: The new system prompt was not used here to avoid changes in benchmark performance.
342
+ # system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
343
+ system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
344
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
345
+ sep_style=SeparatorStyle.MPT,
346
+ sep='<|im_end|>',
347
+ stop_str='<|endoftext|>',
348
+ )
349
+ )
350
+
351
+ register_conv_template(
352
+ Conversation(
353
+ name='internlm2-chat',
354
+ system_template='<|im_start|>system\n{system_message}',
355
+ # note: The new system prompt was not used here to avoid changes in benchmark performance.
356
+ # system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
357
+ system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
358
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
359
+ sep_style=SeparatorStyle.MPT,
360
+ sep='<|im_end|>',
361
+ )
362
+ )
363
+
364
+ register_conv_template(
365
+ Conversation(
366
+ name='phi3-chat',
367
+ system_template='<|system|>\n{system_message}',
368
+ # note: The new system prompt was not used here to avoid changes in benchmark performance.
369
+ # system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
370
+ system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
371
+ roles=('<|user|>\n', '<|assistant|>\n'),
372
+ sep_style=SeparatorStyle.MPT,
373
+ sep='<|end|>',
374
+ )
375
+ )
376
+
377
+ register_conv_template(
378
+ Conversation(
379
+ name='internvl2_5',
380
+ system_template='<|im_start|>system\n{system_message}',
381
+ system_message='你是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
382
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
383
+ sep_style=SeparatorStyle.MPT,
384
+ sep='<|im_end|>\n',
385
+ )
386
+ )
387
+
388
+ register_conv_template(
389
+ Conversation(
390
+ name='neo1_0',
391
+ system_template='<|im_start|>system\n{system_message}',
392
+ system_message='',
393
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
394
+ sep_style=SeparatorStyle.MPT,
395
+ sep='<|im_end|>\n',
396
+ )
397
+ )
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model-00001-of-00008.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aba7fb8fb424afb603c907326df6130c8f5ba2c7522601c71c3cb3348c3572db
3
+ size 4937383712
model-00002-of-00008.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:127b9c3cdecc1a68c76b28f4ca2228d5f29b0e19abd71bcf71f1d279cf3450bb
3
+ size 4999870648
model-00003-of-00008.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0c1c5a4c46b4121bdcd7f7c133fa3ff054f1d54b1b2b42eef6efb733eecf1595
3
+ size 4932725608
model-00004-of-00008.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:07e708038f365bf152dd81a9e0e55b34e8c0713f6f47a0aa788ef71193f0b486
3
+ size 4999868056
model-00005-of-00008.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f01f7e0ce70a92da7a2e68af86facd02cac91927a0387eee612a5a628314e618
3
+ size 4932728352
model-00006-of-00008.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:89eb05f76727185d3747b06c6bd029247f7b947b607a733fd3022007fb0e5a3c
3
+ size 4932725624
model-00007-of-00008.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d0ec946d133991b1bd2963af79548accff18b457746bccc330e30fc35d9651ef
3
+ size 3959659416
model-00008-of-00008.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c864b190def1e7c10665eb073df8c687d40eac16591123b702ec0fcc6f8eb718
3
+ size 1409869776
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_fm_modules.py ADDED
@@ -0,0 +1,591 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ import torch.nn as nn
4
+ import math
5
+ from functools import lru_cache
6
+
7
+ from torch.utils.checkpoint import checkpoint
8
+ def modulate(x, shift, scale=None):
9
+ if shift is None:
10
+ return x * (1 + scale)
11
+ return x * (1 + scale) + shift
12
+
13
+ class RMSNorm(nn.Module):
14
+ def __init__(self, dim: int, eps: float = 1e-5):
15
+ super().__init__()
16
+ self.eps = eps
17
+ self.weight = nn.Parameter(torch.ones(dim))
18
+
19
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
20
+ output = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
21
+ return output * self.weight
22
+
23
+ class TimestepEmbedder(nn.Module):
24
+ """
25
+ Embeds scalar timesteps into vector representations.
26
+ """
27
+
28
+ def __init__(self, hidden_size, frequency_embedding_size=256):
29
+ super().__init__()
30
+ self.mlp = nn.Sequential(
31
+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),
32
+ nn.SiLU(),
33
+ nn.Linear(hidden_size, hidden_size, bias=True),
34
+ )
35
+ self.frequency_embedding_size = frequency_embedding_size
36
+
37
+ @staticmethod
38
+ def timestep_embedding(t: torch.Tensor, dim: int, max_period: float = 10000.0):
39
+ """
40
+ Create sinusoidal timestep embeddings.
41
+ :param t: a 1-D Tensor of N indices, one per batch element. These may be fractional.
42
+ :param dim: the dimension of the output.
43
+ :param max_period: controls the minimum frequency of the embeddings.
44
+ :return: an (N, D) Tensor of positional embeddings.
45
+ """
46
+ # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
47
+ half = dim // 2
48
+ freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(
49
+ device=t.device
50
+ )
51
+ args = t[:, None].float() * freqs[None]
52
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
53
+ if dim % 2:
54
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
55
+ return embedding
56
+
57
+ def forward(self, t):
58
+ t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
59
+ t_emb = self.mlp(t_freq.to(self.mlp[0].weight.dtype))
60
+ return t_emb
61
+
62
+ class ResBlock(nn.Module):
63
+
64
+ def __init__(self, channels, mlp_ratio=1.0):
65
+ super().__init__()
66
+ self.channels = channels
67
+ self.intermediate_size = int(channels * mlp_ratio)
68
+
69
+ self.in_ln = nn.LayerNorm(self.channels, eps=1e-6)
70
+ self.mlp = nn.Sequential(
71
+ nn.Linear(self.channels, self.intermediate_size),
72
+ nn.SiLU(),
73
+ nn.Linear(self.intermediate_size, self.channels),
74
+ )
75
+
76
+ self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(channels, 3 * channels, bias=True))
77
+
78
+ def forward(self, x, y):
79
+ shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(y).chunk(3, dim=-1)
80
+ h = modulate(self.in_ln(x), shift_mlp, scale_mlp)
81
+ h = self.mlp(h)
82
+ return x + gate_mlp * h
83
+
84
+ # class FinalLayer(nn.Module):
85
+
86
+ # def __init__(self, model_channels, out_channels):
87
+ # super().__init__()
88
+ # self.norm_final = nn.LayerNorm(model_channels, elementwise_affine=False, eps=1e-6)
89
+ # self.linear = nn.Linear(model_channels, out_channels, bias=True)
90
+ # self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(model_channels, 2 * model_channels, bias=True))
91
+
92
+ # def forward(self, x, c):
93
+ # shift, scale = self.adaLN_modulation(c).chunk(2, dim=-1)
94
+ # x = modulate(self.norm_final(x), shift, scale)
95
+ # x = self.linear(x)
96
+ # return x
97
+
98
+ # class SimpleMLPAdaLN(nn.Module):
99
+
100
+ # def __init__(self, input_dim, out_dim, dim=1536, layers=12, mlp_ratio=1.0):
101
+ # super().__init__()
102
+ # self.input_dim = input_dim
103
+ # self.out_dim = out_dim
104
+ # self.dim = dim
105
+ # self.layers = layers
106
+ # self.mlp_ratio = mlp_ratio
107
+
108
+ # self.time_embed = TimestepEmbedder(dim)
109
+ # self.input_proj = nn.Linear(input_dim, dim)
110
+
111
+ # res_blocks = []
112
+ # for _ in range(layers):
113
+ # res_blocks.append(ResBlock(dim, mlp_ratio))
114
+ # self.res_blocks = nn.ModuleList(res_blocks)
115
+
116
+ # self.final_layer = FinalLayer(dim, out_dim)
117
+
118
+ # self.grad_checkpointing = False
119
+
120
+ # self.initialize_weights()
121
+
122
+ # def initialize_weights(self):
123
+ # def _basic_init(module):
124
+ # if isinstance(module, nn.Linear):
125
+ # torch.nn.init.xavier_uniform_(module.weight)
126
+ # if module.bias is not None:
127
+ # nn.init.constant_(module.bias, 0)
128
+
129
+ # self.apply(_basic_init)
130
+
131
+ # # Initialize timestep embedding MLP
132
+ # nn.init.normal_(self.time_embed.mlp[0].weight, std=0.02)
133
+ # nn.init.normal_(self.time_embed.mlp[2].weight, std=0.02)
134
+
135
+ # # Zero-out adaLN modulation layers
136
+ # for block in self.res_blocks:
137
+ # nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
138
+ # nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
139
+
140
+ # # Zero-out output layers
141
+ # nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0)
142
+ # nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0)
143
+ # nn.init.constant_(self.final_layer.linear.weight, 0)
144
+ # nn.init.constant_(self.final_layer.linear.bias, 0)
145
+
146
+ # def forward(self, x, t):
147
+ # """
148
+ # x.shape = (bsz, input_dim)
149
+ # t.shape = (bsz,)
150
+ # """
151
+
152
+ # x = self.input_proj(x)
153
+ # t = self.time_embed(t)
154
+
155
+ # y = t
156
+
157
+ # for block in self.res_blocks:
158
+ # if self.grad_checkpointing and self.training:
159
+ # x = checkpoint(block, x, y, use_reentrant=True)
160
+ # else:
161
+ # x = block(x, y)
162
+
163
+ # return self.final_layer(x, y)
164
+
165
+ class FlowMatchingHead(nn.Module):
166
+
167
+ def __init__(self, input_dim, out_dim, dim=1536, layers=12, mlp_ratio=1.0):
168
+ super(FlowMatchingHead, self).__init__()
169
+ self.net = SimpleMLPAdaLN(input_dim=input_dim, out_dim=out_dim, dim=dim, layers=layers, mlp_ratio=mlp_ratio)
170
+
171
+ @property
172
+ def dtype(self):
173
+ return self.net.input_proj.weight.dtype
174
+
175
+ @property
176
+ def device(self):
177
+ return self.net.input_proj.weight.device
178
+
179
+ def forward(self, x, t):
180
+ x = self.net(x, t)
181
+ return x
182
+
183
+
184
+ def precompute_freqs_cis_2d(dim: int, height: int, width:int, theta: float = 10000.0, scale=16.0):
185
+ # assert H * H == end
186
+ # flat_patch_pos = torch.linspace(-1, 1, end) # N = end
187
+ x_pos = torch.linspace(0, scale, width)
188
+ y_pos = torch.linspace(0, scale, height)
189
+ y_pos, x_pos = torch.meshgrid(y_pos, x_pos, indexing="ij")
190
+ y_pos = y_pos.reshape(-1)
191
+ x_pos = x_pos.reshape(-1)
192
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 4)[: (dim // 4)].float() / dim)) # Hc/4
193
+ x_freqs = torch.outer(x_pos, freqs).float() # N Hc/4
194
+ y_freqs = torch.outer(y_pos, freqs).float() # N Hc/4
195
+ x_cis = torch.polar(torch.ones_like(x_freqs), x_freqs)
196
+ y_cis = torch.polar(torch.ones_like(y_freqs), y_freqs)
197
+ freqs_cis = torch.cat([x_cis.unsqueeze(dim=-1), y_cis.unsqueeze(dim=-1)], dim=-1) # N,Hc/4,2
198
+ freqs_cis = freqs_cis.reshape(height*width, -1)
199
+ return freqs_cis
200
+
201
+ class NerfEmbedder(nn.Module):
202
+ def __init__(self, in_channels, hidden_size_input, max_freqs):
203
+ super().__init__()
204
+ self.max_freqs = max_freqs
205
+ self.hidden_size_input = hidden_size_input
206
+ self.embedder = nn.Sequential(
207
+ nn.Linear(in_channels+max_freqs**2, hidden_size_input, bias=True),
208
+ )
209
+
210
+ @lru_cache
211
+ def fetch_pos(self, patch_size, device, dtype):
212
+ pos = precompute_freqs_cis_2d(self.max_freqs ** 2 * 2, patch_size, patch_size).real
213
+ pos = pos[None, :, :].to(device=device, dtype=dtype)
214
+ return pos
215
+
216
+
217
+ def forward(self, inputs):
218
+ B, P2, C = inputs.shape
219
+ patch_size = int(P2 ** 0.5)
220
+ device = inputs.device
221
+ dtype = inputs.dtype
222
+ dct = self.fetch_pos(patch_size, device, dtype)
223
+ dct = dct.repeat(B, 1, 1)
224
+ inputs = torch.cat([inputs, dct], dim=-1)
225
+ inputs = self.embedder(inputs)
226
+ return inputs
227
+
228
+ class SimpleMLPAdaLN(nn.Module):
229
+ """
230
+ The MLP for Diffusion Loss.
231
+ :param in_channels: channels in the input Tensor.
232
+ :param model_channels: base channel count for the model.
233
+ :param out_channels: channels in the output Tensor.
234
+ :param z_channels: channels in the condition.
235
+ :param num_res_blocks: number of residual blocks per downsample.
236
+ """
237
+
238
+ def __init__(
239
+ self,
240
+ in_channels,
241
+ model_channels,
242
+ out_channels,
243
+ z_channels,
244
+ num_res_blocks,
245
+ patch_size,
246
+ grad_checkpointing=False
247
+ ):
248
+ super().__init__()
249
+
250
+ self.in_channels = in_channels
251
+ self.model_channels = model_channels
252
+ self.out_channels = out_channels
253
+ self.num_res_blocks = num_res_blocks
254
+ self.grad_checkpointing = grad_checkpointing
255
+ self.patch_size = patch_size
256
+
257
+ self.cond_embed = nn.Linear(z_channels, patch_size**2*model_channels)
258
+
259
+ self.input_proj = nn.Linear(in_channels, model_channels)
260
+
261
+ res_blocks = []
262
+ for i in range(num_res_blocks):
263
+ res_blocks.append(ResBlock(
264
+ model_channels,
265
+ ))
266
+
267
+ self.res_blocks = nn.ModuleList(res_blocks)
268
+ self.final_layer = FinalLayer(model_channels, out_channels)
269
+
270
+ self.initialize_weights()
271
+
272
+ def initialize_weights(self):
273
+ def _basic_init(module):
274
+ if isinstance(module, nn.Linear):
275
+ torch.nn.init.xavier_uniform_(module.weight)
276
+ if module.bias is not None:
277
+ nn.init.constant_(module.bias, 0)
278
+ self.apply(_basic_init)
279
+
280
+ # Zero-out adaLN modulation layers
281
+ for block in self.res_blocks:
282
+ nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
283
+ nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
284
+
285
+ # Zero-out output layers
286
+ nn.init.constant_(self.final_layer.linear.weight, 0)
287
+ nn.init.constant_(self.final_layer.linear.bias, 0)
288
+
289
+ def forward(self, x, c):
290
+ """
291
+ Apply the model to an input batch.
292
+ :param x: an [N x C] Tensor of inputs.
293
+ :param t: a 1-D batch of timesteps.
294
+ :param c: conditioning from AR transformer.
295
+ :return: an [N x C] Tensor of outputs.
296
+ """
297
+ x = self.input_proj(x)
298
+ c = self.cond_embed(c)
299
+
300
+ y = c.reshape(-1, self.patch_size**2, self.model_channels)
301
+
302
+ for block in self.res_blocks:
303
+ x = block(x, y)
304
+
305
+ return self.final_layer(x)
306
+
307
+
308
+ class FinalLayer(nn.Module):
309
+ """
310
+ The final layer adopted from DiT.
311
+ """
312
+ def __init__(self, model_channels, out_channels):
313
+ super().__init__()
314
+ self.norm_final = nn.LayerNorm(model_channels, elementwise_affine=False, eps=1e-6)
315
+ self.linear = nn.Linear(model_channels, out_channels, bias=True)
316
+
317
+ def forward(self, x):
318
+ x = self.norm_final(x)
319
+ x = self.linear(x)
320
+ return x
321
+
322
+ #################################################################################
323
+ # Sine/Cosine Positional Embedding Functions #
324
+ #################################################################################
325
+ # https://github.com/facebookresearch/mae/blob/main/util/pos_embed.py
326
+
327
+
328
+ def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0, pe_interpolation=1.0):
329
+ """
330
+ grid_size: int of the grid height and width
331
+ return:
332
+ pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
333
+ """
334
+ grid_h = np.arange(grid_size, dtype=np.float32) / pe_interpolation
335
+ grid_w = np.arange(grid_size, dtype=np.float32) / pe_interpolation
336
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
337
+ grid = np.stack(grid, axis=0)
338
+
339
+ grid = grid.reshape([2, 1, grid_size, grid_size])
340
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
341
+ if cls_token and extra_tokens > 0:
342
+ pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
343
+ return pos_embed
344
+
345
+
346
+ def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
347
+ assert embed_dim % 2 == 0
348
+
349
+ # use half of dimensions to encode grid_h
350
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
351
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
352
+
353
+ emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
354
+ return emb
355
+
356
+
357
+ def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
358
+ """
359
+ embed_dim: output dimension for each position
360
+ pos: a list of positions to be encoded: size (M,)
361
+ out: (M, D)
362
+ """
363
+ assert embed_dim % 2 == 0
364
+ omega = np.arange(embed_dim // 2, dtype=np.float64)
365
+ omega /= embed_dim / 2.0
366
+ omega = 1.0 / 10000**omega # (D/2,)
367
+
368
+ pos = pos.reshape(-1) # (M,)
369
+ out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product
370
+
371
+ emb_sin = np.sin(out) # (M, D/2)
372
+ emb_cos = np.cos(out) # (M, D/2)
373
+
374
+ emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
375
+ return emb
376
+
377
+ # --------------------------------------------------------
378
+ # Interpolate position embeddings for high-resolution
379
+ # References:
380
+ # DeiT: https://github.com/facebookresearch/deit
381
+ # --------------------------------------------------------
382
+ def interpolate_pos_embed(model_path, pe_key: str = "gen_pos_embed", new_len: int = 4096):
383
+ state_dict = torch.load(model_path, map_location="cpu")
384
+
385
+ pos_embed_1d = state_dict[pe_key]
386
+ _, ori_len, embed_dim = pos_embed_1d.shape
387
+
388
+ ori_size = int(ori_len**0.5)
389
+ new_size = int(new_len**0.5)
390
+
391
+ if ori_size != new_size:
392
+ logger.info("Position interpolate from %dx%d to %dx%d" % (ori_size, ori_size, new_size, new_size))
393
+ pos_embed_2d = pos_embed_1d.reshape(-1, ori_size, ori_size, embed_dim).permute(0, 3, 1, 2)
394
+ pos_embed_2d = torch.nn.functional.interpolate(
395
+ pos_embed_2d, size=(new_size, new_size), mode="bicubic", align_corners=False
396
+ )
397
+ pos_embed_1d = pos_embed_2d.permute(0, 2, 3, 1).flatten(1, 2)
398
+ state_dict[pe_key] = pos_embed_1d
399
+
400
+ torch.save(state_dict, model_path)
401
+
402
+ class PositionEmbedding(nn.Module):
403
+ def __init__(self, max_num_patch_per_side, hidden_size):
404
+ super().__init__()
405
+ self.max_num_patch_per_side = max_num_patch_per_side
406
+ self.hidden_size = hidden_size
407
+ self.pos_embed = nn.Parameter(
408
+ torch.zeros(max_num_patch_per_side ** 2, hidden_size),
409
+ requires_grad=False
410
+ )
411
+ self._init_weights()
412
+
413
+ def _init_weights(self):
414
+ # Initialize (and freeze) pos_embed by sin-cos embedding:
415
+ pos_embed = get_2d_sincos_pos_embed(self.hidden_size, self.max_num_patch_per_side)
416
+ self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float())
417
+
418
+ def forward(self, position_ids):
419
+ return self.pos_embed[position_ids]
420
+
421
+
422
+ class ResidualConvBlock(nn.Module):
423
+ def __init__(self, channels: int):
424
+ super().__init__()
425
+ self.block = nn.Sequential(
426
+ nn.Conv2d(channels, channels, kernel_size=3, padding=1),
427
+ nn.SiLU(),
428
+ nn.Conv2d(channels, channels, kernel_size=3, padding=1),
429
+ )
430
+ nn.init.zeros_(self.block[2].weight)
431
+ nn.init.zeros_(self.block[2].bias)
432
+
433
+ def forward(self, x):
434
+ return x + self.block(x)
435
+
436
+
437
+ class PostConvSmoother(nn.Module):
438
+ def __init__(self, in_channels=3, hidden_channels=64, num_blocks=3):
439
+ super().__init__()
440
+ self.in_proj = nn.Conv2d(in_channels, hidden_channels, kernel_size=3, padding=1)
441
+ self.blocks = nn.Sequential(*[ResidualConvBlock(hidden_channels) for _ in range(num_blocks)])
442
+ self.out_proj = nn.Conv2d(hidden_channels, in_channels, kernel_size=1)
443
+
444
+ nn.init.zeros_(self.out_proj.weight)
445
+ nn.init.zeros_(self.out_proj.bias)
446
+
447
+ def forward(self, x):
448
+ h = self.in_proj(x)
449
+ h = self.blocks(h)
450
+ return x + self.out_proj(h)
451
+
452
+
453
+ class ProgressiveConvDecoder(nn.Module):
454
+ def __init__(self, hidden_dim=4096, out_channels=3):
455
+ super().__init__()
456
+
457
+ # self.proj = nn.Linear(hidden_dim, 1024)
458
+ # self.act = nn.SiLU()
459
+
460
+ self.up_blocks = nn.ModuleList([
461
+ nn.Sequential(
462
+ nn.Upsample(scale_factor=2, mode='nearest'),
463
+ nn.Conv2d(hidden_dim, 512, kernel_size=3, padding=1),
464
+ nn.GroupNorm(32, 512),
465
+ nn.SiLU()
466
+ ),
467
+ nn.Sequential(
468
+ nn.Upsample(scale_factor=2, mode='nearest'),
469
+ nn.Conv2d(512, 256, kernel_size=3, padding=1),
470
+ nn.GroupNorm(32, 256),
471
+ nn.SiLU()
472
+ ),
473
+ nn.Sequential(
474
+ nn.Upsample(scale_factor=2, mode='nearest'),
475
+ nn.Conv2d(256, 64, kernel_size=3, padding=1),
476
+ nn.GroupNorm(32, 64),
477
+ nn.SiLU()
478
+ ),
479
+ nn.Sequential(
480
+ nn.Upsample(scale_factor=2, mode='nearest'),
481
+ nn.Conv2d(64, 32, kernel_size=3, padding=1),
482
+ nn.GroupNorm(16, 32),
483
+ nn.SiLU()
484
+ ),
485
+ nn.Sequential(
486
+ nn.Upsample(scale_factor=2, mode='nearest'),
487
+ nn.Conv2d(32, 16, kernel_size=3, padding=1),
488
+ nn.SiLU()
489
+ )
490
+ ])
491
+
492
+ self.out_conv = nn.Conv2d(16, out_channels, kernel_size=3, padding=1)
493
+
494
+ def forward(self, x_2d):
495
+ # B, C, H, W = x_2d.shape
496
+ # x = x_2d.permute(0, 2, 3, 1).contiguous() # (B, H, W, C)
497
+ # x = self.proj(x)
498
+ # x = self.act(x)
499
+ # x = x.permute(0, 3, 1, 2).contiguous() # (B, 512, H, W)
500
+ x = x_2d
501
+ for block in self.up_blocks:
502
+ x = block(x)
503
+
504
+ out = self.out_conv(x)
505
+ return out
506
+
507
+
508
+ class PatchDecoder_postps(nn.Module):
509
+ def __init__(self):
510
+ super().__init__()
511
+ # layer 1: H/32 -> H/8 (4x upscale)
512
+
513
+ self.conv1 = nn.Conv2d(4096, 4096, kernel_size=3, padding=1)
514
+ self.ps1 = nn.PixelShuffle(4)
515
+ self.act1 = nn.GELU()
516
+
517
+ # layer 2: H/8 -> H (8x upscale)
518
+ self.conv2 = nn.Conv2d(256, 192, kernel_size=3, padding=1)
519
+ self.ps2 = nn.PixelShuffle(8)
520
+
521
+ def forward(self, x):
522
+ # x shape: [B, 4096, H/32, W/32]
523
+ x = self.ps1(self.act1(self.conv1(x))) # -> [B, 256, H/8, W/8]
524
+ x = self.ps2(self.conv2(x)) # -> [B, 3, H, W]
525
+ return x
526
+
527
+
528
+ class PatchDecoder_preps(nn.Module):
529
+ def __init__(self):
530
+ super().__init__()
531
+ # layer 1: H/32 -> H/16 (2x upscale)
532
+ self.ps1 = nn.PixelShuffle(2)
533
+ self.conv1 = nn.Conv2d(1024, 1024, kernel_size=3, padding=1)
534
+ self.act1 = nn.GELU()
535
+
536
+ # layer 2: H/16 -> H/8 (2x upscale)
537
+ self.ps2 = nn.PixelShuffle(2)
538
+ self.conv2 = nn.Conv2d(256, 256, kernel_size=3, padding=1)
539
+ self.act2 = nn.GELU()
540
+
541
+ # layer 3: H/8 -> H (8x upscale)
542
+ self.ps3 = nn.PixelShuffle(8)
543
+ self.conv3 = nn.Conv2d(4, 3, kernel_size=3, padding=1)
544
+
545
+ def forward(self, x):
546
+ # x shape: [B, 4096, H/32, W/32]
547
+ x = self.act1(self.conv1(self.ps1((x)))) # -> [B, 256, H/16, W/16]
548
+ x = self.act2(self.conv2(self.ps2((x)))) # -> [B, 256, H/8, W/8]
549
+ x = self.conv3(self.ps3((x))) # -> [B, 3, H, W]
550
+ return x
551
+
552
+ class PatchDecoder_preps1(nn.Module):
553
+ def __init__(self):
554
+ super().__init__()
555
+ # layer 1: H/32 -> H/16 (2x upscale)
556
+ self.ps1 = nn.PixelShuffle(2)
557
+ self.conv1 = nn.Conv2d(1024, 1024, kernel_size=3, padding=1)
558
+ self.act1 = nn.GELU()
559
+
560
+ # layer 2: H/16 -> H/8 (2x upscale)
561
+ self.ps2 = nn.PixelShuffle(2)
562
+ self.conv2 = nn.Conv2d(256, 192, kernel_size=3, padding=1)
563
+
564
+ # layer 3: H/8 -> H (8x upscale)
565
+ self.ps3 = nn.PixelShuffle(8)
566
+
567
+ def forward(self, x):
568
+ # x shape: [B, 4096, H/32, W/32]
569
+ x = self.act1(self.conv1(self.ps1((x)))) # -> [B, 256, H/16, W/16]
570
+ x = self.ps3(self.conv2(self.ps2((x)))) # -> [B, 256, H/8, W/8]
571
+ return x
572
+
573
+ class ConvDecoder(nn.Module):
574
+ def __init__(self, input_dim=4096, hidden_dim=1024):
575
+ super().__init__()
576
+ # layer 1: H/32 -> H/16 (2x upscale)
577
+ self.ps1 = nn.PixelShuffle(2)
578
+ self.conv1 = nn.Conv2d(input_dim // 4, hidden_dim, kernel_size=3, padding=1)
579
+ self.act1 = nn.GELU()
580
+
581
+ # layer 2: H/16 -> H/8 (2x upscale)
582
+ self.ps2 = nn.PixelShuffle(2)
583
+ self.conv2 = nn.Conv2d(hidden_dim // 4, 192, kernel_size=3, padding=1)
584
+
585
+ # layer 3: H/8 -> H (8x upscale)
586
+ self.ps3 = nn.PixelShuffle(8)
587
+
588
+ def forward(self, x):
589
+ x = self.act1(self.conv1(self.ps1((x))))
590
+ x = self.ps3(self.conv2(self.ps2((x))))
591
+ return x
modeling_neo_chat.py ADDED
@@ -0,0 +1,1866 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional, Tuple, Union
2
+ import math
3
+ import os
4
+ import torch.utils.checkpoint
5
+ from torch import nn
6
+ import transformers
7
+ from torch.nn import CrossEntropyLoss
8
+ from transformers import GenerationConfig
9
+ from transformers.modeling_outputs import CausalLMOutputWithPast
10
+ from transformers.modeling_utils import PreTrainedModel
11
+ from transformers.utils import logging
12
+
13
+ from .configuration_neo_chat import NEOChatConfig
14
+ from .conversation import get_conv_template
15
+ from .modeling_neo_vit import NEOVisionModel
16
+ from .modeling_qwen3 import Qwen3ForCausalLM, create_block_causal_mask
17
+ from .modeling_fm_modules import PositionEmbedding, TimestepEmbedder, FlowMatchingHead, RMSNorm, NerfEmbedder, SimpleMLPAdaLN, ConvDecoder
18
+ from .utils import load_image_native, SYSTEM_MESSAGE_FOR_GEN
19
+
20
+ logger = logging.get_logger(__name__)
21
+
22
+
23
+ def version_cmp(v1, v2, op='eq'):
24
+ import operator
25
+
26
+ from packaging import version
27
+ op_func = getattr(operator, op)
28
+ return op_func(version.parse(v1), version.parse(v2))
29
+
30
+ def prepare_flash_kv_cache(
31
+ past_key_values,
32
+ current_len: int,
33
+ batch_size: int,
34
+ ):
35
+ """
36
+ Convert prefix cache from [B, H, S, D] to flash-attn friendly [B, S, H, D],
37
+ and preallocate full KV buffer for [prefix + current].
38
+
39
+ This is done once before denoising loop.
40
+ """
41
+ if past_key_values is None:
42
+ return
43
+
44
+ for layer in past_key_values.layers:
45
+ past_k = layer.keys
46
+ past_v = layer.values
47
+
48
+ if past_k is None or past_v is None:
49
+ layer.flash_prefix_len = 0
50
+ layer.flash_total_len = current_len
51
+ layer.flash_k_cache = None
52
+ layer.flash_v_cache = None
53
+ continue
54
+
55
+ # original cache layout assumed: [B, H, S, D]
56
+ past_k_flash = past_k.transpose(1, 2).contiguous() # [B, S, H, D]
57
+ past_v_flash = past_v.transpose(1, 2).contiguous() # [B, S, H, D]
58
+
59
+ prefix_len = past_k_flash.shape[1]
60
+ total_len = prefix_len + current_len
61
+
62
+ k_cache = torch.empty(
63
+ (batch_size, total_len, past_k_flash.shape[2], past_k_flash.shape[3]),
64
+ device=past_k_flash.device,
65
+ dtype=past_k_flash.dtype,
66
+ )
67
+ v_cache = torch.empty(
68
+ (batch_size, total_len, past_v_flash.shape[2], past_v_flash.shape[3]),
69
+ device=past_v_flash.device,
70
+ dtype=past_v_flash.dtype,
71
+ )
72
+
73
+ k_cache[:, :prefix_len].copy_(past_k_flash)
74
+ v_cache[:, :prefix_len].copy_(past_v_flash)
75
+
76
+ layer.flash_prefix_len = prefix_len
77
+ layer.flash_total_len = total_len
78
+ layer.flash_k_cache = k_cache
79
+ layer.flash_v_cache = v_cache
80
+
81
+ def clear_flash_kv_cache(past_key_values):
82
+ if past_key_values is None:
83
+ return
84
+ for layer in past_key_values.layers:
85
+ if hasattr(layer, "flash_prefix_len"):
86
+ delattr(layer, "flash_prefix_len")
87
+ if hasattr(layer, "flash_total_len"):
88
+ delattr(layer, "flash_total_len")
89
+ if hasattr(layer, "flash_k_cache"):
90
+ delattr(layer, "flash_k_cache")
91
+ if hasattr(layer, "flash_v_cache"):
92
+ delattr(layer, "flash_v_cache")
93
+
94
+ @torch.cuda.amp.autocast(dtype=torch.float32)
95
+ def optimized_scale(positive_flat, negative_flat):
96
+
97
+ # Calculate dot production
98
+ dot_product = torch.sum(positive_flat * negative_flat, dim=1, keepdim=True)
99
+
100
+ # Squared norm of uncondition
101
+ squared_norm = torch.sum(negative_flat ** 2, dim=1, keepdim=True) + 1e-8
102
+
103
+ # st_star = v_cond^T * v_uncond / ||v_uncond||^2
104
+ st_star = dot_product / squared_norm
105
+
106
+ return st_star
107
+
108
+ def build_abs_positions_from_grid_hw(grid_hw: torch.Tensor, device=None):
109
+ """
110
+ Compute patch coordinates (x, y)
111
+
112
+ Args:
113
+ grid_hw: (B, 2) tensor representing (H, W) per image
114
+ """
115
+ device = grid_hw.device
116
+ B = grid_hw.shape[0]
117
+
118
+ # Get the number of patches per image
119
+ H = grid_hw[:, 0]
120
+ W = grid_hw[:, 1]
121
+ N = H * W
122
+ N_total = N.sum()
123
+
124
+ # Create the batch index for each patch (B x patch count)
125
+ patch_to_sample = torch.repeat_interleave(torch.arange(B, device=device), N) # (N_total,)
126
+
127
+ # Generate intra-image patch index (row-major order)
128
+ patch_id_within_image = torch.arange(N_total, device=device)
129
+ patch_id_within_image = patch_id_within_image - torch.cumsum(
130
+ torch.cat([torch.tensor([0], device=device), N[:-1]]), dim=0
131
+ )[patch_to_sample]
132
+
133
+ # Get H/W for each patch according to its image
134
+ W_per_patch = W[patch_to_sample]
135
+ abs_x = patch_id_within_image % W_per_patch
136
+ abs_y = patch_id_within_image // W_per_patch
137
+
138
+ return abs_x, abs_y
139
+
140
+
141
+ class NEOChatModel(PreTrainedModel):
142
+ config_class = NEOChatConfig
143
+ main_input_name = 'pixel_values'
144
+ base_model_prefix = 'language_model'
145
+ _supports_flash_attn_2 = True
146
+ supports_gradient_checkpointing = True
147
+ _no_split_modules = [
148
+ "NEOVisionModel",
149
+ "Qwen3DecoderLayer",
150
+ ]
151
+
152
+ # support transformers 4.51.+
153
+ _tp_plan = ''
154
+
155
+ def __init__(self, config: NEOChatConfig, vision_model=None, language_model=None, use_flash_attn=True):
156
+ super().__init__(config)
157
+
158
+ assert version_cmp(transformers.__version__, '4.37.0', 'ge')
159
+ patch_size = config.vision_config.patch_size
160
+ self.patch_size = patch_size
161
+ self.template = config.template
162
+ self.downsample_ratio = config.downsample_ratio
163
+ config.llm_config._attn_implementation = 'eager'
164
+
165
+ if vision_model is not None:
166
+ self.vision_model = vision_model
167
+ else:
168
+ self.vision_model = NEOVisionModel(config.vision_config)
169
+ vision_model_mot_gen = NEOVisionModel(config.vision_config)
170
+ if language_model is not None:
171
+ self.language_model = language_model
172
+ else:
173
+ self.language_model = Qwen3ForCausalLM(config.llm_config)
174
+
175
+ merge_size = int(1 / self.downsample_ratio)
176
+ output_dim = 3*(patch_size*merge_size)**2
177
+ llm_hidden_size = self.config.llm_config.hidden_size
178
+ self.use_deep_fm_head = self.config.fm_head_layers > 2
179
+ self.use_pixel_head = self.config.use_pixel_head
180
+ if self.use_deep_fm_head:
181
+ fm_head = FlowMatchingHead(llm_hidden_size, output_dim, dim=self.config.fm_head_dim, layers=self.config.fm_head_layers, mlp_ratio=self.config.fm_head_mlp_ratio)
182
+ else:
183
+ fm_head = nn.Sequential(
184
+ nn.Linear(llm_hidden_size, 4096, bias=True),
185
+ nn.GELU(),
186
+ nn.Linear(4096, output_dim, bias=True),
187
+ )
188
+
189
+ timestep_embedder = TimestepEmbedder(llm_hidden_size)
190
+ self.fm_modules = nn.ModuleDict(
191
+ {
192
+ "vision_model_mot_gen": vision_model_mot_gen,
193
+ "timestep_embedder": timestep_embedder,
194
+ "fm_head": fm_head
195
+ }
196
+ )
197
+
198
+ if self.use_pixel_head:
199
+ self.fm_modules["fm_head"] = ConvDecoder(llm_hidden_size)
200
+
201
+ self.concat_time_token_num = config.concat_time_token_num
202
+ self.noise_scale = config.noise_scale
203
+ self.noise_scale_mode = config.noise_scale_mode
204
+ self.noise_scale_base_image_seq_len = config.noise_scale_base_image_seq_len
205
+ self.add_noise_scale_embedding = config.add_noise_scale_embedding
206
+ self.noise_scale_max_value = config.noise_scale_max_value
207
+ self.time_schedule = config.time_schedule
208
+ self.time_shift_type = config.time_shift_type
209
+ self.base_shift = config.base_shift
210
+ self.max_shift = config.max_shift
211
+ self.base_image_seq_len = config.base_image_seq_len
212
+ self.max_image_seq_len = config.max_image_seq_len
213
+
214
+ if self.add_noise_scale_embedding:
215
+ noise_scale_embedder = TimestepEmbedder(llm_hidden_size)
216
+ self.fm_modules['noise_scale_embedder'] = noise_scale_embedder
217
+
218
+
219
+ self.img_context_token_id = None
220
+ self.img_start_token_id = 151670
221
+ self.last_think_content = ""
222
+ self.conv_template = get_conv_template(self.template)
223
+ self.system_message = self.conv_template.system_message
224
+
225
+ def forward(
226
+ self,
227
+ pixel_values: torch.FloatTensor,
228
+ input_ids: torch.LongTensor = None,
229
+ attention_mask: Optional[torch.Tensor] = None,
230
+ position_ids: Optional[torch.LongTensor] = None,
231
+ image_flags: Optional[torch.LongTensor] = None,
232
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
233
+ labels: Optional[torch.LongTensor] = None,
234
+ use_cache: Optional[bool] = None,
235
+ output_attentions: Optional[bool] = None,
236
+ output_hidden_states: Optional[bool] = None,
237
+ return_dict: Optional[bool] = None,
238
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
239
+ raise NotImplementedError('forward')
240
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
241
+
242
+ image_flags = image_flags.squeeze(-1)
243
+ input_embeds = self.language_model.get_input_embeddings()(input_ids).clone()
244
+
245
+ vit_embeds = self.extract_feature(pixel_values)
246
+ vit_embeds = vit_embeds[image_flags == 1]
247
+
248
+ B, N, C = input_embeds.shape
249
+ input_embeds = input_embeds.reshape(B * N, C)
250
+
251
+ # if torch.distributed.is_initialized() and torch.distributed.get_rank() == 0:
252
+ # print(f'dynamic ViT batch size: {vit_batch_size}, images per sample: {vit_batch_size / B}, dynamic token length: {N}')
253
+
254
+ input_ids = input_ids.reshape(B * N)
255
+ selected = (input_ids == self.img_context_token_id)
256
+ try:
257
+ input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds.reshape(-1, C)
258
+ except Exception as e:
259
+ vit_embeds = vit_embeds.reshape(-1, C)
260
+ print(f'warning: {e}, input_embeds[selected].shape={input_embeds[selected].shape}, '
261
+ f'vit_embeds.shape={vit_embeds.shape}')
262
+ n_token = min(selected.sum(), vit_embeds.size(0))
263
+ input_embeds[selected][:n_token] = input_embeds[selected][:n_token] * 0.0 + vit_embeds[:n_token]
264
+
265
+ input_embeds = input_embeds.reshape(B, N, C)
266
+
267
+ outputs = self.language_model(
268
+ inputs_embeds=input_embeds,
269
+ attention_mask=attention_mask,
270
+ position_ids=position_ids,
271
+ past_key_values=past_key_values,
272
+ use_cache=use_cache,
273
+ output_attentions=output_attentions,
274
+ output_hidden_states=output_hidden_states,
275
+ return_dict=return_dict,
276
+ )
277
+ logits = outputs.logits
278
+
279
+ loss = None
280
+ if labels is not None:
281
+ # Shift so that tokens < n predict n
282
+ shift_logits = logits[..., :-1, :].contiguous()
283
+ shift_labels = labels[..., 1:].contiguous()
284
+ # Flatten the tokens
285
+ loss_fct = CrossEntropyLoss()
286
+ shift_logits = shift_logits.view(-1, self.language_model.config.vocab_size)
287
+ shift_labels = shift_labels.view(-1)
288
+ # Enable model parallelism
289
+ shift_labels = shift_labels.to(shift_logits.device)
290
+ loss = loss_fct(shift_logits, shift_labels)
291
+
292
+ if not return_dict:
293
+ output = (logits,) + outputs[1:]
294
+ return (loss,) + output if loss is not None else output
295
+
296
+ return CausalLMOutputWithPast(
297
+ loss=loss,
298
+ logits=logits,
299
+ past_key_values=outputs.past_key_values,
300
+ hidden_states=outputs.hidden_states,
301
+ attentions=outputs.attentions,
302
+ )
303
+
304
+ def extract_feature(self, pixel_values, gen_model=False, grid_hw=None):
305
+ if gen_model:
306
+ return self.fm_modules['vision_model_mot_gen'](pixel_values=pixel_values,
307
+ output_hidden_states=False,
308
+ return_dict=True,
309
+ grid_hw=grid_hw).last_hidden_state
310
+ else:
311
+ return self.vision_model(pixel_values=pixel_values,
312
+ output_hidden_states=False,
313
+ return_dict=True,
314
+ grid_hw=grid_hw).last_hidden_state
315
+
316
+ def batch_chat(self, tokenizer, pixel_values, questions, generation_config, num_patches_list=None,
317
+ history=None, return_history=False, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>',
318
+ IMG_CONTEXT_TOKEN='<IMG_CONTEXT>', verbose=False, image_counts=None):
319
+ raise NotImplementedError('batch_chat')
320
+ if history is not None or return_history:
321
+ print('Now multi-turn chat is not supported in batch_chat.')
322
+ raise NotImplementedError
323
+
324
+ if image_counts is not None:
325
+ num_patches_list = image_counts
326
+ print('Warning: `image_counts` is deprecated. Please use `num_patches_list` instead.')
327
+
328
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
329
+ self.img_context_token_id = img_context_token_id
330
+
331
+ if verbose and pixel_values is not None:
332
+ image_bs = pixel_values.shape[0]
333
+ print(f'dynamic ViT batch size: {image_bs}')
334
+
335
+ queries = []
336
+ for idx, num_patches in enumerate(num_patches_list):
337
+ question = questions[idx]
338
+ if pixel_values is not None and '<image>' not in question:
339
+ question = '<image>\n' + question
340
+ template = get_conv_template(self.template)
341
+ template.system_message = self.system_message
342
+ template.append_message(template.roles[0], question)
343
+ template.append_message(template.roles[1], None)
344
+ query = template.get_prompt()
345
+
346
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN + IMG_END_TOKEN
347
+ query = query.replace('<image>', image_tokens, 1)
348
+ queries.append(query)
349
+
350
+ tokenizer.padding_side = 'left'
351
+ model_inputs = tokenizer(queries, return_tensors='pt', padding=True)
352
+ input_ids = model_inputs['input_ids'].to(self.device)
353
+ attention_mask = model_inputs['attention_mask'].to(self.device)
354
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep.strip())
355
+ generation_config['eos_token_id'] = eos_token_id
356
+ generation_output = self.generate(
357
+ pixel_values=pixel_values,
358
+ input_ids=input_ids,
359
+ attention_mask=attention_mask,
360
+ **generation_config
361
+ )
362
+ responses = tokenizer.batch_decode(generation_output, skip_special_tokens=True)
363
+ responses = [response.split(template.sep.strip())[0].strip() for response in responses]
364
+ return responses
365
+
366
+ def patchify(self, images, patch_size, channel_first=False):
367
+ """
368
+ images: (N, 3, H, W)
369
+ x: (N, L, patch_size**2 *3)
370
+ """
371
+ h, w = images.shape[2] // patch_size, images.shape[3] // patch_size
372
+ x = images.reshape(shape=(images.shape[0], 3, h, patch_size, w, patch_size))
373
+
374
+ if channel_first:
375
+ x = torch.einsum('nchpwq->nhwcpq', x)
376
+ else:
377
+ x = torch.einsum('nchpwq->nhwpqc', x)
378
+
379
+ x = x.reshape(shape=(images.shape[0], h * w, patch_size**2 * 3))
380
+ return x
381
+
382
+ def unpatchify(sle, x, patch_size, h=None, w=None):
383
+ """
384
+ x: (N, L, patch_size**2 *3)
385
+ images: (N, 3, H, W)
386
+ """
387
+ if h is None or w is None:
388
+ h = w = int(x.shape[1]**.5)
389
+ else:
390
+ h = h // patch_size
391
+ w = w // patch_size
392
+ x = x.reshape(shape=(x.shape[0], h, w, patch_size, patch_size, 3))
393
+ x = torch.einsum('nhwpqc->nchpwq', x)
394
+ images = x.reshape(shape=(x.shape[0], 3, h * patch_size, w * patch_size))
395
+ return images
396
+
397
+ def _euler_step(self, v_pred, z, t, t_next):
398
+ z_next = z + (t_next - t) * v_pred
399
+ return z_next
400
+
401
+ def _calculate_dynamic_mu(self, image_seq_len: int) -> float:
402
+ denom = self.max_image_seq_len - self.base_image_seq_len
403
+ if denom == 0:
404
+ return float(self.base_shift)
405
+ m = (self.max_shift - self.base_shift) / denom
406
+ b = self.base_shift - m * self.base_image_seq_len
407
+ return float(image_seq_len) * m + b
408
+
409
+ def _apply_time_schedule(self, t: torch.Tensor, image_seq_len: int, timestep_shift: float) -> torch.Tensor:
410
+ self.time_schedule = "standard"
411
+ sigma = 1 - t
412
+ if timestep_shift != 1:
413
+ self.time_schedule = "standard"
414
+ if self.time_schedule == "standard":
415
+ shift = timestep_shift
416
+ sigma = shift * sigma / (1 + (shift - 1) * sigma)
417
+ elif self.time_schedule == "dynamic":
418
+ mu = self._calculate_dynamic_mu(image_seq_len)
419
+ mu_t = t.new_tensor(mu)
420
+ if self.time_shift_type == "exponential":
421
+ shift = torch.exp(mu_t)
422
+ sigma = shift * sigma / (1 + (shift - 1) * sigma)
423
+ elif self.time_shift_type == "linear":
424
+ sigma = mu_t / (mu_t + (1 / sigma - 1))
425
+ else:
426
+ raise ValueError(f"Unsupported time_shift_type: {self.time_shift_type}")
427
+ else:
428
+ raise ValueError(f"Unsupported time_schedule: {self.time_schedule}")
429
+ return 1 - sigma
430
+
431
+ def _build_t2i_query(self, prompt_text, system_message=None, append_text=None):
432
+ template = get_conv_template(self.template)
433
+ template.system_message = self.system_message if system_message is None else system_message
434
+ template.append_message(template.roles[0], prompt_text)
435
+ template.append_message(template.roles[1], None)
436
+ if append_text is not None:
437
+ return template.get_prompt() + append_text
438
+ return template.get_prompt()
439
+
440
+ def _build_t2i_text_inputs(self, tokenizer, query: str):
441
+ model_inputs = tokenizer(query, return_tensors="pt")
442
+ input_ids = model_inputs["input_ids"].to(self.device)
443
+
444
+ t_idx = torch.arange(0, input_ids.shape[1], dtype=torch.long, device=input_ids.device)
445
+ h_idx = torch.zeros_like(t_idx)
446
+ w_idx = torch.zeros_like(t_idx)
447
+ indexes = torch.stack([t_idx, h_idx, w_idx], dim=0)
448
+
449
+ attention_mask = {"full_attention": create_block_causal_mask(indexes[0])}
450
+ return input_ids, indexes, attention_mask
451
+
452
+ def _build_t2i_image_indexes(self, token_h, token_w, text_len, device):
453
+ t_image = torch.full((token_h * token_w,), text_len, dtype=torch.long, device=device)
454
+ idx = torch.arange(token_h * token_w, device=device, dtype=torch.long)
455
+ h_image = idx // token_w
456
+ w_image = idx % token_w
457
+ return torch.stack([t_image, h_image, w_image], dim=0)
458
+
459
+ def _t2i_prefix_forward(self, input_ids, indexes, attention_mask):
460
+ out = self.language_model.model(
461
+ input_ids=input_ids,
462
+ indexes=indexes,
463
+ attention_mask=attention_mask,
464
+ use_cache=True,
465
+ )
466
+ return out.past_key_values, out.last_hidden_state
467
+
468
+ def _it2i_prefix_forward(self, input_imbeds, indexes, attention_mask, gen_indicators=None):
469
+ out = self.language_model.model(
470
+ inputs_embeds=input_imbeds,
471
+ indexes=indexes,
472
+ attention_mask=attention_mask,
473
+ use_cache=True,
474
+ image_gen_indicators=gen_indicators.view(1, -1) if gen_indicators is not None else None
475
+ )
476
+ return out.past_key_values, out.last_hidden_state
477
+
478
+ def _append_text_tokens_to_cache(self, cache, t_idx, input_ids):
479
+ if input_ids.shape[1] == 0:
480
+ return t_idx
481
+
482
+ device = input_ids.device
483
+ seq_len = input_ids.shape[1]
484
+ inputs_embeds = self.language_model.get_input_embeddings()(input_ids)
485
+
486
+ t_indexes = torch.arange(t_idx + 1, t_idx + 1 + seq_len, dtype=torch.long, device=device)
487
+ h_indexes = torch.zeros(seq_len, dtype=torch.long, device=device)
488
+ w_indexes = torch.zeros(seq_len, dtype=torch.long, device=device)
489
+ indexes = torch.stack([t_indexes, h_indexes, w_indexes], dim=0)
490
+
491
+ past_len = cache.get_seq_length()
492
+ mask = torch.zeros(1, 1, seq_len, past_len + seq_len, device=device)
493
+ causal_mask = torch.tril(torch.ones(seq_len, seq_len, device=device))
494
+ causal_mask = torch.where(causal_mask == 1, 0.0, float('-inf'))
495
+ mask[:, :, :, past_len:] = causal_mask
496
+ attention_mask_dict = {"full_attention": mask}
497
+
498
+ self.language_model(
499
+ inputs_embeds=inputs_embeds,
500
+ indexes=indexes,
501
+ attention_mask=attention_mask_dict,
502
+ past_key_values=cache,
503
+ use_cache=True
504
+ )
505
+ return t_idx + seq_len
506
+
507
+ def _generate_think(
508
+ self,
509
+ tokenizer,
510
+ prefix_outputs,
511
+ past_key_values,
512
+ t_idx,
513
+ IMG_START_TOKEN,
514
+ max_think_tokens=1024,
515
+ ):
516
+ template = get_conv_template(self.template)
517
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep.strip())
518
+ think_end_token_id = tokenizer.convert_tokens_to_ids('</think>')
519
+ think_token_ids = []
520
+ next_token = torch.argmax(prefix_outputs.logits[:, -1, :], dim=-1)
521
+
522
+ for _ in range(max_think_tokens):
523
+ token_item = next_token.item()
524
+ if token_item == eos_token_id:
525
+ break
526
+ if token_item == think_end_token_id:
527
+ self.language_model.model.current_index = t_idx
528
+ outputs = self.language_model(
529
+ input_ids=next_token.unsqueeze(0),
530
+ past_key_values=past_key_values,
531
+ use_cache=True
532
+ )
533
+ past_key_values = outputs.past_key_values
534
+ t_idx += 1
535
+ think_token_ids.append(token_item)
536
+ break
537
+
538
+ think_token_ids.append(token_item)
539
+
540
+ self.language_model.model.current_index = t_idx
541
+ outputs = self.language_model(
542
+ input_ids=next_token.unsqueeze(0),
543
+ past_key_values=past_key_values,
544
+ use_cache=True
545
+ )
546
+ past_key_values = outputs.past_key_values
547
+ t_idx += 1
548
+
549
+ next_token = torch.argmax(outputs.logits[:, -1, :], dim=-1)
550
+
551
+ append_ids = tokenizer(
552
+ '\n\n' + IMG_START_TOKEN,
553
+ return_tensors='pt',
554
+ add_special_tokens=False,
555
+ )['input_ids'].to(self.device)
556
+ t_idx = self._append_text_tokens_to_cache(past_key_values, t_idx, append_ids)
557
+
558
+ think_text = tokenizer.decode(think_token_ids, skip_special_tokens=False)
559
+
560
+ return past_key_values, t_idx, think_text
561
+
562
+ def _t2i_predict_v(self, input_embeds, indexes_image, attn_mask, past_key_values, t, z, image_token_num, timestep_embeddings=None, image_size=None):
563
+ B, L = z.shape[0], z.shape[1]
564
+
565
+ outputs = self.language_model.model(
566
+ inputs_embeds=input_embeds,
567
+ image_gen_indicators=torch.ones((input_embeds.shape[0], input_embeds.shape[1]), dtype=torch.bool, device=input_embeds.device),
568
+ indexes=indexes_image,
569
+ attention_mask=attn_mask,
570
+ past_key_values=past_key_values,
571
+ update_cache=False,
572
+ use_cache=True,
573
+ )
574
+
575
+ if self.use_pixel_head:
576
+ merge_size = int(1 / self.downsample_ratio)
577
+ token_h = image_size[1] // (self.patch_size * merge_size)
578
+ token_w = image_size[0] // (self.patch_size * merge_size)
579
+
580
+ img_reshaped = outputs.last_hidden_state[:, -image_token_num:].view(B, token_h, token_w, -1)
581
+ img_2d = torch.einsum("b h w c -> b c h w", img_reshaped)
582
+ img_2d = img_2d.contiguous().view(B, -1, token_h, token_w)
583
+
584
+ smoothed_img_2d = self.fm_modules['fm_head'](img_2d)
585
+
586
+ smoothed_reshaped = smoothed_img_2d.view(B, 3, token_h, self.patch_size * merge_size, token_w, self.patch_size * merge_size)
587
+ smoothed_reshaped = torch.einsum("b c h p w q -> b h w p q c", smoothed_reshaped)
588
+ out_1d = smoothed_reshaped.contiguous().view(B, L, self.patch_size * merge_size * self.patch_size * merge_size * 3)
589
+ x_pred = out_1d
590
+ else:
591
+ if self.use_deep_fm_head:
592
+ x_pred = self.fm_modules["fm_head"](
593
+ outputs.last_hidden_state[:, -image_token_num:].view(B*L, -1), t.repeat(B*L)
594
+ ).view(B, L, -1)
595
+ else:
596
+ x_pred = self.fm_modules["fm_head"](
597
+ outputs.last_hidden_state[:, -image_token_num:].view(B, L, -1)
598
+ ).view(B, L, -1)
599
+
600
+
601
+ v_pred = (x_pred - z) / (1 - t).clamp_min(self.config.t_eps)
602
+ return v_pred
603
+
604
+ def _build_it2i_inputs(self, tokenizer, query, pixel_values=None, grid_hw=None):
605
+ model_inputs = tokenizer(query, return_tensors="pt")
606
+ input_ids = model_inputs["input_ids"].to(self.device)
607
+
608
+ indexes = self.get_thw_indexes(input_ids[0], grid_hw)
609
+
610
+ attention_mask = {"full_attention": create_block_causal_mask(indexes[0])}
611
+
612
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
613
+ B, N, C = input_embeds.shape
614
+ if pixel_values is not None:
615
+ vit_embeds = self.extract_feature(pixel_values, grid_hw=grid_hw)
616
+ input_embeds = input_embeds.reshape(B * N, C)
617
+ input_ids = input_ids.reshape(B * N)
618
+ selected = (input_ids == self.img_context_token_id)
619
+ assert selected.sum() != 0
620
+ input_embeds[selected] = vit_embeds.reshape(-1, C).to(input_embeds.device)
621
+ input_embeds = input_embeds.reshape(B, N, C)
622
+
623
+ return input_embeds, indexes, attention_mask
624
+
625
+ @torch.no_grad()
626
+ def interleave_gen_image_only(
627
+ self,
628
+ tokenizer,
629
+ prompt,
630
+ gt_text,
631
+ images=None,
632
+ gt_images=None,
633
+ cfg_scale=1.0,
634
+ img_cfg_scale=1.0,
635
+ cfg_norm='none',
636
+ max_images=10,
637
+ enable_timestep_shift=True,
638
+ timestep_shift=1.0,
639
+ image_size=(256, 256),
640
+ num_steps=30,
641
+ IMG_START_TOKEN='<img>',
642
+ IMG_END_TOKEN='</img>',
643
+ IMG_CONTEXT_TOKEN='<IMG_CONTEXT>',
644
+ method='euler',
645
+ cfg_interval=(0, 1),
646
+ t_eps=0.02,
647
+ verbose=False,
648
+ system_message='',
649
+ ):
650
+ self.img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
651
+ self.img_start_token_id = tokenizer.convert_tokens_to_ids(IMG_START_TOKEN)
652
+ self.config.t_eps = t_eps
653
+
654
+ if isinstance(image_size, tuple):
655
+ image_size_list = [image_size] * max_images
656
+ elif isinstance(image_size, list) and isinstance(image_size[0], tuple):
657
+ image_size_list = image_size
658
+ if len(image_size) < max_images:
659
+ image_size_list += [image_size_list[-1]] * (max_images - len(image_size_list))
660
+ else:
661
+ assert False, "image size should be a tuple or a list of tuple"
662
+
663
+ if images is None:
664
+ images =[]
665
+
666
+ image_token_count = prompt.count('<image>')
667
+ assert len(images) >= image_token_count
668
+ if len(images) > image_token_count:
669
+ prompt = "<image>\n" * (len(images) - image_token_count) + prompt
670
+
671
+ pixel_values =[]
672
+ grid_hw =[]
673
+ for image in images:
674
+ cur_pixel_values, cur_grid_hw = load_image_native(image, self.patch_size, self.downsample_ratio, min_pixels=512*512, max_pixels=min(2048*2048, (4096*4096)//max(1, len(images))), upscale=False)
675
+ grid_hw.append(cur_grid_hw.to(self.device))
676
+ pixel_values.append(cur_pixel_values.to(self.device).to(torch.bfloat16))
677
+
678
+ merge_size = int(1 / self.downsample_ratio)
679
+ pv_tensor = torch.cat(pixel_values) if pixel_values else None
680
+ ghw_tensor = torch.cat(grid_hw) if grid_hw else None
681
+
682
+ # Condition Initial Cache
683
+ template_cond = get_conv_template(self.template)
684
+ template_cond.system_message = system_message
685
+ template_cond.append_message(template_cond.roles[0], prompt)
686
+ template_cond.append_message(template_cond.roles[1], None)
687
+ query_cond = template_cond.get_prompt() + '<think>\n\n</think>\n\n'
688
+
689
+ def replace_image_tokens(query, grid_hw_list):
690
+ for i in range(len(grid_hw_list)):
691
+ num_patch_token = int(grid_hw_list[i][0, 0] * grid_hw_list[i][0, 1] * self.downsample_ratio**2)
692
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * num_patch_token + IMG_END_TOKEN
693
+ query = query.replace('<image>', image_tokens, 1)
694
+ return query
695
+
696
+ query_cond = replace_image_tokens(query_cond, grid_hw)
697
+ input_embeds_cond, indexes_cond, attention_mask_cond = self._build_it2i_inputs(tokenizer, query_cond, pv_tensor, ghw_tensor)
698
+
699
+ outputs_cond = self.language_model(inputs_embeds=input_embeds_cond, indexes=indexes_cond, attention_mask=attention_mask_cond, use_cache=True)
700
+ past_key_values_cond = outputs_cond.past_key_values
701
+ t_index_cond = indexes_cond[0].max().item()
702
+
703
+ # Text Uncondition Cache Initial
704
+ question_text_uncondition = '<image>' * len(images)
705
+ template_tu = get_conv_template(self.template)
706
+ template_tu.system_message = self.system_message
707
+ template_tu.append_message(template_tu.roles[0], question_text_uncondition)
708
+ template_tu.append_message(template_tu.roles[1], None)
709
+ query_text_uncond = template_tu.get_prompt()
710
+ query_text_uncond = replace_image_tokens(query_text_uncond, grid_hw)
711
+
712
+ input_embeds_tu, indexes_tu, attention_mask_tu = self._build_it2i_inputs(tokenizer, query_text_uncond, pv_tensor, ghw_tensor)
713
+ outputs_tu = self.language_model(inputs_embeds=input_embeds_tu, indexes=indexes_tu, attention_mask=attention_mask_tu, use_cache=True)
714
+ past_key_values_tu = outputs_tu.past_key_values
715
+ t_index_tu = indexes_tu[0].max().item()
716
+
717
+ # Img Uncondition Cache Initial
718
+ query_img_uncond = self._build_t2i_query("", append_text=IMG_START_TOKEN)
719
+ input_embeds_iu, indexes_iu, attention_mask_iu = self._build_it2i_inputs(tokenizer, query_img_uncond)
720
+ outputs_iu = self.language_model(inputs_embeds=input_embeds_iu, indexes=indexes_iu, attention_mask=attention_mask_iu, use_cache=True)
721
+ past_key_values_iu = outputs_iu.past_key_values
722
+
723
+
724
+ generated_images =[]
725
+ img_count = 0
726
+ device = self.device
727
+
728
+ def append_ids_to_cache(cache, t_idx, input_ids):
729
+ if input_ids.shape[1] == 0:
730
+ return t_idx
731
+ seq_len = input_ids.shape[1]
732
+ inputs_embeds = self.language_model.get_input_embeddings()(input_ids)
733
+
734
+ t_indexes = torch.arange(t_idx + 1, t_idx + 1 + seq_len, dtype=torch.long, device=device)
735
+ h_indexes = torch.zeros(seq_len, dtype=torch.long, device=device)
736
+ w_indexes = torch.zeros(seq_len, dtype=torch.long, device=device)
737
+ indexes = torch.stack([t_indexes, h_indexes, w_indexes], dim=0)
738
+
739
+ past_len = cache.get_seq_length()
740
+ mask = torch.zeros(1, 1, seq_len, past_len + seq_len, device=device)
741
+ causal_mask = torch.tril(torch.ones(seq_len, seq_len, device=device))
742
+ causal_mask = torch.where(causal_mask == 1, 0.0, float('-inf'))
743
+ mask[:, :, :, past_len:] = causal_mask
744
+ attention_mask_dict = {"full_attention": mask}
745
+
746
+ self.language_model(
747
+ inputs_embeds=inputs_embeds,
748
+ indexes=indexes,
749
+ attention_mask=attention_mask_dict,
750
+ past_key_values=cache,
751
+ use_cache=True
752
+ )
753
+ return t_idx + seq_len
754
+
755
+ def append_image_to_cache(cache, t_idx, inputs_embeds_img, N_img_tokens, abs_pos_w, abs_pos_h):
756
+ past_len = cache.get_seq_length()
757
+ tgt_len = N_img_tokens + 1
758
+
759
+ t_indexes = torch.zeros(tgt_len, dtype=torch.long, device=device)
760
+ t_indexes[:N_img_tokens] = t_idx + 1
761
+ t_indexes[N_img_tokens] = t_idx + 2
762
+
763
+ h_indexes = torch.zeros(tgt_len, dtype=torch.long, device=device)
764
+ w_indexes = torch.zeros(tgt_len, dtype=torch.long, device=device)
765
+ h_indexes[:N_img_tokens] = abs_pos_h
766
+ w_indexes[:N_img_tokens] = abs_pos_w
767
+
768
+ indexes = torch.stack([t_indexes, h_indexes, w_indexes], dim=0)
769
+
770
+ mask = torch.zeros(1, 1, tgt_len, past_len + tgt_len, device=device)
771
+ mask[0, 0, :N_img_tokens, past_len + N_img_tokens] = float('-inf')
772
+ attention_mask_dict = {"full_attention": mask}
773
+
774
+ self.language_model(
775
+ inputs_embeds=inputs_embeds_img,
776
+ indexes=indexes,
777
+ attention_mask=attention_mask_dict,
778
+ past_key_values=cache,
779
+ use_cache=True
780
+ )
781
+ return t_idx + 2
782
+
783
+ parts = gt_text.split('<image>')
784
+ img_start_id_tensor = torch.tensor([[self.img_start_token_id]], device=device)
785
+
786
+ for i, part in enumerate(parts):
787
+ if len(part) > 0:
788
+ if verbose:
789
+ print(part, end='', flush=True)
790
+ part_ids = tokenizer(part, return_tensors='pt', add_special_tokens=False)['input_ids'].to(device)
791
+ t_index_cond = append_ids_to_cache(past_key_values_cond, t_index_cond, part_ids)
792
+
793
+ if i < len(parts) - 1:
794
+ if img_count >= max_images:
795
+ break
796
+
797
+ if verbose:
798
+ print("<image>", end='', flush=True)
799
+
800
+ t_index_cond = append_ids_to_cache(past_key_values_cond, t_index_cond, img_start_id_tensor)
801
+ t_index_tu = append_ids_to_cache(past_key_values_tu, t_index_tu, img_start_id_tensor)
802
+
803
+ cur_image_size = image_size_list[img_count]
804
+ token_h = cur_image_size[1] // (self.patch_size * merge_size)
805
+ token_w = cur_image_size[0] // (self.patch_size * merge_size)
806
+
807
+ indexes_image_condition = self._build_t2i_image_indexes(token_h, token_w, t_index_cond + 1, device=device)
808
+ indexes_image_text_uncondition = self._build_t2i_image_indexes(token_h, token_w, t_index_tu + 1, device=device)
809
+ indexes_image_img_uncondition = self._build_t2i_image_indexes(token_h, token_w, indexes_iu[0].max() + 1, device=device)
810
+
811
+ grid_h = cur_image_size[1] // self.patch_size
812
+ grid_w = cur_image_size[0] // self.patch_size
813
+ gen_grid_hw = torch.tensor([[grid_h, grid_w]], device=device)
814
+
815
+ noise_scale = self.noise_scale
816
+ if self.noise_scale_mode in ("resolution", "dynamic", 'dynamic_sqrt'):
817
+ noise_scale = math.sqrt((grid_h*grid_w)/(merge_size**2) / self.noise_scale_base_image_seq_len)
818
+ base = float(self.noise_scale_base_image_seq_len)
819
+ noise_scale = math.sqrt((grid_h*grid_w)/(merge_size**2)/base) * float(self.noise_scale)
820
+ if self.noise_scale_mode == 'dynamic_sqrt':
821
+ noise_scale = math.sqrt(noise_scale)
822
+ noise_scale = min(noise_scale, self.noise_scale_max_value)
823
+ image_prediction = noise_scale * torch.randn((1, 3, cur_image_size[1], cur_image_size[0]), device=device, dtype=outputs_cond.logits.dtype)
824
+
825
+ past_key_values_cond_cfg = past_key_values_cond
826
+ past_key_values_tu_cfg = past_key_values_tu
827
+ past_key_values_iu_cfg = past_key_values_iu
828
+
829
+ # attention_mask_condition = {"full_attention": torch.zeros(1, 1, token_h*token_w, past_key_values_cond.get_seq_length() + token_h*token_w, device=device)}
830
+ # attention_mask_text_uncondition = {"full_attention": torch.zeros(1, 1, token_h*token_w, past_key_values_tu.get_seq_length() + token_h*token_w, device=device)}
831
+ # attention_mask_img_uncondition = {"full_attention": torch.zeros(1, 1, token_h*token_w, past_key_values_iu.get_seq_length() + token_h*token_w, device=device)}
832
+ attention_mask_condition = {"full_attention": None}
833
+ attention_mask_text_uncondition = {"full_attention": None}
834
+ attention_mask_img_uncondition = {"full_attention": None}
835
+
836
+ prepare_flash_kv_cache(
837
+ past_key_values_cond_cfg,
838
+ current_len=token_h * token_w,
839
+ batch_size=1,
840
+ )
841
+ prepare_flash_kv_cache(
842
+ past_key_values_tu_cfg,
843
+ current_len=token_h * token_w,
844
+ batch_size=1,
845
+ )
846
+ prepare_flash_kv_cache(
847
+ past_key_values_iu_cfg,
848
+ current_len=token_h * token_w,
849
+ batch_size=1,
850
+ )
851
+
852
+ timesteps = torch.linspace(0.0, 1.0, num_steps+1, device=device)
853
+ if enable_timestep_shift:
854
+ timesteps = self._apply_time_schedule(timesteps, token_h*token_w, timestep_shift)
855
+
856
+ for step_i in range(num_steps):
857
+ t = timesteps[step_i]
858
+ t_next = timesteps[step_i + 1]
859
+
860
+ z = self.patchify(image_prediction, self.patch_size * merge_size)
861
+ image_input = self.patchify(image_prediction, self.patch_size, channel_first=True)
862
+ image_embeds = self.extract_feature(image_input.view(1 * grid_h*grid_w, -1), gen_model=True, grid_hw=gen_grid_hw).view(1, token_h*token_w, -1)
863
+ t_expanded = t.expand(token_h*token_w)
864
+ timestep_embeddings = self.fm_modules['timestep_embedder'](t_expanded).view(1, token_h*token_w, -1)
865
+ if self.add_noise_scale_embedding:
866
+ noise_scale_tensor = torch.full_like(t_expanded, noise_scale/self.noise_scale_max_value)
867
+ noise_embeddings = self.fm_modules['noise_scale_embedder'](noise_scale_tensor).view(1, token_h*token_w, -1)
868
+ timestep_embeddings += noise_embeddings
869
+ image_embeds = image_embeds + timestep_embeddings
870
+
871
+ use_cfg = (t > cfg_interval[0] and t < cfg_interval[1]) or cfg_interval[0] == 0
872
+ out_cond = self._t2i_predict_v(image_embeds, indexes_image_condition, attention_mask_condition, past_key_values_cond_cfg, t, z, image_token_num=token_h*token_w, timestep_embeddings=timestep_embeddings)
873
+ if not use_cfg:
874
+ v_pred = out_cond
875
+ elif cfg_scale == 1 and img_cfg_scale == 1:
876
+ v_pred = out_cond
877
+ elif img_cfg_scale == 1:
878
+ out_img_cond = self._t2i_predict_v(image_embeds, indexes_image_text_uncondition, attention_mask_text_uncondition, past_key_values_tu_cfg, t, z, image_token_num=token_h*token_w, timestep_embeddings=timestep_embeddings)
879
+ v_pred = out_img_cond + cfg_scale * (out_cond - out_img_cond)
880
+ elif cfg_scale == img_cfg_scale:
881
+ out_uncond = self._t2i_predict_v(image_embeds, indexes_image_img_uncondition, attention_mask_img_uncondition, past_key_values_iu_cfg, t, z, image_token_num=token_h*token_w, timestep_embeddings=timestep_embeddings)
882
+ v_pred = out_uncond + cfg_scale * (out_cond - out_uncond)
883
+ else:
884
+ out_img_cond = self._t2i_predict_v(image_embeds, indexes_image_text_uncondition, attention_mask_text_uncondition, past_key_values_tu_cfg, t, z, image_token_num=token_h*token_w, timestep_embeddings=timestep_embeddings)
885
+ out_uncond = self._t2i_predict_v(image_embeds, indexes_image_img_uncondition, attention_mask_img_uncondition, past_key_values_iu_cfg, t, z, image_token_num=token_h*token_w, timestep_embeddings=timestep_embeddings)
886
+ v_pred = (
887
+ out_uncond
888
+ + cfg_scale * (out_cond - out_img_cond)
889
+ + img_cfg_scale * (out_img_cond - out_uncond)
890
+ )
891
+ if (cfg_scale > 1 or img_cfg_scale > 1) and use_cfg:
892
+ if cfg_norm == 'global':
893
+ norm_v_condition = torch.norm(out_cond, dim=(1,2), keepdim=True)
894
+ norm_v_cfg = torch.norm(v_pred, dim=(1,2), keepdim=True)
895
+ scale = (norm_v_condition / (norm_v_cfg + 1e-8)).clamp(min=0, max=1.0)
896
+ v_pred = v_pred * scale
897
+ elif cfg_norm == 'channel':
898
+ norm_v_condition = torch.norm(out_cond, dim=-1, keepdim=True)
899
+ norm_v_cfg = torch.norm(v_pred, dim=-1, keepdim=True)
900
+ scale = (norm_v_condition / (norm_v_cfg + 1e-8)).clamp(min=0, max=1.0)
901
+ v_pred = v_pred * scale
902
+
903
+ z = z + (t_next - t) * v_pred
904
+ image_prediction = self.unpatchify(z, self.patch_size * merge_size, cur_image_size[1], cur_image_size[0])
905
+
906
+ generated_images.append(image_prediction)
907
+
908
+ clear_flash_kv_cache(past_key_values_cond_cfg)
909
+ clear_flash_kv_cache(past_key_values_tu_cfg)
910
+ clear_flash_kv_cache(past_key_values_iu_cfg)
911
+
912
+ if gt_images is not None and img_count < len(gt_images):
913
+ gt_img_pil = gt_images[img_count]
914
+ gt_pixel_values, gt_grid_hw = load_image_native(gt_img_pil, self.patch_size, self.downsample_ratio, min_pixels=512*512, max_pixels=(2048*2048), upscale=False)
915
+ gt_pixel_values = gt_pixel_values.to(device).to(torch.bfloat16)
916
+
917
+ flatten_pixel_values = gt_pixel_values
918
+ gen_grid_hw_und = gt_grid_hw
919
+ else:
920
+ pred_img = image_prediction[0].unsqueeze(0).to(torch.bfloat16)
921
+ raw_img = pred_img * 0.5 + 0.5
922
+ img_mean = torch.tensor([0.485, 0.456, 0.406], dtype=raw_img.dtype, device=device).view(1, 3, 1, 1)
923
+ img_std = torch.tensor([0.229, 0.224, 0.225], dtype=raw_img.dtype, device=device).view(1, 3, 1, 1)
924
+ und_img = (raw_img - img_mean) / img_std
925
+
926
+ c, h, w = und_img[0].shape
927
+ ps = self.patch_size
928
+ p_grid_h = h // ps
929
+ p_grid_w = w // ps
930
+ flatten_pixel_values = (
931
+ und_img[0].view(c, p_grid_h, ps, p_grid_w, ps)
932
+ .permute(1, 3, 0, 2, 4)
933
+ .reshape(p_grid_h * p_grid_w, c * ps ** 2)
934
+ )
935
+ gen_grid_hw_und = torch.tensor([[p_grid_h, p_grid_w]], device=device)
936
+
937
+ vit_embeds = self.extract_feature(flatten_pixel_values, grid_hw=gen_grid_hw_und[:1]).unsqueeze(0)
938
+
939
+ img_end_id = tokenizer.convert_tokens_to_ids(IMG_END_TOKEN)
940
+ img_end_embed = self.language_model.get_input_embeddings()(torch.tensor([[img_end_id]], device=device))
941
+ inputs_embeds_img = torch.cat([vit_embeds, img_end_embed], dim=1) # (1, N + 1, C)
942
+
943
+ N_img_tokens = vit_embeds.shape[1]
944
+ abs_pos_w, abs_pos_h = build_abs_positions_from_grid_hw(gen_grid_hw_und[:1] // int(1 / self.downsample_ratio), device=device)
945
+
946
+ t_index_cond = append_image_to_cache(past_key_values_cond, t_index_cond, inputs_embeds_img, N_img_tokens, abs_pos_w, abs_pos_h)
947
+ t_index_tu = append_image_to_cache(past_key_values_tu, t_index_tu, inputs_embeds_img, N_img_tokens, abs_pos_w, abs_pos_h)
948
+
949
+ img_count += 1
950
+
951
+ return generated_images
952
+
953
+ @torch.no_grad()
954
+ def interleave_gen(
955
+ self,
956
+ tokenizer,
957
+ prompt,
958
+ images=None,
959
+ generation_config=None,
960
+ cfg_scale=1.0,
961
+ img_cfg_scale=1.0,
962
+ cfg_norm='none',
963
+ max_images=10,
964
+ enable_timestep_shift=True,
965
+ timestep_shift=1.0,
966
+ image_size=(256, 256),
967
+ num_steps=30,
968
+ IMG_START_TOKEN='<img>',
969
+ IMG_END_TOKEN='</img>',
970
+ IMG_CONTEXT_TOKEN='<IMG_CONTEXT>',
971
+ method='euler',
972
+ cfg_interval=(0, 1),
973
+ t_eps=0.02,
974
+ verbose=False,
975
+ system_message='',
976
+ think_mode=False
977
+ ):
978
+ self.img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
979
+ self.img_start_token_id = tokenizer.convert_tokens_to_ids(IMG_START_TOKEN)
980
+ self.config.t_eps = t_eps
981
+
982
+ if isinstance(image_size, tuple):
983
+ image_size_list = [image_size] * max_images
984
+ elif isinstance(image_size, list) and isinstance(image_size[0], tuple):
985
+ image_size_list = image_size
986
+ if len(image_size) < max_images:
987
+ image_size_list += [image_size_list[-1]] * (max_images - len(image_size_list))
988
+ else:
989
+ assert False, "image size should be a tuple or a list of tuple"
990
+
991
+ if generation_config and hasattr(generation_config, 'max_new_tokens') and generation_config.max_new_tokens is not None:
992
+ max_new_tokens = generation_config.max_new_tokens
993
+ else:
994
+ max_new_tokens = 1024
995
+
996
+ current_generated_tokens = 0
997
+
998
+ if images is None:
999
+ images = []
1000
+
1001
+ template = get_conv_template(self.template)
1002
+ template.system_message = self.system_message
1003
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep.strip())
1004
+
1005
+ image_token_count = prompt.count('<image>')
1006
+ assert len(images) >= image_token_count
1007
+ if len(images) > image_token_count:
1008
+ prompt = "<image>\n" * (len(images) - image_token_count) + prompt
1009
+
1010
+ pixel_values =[]
1011
+ grid_hw =[]
1012
+ for image in images:
1013
+ cur_pixel_values, cur_grid_hw = load_image_native(image, self.patch_size, self.downsample_ratio, min_pixels=512*512, max_pixels=min(2048*2048, (4096*4096)//max(1, len(images))), upscale=False)
1014
+ grid_hw.append(cur_grid_hw.to(self.device))
1015
+ pixel_values.append(cur_pixel_values.to(self.device).to(torch.bfloat16))
1016
+
1017
+ merge_size = int(1 / self.downsample_ratio)
1018
+ pv_tensor = torch.cat(pixel_values) if pixel_values else None
1019
+ ghw_tensor = torch.cat(grid_hw) if grid_hw else None
1020
+
1021
+ # Condition
1022
+ template_cond = get_conv_template(self.template)
1023
+ template_cond.system_message = system_message
1024
+ template_cond.append_message(template_cond.roles[0], prompt)
1025
+ template_cond.append_message(template_cond.roles[1], None)
1026
+ query_cond = template_cond.get_prompt()
1027
+
1028
+ if not think_mode:
1029
+ query_cond = query_cond + '<think>\n\n</think>\n\n'
1030
+ else:
1031
+ query_cond = query_cond + '<think>\n'
1032
+
1033
+ def replace_image_tokens(query, grid_hw_list):
1034
+ for i in range(len(grid_hw_list)):
1035
+ num_patch_token = int(grid_hw_list[i][0, 0] * grid_hw_list[i][0, 1] * self.downsample_ratio**2)
1036
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * num_patch_token + IMG_END_TOKEN
1037
+ query = query.replace('<image>', image_tokens, 1)
1038
+ return query
1039
+
1040
+ query_cond = replace_image_tokens(query_cond, grid_hw)
1041
+ input_embeds_cond, indexes_cond, attention_mask_cond = self._build_it2i_inputs(tokenizer, query_cond, pv_tensor, ghw_tensor)
1042
+
1043
+ outputs_cond = self.language_model(inputs_embeds=input_embeds_cond, indexes=indexes_cond, attention_mask=attention_mask_cond, use_cache=True)
1044
+ past_key_values_cond = outputs_cond.past_key_values
1045
+ t_index_cond = indexes_cond[0].max().item()
1046
+
1047
+ # Initialize Text Uncondition Cache
1048
+ question_text_uncondition = '<image>' * len(images)
1049
+ template_tu = get_conv_template(self.template)
1050
+ template_tu.system_message = self.system_message
1051
+ template_tu.append_message(template_tu.roles[0], question_text_uncondition)
1052
+ template_tu.append_message(template_tu.roles[1], None)
1053
+ query_text_uncond = template_tu.get_prompt()
1054
+ query_text_uncond = replace_image_tokens(query_text_uncond, grid_hw)
1055
+
1056
+ input_embeds_tu, indexes_tu, attention_mask_tu = self._build_it2i_inputs(tokenizer, query_text_uncond, pv_tensor, ghw_tensor)
1057
+ outputs_tu = self.language_model(inputs_embeds=input_embeds_tu, indexes=indexes_tu, attention_mask=attention_mask_tu, use_cache=True)
1058
+ past_key_values_tu = outputs_tu.past_key_values
1059
+ t_index_tu = indexes_tu[0].max().item()
1060
+
1061
+ # Initialize Img (ALL) Uncondition Cache
1062
+ query_img_uncond = self._build_t2i_query("", append_text=IMG_START_TOKEN)
1063
+ input_embeds_iu, indexes_iu, attention_mask_iu = self._build_it2i_inputs(tokenizer, query_img_uncond)
1064
+ outputs_iu = self.language_model(inputs_embeds=input_embeds_iu, indexes=indexes_iu, attention_mask=attention_mask_iu, use_cache=True)
1065
+ past_key_values_iu = outputs_iu.past_key_values
1066
+
1067
+
1068
+ generated_text = ""
1069
+ generated_images =[]
1070
+ max_images = 10
1071
+ img_count = 0
1072
+
1073
+ next_token = torch.argmax(outputs_cond.logits[:, -1, :], dim=-1)
1074
+
1075
+ while True:
1076
+ # text generation
1077
+ gen_tokens = []
1078
+ hit_max_tokens = False
1079
+ while True:
1080
+ token_item = next_token.item()
1081
+ if token_item == eos_token_id or token_item == self.img_start_token_id:
1082
+ break
1083
+ gen_tokens.append(token_item)
1084
+ current_generated_tokens += 1
1085
+
1086
+ self.language_model.model.current_index = t_index_cond
1087
+ outputs_cond = self.language_model(
1088
+ input_ids=next_token.unsqueeze(0),
1089
+ past_key_values=past_key_values_cond,
1090
+ use_cache=True
1091
+ )
1092
+ past_key_values_cond = outputs_cond.past_key_values
1093
+ t_index_cond += 1
1094
+ next_token = torch.argmax(outputs_cond.logits[:, -1, :], dim=-1)
1095
+
1096
+ if current_generated_tokens >= max_new_tokens:
1097
+ hit_max_tokens = True
1098
+ break
1099
+
1100
+ if len(gen_tokens) > 0:
1101
+ chunk_text = tokenizer.decode(gen_tokens, skip_special_tokens=True)
1102
+ generated_text += chunk_text
1103
+ if verbose:
1104
+ print(chunk_text, end='', flush=True)
1105
+
1106
+ if next_token.item() == eos_token_id or hit_max_tokens:
1107
+ break
1108
+
1109
+ if next_token.item() == self.img_start_token_id:
1110
+ if img_count >= max_images:
1111
+ break
1112
+
1113
+ generated_text += "<image>"
1114
+ if verbose:
1115
+ print("<image>", end='', flush=True)
1116
+
1117
+ # Add the img_start_token for condition and text_uncondition branch
1118
+ self.language_model.model.current_index = t_index_cond
1119
+ outputs_cond = self.language_model(input_ids=next_token.unsqueeze(0), past_key_values=past_key_values_cond, use_cache=True)
1120
+ past_key_values_cond = outputs_cond.past_key_values
1121
+ t_index_cond += 1
1122
+
1123
+ self.language_model.model.current_index = t_index_tu
1124
+ outputs_tu = self.language_model(input_ids=next_token.unsqueeze(0), past_key_values=past_key_values_tu, use_cache=True)
1125
+ past_key_values_tu = outputs_tu.past_key_values
1126
+ t_index_tu += 1
1127
+
1128
+ image_size = image_size_list[img_count]
1129
+ # Image Generation
1130
+ token_h = image_size[1] // (self.patch_size * merge_size)
1131
+ token_w = image_size[0] // (self.patch_size * merge_size)
1132
+ device = self.device
1133
+
1134
+ indexes_image_condition = self._build_t2i_image_indexes(token_h, token_w, t_index_cond + 1, device=device)
1135
+ indexes_image_text_uncondition = self._build_t2i_image_indexes(token_h, token_w, t_index_tu + 1, device=device)
1136
+ indexes_image_img_uncondition = self._build_t2i_image_indexes(token_h, token_w, indexes_iu[0].max() + 1, device=device)
1137
+
1138
+ grid_h = image_size[1] // self.patch_size
1139
+ grid_w = image_size[0] // self.patch_size
1140
+ gen_grid_hw = torch.tensor([[grid_h, grid_w]], device=device)
1141
+
1142
+ noise_scale = self.noise_scale
1143
+ if self.noise_scale_mode in ("resolution", "dynamic", 'dynamic_sqrt'):
1144
+ noise_scale = math.sqrt((grid_h*grid_w)/(merge_size**2) / self.noise_scale_base_image_seq_len)
1145
+ base = float(self.noise_scale_base_image_seq_len)
1146
+ noise_scale = math.sqrt((grid_h*grid_w)/(merge_size**2)/base) * float(self.noise_scale)
1147
+ if self.noise_scale_mode == 'dynamic_sqrt':
1148
+ noise_scale = math.sqrt(noise_scale)
1149
+ noise_scale = min(noise_scale, self.noise_scale_max_value)
1150
+ image_prediction = noise_scale * torch.randn((1, 3, image_size[1], image_size[0]), device=device, dtype=outputs_cond.logits.dtype)
1151
+
1152
+ past_key_values_cond_cfg = past_key_values_cond
1153
+ past_key_values_tu_cfg = past_key_values_tu
1154
+ past_key_values_iu_cfg = past_key_values_iu
1155
+
1156
+ attention_mask_condition = {"full_attention": None}
1157
+ attention_mask_text_uncondition = {"full_attention": None}
1158
+ attention_mask_img_uncondition = {"full_attention": None}
1159
+
1160
+ prepare_flash_kv_cache(
1161
+ past_key_values_cond_cfg,
1162
+ current_len=token_h * token_w,
1163
+ batch_size=1,
1164
+ )
1165
+ prepare_flash_kv_cache(
1166
+ past_key_values_tu_cfg,
1167
+ current_len=token_h * token_w,
1168
+ batch_size=1,
1169
+ )
1170
+ prepare_flash_kv_cache(
1171
+ past_key_values_iu_cfg,
1172
+ current_len=token_h * token_w,
1173
+ batch_size=1,
1174
+ )
1175
+
1176
+ timesteps = torch.linspace(0.0, 1.0, num_steps+1, device=device)
1177
+ if enable_timestep_shift:
1178
+ timesteps = self._apply_time_schedule(timesteps, token_h*token_w, timestep_shift)
1179
+
1180
+ for step_i in range(num_steps):
1181
+ t = timesteps[step_i]
1182
+ t_next = timesteps[step_i + 1]
1183
+
1184
+ z = self.patchify(image_prediction, self.patch_size * merge_size)
1185
+ image_input = self.patchify(image_prediction, self.patch_size, channel_first=True)
1186
+ image_embeds = self.extract_feature(image_input.view(1 * grid_h*grid_w, -1), gen_model=True, grid_hw=gen_grid_hw).view(1, token_h*token_w, -1)
1187
+ t_expanded = t.expand(token_h*token_w)
1188
+ timestep_embeddings = self.fm_modules['timestep_embedder'](t_expanded).view(1, token_h*token_w, -1)
1189
+ if self.add_noise_scale_embedding:
1190
+ noise_scale_tensor = torch.full_like(t_expanded, noise_scale/self.noise_scale_max_value)
1191
+ noise_embeddings = self.fm_modules['noise_scale_embedder'](noise_scale_tensor).view(1, token_h*token_w, -1)
1192
+ timestep_embeddings += noise_embeddings
1193
+ image_embeds = image_embeds + timestep_embeddings
1194
+
1195
+ use_cfg = (t > cfg_interval[0] and t < cfg_interval[1]) or cfg_interval[0] == 0
1196
+ out_cond = self._t2i_predict_v(image_embeds, indexes_image_condition, attention_mask_condition, past_key_values_cond_cfg, t, z, image_token_num=token_h*token_w, timestep_embeddings=timestep_embeddings)
1197
+ if not use_cfg:
1198
+ v_pred = out_cond
1199
+ elif cfg_scale == 1 and img_cfg_scale == 1:
1200
+ v_pred = out_cond
1201
+ elif img_cfg_scale == 1:
1202
+ out_img_cond = self._t2i_predict_v(image_embeds, indexes_image_text_uncondition, attention_mask_text_uncondition, past_key_values_tu_cfg, t, z, image_token_num=token_h*token_w, timestep_embeddings=timestep_embeddings)
1203
+ v_pred = out_img_cond + cfg_scale * (out_cond - out_img_cond)
1204
+ elif cfg_scale == img_cfg_scale:
1205
+ out_uncond = self._t2i_predict_v(image_embeds, indexes_image_img_uncondition, attention_mask_img_uncondition, past_key_values_iu_cfg, t, z, image_token_num=token_h*token_w, timestep_embeddings=timestep_embeddings)
1206
+ v_pred = out_uncond + cfg_scale * (out_cond - out_uncond)
1207
+ else:
1208
+ out_img_cond = self._t2i_predict_v(image_embeds, indexes_image_text_uncondition, attention_mask_text_uncondition, past_key_values_tu_cfg, t, z, image_token_num=token_h*token_w, timestep_embeddings=timestep_embeddings)
1209
+ out_uncond = self._t2i_predict_v(image_embeds, indexes_image_img_uncondition, attention_mask_img_uncondition, past_key_values_iu_cfg, t, z, image_token_num=token_h*token_w, timestep_embeddings=timestep_embeddings)
1210
+ v_pred = (
1211
+ out_uncond
1212
+ + cfg_scale * (out_cond - out_img_cond)
1213
+ + img_cfg_scale * (out_img_cond - out_uncond)
1214
+ )
1215
+ if (cfg_scale > 1 or img_cfg_scale > 1 and use_cfg):
1216
+ if cfg_norm == 'global':
1217
+ norm_v_condition = torch.norm(out_cond, dim=(1,2), keepdim=True)
1218
+ norm_v_cfg = torch.norm(v_pred, dim=(1,2), keepdim=True)
1219
+ scale = (norm_v_condition / (norm_v_cfg + 1e-8)).clamp(min=0, max=1.0)
1220
+ v_pred = v_pred * scale
1221
+ elif cfg_norm == 'channel':
1222
+ norm_v_condition = torch.norm(out_cond, dim=-1, keepdim=True)
1223
+ norm_v_cfg = torch.norm(v_pred, dim=-1, keepdim=True)
1224
+ scale = (norm_v_condition / (norm_v_cfg + 1e-8)).clamp(min=0, max=1.0)
1225
+ v_pred = v_pred * scale
1226
+
1227
+ z = z + (t_next - t) * v_pred
1228
+ image_prediction = self.unpatchify(z, self.patch_size * merge_size, image_size[1], image_size[0])
1229
+
1230
+ generated_images.append(image_prediction)
1231
+
1232
+ clear_flash_kv_cache(past_key_values_cond_cfg)
1233
+ clear_flash_kv_cache(past_key_values_tu_cfg)
1234
+ clear_flash_kv_cache(past_key_values_iu_cfg)
1235
+
1236
+ img_count += 1
1237
+
1238
+ # re-encode the generated image using the und-branch
1239
+ pred_img = image_prediction[0].unsqueeze(0).to(torch.bfloat16)
1240
+ # re-normalize the image
1241
+ raw_img = pred_img * 0.5 + 0.5
1242
+ img_mean = torch.tensor([0.485, 0.456, 0.406], dtype=raw_img.dtype, device=device).view(1, 3, 1, 1)
1243
+ img_std = torch.tensor([0.229, 0.224, 0.225], dtype=raw_img.dtype, device=device).view(1, 3, 1, 1)
1244
+ und_img = (raw_img - img_mean) / img_std
1245
+ c, h, w = und_img[0].shape
1246
+ ps = self.patch_size
1247
+ p_grid_h = h // ps
1248
+ p_grid_w = w // ps
1249
+ flatten_pixel_values = (
1250
+ und_img[0].view(c, p_grid_h, ps, p_grid_w, ps)
1251
+ .permute(1, 3, 0, 2, 4) # [grid_h, grid_w, c, patch_size, patch_size]
1252
+ .reshape(p_grid_h * p_grid_w, c * ps ** 2)
1253
+ )
1254
+ vit_embeds = self.extract_feature(flatten_pixel_values, grid_hw=gen_grid_hw[:1]).unsqueeze(0)
1255
+
1256
+ img_end_id = tokenizer.convert_tokens_to_ids(IMG_END_TOKEN)
1257
+ img_end_embed = self.language_model.get_input_embeddings()(torch.tensor([[img_end_id]], device=device))
1258
+ inputs_embeds_img = torch.cat([vit_embeds, img_end_embed], dim=1) # (1, N + 1, C)
1259
+
1260
+ N_img_tokens = vit_embeds.shape[1]
1261
+ abs_pos_w, abs_pos_h = build_abs_positions_from_grid_hw(gen_grid_hw[:1] // int(1 / self.downsample_ratio), device=device)
1262
+
1263
+ def append_image_to_cache(cache, t_idx):
1264
+ past_len = cache.get_seq_length()
1265
+ tgt_len = N_img_tokens + 1
1266
+
1267
+ t_indexes = torch.zeros(tgt_len, dtype=torch.long, device=device)
1268
+ t_indexes[:N_img_tokens] = t_idx + 1
1269
+ t_indexes[N_img_tokens] = t_idx + 2
1270
+
1271
+ h_indexes = torch.zeros(tgt_len, dtype=torch.long, device=device)
1272
+ w_indexes = torch.zeros(tgt_len, dtype=torch.long, device=device)
1273
+ h_indexes[:N_img_tokens] = abs_pos_h
1274
+ w_indexes[:N_img_tokens] = abs_pos_w
1275
+
1276
+ indexes = torch.stack([t_indexes, h_indexes, w_indexes], dim=0)
1277
+
1278
+ mask = torch.zeros(1, 1, tgt_len, past_len + tgt_len, device=device)
1279
+ mask[0, 0, :N_img_tokens, past_len + N_img_tokens] = float('-inf')
1280
+ attention_mask_dict = {"full_attention": mask}
1281
+
1282
+ outputs = self.language_model(
1283
+ inputs_embeds=inputs_embeds_img,
1284
+ indexes=indexes,
1285
+ attention_mask=attention_mask_dict,
1286
+ past_key_values=cache,
1287
+ use_cache=True
1288
+ )
1289
+ return outputs, t_idx + 2
1290
+
1291
+ outputs_cond, t_index_cond = append_image_to_cache(past_key_values_cond, t_index_cond)
1292
+ outputs_tu, t_index_tu = append_image_to_cache(past_key_values_tu, t_index_tu)
1293
+
1294
+ next_token = torch.argmax(outputs_cond.logits[:, -1, :], dim=-1)
1295
+
1296
+ return generated_text, generated_images
1297
+
1298
+ @torch.no_grad()
1299
+ def it2i_generate(self, tokenizer, prompt, images, cfg_scale=1, img_cfg_scale=1, cfg_norm='none', enable_timestep_shift=True, timestep_shift=1, image_size=(256, 256), num_steps=30, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>', IMG_CONTEXT_TOKEN='<IMG_CONTEXT>', method='euler', cfg_interval=(0, 1), batch_size=1, t_eps=0.02, think_mode=False):
1300
+ assert cfg_norm in ['none', 'global', 'channel']
1301
+
1302
+ self.img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
1303
+ self.config.t_eps = t_eps
1304
+
1305
+ image_token_count = prompt.count('<image>')
1306
+ assert len(images) >= image_token_count
1307
+ if len(images) > image_token_count:
1308
+ prompt = "<image>\n" * (len(images) - image_token_count) + prompt
1309
+
1310
+ pixel_values = []
1311
+ grid_hw = []
1312
+ for image in images:
1313
+ cur_pixel_values, cur_grid_hw = load_image_native(
1314
+ image,
1315
+ self.patch_size,
1316
+ self.downsample_ratio,
1317
+ min_pixels=512 * 512,
1318
+ max_pixels=min(2048*2048, (4096 * 4096) // len(images)),
1319
+ upscale=False,
1320
+ )
1321
+ cur_grid_hw = cur_grid_hw.to(self.device)
1322
+ cur_pixel_values = cur_pixel_values.to(self.device).to(torch.bfloat16)
1323
+ pixel_values.append(cur_pixel_values)
1324
+ grid_hw.append(cur_grid_hw)
1325
+ pixel_values = torch.cat(pixel_values)
1326
+ grid_hw = torch.cat(grid_hw)
1327
+
1328
+ merge_size = int(1 / self.downsample_ratio)
1329
+ question_condition = f"{prompt}"
1330
+ question_img_condition = '<image>' * len(images)
1331
+ question_uncondition = ""
1332
+ think_text = ""
1333
+
1334
+ think_content = '<think>\n' if think_mode else '<think>\n\n</think>\n\n' + IMG_START_TOKEN
1335
+ query_condition = self._build_t2i_query(question_condition, system_message=SYSTEM_MESSAGE_FOR_GEN, append_text=think_content)
1336
+ query_img_condition = self._build_t2i_query(question_img_condition, append_text=IMG_START_TOKEN)
1337
+ query_uncondition = self._build_t2i_query(question_uncondition, append_text=IMG_START_TOKEN)
1338
+
1339
+ for i in range(grid_hw.shape[0]):
1340
+ num_patch_token = int(grid_hw[i, 0] * grid_hw[i, 1] * self.downsample_ratio**2)
1341
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * num_patch_token + IMG_END_TOKEN
1342
+ query_condition = query_condition.replace('<image>', image_tokens, 1)
1343
+ query_img_condition = query_img_condition.replace('<image>', image_tokens, 1)
1344
+
1345
+ input_embeds_condition, indexes_condition, attention_mask_condition_prefix = self._build_it2i_inputs(
1346
+ tokenizer, query_condition, pixel_values, grid_hw
1347
+ )
1348
+ input_embeds_img_condition, indexes_img_condition, attention_mask_img_condition_prefix = self._build_it2i_inputs(
1349
+ tokenizer, query_img_condition, pixel_values, grid_hw
1350
+ )
1351
+ input_embeds_uncondition, indexes_uncondition, attention_mask_uncondition_prefix = self._build_it2i_inputs(
1352
+ tokenizer, query_uncondition
1353
+ )
1354
+
1355
+ token_h = image_size[1] // (self.patch_size * merge_size)
1356
+ token_w = image_size[0] // (self.patch_size * merge_size)
1357
+
1358
+ indexes_image_condition = self._build_t2i_image_indexes(
1359
+ token_h, token_w, indexes_condition[0].max() + 1, device=input_embeds_condition.device
1360
+ )
1361
+ indexes_image_img_condition = self._build_t2i_image_indexes(
1362
+ token_h, token_w, indexes_img_condition[0].max() + 1, device=input_embeds_img_condition.device
1363
+ )
1364
+ indexes_image_uncondition = self._build_t2i_image_indexes(
1365
+ token_h, token_w, indexes_uncondition[0].max() + 1, device=input_embeds_uncondition.device
1366
+ )
1367
+
1368
+ if think_mode:
1369
+ outputs_condition = self.language_model(
1370
+ inputs_embeds=input_embeds_condition,
1371
+ indexes=indexes_condition,
1372
+ attention_mask=attention_mask_condition_prefix,
1373
+ use_cache=True,
1374
+ output_hidden_states=True,
1375
+ )
1376
+ past_key_values_condition = outputs_condition.past_key_values
1377
+ hidden_states_condition = outputs_condition.hidden_states[-1]
1378
+ t_index_condition = indexes_condition[0].max().item()
1379
+ past_key_values_condition, t_index_condition, think_text = self._generate_think(
1380
+ tokenizer,
1381
+ outputs_condition,
1382
+ past_key_values_condition,
1383
+ t_index_condition,
1384
+ IMG_START_TOKEN,
1385
+ )
1386
+ indexes_image_condition = self._build_t2i_image_indexes(
1387
+ token_h, token_w, t_index_condition + 1, device=input_embeds_condition.device
1388
+ )
1389
+ else:
1390
+ past_key_values_condition, hidden_states_condition = self._it2i_prefix_forward(
1391
+ input_embeds_condition, indexes_condition, attention_mask_condition_prefix
1392
+ )
1393
+ past_key_values_img_condition, hidden_states_img_condition = self._it2i_prefix_forward(
1394
+ input_embeds_img_condition, indexes_img_condition, attention_mask_img_condition_prefix
1395
+ )
1396
+ past_key_values_uncondition, hidden_states_uncondition = self._it2i_prefix_forward(
1397
+ input_embeds_uncondition, indexes_uncondition, attention_mask_uncondition_prefix
1398
+ )
1399
+
1400
+ for layer_idx in range(len(past_key_values_condition.layers)):
1401
+ past_key_values_condition.layers[layer_idx].keys = past_key_values_condition.layers[layer_idx].keys.expand(
1402
+ batch_size, *past_key_values_condition.layers[layer_idx].keys.shape[1:]
1403
+ )
1404
+ past_key_values_condition.layers[layer_idx].values = past_key_values_condition.layers[layer_idx].values.expand(
1405
+ batch_size, *past_key_values_condition.layers[layer_idx].values.shape[1:]
1406
+ )
1407
+ past_key_values_img_condition.layers[layer_idx].keys = past_key_values_img_condition.layers[layer_idx].keys.expand(
1408
+ batch_size, *past_key_values_img_condition.layers[layer_idx].keys.shape[1:]
1409
+ )
1410
+ past_key_values_img_condition.layers[layer_idx].values = past_key_values_img_condition.layers[layer_idx].values.expand(
1411
+ batch_size, *past_key_values_img_condition.layers[layer_idx].values.shape[1:]
1412
+ )
1413
+ past_key_values_uncondition.layers[layer_idx].keys = past_key_values_uncondition.layers[layer_idx].keys.expand(
1414
+ batch_size, *past_key_values_uncondition.layers[layer_idx].keys.shape[1:]
1415
+ )
1416
+ past_key_values_uncondition.layers[layer_idx].values = past_key_values_uncondition.layers[layer_idx].values.expand(
1417
+ batch_size, *past_key_values_uncondition.layers[layer_idx].values.shape[1:]
1418
+ )
1419
+
1420
+ prepare_flash_kv_cache(
1421
+ past_key_values_condition,
1422
+ current_len=token_h * token_w,
1423
+ batch_size=batch_size,
1424
+ )
1425
+ prepare_flash_kv_cache(
1426
+ past_key_values_img_condition,
1427
+ current_len=token_h * token_w,
1428
+ batch_size=batch_size,
1429
+ )
1430
+ prepare_flash_kv_cache(
1431
+ past_key_values_uncondition,
1432
+ current_len=token_h * token_w,
1433
+ batch_size=batch_size,
1434
+ )
1435
+
1436
+ device = hidden_states_condition.device
1437
+ dtype = hidden_states_condition.dtype
1438
+
1439
+ grid_h = image_size[1] // self.patch_size
1440
+ grid_w = image_size[0] // self.patch_size
1441
+ grid_hw = torch.tensor([[grid_h, grid_w]] * batch_size, device=device)
1442
+
1443
+ noise_scale = self.noise_scale
1444
+ if self.noise_scale_mode in ("resolution", "dynamic", "dynamic_sqrt"):
1445
+ noise_scale = math.sqrt((grid_h * grid_w) / (merge_size**2) / self.noise_scale_base_image_seq_len)
1446
+ base = float(self.noise_scale_base_image_seq_len)
1447
+ scale = math.sqrt((grid_h * grid_w) / (merge_size**2) / base)
1448
+ noise_scale = scale * float(self.noise_scale)
1449
+ if self.noise_scale_mode == 'dynamic_sqrt':
1450
+ noise_scale = math.sqrt(noise_scale)
1451
+ noise_scale = min(noise_scale, self.noise_scale_max_value)
1452
+ image_prediction = noise_scale * torch.randn(
1453
+ (batch_size, 3, image_size[1], image_size[0]), device=device, dtype=dtype
1454
+ )
1455
+
1456
+ attention_mask_condition = {"full_attention": None}
1457
+ attention_mask_img_condition = {"full_attention": None}
1458
+ attention_mask_uncondition = {"full_attention": None}
1459
+
1460
+ timesteps = torch.linspace(0.0, 1.0, num_steps + 1, device=device)
1461
+ if enable_timestep_shift:
1462
+ timesteps = self._apply_time_schedule(timesteps, token_h * token_w, timestep_shift)
1463
+
1464
+ for step_i in range(num_steps):
1465
+ t = timesteps[step_i]
1466
+ t_next = timesteps[step_i + 1]
1467
+ use_cfg = (t > cfg_interval[0] and t < cfg_interval[1]) or cfg_interval[0] == 0
1468
+
1469
+ z = self.patchify(image_prediction, self.patch_size * merge_size)
1470
+ image_input = self.patchify(image_prediction, self.patch_size, channel_first=True)
1471
+ image_embeds = self.extract_feature(
1472
+ image_input.view(batch_size * grid_h * grid_w, -1),
1473
+ gen_model=True,
1474
+ grid_hw=grid_hw,
1475
+ ).view(batch_size, token_h * token_w, -1)
1476
+ t_expanded = t.expand(batch_size * token_h * token_w)
1477
+ timestep_embeddings = self.fm_modules['timestep_embedder'](t_expanded).view(batch_size, token_h * token_w, -1)
1478
+ if self.add_noise_scale_embedding:
1479
+ noise_scale_tensor = torch.full_like(t_expanded, noise_scale / self.noise_scale_max_value)
1480
+ noise_embeddings = self.fm_modules['noise_scale_embedder'](noise_scale_tensor).view(batch_size, token_h * token_w, -1)
1481
+ timestep_embeddings += noise_embeddings
1482
+ image_embeds = image_embeds + timestep_embeddings
1483
+
1484
+ out_cond = self._t2i_predict_v(
1485
+ image_embeds,
1486
+ indexes_image_condition,
1487
+ attention_mask_condition,
1488
+ past_key_values_condition,
1489
+ t,
1490
+ z,
1491
+ image_token_num=token_h * token_w,
1492
+ timestep_embeddings=timestep_embeddings,
1493
+ image_size=image_size,
1494
+ )
1495
+
1496
+ if not use_cfg:
1497
+ v_pred = out_cond
1498
+ elif cfg_scale == 1 and img_cfg_scale == 1:
1499
+ v_pred = out_cond
1500
+ elif img_cfg_scale == 1:
1501
+ out_img_cond = self._t2i_predict_v(
1502
+ image_embeds,
1503
+ indexes_image_img_condition,
1504
+ attention_mask_img_condition,
1505
+ past_key_values_img_condition,
1506
+ t,
1507
+ z,
1508
+ image_token_num=token_h * token_w,
1509
+ timestep_embeddings=timestep_embeddings,
1510
+ image_size=image_size,
1511
+ )
1512
+ v_pred = out_img_cond + cfg_scale * (out_cond - out_img_cond)
1513
+ elif cfg_scale == img_cfg_scale:
1514
+ out_uncond = self._t2i_predict_v(
1515
+ image_embeds,
1516
+ indexes_image_uncondition,
1517
+ attention_mask_uncondition,
1518
+ past_key_values_uncondition,
1519
+ t,
1520
+ z,
1521
+ image_token_num=token_h * token_w,
1522
+ timestep_embeddings=timestep_embeddings,
1523
+ image_size=image_size,
1524
+ )
1525
+ v_pred = out_uncond + cfg_scale * (out_cond - out_uncond)
1526
+ else:
1527
+ out_img_cond = self._t2i_predict_v(
1528
+ image_embeds,
1529
+ indexes_image_img_condition,
1530
+ attention_mask_img_condition,
1531
+ past_key_values_img_condition,
1532
+ t,
1533
+ z,
1534
+ image_token_num=token_h * token_w,
1535
+ timestep_embeddings=timestep_embeddings,
1536
+ image_size=image_size,
1537
+ )
1538
+ out_uncond = self._t2i_predict_v(
1539
+ image_embeds,
1540
+ indexes_image_uncondition,
1541
+ attention_mask_uncondition,
1542
+ past_key_values_uncondition,
1543
+ t,
1544
+ z,
1545
+ image_token_num=token_h * token_w,
1546
+ timestep_embeddings=timestep_embeddings,
1547
+ image_size=image_size,
1548
+ )
1549
+ v_pred = (
1550
+ out_uncond
1551
+ + cfg_scale * (out_cond - out_img_cond)
1552
+ + img_cfg_scale * (out_img_cond - out_uncond)
1553
+ )
1554
+ if (cfg_scale > 1 or img_cfg_scale > 1) and use_cfg:
1555
+ if cfg_norm == 'global':
1556
+ norm_v_condition = torch.norm(out_cond, dim=(1, 2), keepdim=True)
1557
+ norm_v_cfg = torch.norm(v_pred, dim=(1, 2), keepdim=True)
1558
+ scale = (norm_v_condition / (norm_v_cfg + 1e-8)).clamp(min=0, max=1.0)
1559
+ v_pred = v_pred * scale
1560
+ elif cfg_norm == 'channel':
1561
+ norm_v_condition = torch.norm(out_cond, dim=-1, keepdim=True)
1562
+ norm_v_cfg = torch.norm(v_pred, dim=-1, keepdim=True)
1563
+ scale = (norm_v_condition / (norm_v_cfg + 1e-8)).clamp(min=0, max=1.0)
1564
+ v_pred = v_pred * scale
1565
+
1566
+ z = z + (t_next - t) * v_pred
1567
+ image_prediction = self.unpatchify(z, self.patch_size * merge_size, image_size[1], image_size[0])
1568
+
1569
+ clear_flash_kv_cache(past_key_values_condition)
1570
+ clear_flash_kv_cache(past_key_values_img_condition)
1571
+ clear_flash_kv_cache(past_key_values_uncondition)
1572
+
1573
+ self.last_think_content = think_text
1574
+ if think_mode:
1575
+ return image_prediction, think_text
1576
+ return image_prediction
1577
+
1578
+ @torch.no_grad()
1579
+ def t2i_generate(self, tokenizer, prompt, cfg_scale=1, timestep_shift=1, enable_timestep_shift=True, cfg_norm='none', image_size=(256, 256), num_steps=30, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>', IMG_CONTEXT_TOKEN='<IMG_CONTEXT>', method='euler', cfg_interval=(0, 1), batch_size=1, t_eps=0.02, think_mode=False):
1580
+ assert self.concat_time_token_num == 0
1581
+ assert cfg_norm in ['cfg_zero_star', 'global', 'none', 'channel']
1582
+ merge_size = int(1 / self.downsample_ratio)
1583
+
1584
+ self.config.t_eps = t_eps
1585
+ # question_condition = f"Please generate an image based on the following description: {prompt}"
1586
+ question_condition = f"{prompt}"
1587
+ # question_condition += f"\nThe resolution of the image should be {image_size}"
1588
+
1589
+ question_uncondition = f""
1590
+ # question_uncondition += f"\nThe resolution of the image should be {image_size}"
1591
+ think_text = ""
1592
+
1593
+ think_content = '<think>\n' if think_mode else '<think>\n\n</think>\n\n' + IMG_START_TOKEN
1594
+ query_condition = self._build_t2i_query(question_condition, system_message=SYSTEM_MESSAGE_FOR_GEN, append_text=think_content)
1595
+ query_uncondition = self._build_t2i_query(question_uncondition, append_text=IMG_START_TOKEN)
1596
+
1597
+ input_ids_condition, indexes_condition, attention_mask_condition_prefix = self._build_t2i_text_inputs(tokenizer, query_condition)
1598
+ input_ids_uncondition, indexes_uncondition, attention_mask_uncondition_prefix = self._build_t2i_text_inputs(tokenizer, query_uncondition)
1599
+
1600
+ token_h = image_size[1] // (self.patch_size * merge_size)
1601
+ token_w = image_size[0] // (self.patch_size * merge_size)
1602
+
1603
+ indexes_image_condition = self._build_t2i_image_indexes(token_h, token_w, indexes_condition.shape[1], device=input_ids_condition.device)
1604
+ indexes_image_uncondition = self._build_t2i_image_indexes(token_h, token_w, indexes_uncondition.shape[1], device=input_ids_uncondition.device)
1605
+
1606
+ if think_mode:
1607
+ outputs_condition = self.language_model(
1608
+ input_ids=input_ids_condition,
1609
+ indexes=indexes_condition,
1610
+ attention_mask=attention_mask_condition_prefix,
1611
+ use_cache=True,
1612
+ output_hidden_states=True,
1613
+ )
1614
+ past_key_values_condition = outputs_condition.past_key_values
1615
+ hidden_states_condition = outputs_condition.hidden_states[-1]
1616
+ t_index_condition = indexes_condition[0].max().item()
1617
+ past_key_values_condition, t_index_condition, think_text = self._generate_think(
1618
+ tokenizer,
1619
+ outputs_condition,
1620
+ past_key_values_condition,
1621
+ t_index_condition,
1622
+ IMG_START_TOKEN,
1623
+ )
1624
+ indexes_image_condition = self._build_t2i_image_indexes(
1625
+ token_h, token_w, t_index_condition + 1, device=input_ids_condition.device
1626
+ )
1627
+ else:
1628
+ past_key_values_condition, hidden_states_condition = self._t2i_prefix_forward(input_ids_condition, indexes_condition, attention_mask_condition_prefix)
1629
+ past_key_values_uncondition, hidden_states_uncondition = self._t2i_prefix_forward(input_ids_uncondition, indexes_uncondition, attention_mask_uncondition_prefix)
1630
+
1631
+ for layer_idx in range(len(past_key_values_condition.layers)):
1632
+ past_key_values_condition.layers[layer_idx].keys = past_key_values_condition.layers[layer_idx].keys.expand(batch_size, *past_key_values_condition.layers[layer_idx].keys.shape[1:])
1633
+ past_key_values_condition.layers[layer_idx].values = past_key_values_condition.layers[layer_idx].values.expand(batch_size, *past_key_values_condition.layers[layer_idx].values.shape[1:])
1634
+ past_key_values_uncondition.layers[layer_idx].keys = past_key_values_uncondition.layers[layer_idx].keys.expand(batch_size, *past_key_values_uncondition.layers[layer_idx].keys.shape[1:])
1635
+ past_key_values_uncondition.layers[layer_idx].values = past_key_values_uncondition.layers[layer_idx].values.expand(batch_size, *past_key_values_uncondition.layers[layer_idx].values.shape[1:])
1636
+
1637
+ # prepare flash cache once
1638
+ prepare_flash_kv_cache(
1639
+ past_key_values_condition,
1640
+ current_len=token_h * token_w,
1641
+ batch_size=batch_size,
1642
+ )
1643
+ prepare_flash_kv_cache(
1644
+ past_key_values_uncondition,
1645
+ current_len=token_h * token_w,
1646
+ batch_size=batch_size,
1647
+ )
1648
+
1649
+ device = hidden_states_condition.device
1650
+ dtype = hidden_states_condition.dtype
1651
+
1652
+ # init noise image tokens
1653
+ grid_h = image_size[1] // self.patch_size
1654
+ grid_w = image_size[0] // self.patch_size
1655
+ grid_hw = torch.tensor([[grid_h, grid_w]]*batch_size, device=device)
1656
+
1657
+ noise_scale = self.noise_scale
1658
+ if self.noise_scale_mode in ("resolution", "dynamic", 'dynamic_sqrt'):
1659
+ noise_scale = math.sqrt((grid_h*grid_w)/(merge_size**2) / self.noise_scale_base_image_seq_len)
1660
+ base = float(self.noise_scale_base_image_seq_len)
1661
+ scale = math.sqrt((grid_h*grid_w)/(merge_size**2)/base)
1662
+ noise_scale = scale * float(self.noise_scale)
1663
+ if self.noise_scale_mode == 'dynamic_sqrt':
1664
+ noise_scale = math.sqrt(noise_scale)
1665
+ noise_scale = min(noise_scale, self.noise_scale_max_value)
1666
+ image_prediction = noise_scale * torch.randn((batch_size, 3, image_size[1], image_size[0]), device=device, dtype=dtype)
1667
+
1668
+ # attention_mask_condition = {"full_attention": torch.zeros(batch_size, 1, token_h*token_w, input_ids_condition.shape[1]+token_h*token_w, device=device)}
1669
+ # attention_mask_uncondition = {"full_attention": torch.zeros(batch_size, 1, token_h*token_w, input_ids_uncondition.shape[1]+token_h*token_w, device=device)}
1670
+
1671
+ attention_mask_condition = {"full_attention": None}
1672
+ attention_mask_uncondition = {"full_attention": None}
1673
+
1674
+ timesteps = torch.linspace(0.0, 1.0, num_steps+1, device=device)
1675
+ if enable_timestep_shift:
1676
+ timesteps = self._apply_time_schedule(timesteps, token_h*token_w, timestep_shift)
1677
+
1678
+ for step_i in range(num_steps):
1679
+ t = timesteps[step_i]
1680
+ t_next = timesteps[step_i + 1]
1681
+
1682
+ z = self.patchify(image_prediction, self.patch_size * merge_size)
1683
+ image_input = self.patchify(image_prediction, self.patch_size, channel_first=True)
1684
+ image_embeds = self.extract_feature(image_input.view(batch_size * grid_h*grid_w, -1), gen_model=True, grid_hw=grid_hw).view(batch_size, token_h*token_w, -1)
1685
+ t_expanded = t.expand(batch_size*token_h*token_w)
1686
+ timestep_embeddings = self.fm_modules['timestep_embedder'](t_expanded).view(batch_size, token_h*token_w, -1)
1687
+ if self.add_noise_scale_embedding:
1688
+ noise_scale_tensor = torch.full_like(t_expanded, noise_scale / self.noise_scale_max_value)
1689
+ noise_embeddings = self.fm_modules['noise_scale_embedder'](noise_scale_tensor).view(batch_size, token_h*token_w, -1)
1690
+ timestep_embeddings += noise_embeddings
1691
+ image_embeds = image_embeds + timestep_embeddings
1692
+
1693
+ v_pred_condition = self._t2i_predict_v(image_embeds, indexes_image_condition, attention_mask_condition, past_key_values_condition, t, z, image_token_num=token_h*token_w, timestep_embeddings=timestep_embeddings, image_size=image_size)
1694
+
1695
+ if t >= cfg_interval[0] and t <= cfg_interval[1] and cfg_scale > 1:
1696
+ v_pred_uncondition = self._t2i_predict_v(image_embeds, indexes_image_uncondition, attention_mask_uncondition, past_key_values_uncondition, t, z, image_token_num=token_h*token_w, timestep_embeddings=timestep_embeddings, image_size=image_size)
1697
+ if cfg_norm == 'cfg_zero_star':
1698
+ positive_flat = v_pred_condition.view(batch_size, -1)
1699
+ negative_flat = v_pred_uncondition.view(batch_size, -1)
1700
+
1701
+ alpha = optimized_scale(positive_flat,negative_flat)
1702
+ alpha = alpha.view(batch_size, *([1] * (len(v_pred_condition.shape) - 1)))
1703
+ alpha = alpha.to(positive_flat.dtype)
1704
+
1705
+ if (step_i <= 0):
1706
+ v_pred = v_pred_condition*0.
1707
+ else:
1708
+ v_pred = v_pred_uncondition * alpha + cfg_scale * (v_pred_condition - v_pred_uncondition * alpha)
1709
+ else:
1710
+ v_pred = v_pred_uncondition + cfg_scale * (v_pred_condition - v_pred_uncondition)
1711
+ if cfg_norm == 'global':
1712
+ norm_v_condition = torch.norm(v_pred_condition, dim=(1,2), keepdim=True)
1713
+ norm_v_cfg = torch.norm(v_pred, dim=(1,2), keepdim=True)
1714
+ scale = (norm_v_condition / (norm_v_cfg + 1e-8)).clamp(min=0, max=1.0)
1715
+ v_pred = v_pred * scale
1716
+ elif cfg_norm == 'channel':
1717
+ norm_v_condition = torch.norm(v_pred_condition, dim=-1, keepdim=True)
1718
+ norm_v_cfg = torch.norm(v_pred, dim=-1, keepdim=True)
1719
+ scale = (norm_v_condition / (norm_v_cfg + 1e-8)).clamp(min=0, max=1.0)
1720
+ v_pred = v_pred * scale
1721
+ else:
1722
+ v_pred = v_pred_condition
1723
+
1724
+ z = z + (t_next - t) * v_pred
1725
+
1726
+ image_prediction = self.unpatchify(z, self.patch_size * merge_size, image_size[1], image_size[0])
1727
+
1728
+ clear_flash_kv_cache(past_key_values_condition)
1729
+ clear_flash_kv_cache(past_key_values_uncondition)
1730
+
1731
+ self.last_think_content = think_text
1732
+ if think_mode:
1733
+ return image_prediction, think_text
1734
+ return image_prediction
1735
+
1736
+ def chat(self, tokenizer, pixel_values, question, generation_config, history=None, return_history=False, grid_hw=None,
1737
+ IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>', IMG_CONTEXT_TOKEN='<IMG_CONTEXT>', verbose=False):
1738
+
1739
+ if history is None and pixel_values is not None and '<image>' not in question:
1740
+ question = '<image>\n' + question
1741
+
1742
+ img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
1743
+ self.img_context_token_id = img_context_token_id
1744
+ self.img_start_token_id = tokenizer.convert_tokens_to_ids(IMG_START_TOKEN)
1745
+
1746
+ template = get_conv_template(self.template)
1747
+ template.system_message = self.system_message
1748
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep.strip())
1749
+
1750
+ history = [] if history is None else history
1751
+ for (old_question, old_answer) in history:
1752
+ template.append_message(template.roles[0], old_question)
1753
+ template.append_message(template.roles[1], old_answer)
1754
+ template.append_message(template.roles[0], question)
1755
+ template.append_message(template.roles[1], None)
1756
+ query = template.get_prompt()
1757
+
1758
+ if verbose and pixel_values is not None:
1759
+ print(f'dynamic image size: {grid_hw[0] * self.patch_size}')
1760
+
1761
+ for i in range(grid_hw.shape[0]):
1762
+ num_patch_token = int(grid_hw[i, 0] * grid_hw[i, 1] * self.downsample_ratio**2)
1763
+ image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * num_patch_token + IMG_END_TOKEN
1764
+ query = query.replace('<image>', image_tokens, 1)
1765
+
1766
+ model_inputs = tokenizer(query, return_tensors='pt')
1767
+ input_ids = model_inputs['input_ids'].to(self.device)
1768
+ attention_mask = model_inputs['attention_mask'].to(self.device)
1769
+ generation_config['eos_token_id'] = eos_token_id
1770
+ generation_output = self.generate(
1771
+ pixel_values=pixel_values,
1772
+ input_ids=input_ids,
1773
+ grid_hw=grid_hw,
1774
+ attention_mask=attention_mask,
1775
+ **generation_config
1776
+ )
1777
+ response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]
1778
+ response = response.split(template.sep.strip())[0].strip()
1779
+ history.append((question, response))
1780
+ if return_history:
1781
+ return response, history
1782
+ else:
1783
+ query_to_print = query.replace(IMG_CONTEXT_TOKEN, '')
1784
+ query_to_print = query_to_print.replace(f'{IMG_START_TOKEN}{IMG_END_TOKEN}', '<image>')
1785
+ if verbose:
1786
+ print(query_to_print, response)
1787
+ return response
1788
+
1789
+ @torch.no_grad()
1790
+ def generate(
1791
+ self,
1792
+ pixel_values: Optional[torch.FloatTensor] = None,
1793
+ input_ids: Optional[torch.FloatTensor] = None,
1794
+ grid_hw: Optional[torch.LongTensor] = None,
1795
+ attention_mask: Optional[torch.LongTensor] = None,
1796
+ visual_features: Optional[torch.FloatTensor] = None,
1797
+ generation_config: Optional[GenerationConfig] = None,
1798
+ output_hidden_states: Optional[bool] = None,
1799
+ **generate_kwargs,
1800
+ ) -> torch.LongTensor:
1801
+ assert input_ids.shape[0] == 1
1802
+ assert self.img_context_token_id is not None
1803
+ indexes = self.get_thw_indexes(input_ids[0], grid_hw)
1804
+ if pixel_values is not None:
1805
+ if visual_features is not None:
1806
+ vit_embeds = visual_features
1807
+ else:
1808
+ vit_embeds = self.extract_feature(pixel_values, grid_hw=grid_hw)
1809
+
1810
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
1811
+ B, N, C = input_embeds.shape
1812
+ input_embeds = input_embeds.reshape(B * N, C)
1813
+
1814
+ input_ids = input_ids.reshape(B * N)
1815
+ selected = (input_ids == self.img_context_token_id)
1816
+ assert selected.sum() != 0
1817
+ input_embeds[selected] = vit_embeds.reshape(-1, C).to(input_embeds.device)
1818
+
1819
+ input_embeds = input_embeds.reshape(B, N, C)
1820
+ else:
1821
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
1822
+
1823
+ outputs = self.language_model.generate(
1824
+ inputs_embeds=input_embeds,
1825
+ indexes=indexes,
1826
+ attention_mask=attention_mask,
1827
+ generation_config=generation_config,
1828
+ output_hidden_states=output_hidden_states,
1829
+ use_cache=True,
1830
+ **generate_kwargs,
1831
+ )
1832
+
1833
+ return outputs
1834
+
1835
+ @property
1836
+ def lm_head(self):
1837
+ return self.language_model.get_output_embeddings()
1838
+
1839
+ def get_output_embeddings(self):
1840
+ return self.language_model.get_output_embeddings()
1841
+
1842
+ def get_input_embeddings(self):
1843
+ return self.language_model.get_input_embeddings()
1844
+
1845
+ def set_input_embeddings(self, value):
1846
+ return self.language_model.set_input_embeddings(value)
1847
+
1848
+ def set_output_embeddings(self, value):
1849
+ return self.language_model.set_output_embeddings(value)
1850
+
1851
+ def get_thw_indexes(self, input_ids, grid_hw=None):
1852
+ img_start_shift = torch.cat([torch.zeros(1, dtype=torch.long).to(input_ids.device),
1853
+ (input_ids == self.img_start_token_id).long()], dim=0)[:-1]
1854
+ not_img_token = (input_ids != self.img_context_token_id).long()
1855
+ t_indexes = ((img_start_shift + not_img_token).cumsum(0) - 1)
1856
+ h_indexes = torch.zeros_like(t_indexes).to(t_indexes.device)
1857
+ w_indexes = torch.zeros_like(t_indexes).to(t_indexes.device)
1858
+
1859
+ if grid_hw is not None:
1860
+ selected = (input_ids == self.img_context_token_id)
1861
+ if selected.long().sum() > 0:
1862
+ abs_pos_w, abs_pos_h = build_abs_positions_from_grid_hw(
1863
+ grid_hw // int(1 / self.downsample_ratio), device=t_indexes.device)
1864
+ h_indexes[selected] = abs_pos_h.to(t_indexes.device, t_indexes.dtype)
1865
+ w_indexes[selected] = abs_pos_w.to(t_indexes.device, t_indexes.dtype)
1866
+ return torch.stack([t_indexes, h_indexes, w_indexes], dim=0)
modeling_neo_vit.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Tuple, Union
2
+
3
+ import torch
4
+ import torch.utils.checkpoint
5
+ from torch import nn
6
+ from transformers.modeling_outputs import BaseModelOutputWithPooling
7
+ from transformers.modeling_utils import PreTrainedModel
8
+
9
+ from .configuration_neo_vit import NEOVisionConfig
10
+
11
+
12
+ def precompute_rope_freqs_sincos(
13
+ dim: int, max_position: int, base: float = 10000.0, device=None
14
+ ):
15
+ """预计算 RoPE 的 cos 和 sin 值 (1D)。"""
16
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, device=device).float() / dim))
17
+ t = torch.arange(max_position, device=device).type_as(inv_freq)
18
+ freqs = torch.outer(t, inv_freq)
19
+ return torch.cos(freqs), torch.sin(freqs)
20
+
21
+
22
+ def build_abs_positions_from_grid_hw(grid_hw: torch.Tensor, device=None):
23
+ """
24
+ Compute patch coordinates (x, y)
25
+
26
+ Args:
27
+ grid_hw: (B, 2) tensor representing (H, W) per image
28
+ """
29
+ device = grid_hw.device
30
+ B = grid_hw.shape[0]
31
+
32
+ # Get the number of patches per image
33
+ H = grid_hw[:, 0]
34
+ W = grid_hw[:, 1]
35
+ N = H * W
36
+ N_total = N.sum()
37
+
38
+ # Create the batch index for each patch (B x patch count)
39
+ patch_to_sample = torch.repeat_interleave(torch.arange(B, device=device), N) # (N_total,)
40
+
41
+ # Generate intra-image patch index (row-major order)
42
+ patch_id_within_image = torch.arange(N_total, device=device)
43
+ patch_id_within_image = patch_id_within_image - torch.cumsum(
44
+ torch.cat([torch.tensor([0], device=device), N[:-1]]), dim=0
45
+ )[patch_to_sample]
46
+
47
+ # Get H/W for each patch according to its image
48
+ W_per_patch = W[patch_to_sample]
49
+ abs_x = patch_id_within_image % W_per_patch
50
+ abs_y = patch_id_within_image // W_per_patch
51
+
52
+ return abs_x, abs_y
53
+
54
+
55
+ def apply_rotary_emb_1d(
56
+ x: torch.Tensor,
57
+ cos_cached: torch.Tensor,
58
+ sin_cached: torch.Tensor,
59
+ positions: torch.Tensor,
60
+ ):
61
+ """对输入张量的一部分应用1D RoPE。"""
62
+ # x: (..., seq_len, dim_part)
63
+ # positions: (..., seq_len)
64
+ # cos_cached: (max_pos, dim_part / 2)
65
+
66
+ cos = cos_cached[positions] # Shape: (positions.shape, dim_part / 2)
67
+ sin = sin_cached[positions] # Shape: (positions.shape, dim_part / 2)
68
+
69
+ x1 = x[..., 0::2]
70
+ x2 = x[..., 1::2]
71
+
72
+ rotated_x1 = x1 * cos - x2 * sin
73
+ rotated_x2 = x1 * sin + x2 * cos
74
+
75
+ x_rotated = torch.empty_like(x)
76
+ x_rotated[..., 0::2] = rotated_x1
77
+ x_rotated[..., 1::2] = rotated_x2
78
+ return x_rotated
79
+
80
+
81
+ def apply_2d_rotary_pos_emb(
82
+ x: torch.Tensor,
83
+ cos_cached_x: torch.Tensor,
84
+ sin_cached_x: torch.Tensor,
85
+ cos_cached_y: torch.Tensor,
86
+ sin_cached_y: torch.Tensor,
87
+ abs_positions_x: torch.Tensor,
88
+ abs_positions_y: torch.Tensor
89
+ ):
90
+ """应用2D RoPE到输入张量x。"""
91
+ dim = x.shape[-1]
92
+ dim_half = dim // 2
93
+
94
+ # 假设我们将embedding的前半部分用于一个方向的RoPE,后半部分用于另一个方向
95
+ # 例如,前一半给X坐标,后一半给Y坐标 (或者反过来,但要保持一致)
96
+ x_part_1 = x[..., :dim_half]
97
+ x_part_2 = x[..., dim_half:]
98
+
99
+ # 将与 abs_positions_x 相关的旋转应用于 x_part_1
100
+ rotated_part_1 = apply_rotary_emb_1d(
101
+ x_part_1, cos_cached_x, sin_cached_x, abs_positions_x
102
+ )
103
+ # 将与 abs_positions_y 相关的旋转应用于 x_part_2
104
+ rotated_part_2 = apply_rotary_emb_1d(
105
+ x_part_2, cos_cached_y, sin_cached_y, abs_positions_y
106
+ )
107
+
108
+ # 将它们重新拼接起来。确保顺序与你分割时一致。
109
+ return torch.cat((rotated_part_1, rotated_part_2), dim=-1)
110
+
111
+
112
+ class NEOVisionEmbeddings(nn.Module):
113
+ """
114
+ Embedding Module for Vision.
115
+ """
116
+
117
+ def __init__(self, config: NEOVisionConfig):
118
+ super().__init__()
119
+ self.config = config
120
+ self.embed_dim = config.hidden_size
121
+ self.llm_embed_dim = config.llm_hidden_size[0]
122
+ self.downsample_factor = int(1 / config.downsample_ratio[0])
123
+ self.patch_size = config.patch_size
124
+
125
+ self.patch_embedding = nn.Conv2d(
126
+ in_channels=config.num_channels, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size
127
+ )
128
+ self.dense_embedding = nn.Conv2d(
129
+ in_channels=self.embed_dim, out_channels=self.llm_embed_dim, kernel_size=self.downsample_factor, stride=self.downsample_factor
130
+ )
131
+ self.gelu = nn.GELU()
132
+
133
+ self.rope_dim_part = self.embed_dim // 2
134
+ cos_x, sin_x = precompute_rope_freqs_sincos(
135
+ self.rope_dim_part, config.max_position_embeddings_vision, base=config.rope_theta_vision, device=None
136
+ )
137
+ cos_y, sin_y = precompute_rope_freqs_sincos(
138
+ self.rope_dim_part, config.max_position_embeddings_vision, base=config.rope_theta_vision, device=None
139
+ )
140
+
141
+ self.register_buffer("cos_cached_x", cos_x, persistent=False)
142
+ self.register_buffer("sin_cached_x", sin_x, persistent=False)
143
+ self.register_buffer("cos_cached_y", cos_y, persistent=False)
144
+ self.register_buffer("sin_cached_y", sin_y, persistent=False)
145
+
146
+ def _apply_2d_rotary_pos_emb(self, patch_embeds, grid_hw):
147
+ """
148
+ Apply 2D Rotary Position Embedding to the patch embeddings.
149
+ """
150
+ abs_pos_x, abs_pos_y = build_abs_positions_from_grid_hw(grid_hw, device=patch_embeds.device)
151
+ embeddings = apply_2d_rotary_pos_emb(
152
+ patch_embeds.to(torch.float32), # RoPE calculations are often more stable in float32
153
+ self.cos_cached_x, self.sin_cached_x,
154
+ self.cos_cached_y, self.sin_cached_y,
155
+ abs_pos_x,
156
+ abs_pos_y
157
+ ).to(self.patch_embedding.weight.dtype)
158
+ return embeddings
159
+
160
+ def forward(self, pixel_values: torch.FloatTensor, grid_hw=None) -> torch.Tensor:
161
+
162
+ pixel_values = pixel_values.view( #
163
+ -1,
164
+ 3,
165
+ self.patch_size,
166
+ self.patch_size,
167
+ ) # [28072, 768] -> [28072, 3, 16, 16]
168
+ patch_embeds = self.gelu(self.patch_embedding(pixel_values)).view(-1, self.embed_dim)
169
+ self.cos_cached_x = self.cos_cached_x.to(patch_embeds.device)
170
+ self.sin_cached_x = self.sin_cached_x.to(patch_embeds.device)
171
+ self.cos_cached_y = self.cos_cached_y.to(patch_embeds.device)
172
+ self.sin_cached_y = self.sin_cached_y.to(patch_embeds.device)
173
+ patch_embeds = self._apply_2d_rotary_pos_emb(patch_embeds, grid_hw) # [28072, 1024]
174
+ assert (grid_hw[:,0] * grid_hw[:,1]).sum() == patch_embeds.shape[0]
175
+
176
+ patches_list = []
177
+ cur_position = 0
178
+ for i in range(grid_hw.shape[0]):
179
+ h, w = grid_hw[i]
180
+ patches_per_img = patch_embeds[cur_position : cur_position + h * w].view(h, w, -1).unsqueeze(0)
181
+ patches_per_img = self.dense_embedding(patches_per_img.permute(0, 3, 1, 2))
182
+ patches_per_img = patches_per_img.permute(0, 2, 3, 1)
183
+ patches_list.append(patches_per_img.view(-1, patches_per_img.shape[-1]))
184
+ cur_position += h * w
185
+
186
+ embeddings = torch.cat(patches_list, dim=0) # (N_total // downsample_factor**2, C)
187
+
188
+ assert cur_position == patch_embeds.shape[0]
189
+ assert embeddings.shape[0] == int(patch_embeds.shape[0] / self.downsample_factor**2)
190
+
191
+ return embeddings
192
+
193
+
194
+ class NEOVisionModel(PreTrainedModel):
195
+ main_input_name = 'pixel_values'
196
+ _supports_flash_attn_2 = True
197
+ supports_gradient_checkpointing = True
198
+ config_class = NEOVisionConfig
199
+ # support transformers 4.51.+
200
+ _tp_plan = ''
201
+
202
+ def __init__(self, config: NEOVisionConfig):
203
+ super().__init__(config)
204
+ self.config = config
205
+
206
+ self.embeddings = NEOVisionEmbeddings(config)
207
+
208
+ def forward(
209
+ self,
210
+ pixel_values: Optional[torch.FloatTensor] = None,
211
+ output_hidden_states: Optional[bool] = None,
212
+ return_dict: Optional[bool] = None,
213
+ pixel_embeds: Optional[torch.FloatTensor] = None,
214
+ grid_hw: Optional[torch.Tensor] = None
215
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
216
+ output_hidden_states = (
217
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
218
+ )
219
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
220
+
221
+ if pixel_values is None and pixel_embeds is None:
222
+ raise ValueError('You have to specify pixel_values or pixel_embeds')
223
+
224
+ if pixel_embeds is not None:
225
+ hidden_states = pixel_embeds
226
+ else:
227
+ assert pixel_values.dim() == 2, f"pixel_values must be 2D for native resolution, got: {pixel_values.dim()}"
228
+ hidden_states = self.embeddings(pixel_values, grid_hw=grid_hw)
229
+
230
+ return BaseModelOutputWithPooling(
231
+ last_hidden_state=hidden_states,
232
+ pooler_output=None,
233
+ hidden_states=None,
234
+ attentions=None,
235
+ )
modeling_qwen3.py ADDED
@@ -0,0 +1,1117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, Optional, Union
2
+
3
+ import torch
4
+ import torch._dynamo
5
+ from torch import nn
6
+
7
+ import copy
8
+ import math
9
+ from transformers.activations import ACT2FN
10
+ from transformers.cache_utils import Cache, DynamicCache
11
+ from transformers.generation import GenerationMixin
12
+ from transformers.integrations import use_kernel_forward_from_hub
13
+ from transformers.masking_utils import create_causal_mask
14
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
15
+ from transformers.modeling_layers import (
16
+ GenericForQuestionAnswering,
17
+ GenericForSequenceClassification,
18
+ GenericForTokenClassification,
19
+ GradientCheckpointingLayer,
20
+ )
21
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
22
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
23
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
24
+ from transformers.processing_utils import Unpack
25
+ from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
26
+ from transformers.utils.deprecation import deprecate_kwarg
27
+ from transformers.utils.generic import check_model_inputs
28
+ from transformers import Qwen3Config
29
+
30
+ from flash_attn import flash_attn_func
31
+
32
+
33
+ def create_block_causal_mask(index: torch.Tensor):
34
+ """
35
+ index: (L)
36
+ return: (1, 1, L, L) block-wise causal attention mask
37
+ """
38
+ L = index.size(0)
39
+ idx_i = index.unsqueeze(1).expand(L, L)
40
+ idx_j = index.unsqueeze(0).expand(L, L)
41
+
42
+ arange = torch.arange(L, device=index.device)
43
+ mask = (idx_j == idx_i) | (arange.unsqueeze(0) <= arange.unsqueeze(1))
44
+
45
+ return torch.where(mask[None, None, :, :] > 0, torch.tensor(0.0), torch.tensor(float('-inf')))
46
+
47
+
48
+ def visualize_mask(mask: torch.Tensor, i: int = 0, j: int = 12):
49
+ """
50
+ mask: (1,1, L, L)
51
+ """
52
+ submask = torch.where(mask[0, 0, :, :] == 0, torch.tensor(1.0), torch.tensor(0.0))
53
+ submask = mask[i:j, i:j].int().cpu().numpy()
54
+ for row in submask:
55
+ print(" ".join(map(str, row)))
56
+
57
+
58
+ @use_kernel_forward_from_hub("RMSNorm")
59
+ class Qwen3RMSNorm(nn.Module):
60
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
61
+ """
62
+ Qwen3RMSNorm is equivalent to T5LayerNorm
63
+ """
64
+ super().__init__()
65
+ self.weight = nn.Parameter(torch.ones(hidden_size))
66
+ self.variance_epsilon = eps
67
+
68
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
69
+ input_dtype = hidden_states.dtype
70
+ hidden_states = hidden_states.to(torch.float32)
71
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
72
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
73
+ return self.weight * hidden_states.to(input_dtype)
74
+
75
+ def extra_repr(self):
76
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
77
+
78
+
79
+ class Qwen3MLP(nn.Module):
80
+ def __init__(self, config):
81
+ super().__init__()
82
+ self.config = config
83
+ self.hidden_size = config.hidden_size
84
+ self.intermediate_size = config.intermediate_size
85
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
86
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
87
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
88
+ self.act_fn = ACT2FN[config.hidden_act]
89
+
90
+ def forward(self, x):
91
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
92
+ return down_proj
93
+
94
+
95
+ def rotate_half(x):
96
+ """Rotates half the hidden dims of the input."""
97
+ x1 = x[..., : x.shape[-1] // 2]
98
+ x2 = x[..., x.shape[-1] // 2 :]
99
+ return torch.cat((-x2, x1), dim=-1)
100
+
101
+
102
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
103
+ """Applies Rotary Position Embedding to the query and key tensors.
104
+
105
+ Args:
106
+ q (`torch.Tensor`): The query tensor.
107
+ k (`torch.Tensor`): The key tensor.
108
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
109
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
110
+ position_ids (`torch.Tensor`, *optional*):
111
+ Deprecated and unused.
112
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
113
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
114
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
115
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
116
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
117
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
118
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
119
+ Returns:
120
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
121
+ """
122
+ cos = cos.unsqueeze(unsqueeze_dim)
123
+ sin = sin.unsqueeze(unsqueeze_dim)
124
+ q_embed = (q * cos) + (rotate_half(q) * sin)
125
+ k_embed = (k * cos) + (rotate_half(k) * sin)
126
+ return q_embed, k_embed
127
+
128
+
129
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
130
+ """
131
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
132
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
133
+ """
134
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
135
+ if n_rep == 1:
136
+ return hidden_states
137
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
138
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
139
+
140
+
141
+ def eager_attention_forward(
142
+ module: nn.Module,
143
+ query: torch.Tensor,
144
+ key: torch.Tensor,
145
+ value: torch.Tensor,
146
+ attention_mask: Optional[torch.Tensor],
147
+ scaling: float,
148
+ dropout: float = 0.0,
149
+ **kwargs: Unpack[TransformersKwargs],
150
+ ):
151
+ key_states = repeat_kv(key, module.num_key_value_groups)
152
+ value_states = repeat_kv(value, module.num_key_value_groups)
153
+
154
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
155
+ if attention_mask is not None:
156
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
157
+ attn_weights = attn_weights + causal_mask
158
+
159
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
160
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
161
+ attn_output = torch.matmul(attn_weights, value_states)
162
+ attn_output = attn_output.transpose(1, 2).contiguous()
163
+
164
+ return attn_output, attn_weights
165
+
166
+
167
+ class Qwen3RotaryEmbedding(nn.Module):
168
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
169
+
170
+ def __init__(self, config: Qwen3Config, device=None):
171
+ super().__init__()
172
+ # BC: "rope_type" was originally "type"
173
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
174
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
175
+ else:
176
+ self.rope_type = "default"
177
+ self.max_seq_len_cached = config.max_position_embeddings
178
+ self.original_max_seq_len = config.max_position_embeddings
179
+
180
+ self.config = config
181
+ base_rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
182
+
183
+ def _rope_init_fn_keep_freq_range(cfg: Qwen3Config, dev=None):
184
+ inv_freq, attention_scaling = base_rope_init_fn(cfg, dev)
185
+
186
+ cfg2 = copy.deepcopy(cfg)
187
+ head_dim = getattr(cfg2, "head_dim", None)
188
+ if head_dim is None:
189
+ head_dim = cfg2.hidden_size // cfg2.num_attention_heads
190
+ setattr(cfg2, "head_dim", head_dim)
191
+ cfg2.head_dim = int(head_dim) * 2
192
+
193
+ inv_freq_full, _ = base_rope_init_fn(cfg2, dev)
194
+ inv_freq = inv_freq_full[::2]
195
+
196
+ return inv_freq, attention_scaling
197
+
198
+ self.rope_init_fn = _rope_init_fn_keep_freq_range
199
+
200
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
201
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
202
+ self.original_inv_freq = self.inv_freq
203
+
204
+ @torch.no_grad()
205
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
206
+ def forward(self, x, position_ids):
207
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
208
+ position_ids_expanded = position_ids[:, None, :].float()
209
+
210
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
211
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
212
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
213
+ emb = torch.cat((freqs, freqs), dim=-1)
214
+ cos = emb.cos() * self.attention_scaling
215
+ sin = emb.sin() * self.attention_scaling
216
+
217
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
218
+
219
+
220
+ class Qwen3Attention(nn.Module):
221
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
222
+
223
+ def __init__(self, config: Qwen3Config, layer_idx: int):
224
+ super().__init__()
225
+ self.config = config
226
+ self.layer_idx = layer_idx
227
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
228
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
229
+ self.scaling = self.head_dim**-0.5
230
+ self.attention_dropout = config.attention_dropout
231
+ self.is_causal = True
232
+
233
+ self.q_proj = nn.Linear(
234
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
235
+ )
236
+ self.q_proj_mot_gen = nn.Linear(
237
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
238
+ )
239
+
240
+ self.k_proj = nn.Linear(
241
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
242
+ )
243
+ self.k_proj_mot_gen = nn.Linear(
244
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
245
+ )
246
+
247
+ self.v_proj = nn.Linear(
248
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
249
+ )
250
+ self.v_proj_mot_gen = nn.Linear(
251
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
252
+ )
253
+ self.o_proj = nn.Linear(
254
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
255
+ )
256
+ self.o_proj_mot_gen = nn.Linear(
257
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
258
+ )
259
+
260
+ self.q_norm = Qwen3RMSNorm(self.head_dim // 2, eps=config.rms_norm_eps) # unlike olmo, only on the head dim!
261
+ self.q_norm_mot_gen = Qwen3RMSNorm(self.head_dim // 2, eps=config.rms_norm_eps)
262
+ self.q_norm_hw = Qwen3RMSNorm(self.head_dim // 2, eps=config.rms_norm_eps)
263
+ self.q_norm_hw_mot_gen = Qwen3RMSNorm(self.head_dim // 2, eps=config.rms_norm_eps)
264
+
265
+ self.k_norm = Qwen3RMSNorm(self.head_dim // 2, eps=config.rms_norm_eps) # thus post q_norm does not need reshape
266
+ self.k_norm_mot_gen = Qwen3RMSNorm(self.head_dim // 2, eps=config.rms_norm_eps)
267
+ self.k_norm_hw = Qwen3RMSNorm(self.head_dim // 2, eps=config.rms_norm_eps) # thus post q_norm does not need reshape
268
+ self.k_norm_hw_mot_gen = Qwen3RMSNorm(self.head_dim // 2, eps=config.rms_norm_eps)
269
+
270
+ self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None
271
+
272
+ t_config = copy.deepcopy(config)
273
+ t_config.head_dim = config.head_dim // 2
274
+ self.rotary_emb = Qwen3RotaryEmbedding(config=t_config)
275
+
276
+ hw_config = copy.deepcopy(config)
277
+ hw_config.head_dim = config.head_dim // 4
278
+ hw_config.rope_theta = config.rope_theta_hw
279
+ hw_config.max_position_embeddings = config.max_position_embeddings_hw
280
+ self.rotary_emb_hw = Qwen3RotaryEmbedding(config=hw_config)
281
+
282
+ def forward_und(
283
+ self,
284
+ hidden_states: torch.Tensor,
285
+ indexes: Optional[torch.LongTensor],
286
+ attention_mask: Optional[torch.Tensor],
287
+ past_key_values: Optional[Cache] = None,
288
+ cache_position: Optional[torch.LongTensor] = None,
289
+ **kwargs: Unpack[FlashAttentionKwargs],
290
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
291
+ assert self.config._attn_implementation == "eager"
292
+ input_shape = hidden_states.shape[:-1]
293
+ hidden_shape = (*input_shape, -1, self.head_dim)
294
+
295
+ query_states = self.q_proj(hidden_states).view(hidden_shape)
296
+ query_states_t, query_states_hw = query_states.chunk(2, dim=-1)
297
+ query_states_t = self.q_norm(query_states_t).transpose(1, 2)
298
+ query_states_hw = self.q_norm_hw(query_states_hw).transpose(1, 2)
299
+ query_states_h, query_states_w = query_states_hw.chunk(2, dim=-1)
300
+
301
+ key_states = self.k_proj(hidden_states).view(hidden_shape)
302
+ key_states_t, key_states_hw = key_states.chunk(2, dim=-1)
303
+ key_states_t = self.k_norm(key_states_t).transpose(1, 2)
304
+ key_states_hw = self.k_norm_hw(key_states_hw).transpose(1, 2)
305
+ key_states_h, key_states_w = key_states_hw.chunk(2, dim=-1)
306
+
307
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
308
+
309
+ cos_t, sin_t = self.rotary_emb(hidden_states, indexes[0].unsqueeze(0))
310
+ query_states_t, key_states_t = apply_rotary_pos_emb(query_states_t, key_states_t, cos_t, sin_t)
311
+
312
+ cos_h, sin_h = self.rotary_emb_hw(hidden_states, indexes[1].unsqueeze(0))
313
+ query_states_h, key_states_h = apply_rotary_pos_emb(query_states_h, key_states_h, cos_h, sin_h)
314
+
315
+ cos_w, sin_w = self.rotary_emb_hw(hidden_states, indexes[2].unsqueeze(0))
316
+ query_states_w, key_states_w = apply_rotary_pos_emb(query_states_w, key_states_w, cos_w, sin_w)
317
+
318
+ query_states = torch.cat([query_states_t, query_states_h, query_states_w], dim=-1)
319
+ key_states = torch.cat([key_states_t, key_states_h, key_states_w], dim=-1)
320
+
321
+
322
+ if past_key_values is not None:
323
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
324
+ # cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
325
+ # key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
326
+ update_cache = kwargs.get("update_cache", True)
327
+ if update_cache:
328
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs=None)
329
+ else:
330
+ # only use the past key values but do not append the current one
331
+ layer = past_key_values.layers[self.layer_idx]
332
+ past_k, past_v = layer.keys, layer.values
333
+
334
+ if past_k is not None:
335
+ key_states = torch.cat([past_k, key_states], dim=2) # concat on seq_len
336
+ value_states = torch.cat([past_v, value_states], dim=2)
337
+
338
+ attention_interface: Callable = eager_attention_forward
339
+ if self.config._attn_implementation != "eager":
340
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
341
+
342
+ attn_output, attn_weights = attention_interface(
343
+ self,
344
+ query_states,
345
+ key_states,
346
+ value_states,
347
+ attention_mask,
348
+ dropout=0.0 if not self.training else self.attention_dropout,
349
+ scaling=self.scaling,
350
+ sliding_window=self.sliding_window, # diff with Llama
351
+ **kwargs,
352
+ )
353
+
354
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
355
+ attn_output = self.o_proj(attn_output)
356
+ return attn_output, attn_weights
357
+
358
+ # def forward_gen(
359
+ # self,
360
+ # hidden_states: torch.Tensor,
361
+ # indexes: Optional[torch.LongTensor],
362
+ # attention_mask: Optional[torch.Tensor],
363
+ # past_key_values: Optional[Cache] = None,
364
+ # cache_position: Optional[torch.LongTensor] = None,
365
+ # **kwargs: Unpack[FlashAttentionKwargs],
366
+ # ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
367
+ # assert self.config._attn_implementation == "eager"
368
+ # input_shape = hidden_states.shape[:-1]
369
+ # hidden_shape = (*input_shape, -1, self.head_dim)
370
+
371
+ # query_states = self.q_proj_mot_gen(hidden_states).view(hidden_shape)
372
+ # query_states_t, query_states_hw = query_states.chunk(2, dim=-1)
373
+ # query_states_t = self.q_norm_mot_gen(query_states_t).transpose(1, 2)
374
+ # query_states_hw = self.q_norm_hw_mot_gen(query_states_hw).transpose(1, 2)
375
+ # query_states_h, query_states_w = query_states_hw.chunk(2, dim=-1)
376
+
377
+ # key_states = self.k_proj_mot_gen(hidden_states).view(hidden_shape)
378
+ # key_states_t, key_states_hw = key_states.chunk(2, dim=-1)
379
+ # key_states_t = self.k_norm_mot_gen(key_states_t).transpose(1, 2)
380
+ # key_states_hw = self.k_norm_hw_mot_gen(key_states_hw).transpose(1, 2)
381
+ # key_states_h, key_states_w = key_states_hw.chunk(2, dim=-1)
382
+
383
+ # value_states = self.v_proj_mot_gen(hidden_states).view(hidden_shape).transpose(1, 2)
384
+
385
+ # cos_t, sin_t = self.rotary_emb(hidden_states, indexes[0].unsqueeze(0))
386
+ # query_states_t, key_states_t = apply_rotary_pos_emb(query_states_t, key_states_t, cos_t, sin_t)
387
+
388
+ # cos_h, sin_h = self.rotary_emb_hw(hidden_states, indexes[1].unsqueeze(0))
389
+ # query_states_h, key_states_h = apply_rotary_pos_emb(query_states_h, key_states_h, cos_h, sin_h)
390
+
391
+ # cos_w, sin_w = self.rotary_emb_hw(hidden_states, indexes[2].unsqueeze(0))
392
+ # query_states_w, key_states_w = apply_rotary_pos_emb(query_states_w, key_states_w, cos_w, sin_w)
393
+
394
+ # query_states = torch.cat([query_states_t, query_states_h, query_states_w], dim=-1)
395
+ # key_states = torch.cat([key_states_t, key_states_h, key_states_w], dim=-1)
396
+
397
+
398
+ # if past_key_values is not None:
399
+ # # sin and cos are specific to RoPE models; cache_position needed for the static cache
400
+ # # cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
401
+ # # key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
402
+ # update_cache = kwargs.get("update_cache", True)
403
+ # if update_cache:
404
+ # key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs=None)
405
+ # else:
406
+ # # only use the past key values but do not append the current one
407
+ # layer = past_key_values.layers[self.layer_idx]
408
+ # past_k, past_v = layer.keys, layer.values
409
+
410
+ # if past_k is not None:
411
+ # key_states = torch.cat([past_k, key_states], dim=2) # concat on seq_len
412
+ # value_states = torch.cat([past_v, value_states], dim=2)
413
+
414
+ # attention_interface: Callable = eager_attention_forward
415
+ # if self.config._attn_implementation != "eager":
416
+ # attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
417
+
418
+ # attn_output, attn_weights = attention_interface(
419
+ # self,
420
+ # query_states,
421
+ # key_states,
422
+ # value_states,
423
+ # attention_mask,
424
+ # dropout=0.0 if not self.training else self.attention_dropout,
425
+ # scaling=self.scaling,
426
+ # sliding_window=self.sliding_window, # diff with Llama
427
+ # **kwargs,
428
+ # )
429
+
430
+ # attn_output = attn_output.reshape(*input_shape, -1).contiguous()
431
+ # attn_output = self.o_proj_mot_gen(attn_output)
432
+ # return attn_output, attn_weights
433
+
434
+ def forward_gen(
435
+ self,
436
+ hidden_states: torch.Tensor,
437
+ indexes: Optional[torch.LongTensor],
438
+ attention_mask: Optional[torch.Tensor],
439
+ past_key_values: Optional[Cache] = None,
440
+ cache_position: Optional[torch.LongTensor] = None,
441
+ **kwargs: Unpack[FlashAttentionKwargs],
442
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
443
+ input_shape = hidden_states.shape[:-1]
444
+ hidden_shape = (*input_shape, -1, self.head_dim)
445
+
446
+ # -----------------------------
447
+ # Build q / k / v for current tokens
448
+ # Internal layout before flash:
449
+ # q/k/v: [B, H, S, D]
450
+ # Flash layout:
451
+ # q/k/v: [B, S, H, D]
452
+ # -----------------------------
453
+ query_states = self.q_proj_mot_gen(hidden_states).view(hidden_shape)
454
+ query_states_t, query_states_hw = query_states.chunk(2, dim=-1)
455
+ query_states_t = self.q_norm_mot_gen(query_states_t).transpose(1, 2) # [B,H,S,D/2]
456
+ query_states_hw = self.q_norm_hw_mot_gen(query_states_hw).transpose(1, 2)
457
+ query_states_h, query_states_w = query_states_hw.chunk(2, dim=-1)
458
+
459
+ key_states = self.k_proj_mot_gen(hidden_states).view(hidden_shape)
460
+ key_states_t, key_states_hw = key_states.chunk(2, dim=-1)
461
+ key_states_t = self.k_norm_mot_gen(key_states_t).transpose(1, 2) # [B,H,S,D/2]
462
+ key_states_hw = self.k_norm_hw_mot_gen(key_states_hw).transpose(1, 2)
463
+ key_states_h, key_states_w = key_states_hw.chunk(2, dim=-1)
464
+
465
+ value_states = self.v_proj_mot_gen(hidden_states).view(hidden_shape).transpose(1, 2) # [B,H,S,D]
466
+
467
+ # RoPE
468
+ cos_t, sin_t = self.rotary_emb(hidden_states, indexes[0].unsqueeze(0))
469
+ query_states_t, key_states_t = apply_rotary_pos_emb(query_states_t, key_states_t, cos_t, sin_t)
470
+
471
+ cos_h, sin_h = self.rotary_emb_hw(hidden_states, indexes[1].unsqueeze(0))
472
+ query_states_h, key_states_h = apply_rotary_pos_emb(query_states_h, key_states_h, cos_h, sin_h)
473
+
474
+ cos_w, sin_w = self.rotary_emb_hw(hidden_states, indexes[2].unsqueeze(0))
475
+ query_states_w, key_states_w = apply_rotary_pos_emb(query_states_w, key_states_w, cos_w, sin_w)
476
+
477
+ # concat along head_dim
478
+ # query/key current layout: [B, H, S, D]
479
+ query_states = torch.cat([query_states_t, query_states_h, query_states_w], dim=-1)
480
+ key_states = torch.cat([key_states_t, key_states_h, key_states_w], dim=-1)
481
+
482
+ update_cache = kwargs.get("update_cache", True)
483
+
484
+ # ------------------------------------------------------------------
485
+ # Flash path:
486
+ # Only use when there is no explicit dense mask.
487
+ # This is exactly the t2i denoising use case:
488
+ # current image tokens attend to [prefix + current image tokens]
489
+ # fully bidirectional inside current block => causal=False
490
+ # ------------------------------------------------------------------
491
+ if attention_mask is None:
492
+ # Convert current q/k/v to flash layout [B, S, H, D]
493
+ q = query_states.transpose(1, 2).contiguous()
494
+ k_cur = key_states.transpose(1, 2).contiguous()
495
+ v_cur = value_states.transpose(1, 2).contiguous()
496
+
497
+ if past_key_values is not None:
498
+ if update_cache:
499
+ # Rare path, keep compatibility.
500
+ # past_key_values.update expects [B,H,S,D]
501
+ key_states, value_states = past_key_values.update(
502
+ key_states, value_states, self.layer_idx, cache_kwargs=None
503
+ )
504
+ k = key_states.transpose(1, 2).contiguous()
505
+ v = value_states.transpose(1, 2).contiguous()
506
+ else:
507
+ # Optimized path:
508
+ # use preallocated flash_k_cache / flash_v_cache
509
+ layer = past_key_values.layers[self.layer_idx]
510
+
511
+ if (
512
+ hasattr(layer, "flash_k_cache")
513
+ and layer.flash_k_cache is not None
514
+ and hasattr(layer, "flash_v_cache")
515
+ and layer.flash_v_cache is not None
516
+ ):
517
+ prefix_len = layer.flash_prefix_len
518
+ cur_len = k_cur.shape[1]
519
+
520
+ # overwrite current segment in-place
521
+ layer.flash_k_cache[:, prefix_len:prefix_len + cur_len].copy_(k_cur)
522
+ layer.flash_v_cache[:, prefix_len:prefix_len + cur_len].copy_(v_cur)
523
+
524
+ k = layer.flash_k_cache[:, :prefix_len + cur_len]
525
+ v = layer.flash_v_cache[:, :prefix_len + cur_len]
526
+ else:
527
+ # fallback if user forgot to prepare flash cache
528
+ layer = past_key_values.layers[self.layer_idx]
529
+ past_k, past_v = layer.keys, layer.values
530
+
531
+ if past_k is not None:
532
+ past_k = past_k.transpose(1, 2).contiguous()
533
+ past_v = past_v.transpose(1, 2).contiguous()
534
+ k = torch.cat([past_k, k_cur], dim=1)
535
+ v = torch.cat([past_v, v_cur], dim=1)
536
+ else:
537
+ k = k_cur
538
+ v = v_cur
539
+ else:
540
+ k = k_cur
541
+ v = v_cur
542
+
543
+ # sanity checks
544
+ assert q.ndim == 4 and k.ndim == 4 and v.ndim == 4
545
+ assert q.shape[0] == k.shape[0] == v.shape[0], (q.shape, k.shape, v.shape)
546
+ assert k.shape[1] == v.shape[1], (k.shape, v.shape)
547
+ assert k.shape[2] == v.shape[2], (k.shape, v.shape)
548
+ assert q.shape[3] == k.shape[3] == v.shape[3], (q.shape, k.shape, v.shape)
549
+
550
+ attn_output = flash_attn_func(
551
+ q,
552
+ k,
553
+ v,
554
+ dropout_p=0.0 if not self.training else self.attention_dropout,
555
+ softmax_scale=self.scaling,
556
+ causal=False,
557
+ ) # [B, S_q, H_q, D]
558
+
559
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
560
+ attn_output = self.o_proj_mot_gen(attn_output)
561
+ return attn_output, None
562
+
563
+ # ------------------------------------------------------------------
564
+ # Original eager fallback path
565
+ # ------------------------------------------------------------------
566
+ if past_key_values is not None:
567
+ if update_cache:
568
+ key_states, value_states = past_key_values.update(
569
+ key_states, value_states, self.layer_idx, cache_kwargs=None
570
+ )
571
+ else:
572
+ layer = past_key_values.layers[self.layer_idx]
573
+ past_k, past_v = layer.keys, layer.values
574
+ if past_k is not None:
575
+ key_states = torch.cat([past_k, key_states], dim=2)
576
+ value_states = torch.cat([past_v, value_states], dim=2)
577
+
578
+ attention_interface: Callable = eager_attention_forward
579
+ if self.config._attn_implementation != "eager":
580
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
581
+
582
+ attn_output, attn_weights = attention_interface(
583
+ self,
584
+ query_states,
585
+ key_states,
586
+ value_states,
587
+ attention_mask,
588
+ dropout=0.0 if not self.training else self.attention_dropout,
589
+ scaling=self.scaling,
590
+ sliding_window=self.sliding_window,
591
+ **kwargs,
592
+ )
593
+
594
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
595
+ attn_output = self.o_proj_mot_gen(attn_output)
596
+ return attn_output, attn_weights
597
+
598
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
599
+ def forward(
600
+ self,
601
+ hidden_states: torch.Tensor,
602
+ image_gen_indicators: torch.Tensor,
603
+ exist_non_image_gen_tokens: bool,
604
+ exist_image_gen_tokens: bool,
605
+ indexes: Optional[torch.LongTensor],
606
+ attention_mask: Optional[torch.Tensor],
607
+ past_key_values: Optional[Cache] = None,
608
+ cache_position: Optional[torch.LongTensor] = None,
609
+ **kwargs: Unpack[FlashAttentionKwargs],
610
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
611
+ if exist_non_image_gen_tokens and not exist_image_gen_tokens:
612
+ return self.forward_und(hidden_states, indexes, attention_mask, past_key_values, cache_position, **kwargs)
613
+ if not exist_non_image_gen_tokens and exist_image_gen_tokens:
614
+ return self.forward_gen(hidden_states, indexes, attention_mask, past_key_values, cache_position, **kwargs)
615
+
616
+ assert self.config._attn_implementation == "eager"
617
+ input_shape = hidden_states.shape[:-1]
618
+ hidden_shape = (*input_shape, -1, self.head_dim)
619
+
620
+ query_states = hidden_states.new_zeros((*input_shape, self.config.num_attention_heads*self.head_dim))
621
+ if exist_non_image_gen_tokens:
622
+ query_states[~image_gen_indicators] = self.q_proj(hidden_states[~image_gen_indicators])
623
+ if exist_image_gen_tokens:
624
+ query_states[image_gen_indicators] = self.q_proj_mot_gen(hidden_states[image_gen_indicators])
625
+ query_states_t, query_states_hw = query_states.chunk(2, dim=-1)
626
+
627
+ _query_states_hw = query_states_hw.new_zeros(query_states_hw.shape)
628
+ if exist_non_image_gen_tokens:
629
+ _query_states_hw[~image_gen_indicators] = self.q_norm_hw(query_states_hw[~image_gen_indicators])
630
+ if exist_image_gen_tokens:
631
+ _query_states_hw[image_gen_indicators] = self.q_norm_hw_mot_gen(query_states_h[image_gen_indicators])
632
+ query_states_hw = _query_states_hw.transpose(1, 2)
633
+ query_states_h, query_states_w = query_states_hw.chunk(2, dim=-1)
634
+
635
+ key_states = hidden_states.new_zeros((*input_shape, self.config.num_key_value_heads*self.head_dim))
636
+ if exist_non_image_gen_tokens:
637
+ key_states[~image_gen_indicators] = self.k_proj(hidden_states[~image_gen_indicators])
638
+ if exist_image_gen_tokens:
639
+ key_states[image_gen_indicators] = self.k_proj_mot_gen(hidden_states[image_gen_indicators])
640
+ key_states_t, key_states_hw = key_states.chunk(2, dim=-1)
641
+
642
+ _key_states_hw = key_states_hw.new_zeros(key_states_hw.shape)
643
+ if exist_non_image_gen_tokens:
644
+ _key_states_hw[~image_gen_indicators] = self.k_norm_hw(key_states_hw[~image_gen_indicators])
645
+ if exist_image_gen_tokens:
646
+ _key_states_hw[image_gen_indicators] = self.k_norm_hw_mot_gen(key_states_h[image_gen_indicators])
647
+ key_states_hw = _key_states_hw.transpose(1, 2)
648
+ key_states_h, key_states_w = key_states_hw.chunk(2, dim=-1)
649
+
650
+ value_states = hidden_states.new_zeros((*input_shape, self.config.num_key_value_heads*self.head_dim))
651
+ if exist_non_image_gen_tokens:
652
+ value_states[~image_gen_indicators] = self.v_proj(hidden_states[~image_gen_indicators])
653
+ if exist_image_gen_tokens:
654
+ value_states[image_gen_indicators] = self.v_proj_mot_gen(hidden_states[image_gen_indicators])
655
+ value_states = value_states.view(hidden_shape).transpose(1, 2)
656
+
657
+ cos_t, sin_t = self.rotary_emb(hidden_states, indexes[0].unsqueeze(0))
658
+ query_states_t, key_states_t = apply_rotary_pos_emb(query_states_t, key_states_t, cos_t, sin_t)
659
+
660
+ cos_h, sin_h = self.rotary_emb_hw(hidden_states, indexes[1].unsqueeze(0))
661
+ query_states_h, key_states_h = apply_rotary_pos_emb(query_states_h, key_states_h, cos_h, sin_h)
662
+
663
+ cos_w, sin_w = self.rotary_emb_hw(hidden_states, indexes[2].unsqueeze(0))
664
+ query_states_w, key_states_w = apply_rotary_pos_emb(query_states_w, key_states_w, cos_w, sin_w)
665
+
666
+ query_states = torch.cat([query_states_t, query_states_h, query_states_w], dim=-1)
667
+ key_states = torch.cat([key_states_t, key_states_h, key_states_w], dim=-1)
668
+
669
+
670
+ if past_key_values is not None:
671
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
672
+ # cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
673
+ # key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
674
+ update_cache = kwargs.get("update_cache", True)
675
+ if update_cache:
676
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs=None)
677
+ else:
678
+ # only use the past key values but do not append the current one
679
+ layer = past_key_values.layers[self.layer_idx]
680
+ past_k, past_v = layer.keys, layer.values
681
+
682
+ if past_k is not None:
683
+ key_states = torch.cat([past_k, key_states], dim=2) # concat on seq_len
684
+ value_states = torch.cat([past_v, value_states], dim=2)
685
+
686
+ attention_interface: Callable = eager_attention_forward
687
+ if self.config._attn_implementation != "eager":
688
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
689
+
690
+ attn_output, attn_weights = attention_interface(
691
+ self,
692
+ query_states,
693
+ key_states,
694
+ value_states,
695
+ attention_mask,
696
+ dropout=0.0 if not self.training else self.attention_dropout,
697
+ scaling=self.scaling,
698
+ sliding_window=self.sliding_window, # diff with Llama
699
+ **kwargs,
700
+ )
701
+
702
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
703
+
704
+ _attn_output = attn_output.new_zeros((*input_shape, self.config.hidden_size))
705
+ if exist_non_image_gen_tokens:
706
+ _attn_output[~image_gen_indicators] = self.o_proj(attn_output[~image_gen_indicators])
707
+ if exist_image_gen_tokens:
708
+ _attn_output[image_gen_indicators] = self.o_proj_mot_gen(attn_output[image_gen_indicators])
709
+
710
+ attn_output = _attn_output
711
+ return attn_output, attn_weights
712
+
713
+
714
+ class Qwen3DecoderLayer(GradientCheckpointingLayer):
715
+ def __init__(self, config: Qwen3Config, layer_idx: int):
716
+ super().__init__()
717
+ self.hidden_size = config.hidden_size
718
+
719
+ self.self_attn = Qwen3Attention(config=config, layer_idx=layer_idx)
720
+
721
+ self.mlp = Qwen3MLP(config)
722
+ self.mlp_mot_gen = Qwen3MLP(config)
723
+ self.input_layernorm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
724
+ self.input_layernorm_mot_gen = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
725
+ self.post_attention_layernorm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
726
+ self.post_attention_layernorm_mot_gen = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
727
+ self.attention_type = config.layer_types[layer_idx]
728
+
729
+ def forward_und(
730
+ self,
731
+ hidden_states: torch.Tensor,
732
+ image_gen_indicators: torch.Tensor,
733
+ exist_non_image_gen_tokens: bool,
734
+ exist_image_gen_tokens: bool,
735
+ indexes: Optional[torch.LongTensor] = None,
736
+ attention_mask: Optional[torch.Tensor] = None,
737
+ position_ids: Optional[torch.LongTensor] = None,
738
+ past_key_values: Optional[Cache] = None,
739
+ use_cache: Optional[bool] = False,
740
+ cache_position: Optional[torch.LongTensor] = None,
741
+ **kwargs: Unpack[TransformersKwargs],
742
+ ) -> torch.Tensor:
743
+ residual = hidden_states
744
+ hidden_states = self.input_layernorm(hidden_states)
745
+ # Self Attention
746
+ hidden_states, _ = self.self_attn(
747
+ hidden_states=hidden_states,
748
+ image_gen_indicators=image_gen_indicators,
749
+ exist_non_image_gen_tokens=exist_non_image_gen_tokens,
750
+ exist_image_gen_tokens=exist_image_gen_tokens,
751
+ indexes=indexes,
752
+ attention_mask=attention_mask,
753
+ position_ids=position_ids,
754
+ past_key_values=past_key_values,
755
+ use_cache=use_cache,
756
+ cache_position=cache_position,
757
+ **kwargs,
758
+ )
759
+ hidden_states = residual + hidden_states
760
+
761
+ # Fully Connected
762
+ residual = hidden_states
763
+ hidden_states = self.post_attention_layernorm(hidden_states)
764
+ hidden_states = self.mlp(hidden_states)
765
+ hidden_states = residual + hidden_states
766
+ return hidden_states
767
+
768
+ def forward_gen(
769
+ self,
770
+ hidden_states: torch.Tensor,
771
+ image_gen_indicators: torch.Tensor,
772
+ exist_non_image_gen_tokens: bool,
773
+ exist_image_gen_tokens: bool,
774
+ indexes: Optional[torch.LongTensor] = None,
775
+ attention_mask: Optional[torch.Tensor] = None,
776
+ position_ids: Optional[torch.LongTensor] = None,
777
+ past_key_values: Optional[Cache] = None,
778
+ use_cache: Optional[bool] = False,
779
+ cache_position: Optional[torch.LongTensor] = None,
780
+ **kwargs: Unpack[TransformersKwargs],
781
+ ) -> torch.Tensor:
782
+ residual = hidden_states
783
+ hidden_states = self.input_layernorm_mot_gen(hidden_states)
784
+ # Self Attention
785
+ hidden_states, _ = self.self_attn(
786
+ hidden_states=hidden_states,
787
+ image_gen_indicators=image_gen_indicators,
788
+ exist_non_image_gen_tokens=exist_non_image_gen_tokens,
789
+ exist_image_gen_tokens=exist_image_gen_tokens,
790
+ indexes=indexes,
791
+ attention_mask=attention_mask,
792
+ position_ids=position_ids,
793
+ past_key_values=past_key_values,
794
+ use_cache=use_cache,
795
+ cache_position=cache_position,
796
+ **kwargs,
797
+ )
798
+ hidden_states = residual + hidden_states
799
+
800
+ # Fully Connected
801
+ residual = hidden_states
802
+ hidden_states = self.post_attention_layernorm_mot_gen(hidden_states)
803
+ hidden_states = self.mlp_mot_gen(hidden_states)
804
+ hidden_states = residual + hidden_states
805
+ return hidden_states
806
+
807
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
808
+ def forward(
809
+ self,
810
+ hidden_states: torch.Tensor,
811
+ image_gen_indicators: torch.Tensor,
812
+ exist_non_image_gen_tokens: bool,
813
+ exist_image_gen_tokens: bool,
814
+ indexes: Optional[torch.LongTensor] = None,
815
+ attention_mask: Optional[torch.Tensor] = None,
816
+ position_ids: Optional[torch.LongTensor] = None,
817
+ past_key_values: Optional[Cache] = None,
818
+ use_cache: Optional[bool] = False,
819
+ cache_position: Optional[torch.LongTensor] = None,
820
+ **kwargs: Unpack[TransformersKwargs],
821
+ ) -> torch.Tensor:
822
+ if exist_non_image_gen_tokens and not exist_image_gen_tokens:
823
+ return self.forward_und(hidden_states, image_gen_indicators, exist_non_image_gen_tokens, exist_image_gen_tokens, indexes, attention_mask, position_ids, past_key_values, use_cache, cache_position, **kwargs)
824
+ if not exist_non_image_gen_tokens and exist_image_gen_tokens:
825
+ return self.forward_gen(hidden_states, image_gen_indicators, exist_non_image_gen_tokens, exist_image_gen_tokens, indexes, attention_mask, position_ids, past_key_values, use_cache, cache_position, **kwargs)
826
+
827
+ residual = hidden_states
828
+
829
+ _hidden_states = hidden_states.new_zeros(hidden_states.shape)
830
+ if exist_non_image_gen_tokens:
831
+ _hidden_states[~image_gen_indicators] = self.input_layernorm(hidden_states[~image_gen_indicators])
832
+ if exist_image_gen_tokens:
833
+ _hidden_states[image_gen_indicators] = self.input_layernorm_mot_gen(hidden_states[image_gen_indicators])
834
+ hidden_states = _hidden_states
835
+
836
+ # Self Attention
837
+ hidden_states, _ = self.self_attn(
838
+ hidden_states=hidden_states,
839
+ image_gen_indicators=image_gen_indicators,
840
+ exist_non_image_gen_tokens=exist_non_image_gen_tokens,
841
+ exist_image_gen_tokens=exist_image_gen_tokens,
842
+ indexes=indexes,
843
+ attention_mask=attention_mask,
844
+ position_ids=position_ids,
845
+ past_key_values=past_key_values,
846
+ use_cache=use_cache,
847
+ cache_position=cache_position,
848
+ **kwargs,
849
+ )
850
+ hidden_states = residual + hidden_states
851
+
852
+ # Fully Connected
853
+ residual = hidden_states
854
+
855
+ _hidden_states = hidden_states.new_zeros(hidden_states.shape)
856
+ if exist_non_image_gen_tokens:
857
+ _hidden_states[~image_gen_indicators] = self.mlp(self.post_attention_layernorm(hidden_states[~image_gen_indicators]))
858
+
859
+ if exist_image_gen_tokens:
860
+ _hidden_states[image_gen_indicators] = self.mlp_mot_gen(self.post_attention_layernorm_mot_gen(hidden_states[image_gen_indicators]))
861
+
862
+ hidden_states = _hidden_states
863
+ hidden_states = residual + hidden_states
864
+ return hidden_states
865
+
866
+
867
+ @auto_docstring
868
+ class Qwen3PreTrainedModel(PreTrainedModel):
869
+ config: Qwen3Config
870
+ base_model_prefix = "model"
871
+ supports_gradient_checkpointing = True
872
+ _no_split_modules = ["Qwen3DecoderLayer"]
873
+ _skip_keys_device_placement = ["past_key_values"]
874
+ _supports_flash_attn = True
875
+ _supports_sdpa = True
876
+ _supports_flex_attn = True
877
+
878
+ _can_compile_fullgraph = True
879
+ _supports_attention_backend = True
880
+ _can_record_outputs = {
881
+ "hidden_states": Qwen3DecoderLayer,
882
+ "attentions": Qwen3Attention,
883
+ }
884
+
885
+
886
+ @auto_docstring
887
+ class Qwen3Model(Qwen3PreTrainedModel):
888
+ def __init__(self, config: Qwen3Config):
889
+ super().__init__(config)
890
+ self.padding_idx = config.pad_token_id
891
+ self.vocab_size = config.vocab_size
892
+
893
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
894
+ self.layers = nn.ModuleList(
895
+ [Qwen3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
896
+ )
897
+ self.norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
898
+ self.norm_mot_gen = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
899
+
900
+ self.gradient_checkpointing = False
901
+ self.has_sliding_layers = "sliding_attention" in self.config.layer_types
902
+ self.current_index = -1
903
+
904
+ # Initialize weights and apply final processing
905
+ self.post_init()
906
+
907
+ @check_model_inputs
908
+ @auto_docstring
909
+ def forward(
910
+ self,
911
+ input_ids: Optional[torch.LongTensor] = None,
912
+ image_gen_indicators: Optional[torch.Tensor] = None,
913
+ indexes: Optional[torch.LongTensor] = None,
914
+ attention_mask: Optional[torch.Tensor] = None,
915
+ position_ids: Optional[torch.LongTensor] = None,
916
+ past_key_values: Optional[Cache] = None,
917
+ inputs_embeds: Optional[torch.FloatTensor] = None,
918
+ use_cache: Optional[bool] = None,
919
+ cache_position: Optional[torch.LongTensor] = None,
920
+ **kwargs: Unpack[TransformersKwargs],
921
+ ) -> BaseModelOutputWithPast:
922
+
923
+ # assert position_ids is not None
924
+ # assert cache_position is not None
925
+ # assert past_key_values is not None
926
+
927
+ if image_gen_indicators is None:
928
+ exist_non_image_gen_tokens = True
929
+ exist_image_gen_tokens = False
930
+ else:
931
+ exist_non_image_gen_tokens = (~image_gen_indicators).any()
932
+ exist_image_gen_tokens = image_gen_indicators.any()
933
+
934
+ if (input_ids is None) ^ (inputs_embeds is not None):
935
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
936
+
937
+ if inputs_embeds is None:
938
+ inputs_embeds = self.embed_tokens(input_ids)
939
+
940
+ if use_cache and past_key_values is None:
941
+ past_key_values = DynamicCache(config=self.config)
942
+
943
+ if cache_position is None:
944
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
945
+ cache_position = torch.arange(
946
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
947
+ )
948
+
949
+ if position_ids is None:
950
+ position_ids = cache_position.unsqueeze(0)
951
+
952
+ # It may already have been prepared by e.g. `generate`
953
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
954
+ # Prepare mask arguments
955
+ if input_ids is not None:
956
+ mask_kwargs = {
957
+ "config": self.config,
958
+ "input_embeds": inputs_embeds,
959
+ "attention_mask": attention_mask,
960
+ "cache_position": cache_position,
961
+ "past_key_values": past_key_values,
962
+ "position_ids": position_ids,
963
+ }
964
+ # Create the masks
965
+ causal_mask_mapping = {
966
+ "full_attention": create_causal_mask(**mask_kwargs),
967
+ }
968
+ self.current_index += 1
969
+ indexes = torch.LongTensor([[self.current_index], [0], [0]]).to(input_ids.device)
970
+ else:
971
+ causal_mask_mapping = {
972
+ "full_attention": create_block_causal_mask(indexes[0]),
973
+ }
974
+ self.current_index = indexes[0].max()
975
+ else:
976
+ self.current_index = indexes[0].max()
977
+ # raise NotImplementedError('not isinstance(causal_mask_mapping := attention_mask, dict)')
978
+
979
+ # The sliding window alternating layers are not always activated depending on the config
980
+ # if self.has_sliding_layers:
981
+ # causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs)
982
+
983
+ hidden_states = inputs_embeds
984
+
985
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
986
+ hidden_states = decoder_layer(
987
+ hidden_states,
988
+ image_gen_indicators=image_gen_indicators,
989
+ exist_non_image_gen_tokens=exist_non_image_gen_tokens,
990
+ exist_image_gen_tokens=exist_image_gen_tokens,
991
+ indexes=indexes,
992
+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],
993
+ position_ids=position_ids,
994
+ past_key_values=past_key_values,
995
+ use_cache=use_cache,
996
+ cache_position=cache_position,
997
+ **kwargs,
998
+ )
999
+ if not exist_image_gen_tokens:
1000
+ hidden_states = self.norm(hidden_states)
1001
+ elif not exist_non_image_gen_tokens:
1002
+ hidden_states = self.norm_mot_gen(hidden_states)
1003
+ else:
1004
+ _hidden_states = hidden_states.new_zeros(hidden_states.shape)
1005
+ _hidden_states[~image_gen_indicators] = self.norm(hidden_states[~image_gen_indicators])
1006
+ _hidden_states[image_gen_indicators] = self.norm_mot_gen(hidden_states[image_gen_indicators])
1007
+ hidden_states = _hidden_states
1008
+ return BaseModelOutputWithPast(
1009
+ last_hidden_state=hidden_states,
1010
+ past_key_values=past_key_values if use_cache else None,
1011
+ )
1012
+
1013
+
1014
+ @auto_docstring
1015
+ class Qwen3ForCausalLM(Qwen3PreTrainedModel, GenerationMixin):
1016
+ _tied_weights_keys = ["lm_head.weight"]
1017
+ _tp_plan = {"lm_head": "colwise_rep"}
1018
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
1019
+
1020
+ def __init__(self, config):
1021
+ super().__init__(config)
1022
+ self.model = Qwen3Model(config)
1023
+ self.vocab_size = config.vocab_size
1024
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1025
+
1026
+ # Initialize weights and apply final processing
1027
+ self.post_init()
1028
+
1029
+ @can_return_tuple
1030
+ @auto_docstring
1031
+ def forward(
1032
+ self,
1033
+ input_ids: Optional[torch.LongTensor] = None,
1034
+ indexes: Optional[torch.LongTensor] = None,
1035
+ attention_mask: Optional[torch.Tensor] = None,
1036
+ position_ids: Optional[torch.LongTensor] = None,
1037
+ past_key_values: Optional[Cache] = None,
1038
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1039
+ labels: Optional[torch.LongTensor] = None,
1040
+ use_cache: Optional[bool] = None,
1041
+ cache_position: Optional[torch.LongTensor] = None,
1042
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1043
+ **kwargs: Unpack[TransformersKwargs],
1044
+ ) -> CausalLMOutputWithPast:
1045
+ r"""
1046
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1047
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1048
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1049
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1050
+
1051
+ Example:
1052
+
1053
+ ```python
1054
+ >>> from transformers import AutoTokenizer, Qwen3ForCausalLM
1055
+
1056
+ >>> model = Qwen3ForCausalLM.from_pretrained("Qwen/Qwen3-8B")
1057
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-8B")
1058
+
1059
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1060
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1061
+
1062
+ >>> # Generate
1063
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1064
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1065
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1066
+ ```"""
1067
+
1068
+ outputs: BaseModelOutputWithPast = self.model(
1069
+ input_ids=input_ids,
1070
+ indexes=indexes,
1071
+ attention_mask=attention_mask,
1072
+ position_ids=position_ids,
1073
+ past_key_values=past_key_values,
1074
+ inputs_embeds=inputs_embeds,
1075
+ use_cache=use_cache,
1076
+ cache_position=cache_position,
1077
+ **kwargs,
1078
+ )
1079
+
1080
+ hidden_states = outputs.last_hidden_state
1081
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1082
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1083
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1084
+
1085
+ loss = None
1086
+ if labels is not None:
1087
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
1088
+
1089
+ return CausalLMOutputWithPast(
1090
+ loss=loss,
1091
+ logits=logits,
1092
+ past_key_values=outputs.past_key_values,
1093
+ hidden_states=hidden_states,
1094
+ attentions=outputs.attentions,
1095
+ )
1096
+
1097
+
1098
+ class Qwen3ForSequenceClassification(GenericForSequenceClassification, Qwen3PreTrainedModel):
1099
+ pass
1100
+
1101
+
1102
+ class Qwen3ForTokenClassification(GenericForTokenClassification, Qwen3PreTrainedModel):
1103
+ pass
1104
+
1105
+
1106
+ class Qwen3ForQuestionAnswering(GenericForQuestionAnswering, Qwen3PreTrainedModel):
1107
+ base_model_prefix = "transformer" # For BC, where `transformer` was used instead of `model`
1108
+
1109
+
1110
+ __all__ = [
1111
+ "Qwen3ForCausalLM",
1112
+ "Qwen3ForQuestionAnswering",
1113
+ "Qwen3PreTrainedModel",
1114
+ "Qwen3Model",
1115
+ "Qwen3ForSequenceClassification",
1116
+ "Qwen3ForTokenClassification",
1117
+ ]
special_tokens_map.json ADDED
@@ -0,0 +1,1900 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|object_ref_start|>",
6
+ "<|object_ref_end|>",
7
+ "<|box_start|>",
8
+ "<|box_end|>",
9
+ "<|quad_start|>",
10
+ "<|quad_end|>",
11
+ "<|vision_start|>",
12
+ "<|vision_end|>",
13
+ "<|vision_pad|>",
14
+ "<|image_pad|>",
15
+ "<|video_pad|>",
16
+ {
17
+ "content": "<IMG_CONTEXT>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ {
24
+ "content": "<img>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ {
31
+ "content": "</img>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ },
37
+ {
38
+ "content": "<quad>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false
43
+ },
44
+ {
45
+ "content": "</quad>",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": false,
49
+ "single_word": false
50
+ },
51
+ {
52
+ "content": "<ref>",
53
+ "lstrip": false,
54
+ "normalized": false,
55
+ "rstrip": false,
56
+ "single_word": false
57
+ },
58
+ {
59
+ "content": "</ref>",
60
+ "lstrip": false,
61
+ "normalized": false,
62
+ "rstrip": false,
63
+ "single_word": false
64
+ },
65
+ {
66
+ "content": "<box>",
67
+ "lstrip": false,
68
+ "normalized": false,
69
+ "rstrip": false,
70
+ "single_word": false
71
+ },
72
+ {
73
+ "content": "</box>",
74
+ "lstrip": false,
75
+ "normalized": false,
76
+ "rstrip": false,
77
+ "single_word": false
78
+ },
79
+ {
80
+ "content": "<|action_start|>",
81
+ "lstrip": false,
82
+ "normalized": false,
83
+ "rstrip": false,
84
+ "single_word": false
85
+ },
86
+ {
87
+ "content": "<|action_end|>",
88
+ "lstrip": false,
89
+ "normalized": false,
90
+ "rstrip": false,
91
+ "single_word": false
92
+ },
93
+ {
94
+ "content": "<|plugin|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false
99
+ },
100
+ {
101
+ "content": "<|interpreter|>",
102
+ "lstrip": false,
103
+ "normalized": false,
104
+ "rstrip": false,
105
+ "single_word": false
106
+ },
107
+ {
108
+ "content": "<FAKE_PAD_0>",
109
+ "lstrip": false,
110
+ "normalized": false,
111
+ "rstrip": false,
112
+ "single_word": false
113
+ },
114
+ {
115
+ "content": "<FAKE_PAD_1>",
116
+ "lstrip": false,
117
+ "normalized": false,
118
+ "rstrip": false,
119
+ "single_word": false
120
+ },
121
+ {
122
+ "content": "<FAKE_PAD_2>",
123
+ "lstrip": false,
124
+ "normalized": false,
125
+ "rstrip": false,
126
+ "single_word": false
127
+ },
128
+ {
129
+ "content": "<FAKE_PAD_3>",
130
+ "lstrip": false,
131
+ "normalized": false,
132
+ "rstrip": false,
133
+ "single_word": false
134
+ },
135
+ {
136
+ "content": "<FAKE_PAD_4>",
137
+ "lstrip": false,
138
+ "normalized": false,
139
+ "rstrip": false,
140
+ "single_word": false
141
+ },
142
+ {
143
+ "content": "<FAKE_PAD_5>",
144
+ "lstrip": false,
145
+ "normalized": false,
146
+ "rstrip": false,
147
+ "single_word": false
148
+ },
149
+ {
150
+ "content": "<FAKE_PAD_6>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false
155
+ },
156
+ {
157
+ "content": "<FAKE_PAD_7>",
158
+ "lstrip": false,
159
+ "normalized": false,
160
+ "rstrip": false,
161
+ "single_word": false
162
+ },
163
+ {
164
+ "content": "<FAKE_PAD_8>",
165
+ "lstrip": false,
166
+ "normalized": false,
167
+ "rstrip": false,
168
+ "single_word": false
169
+ },
170
+ {
171
+ "content": "<FAKE_PAD_9>",
172
+ "lstrip": false,
173
+ "normalized": false,
174
+ "rstrip": false,
175
+ "single_word": false
176
+ },
177
+ {
178
+ "content": "<FAKE_PAD_10>",
179
+ "lstrip": false,
180
+ "normalized": false,
181
+ "rstrip": false,
182
+ "single_word": false
183
+ },
184
+ {
185
+ "content": "<FAKE_PAD_11>",
186
+ "lstrip": false,
187
+ "normalized": false,
188
+ "rstrip": false,
189
+ "single_word": false
190
+ },
191
+ {
192
+ "content": "<FAKE_PAD_12>",
193
+ "lstrip": false,
194
+ "normalized": false,
195
+ "rstrip": false,
196
+ "single_word": false
197
+ },
198
+ {
199
+ "content": "<FAKE_PAD_13>",
200
+ "lstrip": false,
201
+ "normalized": false,
202
+ "rstrip": false,
203
+ "single_word": false
204
+ },
205
+ {
206
+ "content": "<FAKE_PAD_14>",
207
+ "lstrip": false,
208
+ "normalized": false,
209
+ "rstrip": false,
210
+ "single_word": false
211
+ },
212
+ {
213
+ "content": "<FAKE_PAD_15>",
214
+ "lstrip": false,
215
+ "normalized": false,
216
+ "rstrip": false,
217
+ "single_word": false
218
+ },
219
+ {
220
+ "content": "<FAKE_PAD_16>",
221
+ "lstrip": false,
222
+ "normalized": false,
223
+ "rstrip": false,
224
+ "single_word": false
225
+ },
226
+ {
227
+ "content": "<FAKE_PAD_17>",
228
+ "lstrip": false,
229
+ "normalized": false,
230
+ "rstrip": false,
231
+ "single_word": false
232
+ },
233
+ {
234
+ "content": "<FAKE_PAD_18>",
235
+ "lstrip": false,
236
+ "normalized": false,
237
+ "rstrip": false,
238
+ "single_word": false
239
+ },
240
+ {
241
+ "content": "<FAKE_PAD_19>",
242
+ "lstrip": false,
243
+ "normalized": false,
244
+ "rstrip": false,
245
+ "single_word": false
246
+ },
247
+ {
248
+ "content": "<FAKE_PAD_20>",
249
+ "lstrip": false,
250
+ "normalized": false,
251
+ "rstrip": false,
252
+ "single_word": false
253
+ },
254
+ {
255
+ "content": "<FAKE_PAD_21>",
256
+ "lstrip": false,
257
+ "normalized": false,
258
+ "rstrip": false,
259
+ "single_word": false
260
+ },
261
+ {
262
+ "content": "<FAKE_PAD_22>",
263
+ "lstrip": false,
264
+ "normalized": false,
265
+ "rstrip": false,
266
+ "single_word": false
267
+ },
268
+ {
269
+ "content": "<FAKE_PAD_23>",
270
+ "lstrip": false,
271
+ "normalized": false,
272
+ "rstrip": false,
273
+ "single_word": false
274
+ },
275
+ {
276
+ "content": "<FAKE_PAD_24>",
277
+ "lstrip": false,
278
+ "normalized": false,
279
+ "rstrip": false,
280
+ "single_word": false
281
+ },
282
+ {
283
+ "content": "<FAKE_PAD_25>",
284
+ "lstrip": false,
285
+ "normalized": false,
286
+ "rstrip": false,
287
+ "single_word": false
288
+ },
289
+ {
290
+ "content": "<FAKE_PAD_26>",
291
+ "lstrip": false,
292
+ "normalized": false,
293
+ "rstrip": false,
294
+ "single_word": false
295
+ },
296
+ {
297
+ "content": "<FAKE_PAD_27>",
298
+ "lstrip": false,
299
+ "normalized": false,
300
+ "rstrip": false,
301
+ "single_word": false
302
+ },
303
+ {
304
+ "content": "<FAKE_PAD_28>",
305
+ "lstrip": false,
306
+ "normalized": false,
307
+ "rstrip": false,
308
+ "single_word": false
309
+ },
310
+ {
311
+ "content": "<FAKE_PAD_29>",
312
+ "lstrip": false,
313
+ "normalized": false,
314
+ "rstrip": false,
315
+ "single_word": false
316
+ },
317
+ {
318
+ "content": "<FAKE_PAD_30>",
319
+ "lstrip": false,
320
+ "normalized": false,
321
+ "rstrip": false,
322
+ "single_word": false
323
+ },
324
+ {
325
+ "content": "<FAKE_PAD_31>",
326
+ "lstrip": false,
327
+ "normalized": false,
328
+ "rstrip": false,
329
+ "single_word": false
330
+ },
331
+ {
332
+ "content": "<FAKE_PAD_32>",
333
+ "lstrip": false,
334
+ "normalized": false,
335
+ "rstrip": false,
336
+ "single_word": false
337
+ },
338
+ {
339
+ "content": "<FAKE_PAD_33>",
340
+ "lstrip": false,
341
+ "normalized": false,
342
+ "rstrip": false,
343
+ "single_word": false
344
+ },
345
+ {
346
+ "content": "<FAKE_PAD_34>",
347
+ "lstrip": false,
348
+ "normalized": false,
349
+ "rstrip": false,
350
+ "single_word": false
351
+ },
352
+ {
353
+ "content": "<FAKE_PAD_35>",
354
+ "lstrip": false,
355
+ "normalized": false,
356
+ "rstrip": false,
357
+ "single_word": false
358
+ },
359
+ {
360
+ "content": "<FAKE_PAD_36>",
361
+ "lstrip": false,
362
+ "normalized": false,
363
+ "rstrip": false,
364
+ "single_word": false
365
+ },
366
+ {
367
+ "content": "<FAKE_PAD_37>",
368
+ "lstrip": false,
369
+ "normalized": false,
370
+ "rstrip": false,
371
+ "single_word": false
372
+ },
373
+ {
374
+ "content": "<FAKE_PAD_38>",
375
+ "lstrip": false,
376
+ "normalized": false,
377
+ "rstrip": false,
378
+ "single_word": false
379
+ },
380
+ {
381
+ "content": "<FAKE_PAD_39>",
382
+ "lstrip": false,
383
+ "normalized": false,
384
+ "rstrip": false,
385
+ "single_word": false
386
+ },
387
+ {
388
+ "content": "<FAKE_PAD_40>",
389
+ "lstrip": false,
390
+ "normalized": false,
391
+ "rstrip": false,
392
+ "single_word": false
393
+ },
394
+ {
395
+ "content": "<FAKE_PAD_41>",
396
+ "lstrip": false,
397
+ "normalized": false,
398
+ "rstrip": false,
399
+ "single_word": false
400
+ },
401
+ {
402
+ "content": "<FAKE_PAD_42>",
403
+ "lstrip": false,
404
+ "normalized": false,
405
+ "rstrip": false,
406
+ "single_word": false
407
+ },
408
+ {
409
+ "content": "<FAKE_PAD_43>",
410
+ "lstrip": false,
411
+ "normalized": false,
412
+ "rstrip": false,
413
+ "single_word": false
414
+ },
415
+ {
416
+ "content": "<FAKE_PAD_44>",
417
+ "lstrip": false,
418
+ "normalized": false,
419
+ "rstrip": false,
420
+ "single_word": false
421
+ },
422
+ {
423
+ "content": "<FAKE_PAD_45>",
424
+ "lstrip": false,
425
+ "normalized": false,
426
+ "rstrip": false,
427
+ "single_word": false
428
+ },
429
+ {
430
+ "content": "<FAKE_PAD_46>",
431
+ "lstrip": false,
432
+ "normalized": false,
433
+ "rstrip": false,
434
+ "single_word": false
435
+ },
436
+ {
437
+ "content": "<FAKE_PAD_47>",
438
+ "lstrip": false,
439
+ "normalized": false,
440
+ "rstrip": false,
441
+ "single_word": false
442
+ },
443
+ {
444
+ "content": "<FAKE_PAD_48>",
445
+ "lstrip": false,
446
+ "normalized": false,
447
+ "rstrip": false,
448
+ "single_word": false
449
+ },
450
+ {
451
+ "content": "<FAKE_PAD_49>",
452
+ "lstrip": false,
453
+ "normalized": false,
454
+ "rstrip": false,
455
+ "single_word": false
456
+ },
457
+ {
458
+ "content": "<FAKE_PAD_50>",
459
+ "lstrip": false,
460
+ "normalized": false,
461
+ "rstrip": false,
462
+ "single_word": false
463
+ },
464
+ {
465
+ "content": "<FAKE_PAD_51>",
466
+ "lstrip": false,
467
+ "normalized": false,
468
+ "rstrip": false,
469
+ "single_word": false
470
+ },
471
+ {
472
+ "content": "<FAKE_PAD_52>",
473
+ "lstrip": false,
474
+ "normalized": false,
475
+ "rstrip": false,
476
+ "single_word": false
477
+ },
478
+ {
479
+ "content": "<FAKE_PAD_53>",
480
+ "lstrip": false,
481
+ "normalized": false,
482
+ "rstrip": false,
483
+ "single_word": false
484
+ },
485
+ {
486
+ "content": "<FAKE_PAD_54>",
487
+ "lstrip": false,
488
+ "normalized": false,
489
+ "rstrip": false,
490
+ "single_word": false
491
+ },
492
+ {
493
+ "content": "<FAKE_PAD_55>",
494
+ "lstrip": false,
495
+ "normalized": false,
496
+ "rstrip": false,
497
+ "single_word": false
498
+ },
499
+ {
500
+ "content": "<FAKE_PAD_56>",
501
+ "lstrip": false,
502
+ "normalized": false,
503
+ "rstrip": false,
504
+ "single_word": false
505
+ },
506
+ {
507
+ "content": "<FAKE_PAD_57>",
508
+ "lstrip": false,
509
+ "normalized": false,
510
+ "rstrip": false,
511
+ "single_word": false
512
+ },
513
+ {
514
+ "content": "<FAKE_PAD_58>",
515
+ "lstrip": false,
516
+ "normalized": false,
517
+ "rstrip": false,
518
+ "single_word": false
519
+ },
520
+ {
521
+ "content": "<FAKE_PAD_59>",
522
+ "lstrip": false,
523
+ "normalized": false,
524
+ "rstrip": false,
525
+ "single_word": false
526
+ },
527
+ {
528
+ "content": "<FAKE_PAD_60>",
529
+ "lstrip": false,
530
+ "normalized": false,
531
+ "rstrip": false,
532
+ "single_word": false
533
+ },
534
+ {
535
+ "content": "<FAKE_PAD_61>",
536
+ "lstrip": false,
537
+ "normalized": false,
538
+ "rstrip": false,
539
+ "single_word": false
540
+ },
541
+ {
542
+ "content": "<FAKE_PAD_62>",
543
+ "lstrip": false,
544
+ "normalized": false,
545
+ "rstrip": false,
546
+ "single_word": false
547
+ },
548
+ {
549
+ "content": "<FAKE_PAD_63>",
550
+ "lstrip": false,
551
+ "normalized": false,
552
+ "rstrip": false,
553
+ "single_word": false
554
+ },
555
+ {
556
+ "content": "<FAKE_PAD_64>",
557
+ "lstrip": false,
558
+ "normalized": false,
559
+ "rstrip": false,
560
+ "single_word": false
561
+ },
562
+ {
563
+ "content": "<FAKE_PAD_65>",
564
+ "lstrip": false,
565
+ "normalized": false,
566
+ "rstrip": false,
567
+ "single_word": false
568
+ },
569
+ {
570
+ "content": "<FAKE_PAD_66>",
571
+ "lstrip": false,
572
+ "normalized": false,
573
+ "rstrip": false,
574
+ "single_word": false
575
+ },
576
+ {
577
+ "content": "<FAKE_PAD_67>",
578
+ "lstrip": false,
579
+ "normalized": false,
580
+ "rstrip": false,
581
+ "single_word": false
582
+ },
583
+ {
584
+ "content": "<FAKE_PAD_68>",
585
+ "lstrip": false,
586
+ "normalized": false,
587
+ "rstrip": false,
588
+ "single_word": false
589
+ },
590
+ {
591
+ "content": "<FAKE_PAD_69>",
592
+ "lstrip": false,
593
+ "normalized": false,
594
+ "rstrip": false,
595
+ "single_word": false
596
+ },
597
+ {
598
+ "content": "<FAKE_PAD_70>",
599
+ "lstrip": false,
600
+ "normalized": false,
601
+ "rstrip": false,
602
+ "single_word": false
603
+ },
604
+ {
605
+ "content": "<FAKE_PAD_71>",
606
+ "lstrip": false,
607
+ "normalized": false,
608
+ "rstrip": false,
609
+ "single_word": false
610
+ },
611
+ {
612
+ "content": "<FAKE_PAD_72>",
613
+ "lstrip": false,
614
+ "normalized": false,
615
+ "rstrip": false,
616
+ "single_word": false
617
+ },
618
+ {
619
+ "content": "<FAKE_PAD_73>",
620
+ "lstrip": false,
621
+ "normalized": false,
622
+ "rstrip": false,
623
+ "single_word": false
624
+ },
625
+ {
626
+ "content": "<FAKE_PAD_74>",
627
+ "lstrip": false,
628
+ "normalized": false,
629
+ "rstrip": false,
630
+ "single_word": false
631
+ },
632
+ {
633
+ "content": "<FAKE_PAD_75>",
634
+ "lstrip": false,
635
+ "normalized": false,
636
+ "rstrip": false,
637
+ "single_word": false
638
+ },
639
+ {
640
+ "content": "<FAKE_PAD_76>",
641
+ "lstrip": false,
642
+ "normalized": false,
643
+ "rstrip": false,
644
+ "single_word": false
645
+ },
646
+ {
647
+ "content": "<FAKE_PAD_77>",
648
+ "lstrip": false,
649
+ "normalized": false,
650
+ "rstrip": false,
651
+ "single_word": false
652
+ },
653
+ {
654
+ "content": "<FAKE_PAD_78>",
655
+ "lstrip": false,
656
+ "normalized": false,
657
+ "rstrip": false,
658
+ "single_word": false
659
+ },
660
+ {
661
+ "content": "<FAKE_PAD_79>",
662
+ "lstrip": false,
663
+ "normalized": false,
664
+ "rstrip": false,
665
+ "single_word": false
666
+ },
667
+ {
668
+ "content": "<FAKE_PAD_80>",
669
+ "lstrip": false,
670
+ "normalized": false,
671
+ "rstrip": false,
672
+ "single_word": false
673
+ },
674
+ {
675
+ "content": "<FAKE_PAD_81>",
676
+ "lstrip": false,
677
+ "normalized": false,
678
+ "rstrip": false,
679
+ "single_word": false
680
+ },
681
+ {
682
+ "content": "<FAKE_PAD_82>",
683
+ "lstrip": false,
684
+ "normalized": false,
685
+ "rstrip": false,
686
+ "single_word": false
687
+ },
688
+ {
689
+ "content": "<FAKE_PAD_83>",
690
+ "lstrip": false,
691
+ "normalized": false,
692
+ "rstrip": false,
693
+ "single_word": false
694
+ },
695
+ {
696
+ "content": "<FAKE_PAD_84>",
697
+ "lstrip": false,
698
+ "normalized": false,
699
+ "rstrip": false,
700
+ "single_word": false
701
+ },
702
+ {
703
+ "content": "<FAKE_PAD_85>",
704
+ "lstrip": false,
705
+ "normalized": false,
706
+ "rstrip": false,
707
+ "single_word": false
708
+ },
709
+ {
710
+ "content": "<FAKE_PAD_86>",
711
+ "lstrip": false,
712
+ "normalized": false,
713
+ "rstrip": false,
714
+ "single_word": false
715
+ },
716
+ {
717
+ "content": "<FAKE_PAD_87>",
718
+ "lstrip": false,
719
+ "normalized": false,
720
+ "rstrip": false,
721
+ "single_word": false
722
+ },
723
+ {
724
+ "content": "<FAKE_PAD_88>",
725
+ "lstrip": false,
726
+ "normalized": false,
727
+ "rstrip": false,
728
+ "single_word": false
729
+ },
730
+ {
731
+ "content": "<FAKE_PAD_89>",
732
+ "lstrip": false,
733
+ "normalized": false,
734
+ "rstrip": false,
735
+ "single_word": false
736
+ },
737
+ {
738
+ "content": "<FAKE_PAD_90>",
739
+ "lstrip": false,
740
+ "normalized": false,
741
+ "rstrip": false,
742
+ "single_word": false
743
+ },
744
+ {
745
+ "content": "<FAKE_PAD_91>",
746
+ "lstrip": false,
747
+ "normalized": false,
748
+ "rstrip": false,
749
+ "single_word": false
750
+ },
751
+ {
752
+ "content": "<FAKE_PAD_92>",
753
+ "lstrip": false,
754
+ "normalized": false,
755
+ "rstrip": false,
756
+ "single_word": false
757
+ },
758
+ {
759
+ "content": "<FAKE_PAD_93>",
760
+ "lstrip": false,
761
+ "normalized": false,
762
+ "rstrip": false,
763
+ "single_word": false
764
+ },
765
+ {
766
+ "content": "<FAKE_PAD_94>",
767
+ "lstrip": false,
768
+ "normalized": false,
769
+ "rstrip": false,
770
+ "single_word": false
771
+ },
772
+ {
773
+ "content": "<FAKE_PAD_95>",
774
+ "lstrip": false,
775
+ "normalized": false,
776
+ "rstrip": false,
777
+ "single_word": false
778
+ },
779
+ {
780
+ "content": "<FAKE_PAD_96>",
781
+ "lstrip": false,
782
+ "normalized": false,
783
+ "rstrip": false,
784
+ "single_word": false
785
+ },
786
+ {
787
+ "content": "<FAKE_PAD_97>",
788
+ "lstrip": false,
789
+ "normalized": false,
790
+ "rstrip": false,
791
+ "single_word": false
792
+ },
793
+ {
794
+ "content": "<FAKE_PAD_98>",
795
+ "lstrip": false,
796
+ "normalized": false,
797
+ "rstrip": false,
798
+ "single_word": false
799
+ },
800
+ {
801
+ "content": "<FAKE_PAD_99>",
802
+ "lstrip": false,
803
+ "normalized": false,
804
+ "rstrip": false,
805
+ "single_word": false
806
+ },
807
+ {
808
+ "content": "<FAKE_PAD_100>",
809
+ "lstrip": false,
810
+ "normalized": false,
811
+ "rstrip": false,
812
+ "single_word": false
813
+ },
814
+ {
815
+ "content": "<FAKE_PAD_101>",
816
+ "lstrip": false,
817
+ "normalized": false,
818
+ "rstrip": false,
819
+ "single_word": false
820
+ },
821
+ {
822
+ "content": "<FAKE_PAD_102>",
823
+ "lstrip": false,
824
+ "normalized": false,
825
+ "rstrip": false,
826
+ "single_word": false
827
+ },
828
+ {
829
+ "content": "<FAKE_PAD_103>",
830
+ "lstrip": false,
831
+ "normalized": false,
832
+ "rstrip": false,
833
+ "single_word": false
834
+ },
835
+ {
836
+ "content": "<FAKE_PAD_104>",
837
+ "lstrip": false,
838
+ "normalized": false,
839
+ "rstrip": false,
840
+ "single_word": false
841
+ },
842
+ {
843
+ "content": "<FAKE_PAD_105>",
844
+ "lstrip": false,
845
+ "normalized": false,
846
+ "rstrip": false,
847
+ "single_word": false
848
+ },
849
+ {
850
+ "content": "<FAKE_PAD_106>",
851
+ "lstrip": false,
852
+ "normalized": false,
853
+ "rstrip": false,
854
+ "single_word": false
855
+ },
856
+ {
857
+ "content": "<FAKE_PAD_107>",
858
+ "lstrip": false,
859
+ "normalized": false,
860
+ "rstrip": false,
861
+ "single_word": false
862
+ },
863
+ {
864
+ "content": "<FAKE_PAD_108>",
865
+ "lstrip": false,
866
+ "normalized": false,
867
+ "rstrip": false,
868
+ "single_word": false
869
+ },
870
+ {
871
+ "content": "<FAKE_PAD_109>",
872
+ "lstrip": false,
873
+ "normalized": false,
874
+ "rstrip": false,
875
+ "single_word": false
876
+ },
877
+ {
878
+ "content": "<FAKE_PAD_110>",
879
+ "lstrip": false,
880
+ "normalized": false,
881
+ "rstrip": false,
882
+ "single_word": false
883
+ },
884
+ {
885
+ "content": "<FAKE_PAD_111>",
886
+ "lstrip": false,
887
+ "normalized": false,
888
+ "rstrip": false,
889
+ "single_word": false
890
+ },
891
+ {
892
+ "content": "<FAKE_PAD_112>",
893
+ "lstrip": false,
894
+ "normalized": false,
895
+ "rstrip": false,
896
+ "single_word": false
897
+ },
898
+ {
899
+ "content": "<FAKE_PAD_113>",
900
+ "lstrip": false,
901
+ "normalized": false,
902
+ "rstrip": false,
903
+ "single_word": false
904
+ },
905
+ {
906
+ "content": "<FAKE_PAD_114>",
907
+ "lstrip": false,
908
+ "normalized": false,
909
+ "rstrip": false,
910
+ "single_word": false
911
+ },
912
+ {
913
+ "content": "<FAKE_PAD_115>",
914
+ "lstrip": false,
915
+ "normalized": false,
916
+ "rstrip": false,
917
+ "single_word": false
918
+ },
919
+ {
920
+ "content": "<FAKE_PAD_116>",
921
+ "lstrip": false,
922
+ "normalized": false,
923
+ "rstrip": false,
924
+ "single_word": false
925
+ },
926
+ {
927
+ "content": "<FAKE_PAD_117>",
928
+ "lstrip": false,
929
+ "normalized": false,
930
+ "rstrip": false,
931
+ "single_word": false
932
+ },
933
+ {
934
+ "content": "<FAKE_PAD_118>",
935
+ "lstrip": false,
936
+ "normalized": false,
937
+ "rstrip": false,
938
+ "single_word": false
939
+ },
940
+ {
941
+ "content": "<FAKE_PAD_119>",
942
+ "lstrip": false,
943
+ "normalized": false,
944
+ "rstrip": false,
945
+ "single_word": false
946
+ },
947
+ {
948
+ "content": "<FAKE_PAD_120>",
949
+ "lstrip": false,
950
+ "normalized": false,
951
+ "rstrip": false,
952
+ "single_word": false
953
+ },
954
+ {
955
+ "content": "<FAKE_PAD_121>",
956
+ "lstrip": false,
957
+ "normalized": false,
958
+ "rstrip": false,
959
+ "single_word": false
960
+ },
961
+ {
962
+ "content": "<FAKE_PAD_122>",
963
+ "lstrip": false,
964
+ "normalized": false,
965
+ "rstrip": false,
966
+ "single_word": false
967
+ },
968
+ {
969
+ "content": "<FAKE_PAD_123>",
970
+ "lstrip": false,
971
+ "normalized": false,
972
+ "rstrip": false,
973
+ "single_word": false
974
+ },
975
+ {
976
+ "content": "<FAKE_PAD_124>",
977
+ "lstrip": false,
978
+ "normalized": false,
979
+ "rstrip": false,
980
+ "single_word": false
981
+ },
982
+ {
983
+ "content": "<FAKE_PAD_125>",
984
+ "lstrip": false,
985
+ "normalized": false,
986
+ "rstrip": false,
987
+ "single_word": false
988
+ },
989
+ {
990
+ "content": "<FAKE_PAD_126>",
991
+ "lstrip": false,
992
+ "normalized": false,
993
+ "rstrip": false,
994
+ "single_word": false
995
+ },
996
+ {
997
+ "content": "<FAKE_PAD_127>",
998
+ "lstrip": false,
999
+ "normalized": false,
1000
+ "rstrip": false,
1001
+ "single_word": false
1002
+ },
1003
+ {
1004
+ "content": "<FAKE_PAD_128>",
1005
+ "lstrip": false,
1006
+ "normalized": false,
1007
+ "rstrip": false,
1008
+ "single_word": false
1009
+ },
1010
+ {
1011
+ "content": "<FAKE_PAD_129>",
1012
+ "lstrip": false,
1013
+ "normalized": false,
1014
+ "rstrip": false,
1015
+ "single_word": false
1016
+ },
1017
+ {
1018
+ "content": "<FAKE_PAD_130>",
1019
+ "lstrip": false,
1020
+ "normalized": false,
1021
+ "rstrip": false,
1022
+ "single_word": false
1023
+ },
1024
+ {
1025
+ "content": "<FAKE_PAD_131>",
1026
+ "lstrip": false,
1027
+ "normalized": false,
1028
+ "rstrip": false,
1029
+ "single_word": false
1030
+ },
1031
+ {
1032
+ "content": "<FAKE_PAD_132>",
1033
+ "lstrip": false,
1034
+ "normalized": false,
1035
+ "rstrip": false,
1036
+ "single_word": false
1037
+ },
1038
+ {
1039
+ "content": "<FAKE_PAD_133>",
1040
+ "lstrip": false,
1041
+ "normalized": false,
1042
+ "rstrip": false,
1043
+ "single_word": false
1044
+ },
1045
+ {
1046
+ "content": "<FAKE_PAD_134>",
1047
+ "lstrip": false,
1048
+ "normalized": false,
1049
+ "rstrip": false,
1050
+ "single_word": false
1051
+ },
1052
+ {
1053
+ "content": "<FAKE_PAD_135>",
1054
+ "lstrip": false,
1055
+ "normalized": false,
1056
+ "rstrip": false,
1057
+ "single_word": false
1058
+ },
1059
+ {
1060
+ "content": "<FAKE_PAD_136>",
1061
+ "lstrip": false,
1062
+ "normalized": false,
1063
+ "rstrip": false,
1064
+ "single_word": false
1065
+ },
1066
+ {
1067
+ "content": "<FAKE_PAD_137>",
1068
+ "lstrip": false,
1069
+ "normalized": false,
1070
+ "rstrip": false,
1071
+ "single_word": false
1072
+ },
1073
+ {
1074
+ "content": "<FAKE_PAD_138>",
1075
+ "lstrip": false,
1076
+ "normalized": false,
1077
+ "rstrip": false,
1078
+ "single_word": false
1079
+ },
1080
+ {
1081
+ "content": "<FAKE_PAD_139>",
1082
+ "lstrip": false,
1083
+ "normalized": false,
1084
+ "rstrip": false,
1085
+ "single_word": false
1086
+ },
1087
+ {
1088
+ "content": "<FAKE_PAD_140>",
1089
+ "lstrip": false,
1090
+ "normalized": false,
1091
+ "rstrip": false,
1092
+ "single_word": false
1093
+ },
1094
+ {
1095
+ "content": "<FAKE_PAD_141>",
1096
+ "lstrip": false,
1097
+ "normalized": false,
1098
+ "rstrip": false,
1099
+ "single_word": false
1100
+ },
1101
+ {
1102
+ "content": "<FAKE_PAD_142>",
1103
+ "lstrip": false,
1104
+ "normalized": false,
1105
+ "rstrip": false,
1106
+ "single_word": false
1107
+ },
1108
+ {
1109
+ "content": "<FAKE_PAD_143>",
1110
+ "lstrip": false,
1111
+ "normalized": false,
1112
+ "rstrip": false,
1113
+ "single_word": false
1114
+ },
1115
+ {
1116
+ "content": "<FAKE_PAD_144>",
1117
+ "lstrip": false,
1118
+ "normalized": false,
1119
+ "rstrip": false,
1120
+ "single_word": false
1121
+ },
1122
+ {
1123
+ "content": "<FAKE_PAD_145>",
1124
+ "lstrip": false,
1125
+ "normalized": false,
1126
+ "rstrip": false,
1127
+ "single_word": false
1128
+ },
1129
+ {
1130
+ "content": "<FAKE_PAD_146>",
1131
+ "lstrip": false,
1132
+ "normalized": false,
1133
+ "rstrip": false,
1134
+ "single_word": false
1135
+ },
1136
+ {
1137
+ "content": "<FAKE_PAD_147>",
1138
+ "lstrip": false,
1139
+ "normalized": false,
1140
+ "rstrip": false,
1141
+ "single_word": false
1142
+ },
1143
+ {
1144
+ "content": "<FAKE_PAD_148>",
1145
+ "lstrip": false,
1146
+ "normalized": false,
1147
+ "rstrip": false,
1148
+ "single_word": false
1149
+ },
1150
+ {
1151
+ "content": "<FAKE_PAD_149>",
1152
+ "lstrip": false,
1153
+ "normalized": false,
1154
+ "rstrip": false,
1155
+ "single_word": false
1156
+ },
1157
+ {
1158
+ "content": "<FAKE_PAD_150>",
1159
+ "lstrip": false,
1160
+ "normalized": false,
1161
+ "rstrip": false,
1162
+ "single_word": false
1163
+ },
1164
+ {
1165
+ "content": "<FAKE_PAD_151>",
1166
+ "lstrip": false,
1167
+ "normalized": false,
1168
+ "rstrip": false,
1169
+ "single_word": false
1170
+ },
1171
+ {
1172
+ "content": "<FAKE_PAD_152>",
1173
+ "lstrip": false,
1174
+ "normalized": false,
1175
+ "rstrip": false,
1176
+ "single_word": false
1177
+ },
1178
+ {
1179
+ "content": "<FAKE_PAD_153>",
1180
+ "lstrip": false,
1181
+ "normalized": false,
1182
+ "rstrip": false,
1183
+ "single_word": false
1184
+ },
1185
+ {
1186
+ "content": "<FAKE_PAD_154>",
1187
+ "lstrip": false,
1188
+ "normalized": false,
1189
+ "rstrip": false,
1190
+ "single_word": false
1191
+ },
1192
+ {
1193
+ "content": "<FAKE_PAD_155>",
1194
+ "lstrip": false,
1195
+ "normalized": false,
1196
+ "rstrip": false,
1197
+ "single_word": false
1198
+ },
1199
+ {
1200
+ "content": "<FAKE_PAD_156>",
1201
+ "lstrip": false,
1202
+ "normalized": false,
1203
+ "rstrip": false,
1204
+ "single_word": false
1205
+ },
1206
+ {
1207
+ "content": "<FAKE_PAD_157>",
1208
+ "lstrip": false,
1209
+ "normalized": false,
1210
+ "rstrip": false,
1211
+ "single_word": false
1212
+ },
1213
+ {
1214
+ "content": "<FAKE_PAD_158>",
1215
+ "lstrip": false,
1216
+ "normalized": false,
1217
+ "rstrip": false,
1218
+ "single_word": false
1219
+ },
1220
+ {
1221
+ "content": "<FAKE_PAD_159>",
1222
+ "lstrip": false,
1223
+ "normalized": false,
1224
+ "rstrip": false,
1225
+ "single_word": false
1226
+ },
1227
+ {
1228
+ "content": "<FAKE_PAD_160>",
1229
+ "lstrip": false,
1230
+ "normalized": false,
1231
+ "rstrip": false,
1232
+ "single_word": false
1233
+ },
1234
+ {
1235
+ "content": "<FAKE_PAD_161>",
1236
+ "lstrip": false,
1237
+ "normalized": false,
1238
+ "rstrip": false,
1239
+ "single_word": false
1240
+ },
1241
+ {
1242
+ "content": "<FAKE_PAD_162>",
1243
+ "lstrip": false,
1244
+ "normalized": false,
1245
+ "rstrip": false,
1246
+ "single_word": false
1247
+ },
1248
+ {
1249
+ "content": "<FAKE_PAD_163>",
1250
+ "lstrip": false,
1251
+ "normalized": false,
1252
+ "rstrip": false,
1253
+ "single_word": false
1254
+ },
1255
+ {
1256
+ "content": "<FAKE_PAD_164>",
1257
+ "lstrip": false,
1258
+ "normalized": false,
1259
+ "rstrip": false,
1260
+ "single_word": false
1261
+ },
1262
+ {
1263
+ "content": "<FAKE_PAD_165>",
1264
+ "lstrip": false,
1265
+ "normalized": false,
1266
+ "rstrip": false,
1267
+ "single_word": false
1268
+ },
1269
+ {
1270
+ "content": "<FAKE_PAD_166>",
1271
+ "lstrip": false,
1272
+ "normalized": false,
1273
+ "rstrip": false,
1274
+ "single_word": false
1275
+ },
1276
+ {
1277
+ "content": "<FAKE_PAD_167>",
1278
+ "lstrip": false,
1279
+ "normalized": false,
1280
+ "rstrip": false,
1281
+ "single_word": false
1282
+ },
1283
+ {
1284
+ "content": "<FAKE_PAD_168>",
1285
+ "lstrip": false,
1286
+ "normalized": false,
1287
+ "rstrip": false,
1288
+ "single_word": false
1289
+ },
1290
+ {
1291
+ "content": "<FAKE_PAD_169>",
1292
+ "lstrip": false,
1293
+ "normalized": false,
1294
+ "rstrip": false,
1295
+ "single_word": false
1296
+ },
1297
+ {
1298
+ "content": "<FAKE_PAD_170>",
1299
+ "lstrip": false,
1300
+ "normalized": false,
1301
+ "rstrip": false,
1302
+ "single_word": false
1303
+ },
1304
+ {
1305
+ "content": "<FAKE_PAD_171>",
1306
+ "lstrip": false,
1307
+ "normalized": false,
1308
+ "rstrip": false,
1309
+ "single_word": false
1310
+ },
1311
+ {
1312
+ "content": "<FAKE_PAD_172>",
1313
+ "lstrip": false,
1314
+ "normalized": false,
1315
+ "rstrip": false,
1316
+ "single_word": false
1317
+ },
1318
+ {
1319
+ "content": "<FAKE_PAD_173>",
1320
+ "lstrip": false,
1321
+ "normalized": false,
1322
+ "rstrip": false,
1323
+ "single_word": false
1324
+ },
1325
+ {
1326
+ "content": "<FAKE_PAD_174>",
1327
+ "lstrip": false,
1328
+ "normalized": false,
1329
+ "rstrip": false,
1330
+ "single_word": false
1331
+ },
1332
+ {
1333
+ "content": "<FAKE_PAD_175>",
1334
+ "lstrip": false,
1335
+ "normalized": false,
1336
+ "rstrip": false,
1337
+ "single_word": false
1338
+ },
1339
+ {
1340
+ "content": "<FAKE_PAD_176>",
1341
+ "lstrip": false,
1342
+ "normalized": false,
1343
+ "rstrip": false,
1344
+ "single_word": false
1345
+ },
1346
+ {
1347
+ "content": "<FAKE_PAD_177>",
1348
+ "lstrip": false,
1349
+ "normalized": false,
1350
+ "rstrip": false,
1351
+ "single_word": false
1352
+ },
1353
+ {
1354
+ "content": "<FAKE_PAD_178>",
1355
+ "lstrip": false,
1356
+ "normalized": false,
1357
+ "rstrip": false,
1358
+ "single_word": false
1359
+ },
1360
+ {
1361
+ "content": "<FAKE_PAD_179>",
1362
+ "lstrip": false,
1363
+ "normalized": false,
1364
+ "rstrip": false,
1365
+ "single_word": false
1366
+ },
1367
+ {
1368
+ "content": "<FAKE_PAD_180>",
1369
+ "lstrip": false,
1370
+ "normalized": false,
1371
+ "rstrip": false,
1372
+ "single_word": false
1373
+ },
1374
+ {
1375
+ "content": "<FAKE_PAD_181>",
1376
+ "lstrip": false,
1377
+ "normalized": false,
1378
+ "rstrip": false,
1379
+ "single_word": false
1380
+ },
1381
+ {
1382
+ "content": "<FAKE_PAD_182>",
1383
+ "lstrip": false,
1384
+ "normalized": false,
1385
+ "rstrip": false,
1386
+ "single_word": false
1387
+ },
1388
+ {
1389
+ "content": "<FAKE_PAD_183>",
1390
+ "lstrip": false,
1391
+ "normalized": false,
1392
+ "rstrip": false,
1393
+ "single_word": false
1394
+ },
1395
+ {
1396
+ "content": "<FAKE_PAD_184>",
1397
+ "lstrip": false,
1398
+ "normalized": false,
1399
+ "rstrip": false,
1400
+ "single_word": false
1401
+ },
1402
+ {
1403
+ "content": "<FAKE_PAD_185>",
1404
+ "lstrip": false,
1405
+ "normalized": false,
1406
+ "rstrip": false,
1407
+ "single_word": false
1408
+ },
1409
+ {
1410
+ "content": "<FAKE_PAD_186>",
1411
+ "lstrip": false,
1412
+ "normalized": false,
1413
+ "rstrip": false,
1414
+ "single_word": false
1415
+ },
1416
+ {
1417
+ "content": "<FAKE_PAD_187>",
1418
+ "lstrip": false,
1419
+ "normalized": false,
1420
+ "rstrip": false,
1421
+ "single_word": false
1422
+ },
1423
+ {
1424
+ "content": "<FAKE_PAD_188>",
1425
+ "lstrip": false,
1426
+ "normalized": false,
1427
+ "rstrip": false,
1428
+ "single_word": false
1429
+ },
1430
+ {
1431
+ "content": "<FAKE_PAD_189>",
1432
+ "lstrip": false,
1433
+ "normalized": false,
1434
+ "rstrip": false,
1435
+ "single_word": false
1436
+ },
1437
+ {
1438
+ "content": "<FAKE_PAD_190>",
1439
+ "lstrip": false,
1440
+ "normalized": false,
1441
+ "rstrip": false,
1442
+ "single_word": false
1443
+ },
1444
+ {
1445
+ "content": "<FAKE_PAD_191>",
1446
+ "lstrip": false,
1447
+ "normalized": false,
1448
+ "rstrip": false,
1449
+ "single_word": false
1450
+ },
1451
+ {
1452
+ "content": "<FAKE_PAD_192>",
1453
+ "lstrip": false,
1454
+ "normalized": false,
1455
+ "rstrip": false,
1456
+ "single_word": false
1457
+ },
1458
+ {
1459
+ "content": "<FAKE_PAD_193>",
1460
+ "lstrip": false,
1461
+ "normalized": false,
1462
+ "rstrip": false,
1463
+ "single_word": false
1464
+ },
1465
+ {
1466
+ "content": "<FAKE_PAD_194>",
1467
+ "lstrip": false,
1468
+ "normalized": false,
1469
+ "rstrip": false,
1470
+ "single_word": false
1471
+ },
1472
+ {
1473
+ "content": "<FAKE_PAD_195>",
1474
+ "lstrip": false,
1475
+ "normalized": false,
1476
+ "rstrip": false,
1477
+ "single_word": false
1478
+ },
1479
+ {
1480
+ "content": "<FAKE_PAD_196>",
1481
+ "lstrip": false,
1482
+ "normalized": false,
1483
+ "rstrip": false,
1484
+ "single_word": false
1485
+ },
1486
+ {
1487
+ "content": "<FAKE_PAD_197>",
1488
+ "lstrip": false,
1489
+ "normalized": false,
1490
+ "rstrip": false,
1491
+ "single_word": false
1492
+ },
1493
+ {
1494
+ "content": "<FAKE_PAD_198>",
1495
+ "lstrip": false,
1496
+ "normalized": false,
1497
+ "rstrip": false,
1498
+ "single_word": false
1499
+ },
1500
+ {
1501
+ "content": "<FAKE_PAD_199>",
1502
+ "lstrip": false,
1503
+ "normalized": false,
1504
+ "rstrip": false,
1505
+ "single_word": false
1506
+ },
1507
+ {
1508
+ "content": "<FAKE_PAD_200>",
1509
+ "lstrip": false,
1510
+ "normalized": false,
1511
+ "rstrip": false,
1512
+ "single_word": false
1513
+ },
1514
+ {
1515
+ "content": "<FAKE_PAD_201>",
1516
+ "lstrip": false,
1517
+ "normalized": false,
1518
+ "rstrip": false,
1519
+ "single_word": false
1520
+ },
1521
+ {
1522
+ "content": "<FAKE_PAD_202>",
1523
+ "lstrip": false,
1524
+ "normalized": false,
1525
+ "rstrip": false,
1526
+ "single_word": false
1527
+ },
1528
+ {
1529
+ "content": "<FAKE_PAD_203>",
1530
+ "lstrip": false,
1531
+ "normalized": false,
1532
+ "rstrip": false,
1533
+ "single_word": false
1534
+ },
1535
+ {
1536
+ "content": "<FAKE_PAD_204>",
1537
+ "lstrip": false,
1538
+ "normalized": false,
1539
+ "rstrip": false,
1540
+ "single_word": false
1541
+ },
1542
+ {
1543
+ "content": "<FAKE_PAD_205>",
1544
+ "lstrip": false,
1545
+ "normalized": false,
1546
+ "rstrip": false,
1547
+ "single_word": false
1548
+ },
1549
+ {
1550
+ "content": "<FAKE_PAD_206>",
1551
+ "lstrip": false,
1552
+ "normalized": false,
1553
+ "rstrip": false,
1554
+ "single_word": false
1555
+ },
1556
+ {
1557
+ "content": "<FAKE_PAD_207>",
1558
+ "lstrip": false,
1559
+ "normalized": false,
1560
+ "rstrip": false,
1561
+ "single_word": false
1562
+ },
1563
+ {
1564
+ "content": "<FAKE_PAD_208>",
1565
+ "lstrip": false,
1566
+ "normalized": false,
1567
+ "rstrip": false,
1568
+ "single_word": false
1569
+ },
1570
+ {
1571
+ "content": "<FAKE_PAD_209>",
1572
+ "lstrip": false,
1573
+ "normalized": false,
1574
+ "rstrip": false,
1575
+ "single_word": false
1576
+ },
1577
+ {
1578
+ "content": "<FAKE_PAD_210>",
1579
+ "lstrip": false,
1580
+ "normalized": false,
1581
+ "rstrip": false,
1582
+ "single_word": false
1583
+ },
1584
+ {
1585
+ "content": "<FAKE_PAD_211>",
1586
+ "lstrip": false,
1587
+ "normalized": false,
1588
+ "rstrip": false,
1589
+ "single_word": false
1590
+ },
1591
+ {
1592
+ "content": "<FAKE_PAD_212>",
1593
+ "lstrip": false,
1594
+ "normalized": false,
1595
+ "rstrip": false,
1596
+ "single_word": false
1597
+ },
1598
+ {
1599
+ "content": "<FAKE_PAD_213>",
1600
+ "lstrip": false,
1601
+ "normalized": false,
1602
+ "rstrip": false,
1603
+ "single_word": false
1604
+ },
1605
+ {
1606
+ "content": "<FAKE_PAD_214>",
1607
+ "lstrip": false,
1608
+ "normalized": false,
1609
+ "rstrip": false,
1610
+ "single_word": false
1611
+ },
1612
+ {
1613
+ "content": "<FAKE_PAD_215>",
1614
+ "lstrip": false,
1615
+ "normalized": false,
1616
+ "rstrip": false,
1617
+ "single_word": false
1618
+ },
1619
+ {
1620
+ "content": "<FAKE_PAD_216>",
1621
+ "lstrip": false,
1622
+ "normalized": false,
1623
+ "rstrip": false,
1624
+ "single_word": false
1625
+ },
1626
+ {
1627
+ "content": "<FAKE_PAD_217>",
1628
+ "lstrip": false,
1629
+ "normalized": false,
1630
+ "rstrip": false,
1631
+ "single_word": false
1632
+ },
1633
+ {
1634
+ "content": "<FAKE_PAD_218>",
1635
+ "lstrip": false,
1636
+ "normalized": false,
1637
+ "rstrip": false,
1638
+ "single_word": false
1639
+ },
1640
+ {
1641
+ "content": "<FAKE_PAD_219>",
1642
+ "lstrip": false,
1643
+ "normalized": false,
1644
+ "rstrip": false,
1645
+ "single_word": false
1646
+ },
1647
+ {
1648
+ "content": "<FAKE_PAD_220>",
1649
+ "lstrip": false,
1650
+ "normalized": false,
1651
+ "rstrip": false,
1652
+ "single_word": false
1653
+ },
1654
+ {
1655
+ "content": "<FAKE_PAD_221>",
1656
+ "lstrip": false,
1657
+ "normalized": false,
1658
+ "rstrip": false,
1659
+ "single_word": false
1660
+ },
1661
+ {
1662
+ "content": "<FAKE_PAD_222>",
1663
+ "lstrip": false,
1664
+ "normalized": false,
1665
+ "rstrip": false,
1666
+ "single_word": false
1667
+ },
1668
+ {
1669
+ "content": "<FAKE_PAD_223>",
1670
+ "lstrip": false,
1671
+ "normalized": false,
1672
+ "rstrip": false,
1673
+ "single_word": false
1674
+ },
1675
+ {
1676
+ "content": "<FAKE_PAD_224>",
1677
+ "lstrip": false,
1678
+ "normalized": false,
1679
+ "rstrip": false,
1680
+ "single_word": false
1681
+ },
1682
+ {
1683
+ "content": "<FAKE_PAD_225>",
1684
+ "lstrip": false,
1685
+ "normalized": false,
1686
+ "rstrip": false,
1687
+ "single_word": false
1688
+ },
1689
+ {
1690
+ "content": "<FAKE_PAD_226>",
1691
+ "lstrip": false,
1692
+ "normalized": false,
1693
+ "rstrip": false,
1694
+ "single_word": false
1695
+ },
1696
+ {
1697
+ "content": "<FAKE_PAD_227>",
1698
+ "lstrip": false,
1699
+ "normalized": false,
1700
+ "rstrip": false,
1701
+ "single_word": false
1702
+ },
1703
+ {
1704
+ "content": "<FAKE_PAD_228>",
1705
+ "lstrip": false,
1706
+ "normalized": false,
1707
+ "rstrip": false,
1708
+ "single_word": false
1709
+ },
1710
+ {
1711
+ "content": "<FAKE_PAD_229>",
1712
+ "lstrip": false,
1713
+ "normalized": false,
1714
+ "rstrip": false,
1715
+ "single_word": false
1716
+ },
1717
+ {
1718
+ "content": "<FAKE_PAD_230>",
1719
+ "lstrip": false,
1720
+ "normalized": false,
1721
+ "rstrip": false,
1722
+ "single_word": false
1723
+ },
1724
+ {
1725
+ "content": "<FAKE_PAD_231>",
1726
+ "lstrip": false,
1727
+ "normalized": false,
1728
+ "rstrip": false,
1729
+ "single_word": false
1730
+ },
1731
+ {
1732
+ "content": "<FAKE_PAD_232>",
1733
+ "lstrip": false,
1734
+ "normalized": false,
1735
+ "rstrip": false,
1736
+ "single_word": false
1737
+ },
1738
+ {
1739
+ "content": "<FAKE_PAD_233>",
1740
+ "lstrip": false,
1741
+ "normalized": false,
1742
+ "rstrip": false,
1743
+ "single_word": false
1744
+ },
1745
+ {
1746
+ "content": "<FAKE_PAD_234>",
1747
+ "lstrip": false,
1748
+ "normalized": false,
1749
+ "rstrip": false,
1750
+ "single_word": false
1751
+ },
1752
+ {
1753
+ "content": "<FAKE_PAD_235>",
1754
+ "lstrip": false,
1755
+ "normalized": false,
1756
+ "rstrip": false,
1757
+ "single_word": false
1758
+ },
1759
+ {
1760
+ "content": "<FAKE_PAD_236>",
1761
+ "lstrip": false,
1762
+ "normalized": false,
1763
+ "rstrip": false,
1764
+ "single_word": false
1765
+ },
1766
+ {
1767
+ "content": "<FAKE_PAD_237>",
1768
+ "lstrip": false,
1769
+ "normalized": false,
1770
+ "rstrip": false,
1771
+ "single_word": false
1772
+ },
1773
+ {
1774
+ "content": "<FAKE_PAD_238>",
1775
+ "lstrip": false,
1776
+ "normalized": false,
1777
+ "rstrip": false,
1778
+ "single_word": false
1779
+ },
1780
+ {
1781
+ "content": "<FAKE_PAD_239>",
1782
+ "lstrip": false,
1783
+ "normalized": false,
1784
+ "rstrip": false,
1785
+ "single_word": false
1786
+ },
1787
+ {
1788
+ "content": "<FAKE_PAD_240>",
1789
+ "lstrip": false,
1790
+ "normalized": false,
1791
+ "rstrip": false,
1792
+ "single_word": false
1793
+ },
1794
+ {
1795
+ "content": "<FAKE_PAD_241>",
1796
+ "lstrip": false,
1797
+ "normalized": false,
1798
+ "rstrip": false,
1799
+ "single_word": false
1800
+ },
1801
+ {
1802
+ "content": "<FAKE_PAD_242>",
1803
+ "lstrip": false,
1804
+ "normalized": false,
1805
+ "rstrip": false,
1806
+ "single_word": false
1807
+ },
1808
+ {
1809
+ "content": "<FAKE_PAD_243>",
1810
+ "lstrip": false,
1811
+ "normalized": false,
1812
+ "rstrip": false,
1813
+ "single_word": false
1814
+ },
1815
+ {
1816
+ "content": "<FAKE_PAD_244>",
1817
+ "lstrip": false,
1818
+ "normalized": false,
1819
+ "rstrip": false,
1820
+ "single_word": false
1821
+ },
1822
+ {
1823
+ "content": "<FAKE_PAD_245>",
1824
+ "lstrip": false,
1825
+ "normalized": false,
1826
+ "rstrip": false,
1827
+ "single_word": false
1828
+ },
1829
+ {
1830
+ "content": "<FAKE_PAD_246>",
1831
+ "lstrip": false,
1832
+ "normalized": false,
1833
+ "rstrip": false,
1834
+ "single_word": false
1835
+ },
1836
+ {
1837
+ "content": "<FAKE_PAD_247>",
1838
+ "lstrip": false,
1839
+ "normalized": false,
1840
+ "rstrip": false,
1841
+ "single_word": false
1842
+ },
1843
+ {
1844
+ "content": "<FAKE_PAD_248>",
1845
+ "lstrip": false,
1846
+ "normalized": false,
1847
+ "rstrip": false,
1848
+ "single_word": false
1849
+ },
1850
+ {
1851
+ "content": "<FAKE_PAD_249>",
1852
+ "lstrip": false,
1853
+ "normalized": false,
1854
+ "rstrip": false,
1855
+ "single_word": false
1856
+ },
1857
+ {
1858
+ "content": "<FAKE_PAD_250>",
1859
+ "lstrip": false,
1860
+ "normalized": false,
1861
+ "rstrip": false,
1862
+ "single_word": false
1863
+ },
1864
+ {
1865
+ "content": "<FAKE_PAD_251>",
1866
+ "lstrip": false,
1867
+ "normalized": false,
1868
+ "rstrip": false,
1869
+ "single_word": false
1870
+ },
1871
+ {
1872
+ "content": "<FAKE_PAD_252>",
1873
+ "lstrip": false,
1874
+ "normalized": false,
1875
+ "rstrip": false,
1876
+ "single_word": false
1877
+ },
1878
+ {
1879
+ "content": "<FAKE_PAD_253>",
1880
+ "lstrip": false,
1881
+ "normalized": false,
1882
+ "rstrip": false,
1883
+ "single_word": false
1884
+ }
1885
+ ],
1886
+ "eos_token": {
1887
+ "content": "<|im_end|>",
1888
+ "lstrip": false,
1889
+ "normalized": false,
1890
+ "rstrip": false,
1891
+ "single_word": false
1892
+ },
1893
+ "pad_token": {
1894
+ "content": "<|endoftext|>",
1895
+ "lstrip": false,
1896
+ "normalized": false,
1897
+ "rstrip": false,
1898
+ "single_word": false
1899
+ }
1900
+ }
tokenizer_config.json ADDED
@@ -0,0 +1,2643 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": false,
5
+ "added_tokens_decoder": {
6
+ "151643": {
7
+ "content": "<|endoftext|>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "151644": {
15
+ "content": "<|im_start|>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "151645": {
23
+ "content": "<|im_end|>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": true
29
+ },
30
+ "151646": {
31
+ "content": "<|object_ref_start|>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ },
38
+ "151647": {
39
+ "content": "<|object_ref_end|>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": false,
43
+ "single_word": false,
44
+ "special": true
45
+ },
46
+ "151648": {
47
+ "content": "<|box_start|>",
48
+ "lstrip": false,
49
+ "normalized": false,
50
+ "rstrip": false,
51
+ "single_word": false,
52
+ "special": true
53
+ },
54
+ "151649": {
55
+ "content": "<|box_end|>",
56
+ "lstrip": false,
57
+ "normalized": false,
58
+ "rstrip": false,
59
+ "single_word": false,
60
+ "special": true
61
+ },
62
+ "151650": {
63
+ "content": "<|quad_start|>",
64
+ "lstrip": false,
65
+ "normalized": false,
66
+ "rstrip": false,
67
+ "single_word": false,
68
+ "special": true
69
+ },
70
+ "151651": {
71
+ "content": "<|quad_end|>",
72
+ "lstrip": false,
73
+ "normalized": false,
74
+ "rstrip": false,
75
+ "single_word": false,
76
+ "special": true
77
+ },
78
+ "151652": {
79
+ "content": "<|vision_start|>",
80
+ "lstrip": false,
81
+ "normalized": false,
82
+ "rstrip": false,
83
+ "single_word": false,
84
+ "special": true
85
+ },
86
+ "151653": {
87
+ "content": "<|vision_end|>",
88
+ "lstrip": false,
89
+ "normalized": false,
90
+ "rstrip": false,
91
+ "single_word": false,
92
+ "special": true
93
+ },
94
+ "151654": {
95
+ "content": "<|vision_pad|>",
96
+ "lstrip": false,
97
+ "normalized": false,
98
+ "rstrip": false,
99
+ "single_word": false,
100
+ "special": true
101
+ },
102
+ "151655": {
103
+ "content": "<|image_pad|>",
104
+ "lstrip": false,
105
+ "normalized": false,
106
+ "rstrip": false,
107
+ "single_word": false,
108
+ "special": true
109
+ },
110
+ "151656": {
111
+ "content": "<|video_pad|>",
112
+ "lstrip": false,
113
+ "normalized": false,
114
+ "rstrip": false,
115
+ "single_word": false,
116
+ "special": true
117
+ },
118
+ "151657": {
119
+ "content": "<tool_call>",
120
+ "lstrip": false,
121
+ "normalized": false,
122
+ "rstrip": false,
123
+ "single_word": false,
124
+ "special": false
125
+ },
126
+ "151658": {
127
+ "content": "</tool_call>",
128
+ "lstrip": false,
129
+ "normalized": false,
130
+ "rstrip": false,
131
+ "single_word": false,
132
+ "special": false
133
+ },
134
+ "151659": {
135
+ "content": "<|fim_prefix|>",
136
+ "lstrip": false,
137
+ "normalized": false,
138
+ "rstrip": false,
139
+ "single_word": false,
140
+ "special": false
141
+ },
142
+ "151660": {
143
+ "content": "<|fim_middle|>",
144
+ "lstrip": false,
145
+ "normalized": false,
146
+ "rstrip": false,
147
+ "single_word": false,
148
+ "special": false
149
+ },
150
+ "151661": {
151
+ "content": "<|fim_suffix|>",
152
+ "lstrip": false,
153
+ "normalized": false,
154
+ "rstrip": false,
155
+ "single_word": false,
156
+ "special": false
157
+ },
158
+ "151662": {
159
+ "content": "<|fim_pad|>",
160
+ "lstrip": false,
161
+ "normalized": false,
162
+ "rstrip": false,
163
+ "single_word": false,
164
+ "special": false
165
+ },
166
+ "151663": {
167
+ "content": "<|repo_name|>",
168
+ "lstrip": false,
169
+ "normalized": false,
170
+ "rstrip": false,
171
+ "single_word": false,
172
+ "special": false
173
+ },
174
+ "151664": {
175
+ "content": "<|file_sep|>",
176
+ "lstrip": false,
177
+ "normalized": false,
178
+ "rstrip": false,
179
+ "single_word": false,
180
+ "special": false
181
+ },
182
+ "151665": {
183
+ "content": "<tool_response>",
184
+ "lstrip": false,
185
+ "normalized": false,
186
+ "rstrip": false,
187
+ "single_word": false,
188
+ "special": false
189
+ },
190
+ "151666": {
191
+ "content": "</tool_response>",
192
+ "lstrip": false,
193
+ "normalized": false,
194
+ "rstrip": false,
195
+ "single_word": false,
196
+ "special": false
197
+ },
198
+ "151667": {
199
+ "content": "<think>",
200
+ "lstrip": false,
201
+ "normalized": false,
202
+ "rstrip": false,
203
+ "single_word": false,
204
+ "special": false
205
+ },
206
+ "151668": {
207
+ "content": "</think>",
208
+ "lstrip": false,
209
+ "normalized": false,
210
+ "rstrip": false,
211
+ "single_word": false,
212
+ "special": false
213
+ },
214
+ "151669": {
215
+ "content": "<IMG_CONTEXT>",
216
+ "lstrip": false,
217
+ "normalized": false,
218
+ "rstrip": false,
219
+ "single_word": false,
220
+ "special": true
221
+ },
222
+ "151670": {
223
+ "content": "<img>",
224
+ "lstrip": false,
225
+ "normalized": false,
226
+ "rstrip": false,
227
+ "single_word": false,
228
+ "special": true
229
+ },
230
+ "151671": {
231
+ "content": "</img>",
232
+ "lstrip": false,
233
+ "normalized": false,
234
+ "rstrip": false,
235
+ "single_word": false,
236
+ "special": true
237
+ },
238
+ "151672": {
239
+ "content": "<quad>",
240
+ "lstrip": false,
241
+ "normalized": false,
242
+ "rstrip": false,
243
+ "single_word": false,
244
+ "special": true
245
+ },
246
+ "151673": {
247
+ "content": "</quad>",
248
+ "lstrip": false,
249
+ "normalized": false,
250
+ "rstrip": false,
251
+ "single_word": false,
252
+ "special": true
253
+ },
254
+ "151674": {
255
+ "content": "<ref>",
256
+ "lstrip": false,
257
+ "normalized": false,
258
+ "rstrip": false,
259
+ "single_word": false,
260
+ "special": true
261
+ },
262
+ "151675": {
263
+ "content": "</ref>",
264
+ "lstrip": false,
265
+ "normalized": false,
266
+ "rstrip": false,
267
+ "single_word": false,
268
+ "special": true
269
+ },
270
+ "151676": {
271
+ "content": "<box>",
272
+ "lstrip": false,
273
+ "normalized": false,
274
+ "rstrip": false,
275
+ "single_word": false,
276
+ "special": true
277
+ },
278
+ "151677": {
279
+ "content": "</box>",
280
+ "lstrip": false,
281
+ "normalized": false,
282
+ "rstrip": false,
283
+ "single_word": false,
284
+ "special": true
285
+ },
286
+ "151678": {
287
+ "content": "<|action_start|>",
288
+ "lstrip": false,
289
+ "normalized": false,
290
+ "rstrip": false,
291
+ "single_word": false,
292
+ "special": true
293
+ },
294
+ "151679": {
295
+ "content": "<|action_end|>",
296
+ "lstrip": false,
297
+ "normalized": false,
298
+ "rstrip": false,
299
+ "single_word": false,
300
+ "special": true
301
+ },
302
+ "151680": {
303
+ "content": "<|plugin|>",
304
+ "lstrip": false,
305
+ "normalized": false,
306
+ "rstrip": false,
307
+ "single_word": false,
308
+ "special": true
309
+ },
310
+ "151681": {
311
+ "content": "<|interpreter|>",
312
+ "lstrip": false,
313
+ "normalized": false,
314
+ "rstrip": false,
315
+ "single_word": false,
316
+ "special": true
317
+ },
318
+ "151682": {
319
+ "content": "<FAKE_PAD_0>",
320
+ "lstrip": false,
321
+ "normalized": false,
322
+ "rstrip": false,
323
+ "single_word": false,
324
+ "special": true
325
+ },
326
+ "151683": {
327
+ "content": "<FAKE_PAD_1>",
328
+ "lstrip": false,
329
+ "normalized": false,
330
+ "rstrip": false,
331
+ "single_word": false,
332
+ "special": true
333
+ },
334
+ "151684": {
335
+ "content": "<FAKE_PAD_2>",
336
+ "lstrip": false,
337
+ "normalized": false,
338
+ "rstrip": false,
339
+ "single_word": false,
340
+ "special": true
341
+ },
342
+ "151685": {
343
+ "content": "<FAKE_PAD_3>",
344
+ "lstrip": false,
345
+ "normalized": false,
346
+ "rstrip": false,
347
+ "single_word": false,
348
+ "special": true
349
+ },
350
+ "151686": {
351
+ "content": "<FAKE_PAD_4>",
352
+ "lstrip": false,
353
+ "normalized": false,
354
+ "rstrip": false,
355
+ "single_word": false,
356
+ "special": true
357
+ },
358
+ "151687": {
359
+ "content": "<FAKE_PAD_5>",
360
+ "lstrip": false,
361
+ "normalized": false,
362
+ "rstrip": false,
363
+ "single_word": false,
364
+ "special": true
365
+ },
366
+ "151688": {
367
+ "content": "<FAKE_PAD_6>",
368
+ "lstrip": false,
369
+ "normalized": false,
370
+ "rstrip": false,
371
+ "single_word": false,
372
+ "special": true
373
+ },
374
+ "151689": {
375
+ "content": "<FAKE_PAD_7>",
376
+ "lstrip": false,
377
+ "normalized": false,
378
+ "rstrip": false,
379
+ "single_word": false,
380
+ "special": true
381
+ },
382
+ "151690": {
383
+ "content": "<FAKE_PAD_8>",
384
+ "lstrip": false,
385
+ "normalized": false,
386
+ "rstrip": false,
387
+ "single_word": false,
388
+ "special": true
389
+ },
390
+ "151691": {
391
+ "content": "<FAKE_PAD_9>",
392
+ "lstrip": false,
393
+ "normalized": false,
394
+ "rstrip": false,
395
+ "single_word": false,
396
+ "special": true
397
+ },
398
+ "151692": {
399
+ "content": "<FAKE_PAD_10>",
400
+ "lstrip": false,
401
+ "normalized": false,
402
+ "rstrip": false,
403
+ "single_word": false,
404
+ "special": true
405
+ },
406
+ "151693": {
407
+ "content": "<FAKE_PAD_11>",
408
+ "lstrip": false,
409
+ "normalized": false,
410
+ "rstrip": false,
411
+ "single_word": false,
412
+ "special": true
413
+ },
414
+ "151694": {
415
+ "content": "<FAKE_PAD_12>",
416
+ "lstrip": false,
417
+ "normalized": false,
418
+ "rstrip": false,
419
+ "single_word": false,
420
+ "special": true
421
+ },
422
+ "151695": {
423
+ "content": "<FAKE_PAD_13>",
424
+ "lstrip": false,
425
+ "normalized": false,
426
+ "rstrip": false,
427
+ "single_word": false,
428
+ "special": true
429
+ },
430
+ "151696": {
431
+ "content": "<FAKE_PAD_14>",
432
+ "lstrip": false,
433
+ "normalized": false,
434
+ "rstrip": false,
435
+ "single_word": false,
436
+ "special": true
437
+ },
438
+ "151697": {
439
+ "content": "<FAKE_PAD_15>",
440
+ "lstrip": false,
441
+ "normalized": false,
442
+ "rstrip": false,
443
+ "single_word": false,
444
+ "special": true
445
+ },
446
+ "151698": {
447
+ "content": "<FAKE_PAD_16>",
448
+ "lstrip": false,
449
+ "normalized": false,
450
+ "rstrip": false,
451
+ "single_word": false,
452
+ "special": true
453
+ },
454
+ "151699": {
455
+ "content": "<FAKE_PAD_17>",
456
+ "lstrip": false,
457
+ "normalized": false,
458
+ "rstrip": false,
459
+ "single_word": false,
460
+ "special": true
461
+ },
462
+ "151700": {
463
+ "content": "<FAKE_PAD_18>",
464
+ "lstrip": false,
465
+ "normalized": false,
466
+ "rstrip": false,
467
+ "single_word": false,
468
+ "special": true
469
+ },
470
+ "151701": {
471
+ "content": "<FAKE_PAD_19>",
472
+ "lstrip": false,
473
+ "normalized": false,
474
+ "rstrip": false,
475
+ "single_word": false,
476
+ "special": true
477
+ },
478
+ "151702": {
479
+ "content": "<FAKE_PAD_20>",
480
+ "lstrip": false,
481
+ "normalized": false,
482
+ "rstrip": false,
483
+ "single_word": false,
484
+ "special": true
485
+ },
486
+ "151703": {
487
+ "content": "<FAKE_PAD_21>",
488
+ "lstrip": false,
489
+ "normalized": false,
490
+ "rstrip": false,
491
+ "single_word": false,
492
+ "special": true
493
+ },
494
+ "151704": {
495
+ "content": "<FAKE_PAD_22>",
496
+ "lstrip": false,
497
+ "normalized": false,
498
+ "rstrip": false,
499
+ "single_word": false,
500
+ "special": true
501
+ },
502
+ "151705": {
503
+ "content": "<FAKE_PAD_23>",
504
+ "lstrip": false,
505
+ "normalized": false,
506
+ "rstrip": false,
507
+ "single_word": false,
508
+ "special": true
509
+ },
510
+ "151706": {
511
+ "content": "<FAKE_PAD_24>",
512
+ "lstrip": false,
513
+ "normalized": false,
514
+ "rstrip": false,
515
+ "single_word": false,
516
+ "special": true
517
+ },
518
+ "151707": {
519
+ "content": "<FAKE_PAD_25>",
520
+ "lstrip": false,
521
+ "normalized": false,
522
+ "rstrip": false,
523
+ "single_word": false,
524
+ "special": true
525
+ },
526
+ "151708": {
527
+ "content": "<FAKE_PAD_26>",
528
+ "lstrip": false,
529
+ "normalized": false,
530
+ "rstrip": false,
531
+ "single_word": false,
532
+ "special": true
533
+ },
534
+ "151709": {
535
+ "content": "<FAKE_PAD_27>",
536
+ "lstrip": false,
537
+ "normalized": false,
538
+ "rstrip": false,
539
+ "single_word": false,
540
+ "special": true
541
+ },
542
+ "151710": {
543
+ "content": "<FAKE_PAD_28>",
544
+ "lstrip": false,
545
+ "normalized": false,
546
+ "rstrip": false,
547
+ "single_word": false,
548
+ "special": true
549
+ },
550
+ "151711": {
551
+ "content": "<FAKE_PAD_29>",
552
+ "lstrip": false,
553
+ "normalized": false,
554
+ "rstrip": false,
555
+ "single_word": false,
556
+ "special": true
557
+ },
558
+ "151712": {
559
+ "content": "<FAKE_PAD_30>",
560
+ "lstrip": false,
561
+ "normalized": false,
562
+ "rstrip": false,
563
+ "single_word": false,
564
+ "special": true
565
+ },
566
+ "151713": {
567
+ "content": "<FAKE_PAD_31>",
568
+ "lstrip": false,
569
+ "normalized": false,
570
+ "rstrip": false,
571
+ "single_word": false,
572
+ "special": true
573
+ },
574
+ "151714": {
575
+ "content": "<FAKE_PAD_32>",
576
+ "lstrip": false,
577
+ "normalized": false,
578
+ "rstrip": false,
579
+ "single_word": false,
580
+ "special": true
581
+ },
582
+ "151715": {
583
+ "content": "<FAKE_PAD_33>",
584
+ "lstrip": false,
585
+ "normalized": false,
586
+ "rstrip": false,
587
+ "single_word": false,
588
+ "special": true
589
+ },
590
+ "151716": {
591
+ "content": "<FAKE_PAD_34>",
592
+ "lstrip": false,
593
+ "normalized": false,
594
+ "rstrip": false,
595
+ "single_word": false,
596
+ "special": true
597
+ },
598
+ "151717": {
599
+ "content": "<FAKE_PAD_35>",
600
+ "lstrip": false,
601
+ "normalized": false,
602
+ "rstrip": false,
603
+ "single_word": false,
604
+ "special": true
605
+ },
606
+ "151718": {
607
+ "content": "<FAKE_PAD_36>",
608
+ "lstrip": false,
609
+ "normalized": false,
610
+ "rstrip": false,
611
+ "single_word": false,
612
+ "special": true
613
+ },
614
+ "151719": {
615
+ "content": "<FAKE_PAD_37>",
616
+ "lstrip": false,
617
+ "normalized": false,
618
+ "rstrip": false,
619
+ "single_word": false,
620
+ "special": true
621
+ },
622
+ "151720": {
623
+ "content": "<FAKE_PAD_38>",
624
+ "lstrip": false,
625
+ "normalized": false,
626
+ "rstrip": false,
627
+ "single_word": false,
628
+ "special": true
629
+ },
630
+ "151721": {
631
+ "content": "<FAKE_PAD_39>",
632
+ "lstrip": false,
633
+ "normalized": false,
634
+ "rstrip": false,
635
+ "single_word": false,
636
+ "special": true
637
+ },
638
+ "151722": {
639
+ "content": "<FAKE_PAD_40>",
640
+ "lstrip": false,
641
+ "normalized": false,
642
+ "rstrip": false,
643
+ "single_word": false,
644
+ "special": true
645
+ },
646
+ "151723": {
647
+ "content": "<FAKE_PAD_41>",
648
+ "lstrip": false,
649
+ "normalized": false,
650
+ "rstrip": false,
651
+ "single_word": false,
652
+ "special": true
653
+ },
654
+ "151724": {
655
+ "content": "<FAKE_PAD_42>",
656
+ "lstrip": false,
657
+ "normalized": false,
658
+ "rstrip": false,
659
+ "single_word": false,
660
+ "special": true
661
+ },
662
+ "151725": {
663
+ "content": "<FAKE_PAD_43>",
664
+ "lstrip": false,
665
+ "normalized": false,
666
+ "rstrip": false,
667
+ "single_word": false,
668
+ "special": true
669
+ },
670
+ "151726": {
671
+ "content": "<FAKE_PAD_44>",
672
+ "lstrip": false,
673
+ "normalized": false,
674
+ "rstrip": false,
675
+ "single_word": false,
676
+ "special": true
677
+ },
678
+ "151727": {
679
+ "content": "<FAKE_PAD_45>",
680
+ "lstrip": false,
681
+ "normalized": false,
682
+ "rstrip": false,
683
+ "single_word": false,
684
+ "special": true
685
+ },
686
+ "151728": {
687
+ "content": "<FAKE_PAD_46>",
688
+ "lstrip": false,
689
+ "normalized": false,
690
+ "rstrip": false,
691
+ "single_word": false,
692
+ "special": true
693
+ },
694
+ "151729": {
695
+ "content": "<FAKE_PAD_47>",
696
+ "lstrip": false,
697
+ "normalized": false,
698
+ "rstrip": false,
699
+ "single_word": false,
700
+ "special": true
701
+ },
702
+ "151730": {
703
+ "content": "<FAKE_PAD_48>",
704
+ "lstrip": false,
705
+ "normalized": false,
706
+ "rstrip": false,
707
+ "single_word": false,
708
+ "special": true
709
+ },
710
+ "151731": {
711
+ "content": "<FAKE_PAD_49>",
712
+ "lstrip": false,
713
+ "normalized": false,
714
+ "rstrip": false,
715
+ "single_word": false,
716
+ "special": true
717
+ },
718
+ "151732": {
719
+ "content": "<FAKE_PAD_50>",
720
+ "lstrip": false,
721
+ "normalized": false,
722
+ "rstrip": false,
723
+ "single_word": false,
724
+ "special": true
725
+ },
726
+ "151733": {
727
+ "content": "<FAKE_PAD_51>",
728
+ "lstrip": false,
729
+ "normalized": false,
730
+ "rstrip": false,
731
+ "single_word": false,
732
+ "special": true
733
+ },
734
+ "151734": {
735
+ "content": "<FAKE_PAD_52>",
736
+ "lstrip": false,
737
+ "normalized": false,
738
+ "rstrip": false,
739
+ "single_word": false,
740
+ "special": true
741
+ },
742
+ "151735": {
743
+ "content": "<FAKE_PAD_53>",
744
+ "lstrip": false,
745
+ "normalized": false,
746
+ "rstrip": false,
747
+ "single_word": false,
748
+ "special": true
749
+ },
750
+ "151736": {
751
+ "content": "<FAKE_PAD_54>",
752
+ "lstrip": false,
753
+ "normalized": false,
754
+ "rstrip": false,
755
+ "single_word": false,
756
+ "special": true
757
+ },
758
+ "151737": {
759
+ "content": "<FAKE_PAD_55>",
760
+ "lstrip": false,
761
+ "normalized": false,
762
+ "rstrip": false,
763
+ "single_word": false,
764
+ "special": true
765
+ },
766
+ "151738": {
767
+ "content": "<FAKE_PAD_56>",
768
+ "lstrip": false,
769
+ "normalized": false,
770
+ "rstrip": false,
771
+ "single_word": false,
772
+ "special": true
773
+ },
774
+ "151739": {
775
+ "content": "<FAKE_PAD_57>",
776
+ "lstrip": false,
777
+ "normalized": false,
778
+ "rstrip": false,
779
+ "single_word": false,
780
+ "special": true
781
+ },
782
+ "151740": {
783
+ "content": "<FAKE_PAD_58>",
784
+ "lstrip": false,
785
+ "normalized": false,
786
+ "rstrip": false,
787
+ "single_word": false,
788
+ "special": true
789
+ },
790
+ "151741": {
791
+ "content": "<FAKE_PAD_59>",
792
+ "lstrip": false,
793
+ "normalized": false,
794
+ "rstrip": false,
795
+ "single_word": false,
796
+ "special": true
797
+ },
798
+ "151742": {
799
+ "content": "<FAKE_PAD_60>",
800
+ "lstrip": false,
801
+ "normalized": false,
802
+ "rstrip": false,
803
+ "single_word": false,
804
+ "special": true
805
+ },
806
+ "151743": {
807
+ "content": "<FAKE_PAD_61>",
808
+ "lstrip": false,
809
+ "normalized": false,
810
+ "rstrip": false,
811
+ "single_word": false,
812
+ "special": true
813
+ },
814
+ "151744": {
815
+ "content": "<FAKE_PAD_62>",
816
+ "lstrip": false,
817
+ "normalized": false,
818
+ "rstrip": false,
819
+ "single_word": false,
820
+ "special": true
821
+ },
822
+ "151745": {
823
+ "content": "<FAKE_PAD_63>",
824
+ "lstrip": false,
825
+ "normalized": false,
826
+ "rstrip": false,
827
+ "single_word": false,
828
+ "special": true
829
+ },
830
+ "151746": {
831
+ "content": "<FAKE_PAD_64>",
832
+ "lstrip": false,
833
+ "normalized": false,
834
+ "rstrip": false,
835
+ "single_word": false,
836
+ "special": true
837
+ },
838
+ "151747": {
839
+ "content": "<FAKE_PAD_65>",
840
+ "lstrip": false,
841
+ "normalized": false,
842
+ "rstrip": false,
843
+ "single_word": false,
844
+ "special": true
845
+ },
846
+ "151748": {
847
+ "content": "<FAKE_PAD_66>",
848
+ "lstrip": false,
849
+ "normalized": false,
850
+ "rstrip": false,
851
+ "single_word": false,
852
+ "special": true
853
+ },
854
+ "151749": {
855
+ "content": "<FAKE_PAD_67>",
856
+ "lstrip": false,
857
+ "normalized": false,
858
+ "rstrip": false,
859
+ "single_word": false,
860
+ "special": true
861
+ },
862
+ "151750": {
863
+ "content": "<FAKE_PAD_68>",
864
+ "lstrip": false,
865
+ "normalized": false,
866
+ "rstrip": false,
867
+ "single_word": false,
868
+ "special": true
869
+ },
870
+ "151751": {
871
+ "content": "<FAKE_PAD_69>",
872
+ "lstrip": false,
873
+ "normalized": false,
874
+ "rstrip": false,
875
+ "single_word": false,
876
+ "special": true
877
+ },
878
+ "151752": {
879
+ "content": "<FAKE_PAD_70>",
880
+ "lstrip": false,
881
+ "normalized": false,
882
+ "rstrip": false,
883
+ "single_word": false,
884
+ "special": true
885
+ },
886
+ "151753": {
887
+ "content": "<FAKE_PAD_71>",
888
+ "lstrip": false,
889
+ "normalized": false,
890
+ "rstrip": false,
891
+ "single_word": false,
892
+ "special": true
893
+ },
894
+ "151754": {
895
+ "content": "<FAKE_PAD_72>",
896
+ "lstrip": false,
897
+ "normalized": false,
898
+ "rstrip": false,
899
+ "single_word": false,
900
+ "special": true
901
+ },
902
+ "151755": {
903
+ "content": "<FAKE_PAD_73>",
904
+ "lstrip": false,
905
+ "normalized": false,
906
+ "rstrip": false,
907
+ "single_word": false,
908
+ "special": true
909
+ },
910
+ "151756": {
911
+ "content": "<FAKE_PAD_74>",
912
+ "lstrip": false,
913
+ "normalized": false,
914
+ "rstrip": false,
915
+ "single_word": false,
916
+ "special": true
917
+ },
918
+ "151757": {
919
+ "content": "<FAKE_PAD_75>",
920
+ "lstrip": false,
921
+ "normalized": false,
922
+ "rstrip": false,
923
+ "single_word": false,
924
+ "special": true
925
+ },
926
+ "151758": {
927
+ "content": "<FAKE_PAD_76>",
928
+ "lstrip": false,
929
+ "normalized": false,
930
+ "rstrip": false,
931
+ "single_word": false,
932
+ "special": true
933
+ },
934
+ "151759": {
935
+ "content": "<FAKE_PAD_77>",
936
+ "lstrip": false,
937
+ "normalized": false,
938
+ "rstrip": false,
939
+ "single_word": false,
940
+ "special": true
941
+ },
942
+ "151760": {
943
+ "content": "<FAKE_PAD_78>",
944
+ "lstrip": false,
945
+ "normalized": false,
946
+ "rstrip": false,
947
+ "single_word": false,
948
+ "special": true
949
+ },
950
+ "151761": {
951
+ "content": "<FAKE_PAD_79>",
952
+ "lstrip": false,
953
+ "normalized": false,
954
+ "rstrip": false,
955
+ "single_word": false,
956
+ "special": true
957
+ },
958
+ "151762": {
959
+ "content": "<FAKE_PAD_80>",
960
+ "lstrip": false,
961
+ "normalized": false,
962
+ "rstrip": false,
963
+ "single_word": false,
964
+ "special": true
965
+ },
966
+ "151763": {
967
+ "content": "<FAKE_PAD_81>",
968
+ "lstrip": false,
969
+ "normalized": false,
970
+ "rstrip": false,
971
+ "single_word": false,
972
+ "special": true
973
+ },
974
+ "151764": {
975
+ "content": "<FAKE_PAD_82>",
976
+ "lstrip": false,
977
+ "normalized": false,
978
+ "rstrip": false,
979
+ "single_word": false,
980
+ "special": true
981
+ },
982
+ "151765": {
983
+ "content": "<FAKE_PAD_83>",
984
+ "lstrip": false,
985
+ "normalized": false,
986
+ "rstrip": false,
987
+ "single_word": false,
988
+ "special": true
989
+ },
990
+ "151766": {
991
+ "content": "<FAKE_PAD_84>",
992
+ "lstrip": false,
993
+ "normalized": false,
994
+ "rstrip": false,
995
+ "single_word": false,
996
+ "special": true
997
+ },
998
+ "151767": {
999
+ "content": "<FAKE_PAD_85>",
1000
+ "lstrip": false,
1001
+ "normalized": false,
1002
+ "rstrip": false,
1003
+ "single_word": false,
1004
+ "special": true
1005
+ },
1006
+ "151768": {
1007
+ "content": "<FAKE_PAD_86>",
1008
+ "lstrip": false,
1009
+ "normalized": false,
1010
+ "rstrip": false,
1011
+ "single_word": false,
1012
+ "special": true
1013
+ },
1014
+ "151769": {
1015
+ "content": "<FAKE_PAD_87>",
1016
+ "lstrip": false,
1017
+ "normalized": false,
1018
+ "rstrip": false,
1019
+ "single_word": false,
1020
+ "special": true
1021
+ },
1022
+ "151770": {
1023
+ "content": "<FAKE_PAD_88>",
1024
+ "lstrip": false,
1025
+ "normalized": false,
1026
+ "rstrip": false,
1027
+ "single_word": false,
1028
+ "special": true
1029
+ },
1030
+ "151771": {
1031
+ "content": "<FAKE_PAD_89>",
1032
+ "lstrip": false,
1033
+ "normalized": false,
1034
+ "rstrip": false,
1035
+ "single_word": false,
1036
+ "special": true
1037
+ },
1038
+ "151772": {
1039
+ "content": "<FAKE_PAD_90>",
1040
+ "lstrip": false,
1041
+ "normalized": false,
1042
+ "rstrip": false,
1043
+ "single_word": false,
1044
+ "special": true
1045
+ },
1046
+ "151773": {
1047
+ "content": "<FAKE_PAD_91>",
1048
+ "lstrip": false,
1049
+ "normalized": false,
1050
+ "rstrip": false,
1051
+ "single_word": false,
1052
+ "special": true
1053
+ },
1054
+ "151774": {
1055
+ "content": "<FAKE_PAD_92>",
1056
+ "lstrip": false,
1057
+ "normalized": false,
1058
+ "rstrip": false,
1059
+ "single_word": false,
1060
+ "special": true
1061
+ },
1062
+ "151775": {
1063
+ "content": "<FAKE_PAD_93>",
1064
+ "lstrip": false,
1065
+ "normalized": false,
1066
+ "rstrip": false,
1067
+ "single_word": false,
1068
+ "special": true
1069
+ },
1070
+ "151776": {
1071
+ "content": "<FAKE_PAD_94>",
1072
+ "lstrip": false,
1073
+ "normalized": false,
1074
+ "rstrip": false,
1075
+ "single_word": false,
1076
+ "special": true
1077
+ },
1078
+ "151777": {
1079
+ "content": "<FAKE_PAD_95>",
1080
+ "lstrip": false,
1081
+ "normalized": false,
1082
+ "rstrip": false,
1083
+ "single_word": false,
1084
+ "special": true
1085
+ },
1086
+ "151778": {
1087
+ "content": "<FAKE_PAD_96>",
1088
+ "lstrip": false,
1089
+ "normalized": false,
1090
+ "rstrip": false,
1091
+ "single_word": false,
1092
+ "special": true
1093
+ },
1094
+ "151779": {
1095
+ "content": "<FAKE_PAD_97>",
1096
+ "lstrip": false,
1097
+ "normalized": false,
1098
+ "rstrip": false,
1099
+ "single_word": false,
1100
+ "special": true
1101
+ },
1102
+ "151780": {
1103
+ "content": "<FAKE_PAD_98>",
1104
+ "lstrip": false,
1105
+ "normalized": false,
1106
+ "rstrip": false,
1107
+ "single_word": false,
1108
+ "special": true
1109
+ },
1110
+ "151781": {
1111
+ "content": "<FAKE_PAD_99>",
1112
+ "lstrip": false,
1113
+ "normalized": false,
1114
+ "rstrip": false,
1115
+ "single_word": false,
1116
+ "special": true
1117
+ },
1118
+ "151782": {
1119
+ "content": "<FAKE_PAD_100>",
1120
+ "lstrip": false,
1121
+ "normalized": false,
1122
+ "rstrip": false,
1123
+ "single_word": false,
1124
+ "special": true
1125
+ },
1126
+ "151783": {
1127
+ "content": "<FAKE_PAD_101>",
1128
+ "lstrip": false,
1129
+ "normalized": false,
1130
+ "rstrip": false,
1131
+ "single_word": false,
1132
+ "special": true
1133
+ },
1134
+ "151784": {
1135
+ "content": "<FAKE_PAD_102>",
1136
+ "lstrip": false,
1137
+ "normalized": false,
1138
+ "rstrip": false,
1139
+ "single_word": false,
1140
+ "special": true
1141
+ },
1142
+ "151785": {
1143
+ "content": "<FAKE_PAD_103>",
1144
+ "lstrip": false,
1145
+ "normalized": false,
1146
+ "rstrip": false,
1147
+ "single_word": false,
1148
+ "special": true
1149
+ },
1150
+ "151786": {
1151
+ "content": "<FAKE_PAD_104>",
1152
+ "lstrip": false,
1153
+ "normalized": false,
1154
+ "rstrip": false,
1155
+ "single_word": false,
1156
+ "special": true
1157
+ },
1158
+ "151787": {
1159
+ "content": "<FAKE_PAD_105>",
1160
+ "lstrip": false,
1161
+ "normalized": false,
1162
+ "rstrip": false,
1163
+ "single_word": false,
1164
+ "special": true
1165
+ },
1166
+ "151788": {
1167
+ "content": "<FAKE_PAD_106>",
1168
+ "lstrip": false,
1169
+ "normalized": false,
1170
+ "rstrip": false,
1171
+ "single_word": false,
1172
+ "special": true
1173
+ },
1174
+ "151789": {
1175
+ "content": "<FAKE_PAD_107>",
1176
+ "lstrip": false,
1177
+ "normalized": false,
1178
+ "rstrip": false,
1179
+ "single_word": false,
1180
+ "special": true
1181
+ },
1182
+ "151790": {
1183
+ "content": "<FAKE_PAD_108>",
1184
+ "lstrip": false,
1185
+ "normalized": false,
1186
+ "rstrip": false,
1187
+ "single_word": false,
1188
+ "special": true
1189
+ },
1190
+ "151791": {
1191
+ "content": "<FAKE_PAD_109>",
1192
+ "lstrip": false,
1193
+ "normalized": false,
1194
+ "rstrip": false,
1195
+ "single_word": false,
1196
+ "special": true
1197
+ },
1198
+ "151792": {
1199
+ "content": "<FAKE_PAD_110>",
1200
+ "lstrip": false,
1201
+ "normalized": false,
1202
+ "rstrip": false,
1203
+ "single_word": false,
1204
+ "special": true
1205
+ },
1206
+ "151793": {
1207
+ "content": "<FAKE_PAD_111>",
1208
+ "lstrip": false,
1209
+ "normalized": false,
1210
+ "rstrip": false,
1211
+ "single_word": false,
1212
+ "special": true
1213
+ },
1214
+ "151794": {
1215
+ "content": "<FAKE_PAD_112>",
1216
+ "lstrip": false,
1217
+ "normalized": false,
1218
+ "rstrip": false,
1219
+ "single_word": false,
1220
+ "special": true
1221
+ },
1222
+ "151795": {
1223
+ "content": "<FAKE_PAD_113>",
1224
+ "lstrip": false,
1225
+ "normalized": false,
1226
+ "rstrip": false,
1227
+ "single_word": false,
1228
+ "special": true
1229
+ },
1230
+ "151796": {
1231
+ "content": "<FAKE_PAD_114>",
1232
+ "lstrip": false,
1233
+ "normalized": false,
1234
+ "rstrip": false,
1235
+ "single_word": false,
1236
+ "special": true
1237
+ },
1238
+ "151797": {
1239
+ "content": "<FAKE_PAD_115>",
1240
+ "lstrip": false,
1241
+ "normalized": false,
1242
+ "rstrip": false,
1243
+ "single_word": false,
1244
+ "special": true
1245
+ },
1246
+ "151798": {
1247
+ "content": "<FAKE_PAD_116>",
1248
+ "lstrip": false,
1249
+ "normalized": false,
1250
+ "rstrip": false,
1251
+ "single_word": false,
1252
+ "special": true
1253
+ },
1254
+ "151799": {
1255
+ "content": "<FAKE_PAD_117>",
1256
+ "lstrip": false,
1257
+ "normalized": false,
1258
+ "rstrip": false,
1259
+ "single_word": false,
1260
+ "special": true
1261
+ },
1262
+ "151800": {
1263
+ "content": "<FAKE_PAD_118>",
1264
+ "lstrip": false,
1265
+ "normalized": false,
1266
+ "rstrip": false,
1267
+ "single_word": false,
1268
+ "special": true
1269
+ },
1270
+ "151801": {
1271
+ "content": "<FAKE_PAD_119>",
1272
+ "lstrip": false,
1273
+ "normalized": false,
1274
+ "rstrip": false,
1275
+ "single_word": false,
1276
+ "special": true
1277
+ },
1278
+ "151802": {
1279
+ "content": "<FAKE_PAD_120>",
1280
+ "lstrip": false,
1281
+ "normalized": false,
1282
+ "rstrip": false,
1283
+ "single_word": false,
1284
+ "special": true
1285
+ },
1286
+ "151803": {
1287
+ "content": "<FAKE_PAD_121>",
1288
+ "lstrip": false,
1289
+ "normalized": false,
1290
+ "rstrip": false,
1291
+ "single_word": false,
1292
+ "special": true
1293
+ },
1294
+ "151804": {
1295
+ "content": "<FAKE_PAD_122>",
1296
+ "lstrip": false,
1297
+ "normalized": false,
1298
+ "rstrip": false,
1299
+ "single_word": false,
1300
+ "special": true
1301
+ },
1302
+ "151805": {
1303
+ "content": "<FAKE_PAD_123>",
1304
+ "lstrip": false,
1305
+ "normalized": false,
1306
+ "rstrip": false,
1307
+ "single_word": false,
1308
+ "special": true
1309
+ },
1310
+ "151806": {
1311
+ "content": "<FAKE_PAD_124>",
1312
+ "lstrip": false,
1313
+ "normalized": false,
1314
+ "rstrip": false,
1315
+ "single_word": false,
1316
+ "special": true
1317
+ },
1318
+ "151807": {
1319
+ "content": "<FAKE_PAD_125>",
1320
+ "lstrip": false,
1321
+ "normalized": false,
1322
+ "rstrip": false,
1323
+ "single_word": false,
1324
+ "special": true
1325
+ },
1326
+ "151808": {
1327
+ "content": "<FAKE_PAD_126>",
1328
+ "lstrip": false,
1329
+ "normalized": false,
1330
+ "rstrip": false,
1331
+ "single_word": false,
1332
+ "special": true
1333
+ },
1334
+ "151809": {
1335
+ "content": "<FAKE_PAD_127>",
1336
+ "lstrip": false,
1337
+ "normalized": false,
1338
+ "rstrip": false,
1339
+ "single_word": false,
1340
+ "special": true
1341
+ },
1342
+ "151810": {
1343
+ "content": "<FAKE_PAD_128>",
1344
+ "lstrip": false,
1345
+ "normalized": false,
1346
+ "rstrip": false,
1347
+ "single_word": false,
1348
+ "special": true
1349
+ },
1350
+ "151811": {
1351
+ "content": "<FAKE_PAD_129>",
1352
+ "lstrip": false,
1353
+ "normalized": false,
1354
+ "rstrip": false,
1355
+ "single_word": false,
1356
+ "special": true
1357
+ },
1358
+ "151812": {
1359
+ "content": "<FAKE_PAD_130>",
1360
+ "lstrip": false,
1361
+ "normalized": false,
1362
+ "rstrip": false,
1363
+ "single_word": false,
1364
+ "special": true
1365
+ },
1366
+ "151813": {
1367
+ "content": "<FAKE_PAD_131>",
1368
+ "lstrip": false,
1369
+ "normalized": false,
1370
+ "rstrip": false,
1371
+ "single_word": false,
1372
+ "special": true
1373
+ },
1374
+ "151814": {
1375
+ "content": "<FAKE_PAD_132>",
1376
+ "lstrip": false,
1377
+ "normalized": false,
1378
+ "rstrip": false,
1379
+ "single_word": false,
1380
+ "special": true
1381
+ },
1382
+ "151815": {
1383
+ "content": "<FAKE_PAD_133>",
1384
+ "lstrip": false,
1385
+ "normalized": false,
1386
+ "rstrip": false,
1387
+ "single_word": false,
1388
+ "special": true
1389
+ },
1390
+ "151816": {
1391
+ "content": "<FAKE_PAD_134>",
1392
+ "lstrip": false,
1393
+ "normalized": false,
1394
+ "rstrip": false,
1395
+ "single_word": false,
1396
+ "special": true
1397
+ },
1398
+ "151817": {
1399
+ "content": "<FAKE_PAD_135>",
1400
+ "lstrip": false,
1401
+ "normalized": false,
1402
+ "rstrip": false,
1403
+ "single_word": false,
1404
+ "special": true
1405
+ },
1406
+ "151818": {
1407
+ "content": "<FAKE_PAD_136>",
1408
+ "lstrip": false,
1409
+ "normalized": false,
1410
+ "rstrip": false,
1411
+ "single_word": false,
1412
+ "special": true
1413
+ },
1414
+ "151819": {
1415
+ "content": "<FAKE_PAD_137>",
1416
+ "lstrip": false,
1417
+ "normalized": false,
1418
+ "rstrip": false,
1419
+ "single_word": false,
1420
+ "special": true
1421
+ },
1422
+ "151820": {
1423
+ "content": "<FAKE_PAD_138>",
1424
+ "lstrip": false,
1425
+ "normalized": false,
1426
+ "rstrip": false,
1427
+ "single_word": false,
1428
+ "special": true
1429
+ },
1430
+ "151821": {
1431
+ "content": "<FAKE_PAD_139>",
1432
+ "lstrip": false,
1433
+ "normalized": false,
1434
+ "rstrip": false,
1435
+ "single_word": false,
1436
+ "special": true
1437
+ },
1438
+ "151822": {
1439
+ "content": "<FAKE_PAD_140>",
1440
+ "lstrip": false,
1441
+ "normalized": false,
1442
+ "rstrip": false,
1443
+ "single_word": false,
1444
+ "special": true
1445
+ },
1446
+ "151823": {
1447
+ "content": "<FAKE_PAD_141>",
1448
+ "lstrip": false,
1449
+ "normalized": false,
1450
+ "rstrip": false,
1451
+ "single_word": false,
1452
+ "special": true
1453
+ },
1454
+ "151824": {
1455
+ "content": "<FAKE_PAD_142>",
1456
+ "lstrip": false,
1457
+ "normalized": false,
1458
+ "rstrip": false,
1459
+ "single_word": false,
1460
+ "special": true
1461
+ },
1462
+ "151825": {
1463
+ "content": "<FAKE_PAD_143>",
1464
+ "lstrip": false,
1465
+ "normalized": false,
1466
+ "rstrip": false,
1467
+ "single_word": false,
1468
+ "special": true
1469
+ },
1470
+ "151826": {
1471
+ "content": "<FAKE_PAD_144>",
1472
+ "lstrip": false,
1473
+ "normalized": false,
1474
+ "rstrip": false,
1475
+ "single_word": false,
1476
+ "special": true
1477
+ },
1478
+ "151827": {
1479
+ "content": "<FAKE_PAD_145>",
1480
+ "lstrip": false,
1481
+ "normalized": false,
1482
+ "rstrip": false,
1483
+ "single_word": false,
1484
+ "special": true
1485
+ },
1486
+ "151828": {
1487
+ "content": "<FAKE_PAD_146>",
1488
+ "lstrip": false,
1489
+ "normalized": false,
1490
+ "rstrip": false,
1491
+ "single_word": false,
1492
+ "special": true
1493
+ },
1494
+ "151829": {
1495
+ "content": "<FAKE_PAD_147>",
1496
+ "lstrip": false,
1497
+ "normalized": false,
1498
+ "rstrip": false,
1499
+ "single_word": false,
1500
+ "special": true
1501
+ },
1502
+ "151830": {
1503
+ "content": "<FAKE_PAD_148>",
1504
+ "lstrip": false,
1505
+ "normalized": false,
1506
+ "rstrip": false,
1507
+ "single_word": false,
1508
+ "special": true
1509
+ },
1510
+ "151831": {
1511
+ "content": "<FAKE_PAD_149>",
1512
+ "lstrip": false,
1513
+ "normalized": false,
1514
+ "rstrip": false,
1515
+ "single_word": false,
1516
+ "special": true
1517
+ },
1518
+ "151832": {
1519
+ "content": "<FAKE_PAD_150>",
1520
+ "lstrip": false,
1521
+ "normalized": false,
1522
+ "rstrip": false,
1523
+ "single_word": false,
1524
+ "special": true
1525
+ },
1526
+ "151833": {
1527
+ "content": "<FAKE_PAD_151>",
1528
+ "lstrip": false,
1529
+ "normalized": false,
1530
+ "rstrip": false,
1531
+ "single_word": false,
1532
+ "special": true
1533
+ },
1534
+ "151834": {
1535
+ "content": "<FAKE_PAD_152>",
1536
+ "lstrip": false,
1537
+ "normalized": false,
1538
+ "rstrip": false,
1539
+ "single_word": false,
1540
+ "special": true
1541
+ },
1542
+ "151835": {
1543
+ "content": "<FAKE_PAD_153>",
1544
+ "lstrip": false,
1545
+ "normalized": false,
1546
+ "rstrip": false,
1547
+ "single_word": false,
1548
+ "special": true
1549
+ },
1550
+ "151836": {
1551
+ "content": "<FAKE_PAD_154>",
1552
+ "lstrip": false,
1553
+ "normalized": false,
1554
+ "rstrip": false,
1555
+ "single_word": false,
1556
+ "special": true
1557
+ },
1558
+ "151837": {
1559
+ "content": "<FAKE_PAD_155>",
1560
+ "lstrip": false,
1561
+ "normalized": false,
1562
+ "rstrip": false,
1563
+ "single_word": false,
1564
+ "special": true
1565
+ },
1566
+ "151838": {
1567
+ "content": "<FAKE_PAD_156>",
1568
+ "lstrip": false,
1569
+ "normalized": false,
1570
+ "rstrip": false,
1571
+ "single_word": false,
1572
+ "special": true
1573
+ },
1574
+ "151839": {
1575
+ "content": "<FAKE_PAD_157>",
1576
+ "lstrip": false,
1577
+ "normalized": false,
1578
+ "rstrip": false,
1579
+ "single_word": false,
1580
+ "special": true
1581
+ },
1582
+ "151840": {
1583
+ "content": "<FAKE_PAD_158>",
1584
+ "lstrip": false,
1585
+ "normalized": false,
1586
+ "rstrip": false,
1587
+ "single_word": false,
1588
+ "special": true
1589
+ },
1590
+ "151841": {
1591
+ "content": "<FAKE_PAD_159>",
1592
+ "lstrip": false,
1593
+ "normalized": false,
1594
+ "rstrip": false,
1595
+ "single_word": false,
1596
+ "special": true
1597
+ },
1598
+ "151842": {
1599
+ "content": "<FAKE_PAD_160>",
1600
+ "lstrip": false,
1601
+ "normalized": false,
1602
+ "rstrip": false,
1603
+ "single_word": false,
1604
+ "special": true
1605
+ },
1606
+ "151843": {
1607
+ "content": "<FAKE_PAD_161>",
1608
+ "lstrip": false,
1609
+ "normalized": false,
1610
+ "rstrip": false,
1611
+ "single_word": false,
1612
+ "special": true
1613
+ },
1614
+ "151844": {
1615
+ "content": "<FAKE_PAD_162>",
1616
+ "lstrip": false,
1617
+ "normalized": false,
1618
+ "rstrip": false,
1619
+ "single_word": false,
1620
+ "special": true
1621
+ },
1622
+ "151845": {
1623
+ "content": "<FAKE_PAD_163>",
1624
+ "lstrip": false,
1625
+ "normalized": false,
1626
+ "rstrip": false,
1627
+ "single_word": false,
1628
+ "special": true
1629
+ },
1630
+ "151846": {
1631
+ "content": "<FAKE_PAD_164>",
1632
+ "lstrip": false,
1633
+ "normalized": false,
1634
+ "rstrip": false,
1635
+ "single_word": false,
1636
+ "special": true
1637
+ },
1638
+ "151847": {
1639
+ "content": "<FAKE_PAD_165>",
1640
+ "lstrip": false,
1641
+ "normalized": false,
1642
+ "rstrip": false,
1643
+ "single_word": false,
1644
+ "special": true
1645
+ },
1646
+ "151848": {
1647
+ "content": "<FAKE_PAD_166>",
1648
+ "lstrip": false,
1649
+ "normalized": false,
1650
+ "rstrip": false,
1651
+ "single_word": false,
1652
+ "special": true
1653
+ },
1654
+ "151849": {
1655
+ "content": "<FAKE_PAD_167>",
1656
+ "lstrip": false,
1657
+ "normalized": false,
1658
+ "rstrip": false,
1659
+ "single_word": false,
1660
+ "special": true
1661
+ },
1662
+ "151850": {
1663
+ "content": "<FAKE_PAD_168>",
1664
+ "lstrip": false,
1665
+ "normalized": false,
1666
+ "rstrip": false,
1667
+ "single_word": false,
1668
+ "special": true
1669
+ },
1670
+ "151851": {
1671
+ "content": "<FAKE_PAD_169>",
1672
+ "lstrip": false,
1673
+ "normalized": false,
1674
+ "rstrip": false,
1675
+ "single_word": false,
1676
+ "special": true
1677
+ },
1678
+ "151852": {
1679
+ "content": "<FAKE_PAD_170>",
1680
+ "lstrip": false,
1681
+ "normalized": false,
1682
+ "rstrip": false,
1683
+ "single_word": false,
1684
+ "special": true
1685
+ },
1686
+ "151853": {
1687
+ "content": "<FAKE_PAD_171>",
1688
+ "lstrip": false,
1689
+ "normalized": false,
1690
+ "rstrip": false,
1691
+ "single_word": false,
1692
+ "special": true
1693
+ },
1694
+ "151854": {
1695
+ "content": "<FAKE_PAD_172>",
1696
+ "lstrip": false,
1697
+ "normalized": false,
1698
+ "rstrip": false,
1699
+ "single_word": false,
1700
+ "special": true
1701
+ },
1702
+ "151855": {
1703
+ "content": "<FAKE_PAD_173>",
1704
+ "lstrip": false,
1705
+ "normalized": false,
1706
+ "rstrip": false,
1707
+ "single_word": false,
1708
+ "special": true
1709
+ },
1710
+ "151856": {
1711
+ "content": "<FAKE_PAD_174>",
1712
+ "lstrip": false,
1713
+ "normalized": false,
1714
+ "rstrip": false,
1715
+ "single_word": false,
1716
+ "special": true
1717
+ },
1718
+ "151857": {
1719
+ "content": "<FAKE_PAD_175>",
1720
+ "lstrip": false,
1721
+ "normalized": false,
1722
+ "rstrip": false,
1723
+ "single_word": false,
1724
+ "special": true
1725
+ },
1726
+ "151858": {
1727
+ "content": "<FAKE_PAD_176>",
1728
+ "lstrip": false,
1729
+ "normalized": false,
1730
+ "rstrip": false,
1731
+ "single_word": false,
1732
+ "special": true
1733
+ },
1734
+ "151859": {
1735
+ "content": "<FAKE_PAD_177>",
1736
+ "lstrip": false,
1737
+ "normalized": false,
1738
+ "rstrip": false,
1739
+ "single_word": false,
1740
+ "special": true
1741
+ },
1742
+ "151860": {
1743
+ "content": "<FAKE_PAD_178>",
1744
+ "lstrip": false,
1745
+ "normalized": false,
1746
+ "rstrip": false,
1747
+ "single_word": false,
1748
+ "special": true
1749
+ },
1750
+ "151861": {
1751
+ "content": "<FAKE_PAD_179>",
1752
+ "lstrip": false,
1753
+ "normalized": false,
1754
+ "rstrip": false,
1755
+ "single_word": false,
1756
+ "special": true
1757
+ },
1758
+ "151862": {
1759
+ "content": "<FAKE_PAD_180>",
1760
+ "lstrip": false,
1761
+ "normalized": false,
1762
+ "rstrip": false,
1763
+ "single_word": false,
1764
+ "special": true
1765
+ },
1766
+ "151863": {
1767
+ "content": "<FAKE_PAD_181>",
1768
+ "lstrip": false,
1769
+ "normalized": false,
1770
+ "rstrip": false,
1771
+ "single_word": false,
1772
+ "special": true
1773
+ },
1774
+ "151864": {
1775
+ "content": "<FAKE_PAD_182>",
1776
+ "lstrip": false,
1777
+ "normalized": false,
1778
+ "rstrip": false,
1779
+ "single_word": false,
1780
+ "special": true
1781
+ },
1782
+ "151865": {
1783
+ "content": "<FAKE_PAD_183>",
1784
+ "lstrip": false,
1785
+ "normalized": false,
1786
+ "rstrip": false,
1787
+ "single_word": false,
1788
+ "special": true
1789
+ },
1790
+ "151866": {
1791
+ "content": "<FAKE_PAD_184>",
1792
+ "lstrip": false,
1793
+ "normalized": false,
1794
+ "rstrip": false,
1795
+ "single_word": false,
1796
+ "special": true
1797
+ },
1798
+ "151867": {
1799
+ "content": "<FAKE_PAD_185>",
1800
+ "lstrip": false,
1801
+ "normalized": false,
1802
+ "rstrip": false,
1803
+ "single_word": false,
1804
+ "special": true
1805
+ },
1806
+ "151868": {
1807
+ "content": "<FAKE_PAD_186>",
1808
+ "lstrip": false,
1809
+ "normalized": false,
1810
+ "rstrip": false,
1811
+ "single_word": false,
1812
+ "special": true
1813
+ },
1814
+ "151869": {
1815
+ "content": "<FAKE_PAD_187>",
1816
+ "lstrip": false,
1817
+ "normalized": false,
1818
+ "rstrip": false,
1819
+ "single_word": false,
1820
+ "special": true
1821
+ },
1822
+ "151870": {
1823
+ "content": "<FAKE_PAD_188>",
1824
+ "lstrip": false,
1825
+ "normalized": false,
1826
+ "rstrip": false,
1827
+ "single_word": false,
1828
+ "special": true
1829
+ },
1830
+ "151871": {
1831
+ "content": "<FAKE_PAD_189>",
1832
+ "lstrip": false,
1833
+ "normalized": false,
1834
+ "rstrip": false,
1835
+ "single_word": false,
1836
+ "special": true
1837
+ },
1838
+ "151872": {
1839
+ "content": "<FAKE_PAD_190>",
1840
+ "lstrip": false,
1841
+ "normalized": false,
1842
+ "rstrip": false,
1843
+ "single_word": false,
1844
+ "special": true
1845
+ },
1846
+ "151873": {
1847
+ "content": "<FAKE_PAD_191>",
1848
+ "lstrip": false,
1849
+ "normalized": false,
1850
+ "rstrip": false,
1851
+ "single_word": false,
1852
+ "special": true
1853
+ },
1854
+ "151874": {
1855
+ "content": "<FAKE_PAD_192>",
1856
+ "lstrip": false,
1857
+ "normalized": false,
1858
+ "rstrip": false,
1859
+ "single_word": false,
1860
+ "special": true
1861
+ },
1862
+ "151875": {
1863
+ "content": "<FAKE_PAD_193>",
1864
+ "lstrip": false,
1865
+ "normalized": false,
1866
+ "rstrip": false,
1867
+ "single_word": false,
1868
+ "special": true
1869
+ },
1870
+ "151876": {
1871
+ "content": "<FAKE_PAD_194>",
1872
+ "lstrip": false,
1873
+ "normalized": false,
1874
+ "rstrip": false,
1875
+ "single_word": false,
1876
+ "special": true
1877
+ },
1878
+ "151877": {
1879
+ "content": "<FAKE_PAD_195>",
1880
+ "lstrip": false,
1881
+ "normalized": false,
1882
+ "rstrip": false,
1883
+ "single_word": false,
1884
+ "special": true
1885
+ },
1886
+ "151878": {
1887
+ "content": "<FAKE_PAD_196>",
1888
+ "lstrip": false,
1889
+ "normalized": false,
1890
+ "rstrip": false,
1891
+ "single_word": false,
1892
+ "special": true
1893
+ },
1894
+ "151879": {
1895
+ "content": "<FAKE_PAD_197>",
1896
+ "lstrip": false,
1897
+ "normalized": false,
1898
+ "rstrip": false,
1899
+ "single_word": false,
1900
+ "special": true
1901
+ },
1902
+ "151880": {
1903
+ "content": "<FAKE_PAD_198>",
1904
+ "lstrip": false,
1905
+ "normalized": false,
1906
+ "rstrip": false,
1907
+ "single_word": false,
1908
+ "special": true
1909
+ },
1910
+ "151881": {
1911
+ "content": "<FAKE_PAD_199>",
1912
+ "lstrip": false,
1913
+ "normalized": false,
1914
+ "rstrip": false,
1915
+ "single_word": false,
1916
+ "special": true
1917
+ },
1918
+ "151882": {
1919
+ "content": "<FAKE_PAD_200>",
1920
+ "lstrip": false,
1921
+ "normalized": false,
1922
+ "rstrip": false,
1923
+ "single_word": false,
1924
+ "special": true
1925
+ },
1926
+ "151883": {
1927
+ "content": "<FAKE_PAD_201>",
1928
+ "lstrip": false,
1929
+ "normalized": false,
1930
+ "rstrip": false,
1931
+ "single_word": false,
1932
+ "special": true
1933
+ },
1934
+ "151884": {
1935
+ "content": "<FAKE_PAD_202>",
1936
+ "lstrip": false,
1937
+ "normalized": false,
1938
+ "rstrip": false,
1939
+ "single_word": false,
1940
+ "special": true
1941
+ },
1942
+ "151885": {
1943
+ "content": "<FAKE_PAD_203>",
1944
+ "lstrip": false,
1945
+ "normalized": false,
1946
+ "rstrip": false,
1947
+ "single_word": false,
1948
+ "special": true
1949
+ },
1950
+ "151886": {
1951
+ "content": "<FAKE_PAD_204>",
1952
+ "lstrip": false,
1953
+ "normalized": false,
1954
+ "rstrip": false,
1955
+ "single_word": false,
1956
+ "special": true
1957
+ },
1958
+ "151887": {
1959
+ "content": "<FAKE_PAD_205>",
1960
+ "lstrip": false,
1961
+ "normalized": false,
1962
+ "rstrip": false,
1963
+ "single_word": false,
1964
+ "special": true
1965
+ },
1966
+ "151888": {
1967
+ "content": "<FAKE_PAD_206>",
1968
+ "lstrip": false,
1969
+ "normalized": false,
1970
+ "rstrip": false,
1971
+ "single_word": false,
1972
+ "special": true
1973
+ },
1974
+ "151889": {
1975
+ "content": "<FAKE_PAD_207>",
1976
+ "lstrip": false,
1977
+ "normalized": false,
1978
+ "rstrip": false,
1979
+ "single_word": false,
1980
+ "special": true
1981
+ },
1982
+ "151890": {
1983
+ "content": "<FAKE_PAD_208>",
1984
+ "lstrip": false,
1985
+ "normalized": false,
1986
+ "rstrip": false,
1987
+ "single_word": false,
1988
+ "special": true
1989
+ },
1990
+ "151891": {
1991
+ "content": "<FAKE_PAD_209>",
1992
+ "lstrip": false,
1993
+ "normalized": false,
1994
+ "rstrip": false,
1995
+ "single_word": false,
1996
+ "special": true
1997
+ },
1998
+ "151892": {
1999
+ "content": "<FAKE_PAD_210>",
2000
+ "lstrip": false,
2001
+ "normalized": false,
2002
+ "rstrip": false,
2003
+ "single_word": false,
2004
+ "special": true
2005
+ },
2006
+ "151893": {
2007
+ "content": "<FAKE_PAD_211>",
2008
+ "lstrip": false,
2009
+ "normalized": false,
2010
+ "rstrip": false,
2011
+ "single_word": false,
2012
+ "special": true
2013
+ },
2014
+ "151894": {
2015
+ "content": "<FAKE_PAD_212>",
2016
+ "lstrip": false,
2017
+ "normalized": false,
2018
+ "rstrip": false,
2019
+ "single_word": false,
2020
+ "special": true
2021
+ },
2022
+ "151895": {
2023
+ "content": "<FAKE_PAD_213>",
2024
+ "lstrip": false,
2025
+ "normalized": false,
2026
+ "rstrip": false,
2027
+ "single_word": false,
2028
+ "special": true
2029
+ },
2030
+ "151896": {
2031
+ "content": "<FAKE_PAD_214>",
2032
+ "lstrip": false,
2033
+ "normalized": false,
2034
+ "rstrip": false,
2035
+ "single_word": false,
2036
+ "special": true
2037
+ },
2038
+ "151897": {
2039
+ "content": "<FAKE_PAD_215>",
2040
+ "lstrip": false,
2041
+ "normalized": false,
2042
+ "rstrip": false,
2043
+ "single_word": false,
2044
+ "special": true
2045
+ },
2046
+ "151898": {
2047
+ "content": "<FAKE_PAD_216>",
2048
+ "lstrip": false,
2049
+ "normalized": false,
2050
+ "rstrip": false,
2051
+ "single_word": false,
2052
+ "special": true
2053
+ },
2054
+ "151899": {
2055
+ "content": "<FAKE_PAD_217>",
2056
+ "lstrip": false,
2057
+ "normalized": false,
2058
+ "rstrip": false,
2059
+ "single_word": false,
2060
+ "special": true
2061
+ },
2062
+ "151900": {
2063
+ "content": "<FAKE_PAD_218>",
2064
+ "lstrip": false,
2065
+ "normalized": false,
2066
+ "rstrip": false,
2067
+ "single_word": false,
2068
+ "special": true
2069
+ },
2070
+ "151901": {
2071
+ "content": "<FAKE_PAD_219>",
2072
+ "lstrip": false,
2073
+ "normalized": false,
2074
+ "rstrip": false,
2075
+ "single_word": false,
2076
+ "special": true
2077
+ },
2078
+ "151902": {
2079
+ "content": "<FAKE_PAD_220>",
2080
+ "lstrip": false,
2081
+ "normalized": false,
2082
+ "rstrip": false,
2083
+ "single_word": false,
2084
+ "special": true
2085
+ },
2086
+ "151903": {
2087
+ "content": "<FAKE_PAD_221>",
2088
+ "lstrip": false,
2089
+ "normalized": false,
2090
+ "rstrip": false,
2091
+ "single_word": false,
2092
+ "special": true
2093
+ },
2094
+ "151904": {
2095
+ "content": "<FAKE_PAD_222>",
2096
+ "lstrip": false,
2097
+ "normalized": false,
2098
+ "rstrip": false,
2099
+ "single_word": false,
2100
+ "special": true
2101
+ },
2102
+ "151905": {
2103
+ "content": "<FAKE_PAD_223>",
2104
+ "lstrip": false,
2105
+ "normalized": false,
2106
+ "rstrip": false,
2107
+ "single_word": false,
2108
+ "special": true
2109
+ },
2110
+ "151906": {
2111
+ "content": "<FAKE_PAD_224>",
2112
+ "lstrip": false,
2113
+ "normalized": false,
2114
+ "rstrip": false,
2115
+ "single_word": false,
2116
+ "special": true
2117
+ },
2118
+ "151907": {
2119
+ "content": "<FAKE_PAD_225>",
2120
+ "lstrip": false,
2121
+ "normalized": false,
2122
+ "rstrip": false,
2123
+ "single_word": false,
2124
+ "special": true
2125
+ },
2126
+ "151908": {
2127
+ "content": "<FAKE_PAD_226>",
2128
+ "lstrip": false,
2129
+ "normalized": false,
2130
+ "rstrip": false,
2131
+ "single_word": false,
2132
+ "special": true
2133
+ },
2134
+ "151909": {
2135
+ "content": "<FAKE_PAD_227>",
2136
+ "lstrip": false,
2137
+ "normalized": false,
2138
+ "rstrip": false,
2139
+ "single_word": false,
2140
+ "special": true
2141
+ },
2142
+ "151910": {
2143
+ "content": "<FAKE_PAD_228>",
2144
+ "lstrip": false,
2145
+ "normalized": false,
2146
+ "rstrip": false,
2147
+ "single_word": false,
2148
+ "special": true
2149
+ },
2150
+ "151911": {
2151
+ "content": "<FAKE_PAD_229>",
2152
+ "lstrip": false,
2153
+ "normalized": false,
2154
+ "rstrip": false,
2155
+ "single_word": false,
2156
+ "special": true
2157
+ },
2158
+ "151912": {
2159
+ "content": "<FAKE_PAD_230>",
2160
+ "lstrip": false,
2161
+ "normalized": false,
2162
+ "rstrip": false,
2163
+ "single_word": false,
2164
+ "special": true
2165
+ },
2166
+ "151913": {
2167
+ "content": "<FAKE_PAD_231>",
2168
+ "lstrip": false,
2169
+ "normalized": false,
2170
+ "rstrip": false,
2171
+ "single_word": false,
2172
+ "special": true
2173
+ },
2174
+ "151914": {
2175
+ "content": "<FAKE_PAD_232>",
2176
+ "lstrip": false,
2177
+ "normalized": false,
2178
+ "rstrip": false,
2179
+ "single_word": false,
2180
+ "special": true
2181
+ },
2182
+ "151915": {
2183
+ "content": "<FAKE_PAD_233>",
2184
+ "lstrip": false,
2185
+ "normalized": false,
2186
+ "rstrip": false,
2187
+ "single_word": false,
2188
+ "special": true
2189
+ },
2190
+ "151916": {
2191
+ "content": "<FAKE_PAD_234>",
2192
+ "lstrip": false,
2193
+ "normalized": false,
2194
+ "rstrip": false,
2195
+ "single_word": false,
2196
+ "special": true
2197
+ },
2198
+ "151917": {
2199
+ "content": "<FAKE_PAD_235>",
2200
+ "lstrip": false,
2201
+ "normalized": false,
2202
+ "rstrip": false,
2203
+ "single_word": false,
2204
+ "special": true
2205
+ },
2206
+ "151918": {
2207
+ "content": "<FAKE_PAD_236>",
2208
+ "lstrip": false,
2209
+ "normalized": false,
2210
+ "rstrip": false,
2211
+ "single_word": false,
2212
+ "special": true
2213
+ },
2214
+ "151919": {
2215
+ "content": "<FAKE_PAD_237>",
2216
+ "lstrip": false,
2217
+ "normalized": false,
2218
+ "rstrip": false,
2219
+ "single_word": false,
2220
+ "special": true
2221
+ },
2222
+ "151920": {
2223
+ "content": "<FAKE_PAD_238>",
2224
+ "lstrip": false,
2225
+ "normalized": false,
2226
+ "rstrip": false,
2227
+ "single_word": false,
2228
+ "special": true
2229
+ },
2230
+ "151921": {
2231
+ "content": "<FAKE_PAD_239>",
2232
+ "lstrip": false,
2233
+ "normalized": false,
2234
+ "rstrip": false,
2235
+ "single_word": false,
2236
+ "special": true
2237
+ },
2238
+ "151922": {
2239
+ "content": "<FAKE_PAD_240>",
2240
+ "lstrip": false,
2241
+ "normalized": false,
2242
+ "rstrip": false,
2243
+ "single_word": false,
2244
+ "special": true
2245
+ },
2246
+ "151923": {
2247
+ "content": "<FAKE_PAD_241>",
2248
+ "lstrip": false,
2249
+ "normalized": false,
2250
+ "rstrip": false,
2251
+ "single_word": false,
2252
+ "special": true
2253
+ },
2254
+ "151924": {
2255
+ "content": "<FAKE_PAD_242>",
2256
+ "lstrip": false,
2257
+ "normalized": false,
2258
+ "rstrip": false,
2259
+ "single_word": false,
2260
+ "special": true
2261
+ },
2262
+ "151925": {
2263
+ "content": "<FAKE_PAD_243>",
2264
+ "lstrip": false,
2265
+ "normalized": false,
2266
+ "rstrip": false,
2267
+ "single_word": false,
2268
+ "special": true
2269
+ },
2270
+ "151926": {
2271
+ "content": "<FAKE_PAD_244>",
2272
+ "lstrip": false,
2273
+ "normalized": false,
2274
+ "rstrip": false,
2275
+ "single_word": false,
2276
+ "special": true
2277
+ },
2278
+ "151927": {
2279
+ "content": "<FAKE_PAD_245>",
2280
+ "lstrip": false,
2281
+ "normalized": false,
2282
+ "rstrip": false,
2283
+ "single_word": false,
2284
+ "special": true
2285
+ },
2286
+ "151928": {
2287
+ "content": "<FAKE_PAD_246>",
2288
+ "lstrip": false,
2289
+ "normalized": false,
2290
+ "rstrip": false,
2291
+ "single_word": false,
2292
+ "special": true
2293
+ },
2294
+ "151929": {
2295
+ "content": "<FAKE_PAD_247>",
2296
+ "lstrip": false,
2297
+ "normalized": false,
2298
+ "rstrip": false,
2299
+ "single_word": false,
2300
+ "special": true
2301
+ },
2302
+ "151930": {
2303
+ "content": "<FAKE_PAD_248>",
2304
+ "lstrip": false,
2305
+ "normalized": false,
2306
+ "rstrip": false,
2307
+ "single_word": false,
2308
+ "special": true
2309
+ },
2310
+ "151931": {
2311
+ "content": "<FAKE_PAD_249>",
2312
+ "lstrip": false,
2313
+ "normalized": false,
2314
+ "rstrip": false,
2315
+ "single_word": false,
2316
+ "special": true
2317
+ },
2318
+ "151932": {
2319
+ "content": "<FAKE_PAD_250>",
2320
+ "lstrip": false,
2321
+ "normalized": false,
2322
+ "rstrip": false,
2323
+ "single_word": false,
2324
+ "special": true
2325
+ },
2326
+ "151933": {
2327
+ "content": "<FAKE_PAD_251>",
2328
+ "lstrip": false,
2329
+ "normalized": false,
2330
+ "rstrip": false,
2331
+ "single_word": false,
2332
+ "special": true
2333
+ },
2334
+ "151934": {
2335
+ "content": "<FAKE_PAD_252>",
2336
+ "lstrip": false,
2337
+ "normalized": false,
2338
+ "rstrip": false,
2339
+ "single_word": false,
2340
+ "special": true
2341
+ },
2342
+ "151935": {
2343
+ "content": "<FAKE_PAD_253>",
2344
+ "lstrip": false,
2345
+ "normalized": false,
2346
+ "rstrip": false,
2347
+ "single_word": false,
2348
+ "special": true
2349
+ }
2350
+ },
2351
+ "additional_special_tokens": [
2352
+ "<|im_start|>",
2353
+ "<|im_end|>",
2354
+ "<|object_ref_start|>",
2355
+ "<|object_ref_end|>",
2356
+ "<|box_start|>",
2357
+ "<|box_end|>",
2358
+ "<|quad_start|>",
2359
+ "<|quad_end|>",
2360
+ "<|vision_start|>",
2361
+ "<|vision_end|>",
2362
+ "<|vision_pad|>",
2363
+ "<|image_pad|>",
2364
+ "<|video_pad|>",
2365
+ "<IMG_CONTEXT>",
2366
+ "<img>",
2367
+ "</img>",
2368
+ "<quad>",
2369
+ "</quad>",
2370
+ "<ref>",
2371
+ "</ref>",
2372
+ "<box>",
2373
+ "</box>",
2374
+ "<|action_start|>",
2375
+ "<|action_end|>",
2376
+ "<|plugin|>",
2377
+ "<|interpreter|>",
2378
+ "<FAKE_PAD_0>",
2379
+ "<FAKE_PAD_1>",
2380
+ "<FAKE_PAD_2>",
2381
+ "<FAKE_PAD_3>",
2382
+ "<FAKE_PAD_4>",
2383
+ "<FAKE_PAD_5>",
2384
+ "<FAKE_PAD_6>",
2385
+ "<FAKE_PAD_7>",
2386
+ "<FAKE_PAD_8>",
2387
+ "<FAKE_PAD_9>",
2388
+ "<FAKE_PAD_10>",
2389
+ "<FAKE_PAD_11>",
2390
+ "<FAKE_PAD_12>",
2391
+ "<FAKE_PAD_13>",
2392
+ "<FAKE_PAD_14>",
2393
+ "<FAKE_PAD_15>",
2394
+ "<FAKE_PAD_16>",
2395
+ "<FAKE_PAD_17>",
2396
+ "<FAKE_PAD_18>",
2397
+ "<FAKE_PAD_19>",
2398
+ "<FAKE_PAD_20>",
2399
+ "<FAKE_PAD_21>",
2400
+ "<FAKE_PAD_22>",
2401
+ "<FAKE_PAD_23>",
2402
+ "<FAKE_PAD_24>",
2403
+ "<FAKE_PAD_25>",
2404
+ "<FAKE_PAD_26>",
2405
+ "<FAKE_PAD_27>",
2406
+ "<FAKE_PAD_28>",
2407
+ "<FAKE_PAD_29>",
2408
+ "<FAKE_PAD_30>",
2409
+ "<FAKE_PAD_31>",
2410
+ "<FAKE_PAD_32>",
2411
+ "<FAKE_PAD_33>",
2412
+ "<FAKE_PAD_34>",
2413
+ "<FAKE_PAD_35>",
2414
+ "<FAKE_PAD_36>",
2415
+ "<FAKE_PAD_37>",
2416
+ "<FAKE_PAD_38>",
2417
+ "<FAKE_PAD_39>",
2418
+ "<FAKE_PAD_40>",
2419
+ "<FAKE_PAD_41>",
2420
+ "<FAKE_PAD_42>",
2421
+ "<FAKE_PAD_43>",
2422
+ "<FAKE_PAD_44>",
2423
+ "<FAKE_PAD_45>",
2424
+ "<FAKE_PAD_46>",
2425
+ "<FAKE_PAD_47>",
2426
+ "<FAKE_PAD_48>",
2427
+ "<FAKE_PAD_49>",
2428
+ "<FAKE_PAD_50>",
2429
+ "<FAKE_PAD_51>",
2430
+ "<FAKE_PAD_52>",
2431
+ "<FAKE_PAD_53>",
2432
+ "<FAKE_PAD_54>",
2433
+ "<FAKE_PAD_55>",
2434
+ "<FAKE_PAD_56>",
2435
+ "<FAKE_PAD_57>",
2436
+ "<FAKE_PAD_58>",
2437
+ "<FAKE_PAD_59>",
2438
+ "<FAKE_PAD_60>",
2439
+ "<FAKE_PAD_61>",
2440
+ "<FAKE_PAD_62>",
2441
+ "<FAKE_PAD_63>",
2442
+ "<FAKE_PAD_64>",
2443
+ "<FAKE_PAD_65>",
2444
+ "<FAKE_PAD_66>",
2445
+ "<FAKE_PAD_67>",
2446
+ "<FAKE_PAD_68>",
2447
+ "<FAKE_PAD_69>",
2448
+ "<FAKE_PAD_70>",
2449
+ "<FAKE_PAD_71>",
2450
+ "<FAKE_PAD_72>",
2451
+ "<FAKE_PAD_73>",
2452
+ "<FAKE_PAD_74>",
2453
+ "<FAKE_PAD_75>",
2454
+ "<FAKE_PAD_76>",
2455
+ "<FAKE_PAD_77>",
2456
+ "<FAKE_PAD_78>",
2457
+ "<FAKE_PAD_79>",
2458
+ "<FAKE_PAD_80>",
2459
+ "<FAKE_PAD_81>",
2460
+ "<FAKE_PAD_82>",
2461
+ "<FAKE_PAD_83>",
2462
+ "<FAKE_PAD_84>",
2463
+ "<FAKE_PAD_85>",
2464
+ "<FAKE_PAD_86>",
2465
+ "<FAKE_PAD_87>",
2466
+ "<FAKE_PAD_88>",
2467
+ "<FAKE_PAD_89>",
2468
+ "<FAKE_PAD_90>",
2469
+ "<FAKE_PAD_91>",
2470
+ "<FAKE_PAD_92>",
2471
+ "<FAKE_PAD_93>",
2472
+ "<FAKE_PAD_94>",
2473
+ "<FAKE_PAD_95>",
2474
+ "<FAKE_PAD_96>",
2475
+ "<FAKE_PAD_97>",
2476
+ "<FAKE_PAD_98>",
2477
+ "<FAKE_PAD_99>",
2478
+ "<FAKE_PAD_100>",
2479
+ "<FAKE_PAD_101>",
2480
+ "<FAKE_PAD_102>",
2481
+ "<FAKE_PAD_103>",
2482
+ "<FAKE_PAD_104>",
2483
+ "<FAKE_PAD_105>",
2484
+ "<FAKE_PAD_106>",
2485
+ "<FAKE_PAD_107>",
2486
+ "<FAKE_PAD_108>",
2487
+ "<FAKE_PAD_109>",
2488
+ "<FAKE_PAD_110>",
2489
+ "<FAKE_PAD_111>",
2490
+ "<FAKE_PAD_112>",
2491
+ "<FAKE_PAD_113>",
2492
+ "<FAKE_PAD_114>",
2493
+ "<FAKE_PAD_115>",
2494
+ "<FAKE_PAD_116>",
2495
+ "<FAKE_PAD_117>",
2496
+ "<FAKE_PAD_118>",
2497
+ "<FAKE_PAD_119>",
2498
+ "<FAKE_PAD_120>",
2499
+ "<FAKE_PAD_121>",
2500
+ "<FAKE_PAD_122>",
2501
+ "<FAKE_PAD_123>",
2502
+ "<FAKE_PAD_124>",
2503
+ "<FAKE_PAD_125>",
2504
+ "<FAKE_PAD_126>",
2505
+ "<FAKE_PAD_127>",
2506
+ "<FAKE_PAD_128>",
2507
+ "<FAKE_PAD_129>",
2508
+ "<FAKE_PAD_130>",
2509
+ "<FAKE_PAD_131>",
2510
+ "<FAKE_PAD_132>",
2511
+ "<FAKE_PAD_133>",
2512
+ "<FAKE_PAD_134>",
2513
+ "<FAKE_PAD_135>",
2514
+ "<FAKE_PAD_136>",
2515
+ "<FAKE_PAD_137>",
2516
+ "<FAKE_PAD_138>",
2517
+ "<FAKE_PAD_139>",
2518
+ "<FAKE_PAD_140>",
2519
+ "<FAKE_PAD_141>",
2520
+ "<FAKE_PAD_142>",
2521
+ "<FAKE_PAD_143>",
2522
+ "<FAKE_PAD_144>",
2523
+ "<FAKE_PAD_145>",
2524
+ "<FAKE_PAD_146>",
2525
+ "<FAKE_PAD_147>",
2526
+ "<FAKE_PAD_148>",
2527
+ "<FAKE_PAD_149>",
2528
+ "<FAKE_PAD_150>",
2529
+ "<FAKE_PAD_151>",
2530
+ "<FAKE_PAD_152>",
2531
+ "<FAKE_PAD_153>",
2532
+ "<FAKE_PAD_154>",
2533
+ "<FAKE_PAD_155>",
2534
+ "<FAKE_PAD_156>",
2535
+ "<FAKE_PAD_157>",
2536
+ "<FAKE_PAD_158>",
2537
+ "<FAKE_PAD_159>",
2538
+ "<FAKE_PAD_160>",
2539
+ "<FAKE_PAD_161>",
2540
+ "<FAKE_PAD_162>",
2541
+ "<FAKE_PAD_163>",
2542
+ "<FAKE_PAD_164>",
2543
+ "<FAKE_PAD_165>",
2544
+ "<FAKE_PAD_166>",
2545
+ "<FAKE_PAD_167>",
2546
+ "<FAKE_PAD_168>",
2547
+ "<FAKE_PAD_169>",
2548
+ "<FAKE_PAD_170>",
2549
+ "<FAKE_PAD_171>",
2550
+ "<FAKE_PAD_172>",
2551
+ "<FAKE_PAD_173>",
2552
+ "<FAKE_PAD_174>",
2553
+ "<FAKE_PAD_175>",
2554
+ "<FAKE_PAD_176>",
2555
+ "<FAKE_PAD_177>",
2556
+ "<FAKE_PAD_178>",
2557
+ "<FAKE_PAD_179>",
2558
+ "<FAKE_PAD_180>",
2559
+ "<FAKE_PAD_181>",
2560
+ "<FAKE_PAD_182>",
2561
+ "<FAKE_PAD_183>",
2562
+ "<FAKE_PAD_184>",
2563
+ "<FAKE_PAD_185>",
2564
+ "<FAKE_PAD_186>",
2565
+ "<FAKE_PAD_187>",
2566
+ "<FAKE_PAD_188>",
2567
+ "<FAKE_PAD_189>",
2568
+ "<FAKE_PAD_190>",
2569
+ "<FAKE_PAD_191>",
2570
+ "<FAKE_PAD_192>",
2571
+ "<FAKE_PAD_193>",
2572
+ "<FAKE_PAD_194>",
2573
+ "<FAKE_PAD_195>",
2574
+ "<FAKE_PAD_196>",
2575
+ "<FAKE_PAD_197>",
2576
+ "<FAKE_PAD_198>",
2577
+ "<FAKE_PAD_199>",
2578
+ "<FAKE_PAD_200>",
2579
+ "<FAKE_PAD_201>",
2580
+ "<FAKE_PAD_202>",
2581
+ "<FAKE_PAD_203>",
2582
+ "<FAKE_PAD_204>",
2583
+ "<FAKE_PAD_205>",
2584
+ "<FAKE_PAD_206>",
2585
+ "<FAKE_PAD_207>",
2586
+ "<FAKE_PAD_208>",
2587
+ "<FAKE_PAD_209>",
2588
+ "<FAKE_PAD_210>",
2589
+ "<FAKE_PAD_211>",
2590
+ "<FAKE_PAD_212>",
2591
+ "<FAKE_PAD_213>",
2592
+ "<FAKE_PAD_214>",
2593
+ "<FAKE_PAD_215>",
2594
+ "<FAKE_PAD_216>",
2595
+ "<FAKE_PAD_217>",
2596
+ "<FAKE_PAD_218>",
2597
+ "<FAKE_PAD_219>",
2598
+ "<FAKE_PAD_220>",
2599
+ "<FAKE_PAD_221>",
2600
+ "<FAKE_PAD_222>",
2601
+ "<FAKE_PAD_223>",
2602
+ "<FAKE_PAD_224>",
2603
+ "<FAKE_PAD_225>",
2604
+ "<FAKE_PAD_226>",
2605
+ "<FAKE_PAD_227>",
2606
+ "<FAKE_PAD_228>",
2607
+ "<FAKE_PAD_229>",
2608
+ "<FAKE_PAD_230>",
2609
+ "<FAKE_PAD_231>",
2610
+ "<FAKE_PAD_232>",
2611
+ "<FAKE_PAD_233>",
2612
+ "<FAKE_PAD_234>",
2613
+ "<FAKE_PAD_235>",
2614
+ "<FAKE_PAD_236>",
2615
+ "<FAKE_PAD_237>",
2616
+ "<FAKE_PAD_238>",
2617
+ "<FAKE_PAD_239>",
2618
+ "<FAKE_PAD_240>",
2619
+ "<FAKE_PAD_241>",
2620
+ "<FAKE_PAD_242>",
2621
+ "<FAKE_PAD_243>",
2622
+ "<FAKE_PAD_244>",
2623
+ "<FAKE_PAD_245>",
2624
+ "<FAKE_PAD_246>",
2625
+ "<FAKE_PAD_247>",
2626
+ "<FAKE_PAD_248>",
2627
+ "<FAKE_PAD_249>",
2628
+ "<FAKE_PAD_250>",
2629
+ "<FAKE_PAD_251>",
2630
+ "<FAKE_PAD_252>",
2631
+ "<FAKE_PAD_253>"
2632
+ ],
2633
+ "bos_token": null,
2634
+ "chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0].role == 'system' %}\n {{- messages[0].content + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0].role == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0].content + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set content = message.content %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is defined and message.reasoning_content is not none %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- else %}\n {%- if '</think>' in message.content %}\n {%- set content = message.content.split('</think>')[-1].lstrip('\\n') %}\n {%- set reasoning_content = message.content.split('</think>')[0].rstrip('\\n').split('<think>')[-1].lstrip('\\n') %}\n {%- endif %}\n {%- endif %}\n {%- if loop.index0 > ns.last_query_index %}\n {%- if loop.last or (not loop.last and reasoning_content) %}\n {{- '<|im_start|>' + message.role + '\\n<think>\\n' + reasoning_content.strip('\\n') + '\\n</think>\\n\\n' + content.lstrip('\\n') }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls %}\n {%- for tool_call in message.tool_calls %}\n {%- if (loop.first and content) or (not loop.first) %}\n {{- '\\n' }}\n {%- endif %}\n {%- if tool_call.function %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {%- if tool_call.arguments is string %}\n {{- tool_call.arguments }}\n {%- else %}\n {{- tool_call.arguments | tojson }}\n {%- endif %}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.first or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '<think>\\n\\n</think>\\n\\n' }}\n {%- endif %}\n{%- endif %}",
2635
+ "clean_up_tokenization_spaces": false,
2636
+ "eos_token": "<|im_end|>",
2637
+ "errors": "replace",
2638
+ "model_max_length": 12288,
2639
+ "pad_token": "<|endoftext|>",
2640
+ "split_special_tokens": false,
2641
+ "tokenizer_class": "Qwen2Tokenizer",
2642
+ "unk_token": null
2643
+ }
utils.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import math
3
+ import torch
4
+ import string
5
+ import numpy as np
6
+ import pandas as pd
7
+ from PIL import Image
8
+ import torch.distributed as dist
9
+ import torchvision.transforms as T
10
+ from transformers import AutoModel, AutoTokenizer
11
+
12
+ SYSTEM_MESSAGE_FOR_GEN = "You are an image generation and editing assistant that accurately understands and executes user intent.\n\nYou support two modes:\n\n1. Think Mode:\nIf the task requires reasoning, you MUST start with a <think></think> block. Put all reasoning inside the block using plain text. DO NOT include any image tags. Keep it reasonable and directly useful for producing the final image.\n\n2. Non-Think Mode:\nIf no reasoning is needed, directly produce the final image.\n\nTask Types:\n\nA. Text-to-Image Generation:\n- Generate a high-quality image based on the user's description.\n- Ensure visual clarity, semantic consistency, and completeness.\n- DO NOT introduce elements that contradict or override the user's intent.\n\nB. Image Editing:\n- Use the provided image(s) as input or reference for modification or transformation.\n- The result can be an edited image or a new image based on the reference(s).\n- Preserve all unspecified attributes unless explicitly changed.\n\nGeneral Rules:\n- For any visible text in the image, follow the language specified for the rendered text in the user's description, not the language of the prompt. If no language is specified, use the user's input language."
13
+
14
+ IMAGENET_MEAN = (0.485, 0.456, 0.406)
15
+ IMAGENET_STD = (0.229, 0.224, 0.225)
16
+
17
+ def round_by_factor(number: int, factor: int) -> int:
18
+ """Returns the closest integer to 'number' that is divisible by 'factor'."""
19
+ return round(number / factor) * factor
20
+
21
+
22
+ def ceil_by_factor(number: int, factor: int) -> int:
23
+ """Returns the smallest integer greater than or equal to 'number' that is divisible by 'factor'."""
24
+ return math.ceil(number / factor) * factor
25
+
26
+
27
+ def floor_by_factor(number: int, factor: int) -> int:
28
+ """Returns the largest integer less than or equal to 'number' that is divisible by 'factor'."""
29
+ return math.floor(number / factor) * factor
30
+
31
+
32
+ # copy from https://github.com/QwenLM/Qwen2.5-VL/blob/main/qwen-vl-utils/src/qwen_vl_utils/vision_process.py#L60
33
+ def smart_resize(
34
+ height: int, width: int, factor: int = 32, min_pixels: int = 65536, max_pixels: int = 4194304
35
+ ) -> tuple[int, int]:
36
+ """
37
+ Rescales the image so that the following conditions are met:
38
+
39
+ 1. Both dimensions (height and width) are divisible by 'factor'.
40
+
41
+ 2. The total number of pixels is within the range ['min_pixels', 'max_pixels'].
42
+
43
+ 3. The aspect ratio of the image is maintained as closely as possible.
44
+ """
45
+ if max(height, width) / min(height, width) > 200:
46
+ raise ValueError(
47
+ f"absolute aspect ratio must be smaller than {200}, got {max(height, width) / min(height, width)}"
48
+ )
49
+ h_bar = max(factor, round_by_factor(height, factor))
50
+ w_bar = max(factor, round_by_factor(width, factor))
51
+ if h_bar * w_bar > max_pixels:
52
+ beta = math.sqrt((height * width) / max_pixels)
53
+ h_bar = max(factor, floor_by_factor(height / beta, factor))
54
+ w_bar = max(factor, floor_by_factor(width / beta, factor))
55
+ elif h_bar * w_bar < min_pixels:
56
+ beta = math.sqrt(min_pixels / (height * width))
57
+ h_bar = ceil_by_factor(height * beta, factor)
58
+ w_bar = ceil_by_factor(width * beta, factor)
59
+ return h_bar, w_bar
60
+
61
+
62
+ def dynamic_preprocess_native_resolution(
63
+ image, size_factor=32, min_pixels=65536, max_pixels=4194304, **kwargs
64
+ ):
65
+ width, height = image.size
66
+ resized_height, resized_width = smart_resize(
67
+ height,
68
+ width,
69
+ factor=size_factor,
70
+ min_pixels=min_pixels,
71
+ max_pixels=max_pixels,
72
+ )
73
+ image = image.resize((resized_width, resized_height))
74
+
75
+ return image
76
+
77
+ def preprocess_pixel_values(pixel_values, patch_size=16):
78
+ c, h, w = pixel_values.shape
79
+ grid_h = h // patch_size
80
+ grid_w = w // patch_size
81
+
82
+ flatten_pixel_values = (
83
+ pixel_values.view(c, grid_h, patch_size, grid_w, patch_size)
84
+ .permute(1, 3, 0, 2, 4) # [grid_h, grid_w, c, patch_size, patch_size]
85
+ .reshape(grid_h * grid_w, c * patch_size ** 2)
86
+ )
87
+
88
+ grid_hw = torch.tensor([[grid_h, grid_w]]).to(device=pixel_values.device)
89
+
90
+ return flatten_pixel_values, grid_hw
91
+
92
+ def get_contrasting_background(image):
93
+ """
94
+ Calculate the color (white or black) that is different from the average foreground color
95
+ to use as the background color
96
+ """
97
+ image_np = np.array(image)
98
+ if (image_np[:, :, 3] == 0).any():
99
+ non_transparent_pixels = image_np[:, :, :3][image_np[:, :, 3] > 0]
100
+ if non_transparent_pixels.size == 0:
101
+ return None
102
+ pixel_mean = non_transparent_pixels.mean()
103
+ contrasting_color = (0, 0, 0) if pixel_mean > 382.5 else (255, 255, 255)
104
+ return contrasting_color
105
+ else:
106
+ return None
107
+
108
+ def load_image_native(
109
+ image, patch_size=16, downsample_ratio=0.5, min_pixels=65536, max_pixels=4194304, upscale=False
110
+ ):
111
+ """
112
+ Load and preprocess an image file, converting it to RGB mode,
113
+ resizing, normalizing, and optionally adding a thumbnail version.
114
+ """
115
+ if not isinstance(image, Image.Image):
116
+ image = Image.open(image)
117
+ if image.mode == "RGBA":
118
+ bg_color = get_contrasting_background(image)
119
+ if bg_color:
120
+ background = Image.new("RGB", image.size, bg_color)
121
+ background.paste(image, mask=image.split()[3])
122
+ image = background.convert("RGB")
123
+ else:
124
+ image = image.convert("RGB")
125
+ else:
126
+ image = image.convert("RGB")
127
+
128
+ if upscale:
129
+ image = image.resize((image.width * 2, image.height * 2), Image.BILINEAR)
130
+
131
+ transform = T.Compose(
132
+ [
133
+ T.Lambda(lambda img: img.convert("RGB") if img.mode != "RGB" else img),
134
+ T.ToTensor(),
135
+ T.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD),
136
+ ]
137
+ )
138
+
139
+ new_image = dynamic_preprocess_native_resolution(
140
+ image, size_factor=int(patch_size // downsample_ratio), min_pixels=min_pixels, max_pixels=max_pixels
141
+ )
142
+ pixel_values, grid_hw = preprocess_pixel_values(transform(new_image).to(torch.float32), patch_size=patch_size)
143
+
144
+ # print(f'Transfer image_size from ({image.height, image.width}) to ({new_image.height, new_image.width})')
145
+
146
+ return pixel_values, grid_hw
vocab.json ADDED
The diff for this file is too large to render. See raw diff