PandaJunkai commited on
Commit
5cf8191
·
verified ·
1 Parent(s): 7b510f6

Add files using upload-large-folder tool

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
added_tokens.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</tool_call>": 151658,
3
+ "<tool_call>": 151657,
4
+ "<ts/>": 151666,
5
+ "<ts>": 151665,
6
+ "<|box_end|>": 151649,
7
+ "<|box_start|>": 151648,
8
+ "<|endoftext|>": 151643,
9
+ "<|file_sep|>": 151664,
10
+ "<|fim_middle|>": 151660,
11
+ "<|fim_pad|>": 151662,
12
+ "<|fim_prefix|>": 151659,
13
+ "<|fim_suffix|>": 151661,
14
+ "<|im_end|>": 151645,
15
+ "<|im_start|>": 151644,
16
+ "<|image_pad|>": 151655,
17
+ "<|object_ref_end|>": 151647,
18
+ "<|object_ref_start|>": 151646,
19
+ "<|quad_end|>": 151651,
20
+ "<|quad_start|>": 151650,
21
+ "<|repo_name|>": 151663,
22
+ "<|video_pad|>": 151656,
23
+ "<|vision_end|>": 151653,
24
+ "<|vision_pad|>": 151654,
25
+ "<|vision_start|>": 151652
26
+ }
chat_template.jinja ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {% set system_message = 'You are a helpful assistant.' %}{% if messages[0]['role'] == 'system' %}{% set system_message = messages[0]['content'] %}{% endif %}{% if system_message is defined %}{{ '<|im_start|>system
2
+ ' + system_message + '<|im_end|>
3
+ ' }}{% endif %}{% for message in messages %}{% set content = message['content'] %}{% if message['role'] == 'user' %}{{ '<|im_start|>user
4
+ ' + content + '<|im_end|>
5
+ <|im_start|>assistant
6
+ ' }}{% elif message['role'] == 'assistant' %}{{ content + '<|im_end|>' + '
7
+ ' }}{% endif %}{% endfor %}
configuration_qwen2.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # The following code are reused from the QWen project (https://huggingface.co/Qwen/Qwen2.5-14B-Instruct) of Alibaba Cloud.
3
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ # The code is modified by ByteDance and Tsinghua University from the original implementation of Qwen:
18
+ # - We changed Qwen2Config to Qwen2TSConfig to support time series modeling.
19
+ """ Qwen2 model configuration"""
20
+
21
+ from transformers import PretrainedConfig
22
+ from transformers.utils import logging
23
+ from typing import *
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+
29
+ class Qwen2TSConfig(PretrainedConfig):
30
+ r"""
31
+ This is the configuration class to store the configuration of a [`Qwen2Model`]. It is used to instantiate a
32
+ Qwen2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
33
+ with the defaults will yield a similar configuration to that of
34
+ Qwen2-7B-beta [Qwen/Qwen2-7B-beta](https://huggingface.co/Qwen/Qwen2-7B-beta).
35
+
36
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
37
+ documentation from [`PretrainedConfig`] for more information.
38
+
39
+
40
+ Args:
41
+ vocab_size (`int`, *optional*, defaults to 151936):
42
+ Vocabulary size of the Qwen2 model. Defines the number of different tokens that can be represented by the
43
+ `inputs_ids` passed when calling [`Qwen2Model`]
44
+ hidden_size (`int`, *optional*, defaults to 4096):
45
+ Dimension of the hidden representations.
46
+ intermediate_size (`int`, *optional*, defaults to 22016):
47
+ Dimension of the MLP representations.
48
+ num_hidden_layers (`int`, *optional*, defaults to 32):
49
+ Number of hidden layers in the Transformer encoder.
50
+ num_attention_heads (`int`, *optional*, defaults to 32):
51
+ Number of attention heads for each attention layer in the Transformer encoder.
52
+ num_key_value_heads (`int`, *optional*, defaults to 32):
53
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
54
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
55
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
56
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
57
+ by meanpooling all the original heads within that group. For more details checkout [this
58
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
59
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
60
+ The non-linear activation function (function or string) in the decoder.
61
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
62
+ The maximum sequence length that this model might ever be used with.
63
+ initializer_range (`float`, *optional*, defaults to 0.02):
64
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
65
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
66
+ The epsilon used by the rms normalization layers.
67
+ use_cache (`bool`, *optional*, defaults to `True`):
68
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
69
+ relevant if `config.is_decoder=True`.
70
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
71
+ Whether the model's input and output word embeddings should be tied.
72
+ rope_theta (`float`, *optional*, defaults to 10000.0):
73
+ The base period of the RoPE embeddings.
74
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
75
+ Whether to use sliding window attention.
76
+ sliding_window (`int`, *optional*, defaults to 4096):
77
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
78
+ max_window_layers (`int`, *optional*, defaults to 28):
79
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
80
+ attention_dropout (`float`, *optional*, defaults to 0.0):
81
+ The dropout ratio for the attention probabilities.
82
+
83
+ ```python
84
+ >>> from transformers import Qwen2Model, Qwen2Config
85
+
86
+ >>> # Initializing a Qwen2 style configuration
87
+ >>> configuration = Qwen2Config()
88
+
89
+ >>> # Initializing a model from the Qwen2-7B style configuration
90
+ >>> model = Qwen2Model(configuration)
91
+
92
+ >>> # Accessing the model configuration
93
+ >>> configuration = model.config
94
+ ```"""
95
+
96
+ model_type = "patra"
97
+ keys_to_ignore_at_inference = ["past_key_values"]
98
+
99
+ def __init__(
100
+ self,
101
+ vocab_size=151936,
102
+ hidden_size=4096,
103
+ intermediate_size=22016,
104
+ num_hidden_layers=32,
105
+ num_attention_heads=32,
106
+ num_key_value_heads=32,
107
+ hidden_act="silu",
108
+ max_position_embeddings=32768,
109
+ initializer_range=0.02,
110
+ rms_norm_eps=1e-6,
111
+ use_cache=True,
112
+ tie_word_embeddings=False,
113
+ rope_theta=10000.0,
114
+ use_sliding_window=False,
115
+ sliding_window=4096,
116
+ max_window_layers=28,
117
+ attention_dropout=0.0,
118
+ **kwargs,
119
+ ):
120
+ self.vocab_size = vocab_size
121
+ self.max_position_embeddings = max_position_embeddings
122
+ self.hidden_size = hidden_size
123
+ self.intermediate_size = intermediate_size
124
+ self.num_hidden_layers = num_hidden_layers
125
+ self.num_attention_heads = num_attention_heads
126
+ self.use_sliding_window = use_sliding_window
127
+ self.sliding_window = sliding_window
128
+ self.max_window_layers = max_window_layers
129
+
130
+ # for backward compatibility
131
+ if num_key_value_heads is None:
132
+ num_key_value_heads = num_attention_heads
133
+
134
+ self.num_key_value_heads = num_key_value_heads
135
+ self.hidden_act = hidden_act
136
+ self.initializer_range = initializer_range
137
+ self.rms_norm_eps = rms_norm_eps
138
+ self.use_cache = use_cache
139
+ self.rope_theta = rope_theta
140
+ self.attention_dropout = attention_dropout
141
+
142
+ super().__init__(
143
+ tie_word_embeddings=tie_word_embeddings,
144
+ **kwargs,
145
+ )
146
+
147
+ TINYTIMEMIXER_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
148
+
149
+
150
+ class TinyTimeMixerConfig(PretrainedConfig):
151
+ r"""
152
+ This is the configuration class to store the configuration of a [`TinyTimeMixerModel`]. It is used to instantiate a
153
+ TinyTimeMixer model according to the specified arguments, defining the model architecture. Instantiating a
154
+ configuration with the defaults will yield a similar configuration to that of the TinyTimeMixer {} architecture.
155
+
156
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
157
+ documentation from [`PretrainedConfig`] for more information.
158
+
159
+ Args:
160
+ context_length (`int`, *optional*, defaults to 64)
161
+ The context/history length for the input sequence.
162
+ patch_length (`int`, *optional*, defaults to 8)
163
+ The patch length for the input sequence.
164
+ num_input_channels (`int`):
165
+ Number of input variates. For Univariate, set it to 1.
166
+ patch_stride (`int`, *optional*, defaults to 8):
167
+ Amount of points to stride. If its value is same as patch_length, we get non-overlapping patches.
168
+ d_model (`int`, *optional*, defaults to 16):
169
+ Hidden feature size of the model.
170
+ prediction_length (`int`, *optional*, defaults to 16)
171
+ Number of time steps to forecast for a forecasting task. Also known as the Forecast Horizon.
172
+ expansion_factor (`int`, *optional*, defaults to 2):
173
+ Expansion factor to use inside MLP. Recommended range is 2-5. Larger value indicates more complex model.
174
+ num_layers (`int`, *optional*, defaults to 3):
175
+ Number of layers to use. Recommended range is 3-15. Larger value indicates more complex model.
176
+ dropout (`float`, *optional*, defaults to 0.2):
177
+ The dropout probability the `TinyTimeMixer` backbone. Recommended range is 0.2-0.7
178
+ mode (`str`, *optional*, defaults to `"common_channel"`):
179
+ Mixer Mode. Determines how to process the channels. Allowed values: "common_channel", "mix_channel". In
180
+ "common_channel" mode, we follow Channel-independent modelling with no explicit channel-mixing. Channel
181
+ mixing happens in an implicit manner via shared weights across channels. (preferred first approach) In
182
+ "mix_channel" mode, we follow explicit channel-mixing in addition to patch and feature mixer. (preferred
183
+ approach when channel correlations are very important to model)
184
+ gated_attn (`bool`, *optional*, defaults to `True`):
185
+ Enable Gated Attention.
186
+ norm_mlp (`str`, *optional*, defaults to `"LayerNorm"`):
187
+ Normalization layer (BatchNorm or LayerNorm).
188
+ self_attn (`bool`, *optional*, defaults to `False`):
189
+ Enable Tiny self attention across patches. This can be enabled when the output of Vanilla TinyTimeMixer with
190
+ gated attention is not satisfactory. Enabling this leads to explicit pair-wise attention and modelling
191
+ across patches.
192
+ self_attn_heads (`int`, *optional*, defaults to 1):
193
+ Number of self-attention heads. Works only when `self_attn` is set to `True`.
194
+ use_positional_encoding (`bool`, *optional*, defaults to `False`):
195
+ Enable the use of positional embedding for the tiny self-attention layers. Works only when `self_attn` is
196
+ set to `True`.
197
+ positional_encoding_type (`str`, *optional*, defaults to `"sincos"`):
198
+ Positional encodings. Options `"random"` and `"sincos"` are supported. Works only when
199
+ `use_positional_encoding` is set to `True`
200
+ scaling (`string` or `bool`, *optional*, defaults to `"std"`):
201
+ Whether to scale the input targets via "mean" scaler, "std" scaler or no scaler if `None`. If `True`, the
202
+ scaler is set to "mean".
203
+ loss (`string`, *optional*, defaults to `"mse"`):
204
+ The loss function for the model. Defaults to mean squared error "mse". Allowed values: ["mse", "mae"]
205
+ init_std (`float`, *optional*, defaults to 0.02):
206
+ The standard deviation of the truncated normal weight initialization distribution.
207
+ post_init (`bool`, *optional*, defaults to `False`):
208
+ Whether to use custom weight initialization from `transformers` library, or the default initialization in
209
+ `PyTorch`. Setting it to `False` performs `PyTorch` weight initialization.
210
+ norm_eps (`float`, *optional*, defaults to 1e-05):
211
+ A value added to the denominator for numerical stability of normalization.
212
+ adaptive_patching_levels (`int`, *optional*, defaults to 0):
213
+ If adaptive_patching_levels is i, then we will have i levels with each level having n_layers.
214
+ Level id starts with 0. num_patches at level i will be multipled by (2^i) and num_features at level i will be divided by (2^i).
215
+ For Ex. if adaptive_patching_levels is 3 - then we will have 3 levels:
216
+ level 2: num_features//(2^2), num_patches*(2^2)
217
+ level 1: num_features//(2^1), num_patches*(2^1)
218
+ level 0: num_features//(2^0), num_patches*(2^0)
219
+ adaptive_patching_levels = 1 is same as one level PatchTSMixer. This module gets disabled when adaptive_patching_levels is 0 or neg value. Defaults to 0 (off mode).
220
+ resolution_prefix_tuning (`bool`, *optional*, defaults to `False`):
221
+ Enable if your dataloader has time resolution information as defined in `get_freq_mapping` function in `modelling_tinytimemixer`.
222
+ frequency_token_vocab_size (`int`, *optional*, defaults to 5):
223
+ Vocab size to use when resolution_prefix_tuning is enabled.
224
+ head_dropout (`float`, *optional*, defaults to 0.2):
225
+ The dropout probability the `TinyTimeMixer` head.
226
+ prediction_channel_indices (`list`, *optional*):
227
+ List of channel indices to forecast. If None, forecast all channels. Target data is expected to have all
228
+ channels and we explicitly filter the channels in prediction and target before loss computation. Please provide the indices
229
+ in sorted ascending order.
230
+ decoder_num_layers (`int`, *optional*, defaults to 8):
231
+ Number of layers to use in decoder
232
+ decoder_d_model(`int`, *optional*, defaults to 16):
233
+ Defines the hidden feature size of the decoder.
234
+ decoder_adaptive_patching_levels (`int`, *optional*, defaults to 0):
235
+ Adaptive Patching levels for decoder. Preferable to set it to 0 for decoder to keep it light weight.
236
+ decoder_raw_residual (`bool`, *optional*, defaults to `False`):
237
+ Flag to enable merging of raw embedding with encoder embedding for decoder input. Defaults to False.
238
+ decoder_mode (`string`, *optional*, defaults to `"common_channel"`):
239
+ Decoder channel mode. Use `"common_channel" for channel-independent modelling and `"mix_channel"` for channel-mixing modelling
240
+ use_decoder (`bool`, *optional*, defaults to `True`):
241
+ Enable to use decoder.
242
+ prediction_filter_length (`int`,*optional*, defaults to None):
243
+ Actual length in the prediction output to use for loss calculations.
244
+
245
+
246
+ Example:
247
+
248
+ ```python
249
+ >>> from transformers import TinyTimeMixerConfig, TinyTimeMixerModel
250
+
251
+ >>> # Initializing a default TinyTimeMixer configuration
252
+ >>> configuration = TinyTimeMixerConfig()
253
+
254
+ >>> # Randomly initializing a model (with random weights) from the configuration
255
+ >>> model = TinyTimeMixerModel(configuration)
256
+
257
+ >>> # Accessing the model configuration
258
+ >>> configuration = model.config
259
+ ```"""
260
+
261
+ model_type = "tinytimemixer"
262
+ attribute_map = {
263
+ "hidden_size": "d_model",
264
+ "num_hidden_layers": "num_layers",
265
+ }
266
+
267
+ def __init__(
268
+ self,
269
+ # Time series specific configuration
270
+ context_length: int = 64,
271
+ patch_length: int = 8,
272
+ num_input_channels: int = 1,
273
+ prediction_length: int = 16,
274
+ patch_stride: int = 8,
275
+ prediction_channel_indices: Optional[list] = None,
276
+ # General model configuration
277
+ d_model: int = 16,
278
+ expansion_factor: int = 2,
279
+ num_layers: int = 3,
280
+ dropout: float = 0.2,
281
+ mode: str = "common_channel",
282
+ gated_attn: bool = True,
283
+ norm_mlp: str = "LayerNorm",
284
+ self_attn: bool = False,
285
+ self_attn_heads: int = 1,
286
+ use_positional_encoding: bool = False,
287
+ positional_encoding_type: str = "sincos",
288
+ scaling: Optional[Union[str, bool]] = "std",
289
+ loss: str = "mse",
290
+ init_std: float = 0.02,
291
+ post_init: bool = False,
292
+ norm_eps: float = 1e-5,
293
+ adaptive_patching_levels: int = 0,
294
+ resolution_prefix_tuning: bool = False,
295
+ frequency_token_vocab_size: int = 5,
296
+ # General head configuration
297
+ head_dropout: float = 0.2,
298
+ # decoder parameters
299
+ decoder_num_layers: int = 8,
300
+ decoder_d_model: int = 8,
301
+ decoder_adaptive_patching_levels: int = 0,
302
+ decoder_raw_residual: bool = False,
303
+ decoder_mode: str = "common_channel",
304
+ use_decoder: bool = True,
305
+ # prediction length filtering
306
+ prediction_filter_length: Optional[int] = None,
307
+ **kwargs,
308
+ ):
309
+ self.num_input_channels = num_input_channels
310
+ self.context_length = context_length
311
+ self.patch_length = patch_length
312
+ self.expansion_factor = expansion_factor
313
+ self.num_layers = num_layers
314
+ self.dropout = dropout
315
+ self.mode = mode
316
+ self.gated_attn = gated_attn
317
+ self.norm_mlp = norm_mlp
318
+ self.scaling = scaling
319
+ self.head_dropout = head_dropout
320
+
321
+ self.patch_last = True
322
+ self.use_positional_encoding = use_positional_encoding
323
+ self.positional_encoding_type = positional_encoding_type
324
+ self.prediction_length = prediction_length
325
+ self.prediction_channel_indices = prediction_channel_indices
326
+ self.self_attn = self_attn
327
+ self.self_attn_heads = self_attn_heads
328
+ self.init_std = init_std
329
+ self.post_init = post_init
330
+ self.loss = loss
331
+ self.norm_eps = norm_eps
332
+
333
+ self.use_decoder = use_decoder
334
+
335
+ self.adaptive_patching_levels = adaptive_patching_levels
336
+ self.resolution_prefix_tuning = resolution_prefix_tuning
337
+ self.decoder_num_layers = decoder_num_layers
338
+ self.decoder_adaptive_patching_levels = decoder_adaptive_patching_levels
339
+ self.decoder_raw_residual = decoder_raw_residual
340
+ self.decoder_mode = decoder_mode
341
+ self.frequency_token_vocab_size = frequency_token_vocab_size
342
+ self.d_model = d_model
343
+ self.patch_stride = patch_stride
344
+ self.decoder_d_model = decoder_d_model
345
+ self.init_processing = False
346
+ self.prediction_filter_length = prediction_filter_length
347
+
348
+ super().__init__(**kwargs)
349
+
350
+ def check_and_init_preprocessing(self):
351
+ self.init_processing = True
352
+
353
+ if not hasattr(self, "num_patches"):
354
+ self.num_patches = (
355
+ max(self.context_length, self.patch_length) - self.patch_length
356
+ ) // self.patch_stride + 1
357
+
358
+ if self.resolution_prefix_tuning:
359
+ self.num_patches += 1
360
+
361
+ if self.prediction_filter_length is not None:
362
+ if self.prediction_filter_length > self.prediction_length or self.prediction_filter_length <= 0:
363
+ raise ValueError("prediction_filter_length should be positive and less than prediction_length")
364
+
365
+ if self.prediction_channel_indices is not None:
366
+ self.prediction_channel_indices.sort()
generation_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 151645,
6
+ 151643
7
+ ],
8
+ "pad_token_id": 151643,
9
+ "repetition_penalty": 1.05,
10
+ "temperature": 0.7,
11
+ "top_k": 20,
12
+ "top_p": 0.8,
13
+ "transformers_version": "4.52.4"
14
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model-00001-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:16dc053b538cdbd9ab3e2b4934844b5241f73fd801efe90ceecb4760d632b94b
3
+ size 4877660672
model-00002-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:39db11c822983834196dc9ae8e8320b490f30d4a18f99f1113822ce016c75c2f
3
+ size 4932750888
model-00003-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1c133f9d6cbfa9bddc8aa14e636504473a454d28dc50617c838b1f63a56f40f4
3
+ size 4330865088
model-00004-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4b1901d32d8623d405f1c265ad13d87617bf0f9700b368134d0fcded5cebc76a
3
+ size 1809862144
model.safetensors.index.json ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 15951093760
4
+ },
5
+ "weight_map": {
6
+ "align.complete_cross_attn.k_proj.bias": "model-00004-of-00004.safetensors",
7
+ "align.complete_cross_attn.k_proj.weight": "model-00004-of-00004.safetensors",
8
+ "align.complete_cross_attn.o_proj.bias": "model-00004-of-00004.safetensors",
9
+ "align.complete_cross_attn.o_proj.weight": "model-00004-of-00004.safetensors",
10
+ "align.complete_cross_attn.q_proj.bias": "model-00004-of-00004.safetensors",
11
+ "align.complete_cross_attn.q_proj.weight": "model-00004-of-00004.safetensors",
12
+ "align.complete_cross_attn.v_proj.bias": "model-00004-of-00004.safetensors",
13
+ "align.complete_cross_attn.v_proj.weight": "model-00004-of-00004.safetensors",
14
+ "align.complete_query.weight": "model-00004-of-00004.safetensors",
15
+ "align.complete_text_attn.k_proj.bias": "model-00004-of-00004.safetensors",
16
+ "align.complete_text_attn.k_proj.weight": "model-00004-of-00004.safetensors",
17
+ "align.complete_text_attn.o_proj.bias": "model-00004-of-00004.safetensors",
18
+ "align.complete_text_attn.o_proj.weight": "model-00004-of-00004.safetensors",
19
+ "align.complete_text_attn.q_proj.bias": "model-00004-of-00004.safetensors",
20
+ "align.complete_text_attn.q_proj.weight": "model-00004-of-00004.safetensors",
21
+ "align.complete_text_attn.v_proj.bias": "model-00004-of-00004.safetensors",
22
+ "align.complete_text_attn.v_proj.weight": "model-00004-of-00004.safetensors",
23
+ "align.seasonal_cross_attn.k_proj.bias": "model-00004-of-00004.safetensors",
24
+ "align.seasonal_cross_attn.k_proj.weight": "model-00004-of-00004.safetensors",
25
+ "align.seasonal_cross_attn.o_proj.bias": "model-00004-of-00004.safetensors",
26
+ "align.seasonal_cross_attn.o_proj.weight": "model-00004-of-00004.safetensors",
27
+ "align.seasonal_cross_attn.q_proj.bias": "model-00004-of-00004.safetensors",
28
+ "align.seasonal_cross_attn.q_proj.weight": "model-00004-of-00004.safetensors",
29
+ "align.seasonal_cross_attn.v_proj.bias": "model-00004-of-00004.safetensors",
30
+ "align.seasonal_cross_attn.v_proj.weight": "model-00004-of-00004.safetensors",
31
+ "align.seasonal_query.weight": "model-00004-of-00004.safetensors",
32
+ "align.seasonal_text_attn.k_proj.bias": "model-00004-of-00004.safetensors",
33
+ "align.seasonal_text_attn.k_proj.weight": "model-00004-of-00004.safetensors",
34
+ "align.seasonal_text_attn.o_proj.bias": "model-00004-of-00004.safetensors",
35
+ "align.seasonal_text_attn.o_proj.weight": "model-00004-of-00004.safetensors",
36
+ "align.seasonal_text_attn.q_proj.bias": "model-00004-of-00004.safetensors",
37
+ "align.seasonal_text_attn.q_proj.weight": "model-00004-of-00004.safetensors",
38
+ "align.seasonal_text_attn.v_proj.bias": "model-00004-of-00004.safetensors",
39
+ "align.seasonal_text_attn.v_proj.weight": "model-00004-of-00004.safetensors",
40
+ "align.trend_cross_attn.k_proj.bias": "model-00004-of-00004.safetensors",
41
+ "align.trend_cross_attn.k_proj.weight": "model-00004-of-00004.safetensors",
42
+ "align.trend_cross_attn.o_proj.bias": "model-00004-of-00004.safetensors",
43
+ "align.trend_cross_attn.o_proj.weight": "model-00004-of-00004.safetensors",
44
+ "align.trend_cross_attn.q_proj.bias": "model-00004-of-00004.safetensors",
45
+ "align.trend_cross_attn.q_proj.weight": "model-00004-of-00004.safetensors",
46
+ "align.trend_cross_attn.v_proj.bias": "model-00004-of-00004.safetensors",
47
+ "align.trend_cross_attn.v_proj.weight": "model-00004-of-00004.safetensors",
48
+ "align.trend_query.weight": "model-00004-of-00004.safetensors",
49
+ "align.trend_text_attn.k_proj.bias": "model-00004-of-00004.safetensors",
50
+ "align.trend_text_attn.k_proj.weight": "model-00004-of-00004.safetensors",
51
+ "align.trend_text_attn.o_proj.bias": "model-00004-of-00004.safetensors",
52
+ "align.trend_text_attn.o_proj.weight": "model-00004-of-00004.safetensors",
53
+ "align.trend_text_attn.q_proj.bias": "model-00004-of-00004.safetensors",
54
+ "align.trend_text_attn.q_proj.weight": "model-00004-of-00004.safetensors",
55
+ "align.trend_text_attn.v_proj.bias": "model-00004-of-00004.safetensors",
56
+ "align.trend_text_attn.v_proj.weight": "model-00004-of-00004.safetensors",
57
+ "lm_head.weight": "model-00004-of-00004.safetensors",
58
+ "model.embed_tokens.weight": "model-00001-of-00004.safetensors",
59
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00004.safetensors",
60
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
61
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
62
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
63
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
64
+ "model.layers.0.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
65
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
66
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
67
+ "model.layers.0.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
68
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
69
+ "model.layers.0.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
70
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
71
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00004.safetensors",
72
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
73
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
74
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
75
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
76
+ "model.layers.1.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
77
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
78
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
79
+ "model.layers.1.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
80
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
81
+ "model.layers.1.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
82
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
83
+ "model.layers.10.input_layernorm.weight": "model-00002-of-00004.safetensors",
84
+ "model.layers.10.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
85
+ "model.layers.10.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
86
+ "model.layers.10.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
87
+ "model.layers.10.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
88
+ "model.layers.10.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
89
+ "model.layers.10.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
90
+ "model.layers.10.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
91
+ "model.layers.10.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
92
+ "model.layers.10.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
93
+ "model.layers.10.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
94
+ "model.layers.10.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
95
+ "model.layers.11.input_layernorm.weight": "model-00002-of-00004.safetensors",
96
+ "model.layers.11.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
97
+ "model.layers.11.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
98
+ "model.layers.11.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
99
+ "model.layers.11.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
100
+ "model.layers.11.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
101
+ "model.layers.11.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
102
+ "model.layers.11.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
103
+ "model.layers.11.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
104
+ "model.layers.11.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
105
+ "model.layers.11.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
106
+ "model.layers.11.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
107
+ "model.layers.12.input_layernorm.weight": "model-00002-of-00004.safetensors",
108
+ "model.layers.12.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
109
+ "model.layers.12.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
110
+ "model.layers.12.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
111
+ "model.layers.12.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
112
+ "model.layers.12.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
113
+ "model.layers.12.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
114
+ "model.layers.12.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
115
+ "model.layers.12.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
116
+ "model.layers.12.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
117
+ "model.layers.12.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
118
+ "model.layers.12.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
119
+ "model.layers.13.input_layernorm.weight": "model-00002-of-00004.safetensors",
120
+ "model.layers.13.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
121
+ "model.layers.13.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
122
+ "model.layers.13.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
123
+ "model.layers.13.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
124
+ "model.layers.13.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
125
+ "model.layers.13.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
126
+ "model.layers.13.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
127
+ "model.layers.13.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
128
+ "model.layers.13.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
129
+ "model.layers.13.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
130
+ "model.layers.13.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
131
+ "model.layers.14.input_layernorm.weight": "model-00002-of-00004.safetensors",
132
+ "model.layers.14.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
133
+ "model.layers.14.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
134
+ "model.layers.14.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
135
+ "model.layers.14.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
136
+ "model.layers.14.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
137
+ "model.layers.14.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
138
+ "model.layers.14.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
139
+ "model.layers.14.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
140
+ "model.layers.14.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
141
+ "model.layers.14.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
142
+ "model.layers.14.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
143
+ "model.layers.15.input_layernorm.weight": "model-00002-of-00004.safetensors",
144
+ "model.layers.15.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
145
+ "model.layers.15.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
146
+ "model.layers.15.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
147
+ "model.layers.15.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
148
+ "model.layers.15.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
149
+ "model.layers.15.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
150
+ "model.layers.15.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
151
+ "model.layers.15.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
152
+ "model.layers.15.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
153
+ "model.layers.15.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
154
+ "model.layers.15.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
155
+ "model.layers.16.input_layernorm.weight": "model-00002-of-00004.safetensors",
156
+ "model.layers.16.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
157
+ "model.layers.16.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
158
+ "model.layers.16.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
159
+ "model.layers.16.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
160
+ "model.layers.16.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
161
+ "model.layers.16.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
162
+ "model.layers.16.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
163
+ "model.layers.16.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
164
+ "model.layers.16.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
165
+ "model.layers.16.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
166
+ "model.layers.16.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
167
+ "model.layers.17.input_layernorm.weight": "model-00002-of-00004.safetensors",
168
+ "model.layers.17.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
169
+ "model.layers.17.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
170
+ "model.layers.17.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
171
+ "model.layers.17.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
172
+ "model.layers.17.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
173
+ "model.layers.17.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
174
+ "model.layers.17.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
175
+ "model.layers.17.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
176
+ "model.layers.17.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
177
+ "model.layers.17.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
178
+ "model.layers.17.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
179
+ "model.layers.18.input_layernorm.weight": "model-00003-of-00004.safetensors",
180
+ "model.layers.18.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
181
+ "model.layers.18.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
182
+ "model.layers.18.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
183
+ "model.layers.18.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
184
+ "model.layers.18.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
185
+ "model.layers.18.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
186
+ "model.layers.18.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
187
+ "model.layers.18.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
188
+ "model.layers.18.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
189
+ "model.layers.18.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
190
+ "model.layers.18.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
191
+ "model.layers.19.input_layernorm.weight": "model-00003-of-00004.safetensors",
192
+ "model.layers.19.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
193
+ "model.layers.19.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
194
+ "model.layers.19.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
195
+ "model.layers.19.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
196
+ "model.layers.19.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
197
+ "model.layers.19.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
198
+ "model.layers.19.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
199
+ "model.layers.19.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
200
+ "model.layers.19.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
201
+ "model.layers.19.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
202
+ "model.layers.19.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
203
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00004.safetensors",
204
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
205
+ "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
206
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
207
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
208
+ "model.layers.2.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
209
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
210
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
211
+ "model.layers.2.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
212
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
213
+ "model.layers.2.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
214
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
215
+ "model.layers.20.input_layernorm.weight": "model-00003-of-00004.safetensors",
216
+ "model.layers.20.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
217
+ "model.layers.20.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
218
+ "model.layers.20.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
219
+ "model.layers.20.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
220
+ "model.layers.20.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
221
+ "model.layers.20.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
222
+ "model.layers.20.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
223
+ "model.layers.20.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
224
+ "model.layers.20.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
225
+ "model.layers.20.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
226
+ "model.layers.20.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
227
+ "model.layers.21.input_layernorm.weight": "model-00003-of-00004.safetensors",
228
+ "model.layers.21.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
229
+ "model.layers.21.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
230
+ "model.layers.21.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
231
+ "model.layers.21.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
232
+ "model.layers.21.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
233
+ "model.layers.21.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
234
+ "model.layers.21.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
235
+ "model.layers.21.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
236
+ "model.layers.21.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
237
+ "model.layers.21.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
238
+ "model.layers.21.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
239
+ "model.layers.22.input_layernorm.weight": "model-00003-of-00004.safetensors",
240
+ "model.layers.22.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
241
+ "model.layers.22.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
242
+ "model.layers.22.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
243
+ "model.layers.22.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
244
+ "model.layers.22.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
245
+ "model.layers.22.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
246
+ "model.layers.22.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
247
+ "model.layers.22.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
248
+ "model.layers.22.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
249
+ "model.layers.22.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
250
+ "model.layers.22.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
251
+ "model.layers.23.input_layernorm.weight": "model-00003-of-00004.safetensors",
252
+ "model.layers.23.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
253
+ "model.layers.23.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
254
+ "model.layers.23.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
255
+ "model.layers.23.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
256
+ "model.layers.23.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
257
+ "model.layers.23.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
258
+ "model.layers.23.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
259
+ "model.layers.23.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
260
+ "model.layers.23.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
261
+ "model.layers.23.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
262
+ "model.layers.23.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
263
+ "model.layers.24.input_layernorm.weight": "model-00003-of-00004.safetensors",
264
+ "model.layers.24.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
265
+ "model.layers.24.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
266
+ "model.layers.24.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
267
+ "model.layers.24.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
268
+ "model.layers.24.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
269
+ "model.layers.24.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
270
+ "model.layers.24.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
271
+ "model.layers.24.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
272
+ "model.layers.24.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
273
+ "model.layers.24.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
274
+ "model.layers.24.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
275
+ "model.layers.25.input_layernorm.weight": "model-00003-of-00004.safetensors",
276
+ "model.layers.25.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
277
+ "model.layers.25.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
278
+ "model.layers.25.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
279
+ "model.layers.25.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
280
+ "model.layers.25.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
281
+ "model.layers.25.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
282
+ "model.layers.25.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
283
+ "model.layers.25.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
284
+ "model.layers.25.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
285
+ "model.layers.25.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
286
+ "model.layers.25.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
287
+ "model.layers.26.input_layernorm.weight": "model-00003-of-00004.safetensors",
288
+ "model.layers.26.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
289
+ "model.layers.26.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
290
+ "model.layers.26.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
291
+ "model.layers.26.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
292
+ "model.layers.26.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
293
+ "model.layers.26.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
294
+ "model.layers.26.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
295
+ "model.layers.26.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
296
+ "model.layers.26.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
297
+ "model.layers.26.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
298
+ "model.layers.26.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
299
+ "model.layers.27.input_layernorm.weight": "model-00003-of-00004.safetensors",
300
+ "model.layers.27.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
301
+ "model.layers.27.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
302
+ "model.layers.27.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
303
+ "model.layers.27.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
304
+ "model.layers.27.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
305
+ "model.layers.27.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
306
+ "model.layers.27.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
307
+ "model.layers.27.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
308
+ "model.layers.27.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
309
+ "model.layers.27.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
310
+ "model.layers.27.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
311
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00004.safetensors",
312
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
313
+ "model.layers.3.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
314
+ "model.layers.3.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
315
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
316
+ "model.layers.3.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
317
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
318
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
319
+ "model.layers.3.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
320
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
321
+ "model.layers.3.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
322
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
323
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00004.safetensors",
324
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
325
+ "model.layers.4.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
326
+ "model.layers.4.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
327
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
328
+ "model.layers.4.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
329
+ "model.layers.4.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
330
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
331
+ "model.layers.4.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
332
+ "model.layers.4.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
333
+ "model.layers.4.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
334
+ "model.layers.4.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
335
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00004.safetensors",
336
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
337
+ "model.layers.5.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
338
+ "model.layers.5.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
339
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
340
+ "model.layers.5.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
341
+ "model.layers.5.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
342
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
343
+ "model.layers.5.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
344
+ "model.layers.5.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
345
+ "model.layers.5.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
346
+ "model.layers.5.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
347
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00004.safetensors",
348
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
349
+ "model.layers.6.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
350
+ "model.layers.6.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
351
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
352
+ "model.layers.6.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
353
+ "model.layers.6.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
354
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
355
+ "model.layers.6.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
356
+ "model.layers.6.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
357
+ "model.layers.6.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
358
+ "model.layers.6.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
359
+ "model.layers.7.input_layernorm.weight": "model-00001-of-00004.safetensors",
360
+ "model.layers.7.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
361
+ "model.layers.7.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
362
+ "model.layers.7.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
363
+ "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
364
+ "model.layers.7.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
365
+ "model.layers.7.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
366
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
367
+ "model.layers.7.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
368
+ "model.layers.7.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
369
+ "model.layers.7.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
370
+ "model.layers.7.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
371
+ "model.layers.8.input_layernorm.weight": "model-00002-of-00004.safetensors",
372
+ "model.layers.8.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
373
+ "model.layers.8.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
374
+ "model.layers.8.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
375
+ "model.layers.8.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
376
+ "model.layers.8.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
377
+ "model.layers.8.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
378
+ "model.layers.8.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
379
+ "model.layers.8.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
380
+ "model.layers.8.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
381
+ "model.layers.8.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
382
+ "model.layers.8.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
383
+ "model.layers.9.input_layernorm.weight": "model-00002-of-00004.safetensors",
384
+ "model.layers.9.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
385
+ "model.layers.9.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
386
+ "model.layers.9.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
387
+ "model.layers.9.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
388
+ "model.layers.9.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
389
+ "model.layers.9.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
390
+ "model.layers.9.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
391
+ "model.layers.9.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
392
+ "model.layers.9.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
393
+ "model.layers.9.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
394
+ "model.layers.9.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
395
+ "model.norm.weight": "model-00003-of-00004.safetensors",
396
+ "ts_encoder.mlp.0.bias": "model-00004-of-00004.safetensors",
397
+ "ts_encoder.mlp.0.weight": "model-00004-of-00004.safetensors",
398
+ "ts_encoder.mlp.2.bias": "model-00004-of-00004.safetensors",
399
+ "ts_encoder.mlp.2.weight": "model-00004-of-00004.safetensors",
400
+ "ts_encoder.mlp.4.bias": "model-00004-of-00004.safetensors",
401
+ "ts_encoder.mlp.4.weight": "model-00004-of-00004.safetensors",
402
+ "ts_encoder.mlp.6.bias": "model-00004-of-00004.safetensors",
403
+ "ts_encoder.mlp.6.weight": "model-00004-of-00004.safetensors",
404
+ "ts_encoder.mlp.8.bias": "model-00004-of-00004.safetensors",
405
+ "ts_encoder.mlp.8.weight": "model-00004-of-00004.safetensors"
406
+ }
407
+ }
modeling_qwen2.py ADDED
@@ -0,0 +1,2113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # The following code are reused from the QWen project (https://huggingface.co/Qwen/Qwen2.5-14B-Instruct) of Alibaba Cloud.
3
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
4
+ #
5
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
6
+ # and OPT implementations in this library. It has been modified from its
7
+ # original forms to accommodate minor architectural differences compared
8
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+ # The code is modified by ByteDance and Tsinghua University from the original implementation of Qwen:
23
+ # - Support time series modality for Qwen2 model.
24
+
25
+ """ PyTorch Qwen2 model."""
26
+ import inspect
27
+ import math
28
+ import copy
29
+ from typing import List, Optional, Tuple, Union, Dict, Any
30
+ from dataclasses import dataclass
31
+
32
+ import torch
33
+ import torch.nn.functional as F
34
+ import torch.utils.checkpoint
35
+ from torch import nn
36
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
37
+
38
+ from transformers.activations import ACT2FN
39
+ from transformers.cache_utils import Cache, DynamicCache
40
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa
41
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
42
+ from transformers.modeling_utils import PreTrainedModel
43
+ from transformers import AutoConfig
44
+ from transformers.utils import (
45
+ add_start_docstrings,
46
+ add_start_docstrings_to_model_forward,
47
+ is_flash_attn_2_available,
48
+ is_flash_attn_greater_or_equal_2_10,
49
+ logging,
50
+ replace_return_docstrings,
51
+ ModelOutput
52
+ )
53
+ from .configuration_qwen2 import Qwen2TSConfig, TinyTimeMixerConfig
54
+
55
+ # from .modeling_tinytimemixer import TinyTimeMixerForPrediction
56
+ # from .configuration_tinytimemixer import TinyTimeMixerConfig
57
+
58
+ if is_flash_attn_2_available():
59
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
60
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
61
+
62
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
63
+
64
+
65
+ logger = logging.get_logger(__name__)
66
+
67
+ _CHECKPOINT_FOR_DOC = "Qwen/Qwen2-7B-beta"
68
+ _CONFIG_FOR_DOC = "Qwen2TSConfig"
69
+
70
+
71
+ @dataclass
72
+ class Qwen2TSCausalLMOutputWithPast(ModelOutput):
73
+ """
74
+ Base class for Qwen2TS causal language model (or autoregressive) outputs.
75
+
76
+ Args:
77
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
78
+ Language modeling loss (for next-token prediction).
79
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
80
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
81
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
82
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
83
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
84
+
85
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
86
+ `past_key_values` input) to speed up sequential decoding.
87
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
88
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
89
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
90
+
91
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
92
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
93
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
94
+ sequence_length)`.
95
+
96
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
97
+ heads.
98
+ attention_mask (`torch.FloatTensor`, *optional*):
99
+ Attentions mask, used to update attention mask and position_ids.
100
+ """
101
+
102
+ loss: Optional[torch.FloatTensor] = None
103
+ logits: torch.FloatTensor = None
104
+ labels: torch.LongTensor = None
105
+ past_key_values: Optional[List[torch.FloatTensor]] = None
106
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
107
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
108
+ attention_mask: Optional[torch.FloatTensor] = None
109
+
110
+ ########################Naive TS Embedding#####################
111
+ class TimeSeriesEmbedding(nn.Module):
112
+ def __init__(self, config):
113
+ super(TimeSeriesEmbedding, self).__init__()
114
+ self.patch_size = config['patch_size']
115
+ self.num_layers = config['num_layers']
116
+ self.hidden_size = config['hidden_size']
117
+ self.num_features = config['num_features']
118
+
119
+ layers = []
120
+ input_size = 1 * self.patch_size
121
+
122
+ for _ in range(self.num_layers - 1):
123
+ layers.append(nn.Linear(input_size, self.hidden_size))
124
+ layers.append(nn.GELU())
125
+ input_size = self.hidden_size
126
+ layers.append(nn.Linear(input_size, self.hidden_size))
127
+
128
+ self.mlp = nn.Sequential(*layers)
129
+
130
+ def forward(self, x: torch.Tensor):
131
+ batch_size = x.size(0)
132
+ x = x.reshape(batch_size, -1, self.num_features)
133
+
134
+ mask = x[:, :, -1].long()
135
+ valid_lengths = mask.sum(dim=1).long() # Shape: (batch_size)
136
+
137
+ patch_cnt = (valid_lengths + self.patch_size - 1) // self.patch_size # 向上取整
138
+
139
+ patches_list = []
140
+ for i in range(batch_size):
141
+ vl = valid_lengths[i].item()
142
+ pc = patch_cnt[i].item()
143
+ if pc == 0:
144
+ continue
145
+ xi = x[i, :vl, :1]
146
+ total_padded_length = pc * self.patch_size
147
+ padding_length = total_padded_length - vl
148
+ if padding_length > 0:
149
+ padding = torch.zeros(padding_length, 1, device=x.device, dtype=x.dtype)
150
+ xi = torch.cat([xi, padding], dim=0)
151
+ xi = xi.reshape(pc, self.patch_size * 1)
152
+ patches_list.append(xi)
153
+
154
+ if patches_list:
155
+ x_patches = torch.cat(patches_list, dim=0) # Shape: (total_patch_cnt, patch_size * num_features)
156
+ x = self.mlp(x_patches)
157
+ else:
158
+ x = torch.empty(0, self.hidden_size, device=x.device)
159
+
160
+ return x, patch_cnt
161
+
162
+ class moving_avg(nn.Module):
163
+ """
164
+ Moving average block to highlight the trend of time series
165
+ """
166
+
167
+ def __init__(self, kernel_size, stride):
168
+ super(moving_avg, self).__init__()
169
+ self.kernel_size = kernel_size
170
+ self.avg = nn.AvgPool1d(kernel_size=kernel_size, stride=stride, padding=0)
171
+
172
+ def forward(self, x):
173
+ # padding on the both ends of time series
174
+ front = x[:, 0:1, :].repeat(1, (self.kernel_size - 1) // 2, 1)
175
+ end = x[:, -1:, :].repeat(1, (self.kernel_size - 1) // 2, 1)
176
+ x = torch.cat([front, x, end], dim=1)
177
+ x = self.avg(x.permute(0, 2, 1))
178
+ x = x.permute(0, 2, 1)
179
+ return x
180
+
181
+ class series_decomp(nn.Module):
182
+ """
183
+ Series decomposition block
184
+ """
185
+
186
+ def __init__(self, kernel_size):
187
+ super(series_decomp, self).__init__()
188
+ self.moving_avg = moving_avg(kernel_size, stride=1)
189
+
190
+ def forward(self, x):
191
+ moving_mean = self.moving_avg(x)
192
+ res = x - moving_mean
193
+
194
+ # save_dict = {
195
+ # 'seasonality': res.detach().cpu(),
196
+ # 'trend': moving_mean.detach().cpu()
197
+ # }
198
+ # torch.save(save_dict, '/root/ljk/PATRA/latent_decomposition_vis.pt')
199
+
200
+ return res, moving_mean
201
+
202
+ class MultiHeadAttention(nn.Module):
203
+
204
+ def __init__(
205
+ self,
206
+ embed_dim: int,
207
+ num_heads: int,
208
+ kdim: Optional[int] = None,
209
+ vdim: Optional[int] = None,
210
+ dropout: float = 0.0,
211
+ bias: bool = True,
212
+ ) -> None:
213
+ super().__init__()
214
+ assert embed_dim % num_heads == 0, "embed_dim 必须能被 num_heads 整除"
215
+ self.embed_dim = embed_dim
216
+ self.num_heads = num_heads
217
+ self.head_dim = embed_dim // num_heads
218
+ self.scale = 1.0 / math.sqrt(self.head_dim)
219
+
220
+
221
+ kdim = embed_dim if kdim is None else kdim
222
+ vdim = embed_dim if vdim is None else vdim
223
+
224
+
225
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
226
+ self.k_proj = nn.Linear(kdim, embed_dim, bias=bias)
227
+ self.v_proj = nn.Linear(vdim, embed_dim, bias=bias)
228
+ self.o_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
229
+
230
+
231
+ self.attn_drop = nn.Dropout(dropout)
232
+ self.proj_drop = nn.Dropout(dropout)
233
+
234
+
235
+ def _shape(self, x, B: int, T: int):
236
+ # (B, T, D) -> (B, H, T, Dh)
237
+ return x.view(B, T, self.num_heads, self.head_dim).transpose(1, 2)
238
+
239
+ def forward(
240
+ self,
241
+ query,
242
+ key,
243
+ value,
244
+ attn_mask = None,
245
+ key_padding_mask = None,
246
+ need_weights: bool = False,
247
+ is_causal: bool = False,
248
+ ):
249
+ B, T_q, _ = query.shape
250
+ _, T_k, _ = key.shape
251
+
252
+
253
+ # 线性映射
254
+ q = self.q_proj(query)
255
+ k = self.k_proj(key)
256
+ v = self.v_proj(value)
257
+
258
+
259
+ # 形状变换
260
+ q = self._shape(q, B, T_q) # (B,H,T_q,Dh)
261
+ k = self._shape(k, B, T_k) # (B,H,T_k,Dh)
262
+ v = self._shape(v, B, T_k) # (B,H,T_k,Dh)
263
+
264
+
265
+ # Scaled Dot-Product Attention
266
+ # scores: (B,H,T_q,T_k)
267
+ scores = torch.matmul(q, k.transpose(-2, -1)) * self.scale
268
+
269
+
270
+ # 处理 mask
271
+ if attn_mask is not None:
272
+ # 支持 bool 或 float。广播到 (B,H,T_q,T_k)
273
+ if attn_mask.dtype == torch.bool:
274
+ mask = attn_mask
275
+ # 统一 shape
276
+ if mask.ndim == 2:
277
+ mask = mask.view(1, 1, T_q, T_k)
278
+ elif mask.ndim == 3:
279
+ if mask.shape[0] == B * self.num_heads:
280
+ mask = mask.view(B, self.num_heads, T_q, T_k)
281
+ else:
282
+ mask = mask.view(B, 1, T_q, T_k)
283
+ else:
284
+ raise ValueError("attn_mask bool 需为 2D 或 3D")
285
+ scores = scores.masked_fill(mask, float("-inf"))
286
+ else:
287
+ # 加法掩码(一般为 -inf 或者大负数)
288
+ add_mask = attn_mask
289
+ if add_mask.ndim == 2:
290
+ add_mask = add_mask.view(1, 1, T_q, T_k)
291
+ elif add_mask.ndim == 3:
292
+ if add_mask.shape[0] == B * self.num_heads:
293
+ add_mask = add_mask.view(B, self.num_heads, T_q, T_k)
294
+ else:
295
+ add_mask = add_mask.view(B, 1, T_q, T_k)
296
+ else:
297
+ raise ValueError("attn_mask float 需为 2D 或 3D")
298
+ scores = scores + add_mask
299
+
300
+
301
+ if key_padding_mask is not None:
302
+ # key_padding_mask: (B, T_k) True 表示屏蔽
303
+ kpm = key_padding_mask.view(B, 1, 1, T_k).expand(-1, self.num_heads, T_q, -1)
304
+ scores = scores.masked_fill(kpm, float("-inf"))
305
+
306
+
307
+ if is_causal:
308
+ if T_q != T_k:
309
+ # 允许 cross-attn 的 causal:仅限制每个 query 不能看未来的 key
310
+ causal_mask = torch.ones(T_q, T_k, dtype=torch.bool, device=scores.device).triu(1 + max(0, T_k - T_q))
311
+ else:
312
+ causal_mask = torch.ones(T_q, T_k, dtype=torch.bool, device=scores.device).triu(1)
313
+ scores = scores.masked_fill(causal_mask.view(1, 1, T_q, T_k), float("-inf"))
314
+
315
+
316
+ attn = F.softmax(scores, dim=-1)
317
+ attn = self.attn_drop(attn)
318
+
319
+
320
+ # 聚合
321
+ out = torch.matmul(attn, v) # (B,H,T_q,Dh)
322
+ out = out.transpose(1, 2).contiguous().view(B, T_q, self.embed_dim)
323
+ out = self.o_proj(out)
324
+ out = self.proj_drop(out)
325
+
326
+ if need_weights:
327
+ # 返回平均后的权重 (B, T_q, T_k)
328
+ avg_weights = attn.mean(dim=1)
329
+ return out, avg_weights
330
+ else:
331
+ return out, None
332
+
333
+ class MultiModalAlignment(nn.Module):
334
+ """
335
+ Alignment module for text and time series modality alignment
336
+ """
337
+ def __init__(self, all_config):
338
+ super().__init__()
339
+ self.config = all_config
340
+ config = all_config.ts
341
+ self.hidden_size = config.get('hidden_size', 25)
342
+
343
+ # Time series decomposition
344
+ self.ts_decomposer = series_decomp(kernel_size=config.get('decomp_kernel_size', 25))
345
+ self.num_align_tokens = config.get('num_align_tokens', 10)
346
+ # Learnable query parameters for three aspects
347
+ # self.complete_query = nn.Parameter(torch.randn(1, self.num_align_tokens, self.hidden_size, dtype=torch.float32)).half()
348
+ # self.trend_query = nn.Parameter(torch.randn(1, self.num_align_tokens, self.hidden_size, dtype=torch.float32)).half()
349
+ # self.seasonal_query = nn.Parameter(torch.randn(1, self.num_align_tokens, self.hidden_size, dtype=torch.float32)).half()
350
+ self.complete_query = nn.Linear(self.num_align_tokens, self.hidden_size, bias=False)
351
+ self.trend_query = nn.Linear(self.num_align_tokens, self.hidden_size, bias=False)
352
+ self.seasonal_query = nn.Linear(self.num_align_tokens, self.hidden_size, bias=False)
353
+
354
+ # Text attention modules for decomposition
355
+ self.complete_text_attn = MultiHeadAttention(
356
+ embed_dim=self.hidden_size,
357
+ num_heads=config.get('alignment_num_heads', 8),
358
+ dropout=config.get('alignment_dropout', 0.1),
359
+ )
360
+ self.trend_text_attn = MultiHeadAttention(
361
+ embed_dim=self.hidden_size,
362
+ num_heads=config.get('alignment_num_heads', 8),
363
+ dropout=config.get('alignment_dropout', 0.1),
364
+ )
365
+ self.seasonal_text_attn = MultiHeadAttention(
366
+ embed_dim=self.hidden_size,
367
+ num_heads=config.get('alignment_num_heads', 8),
368
+ dropout=config.get('alignment_dropout', 0.1),
369
+ )
370
+
371
+ # fusion attention modules
372
+ self.complete_cross_attn = MultiHeadAttention(
373
+ embed_dim=self.hidden_size,
374
+ num_heads=config.get('alignment_num_heads', 8),
375
+ dropout=config.get('alignment_dropout', 0.1),
376
+ )
377
+ self.trend_cross_attn = MultiHeadAttention(
378
+ embed_dim=self.hidden_size,
379
+ num_heads=config.get('alignment_num_heads', 8),
380
+ dropout=config.get('alignment_dropout', 0.1),
381
+ )
382
+ self.seasonal_cross_attn = MultiHeadAttention(
383
+ embed_dim=self.hidden_size,
384
+ num_heads=config.get('alignment_num_heads', 8),
385
+ dropout=config.get('alignment_dropout', 0.1),
386
+ )
387
+
388
+ # Fusion layers
389
+ # self.fusion_layer = nn.Linear(self.hidden_size * 3, self.hidden_size)
390
+
391
+ def forward(self, input_ids, text_embeddings, ts_features, patch_counts, text_attention_mask=None):
392
+ """
393
+ Forward pass of alignment module
394
+ Args:
395
+ text_embeddings: [batch_size, text_seq_len, hidden_size]
396
+ ts_features_list: List of [patch_count_i, hidden_size] for each time series
397
+ patch_counts: [num_ts] - number of patches for each time series
398
+ text_attention_mask: [batch_size, text_seq_len]
399
+ Returns:
400
+ aligned_features_list: List of aligned features for each time series
401
+ """
402
+ batch_size = text_embeddings.size(0)
403
+
404
+ # 1. 计算每个batch有几个ts
405
+ special_ts_token_mask_start = input_ids == self.config.ts_token_start_index
406
+ num_special_ts_tokens = torch.sum(special_ts_token_mask_start, dim=-1)
407
+
408
+ # 2. 计算一共有多少ts, 每个batch有多少个patch
409
+ num_ts = num_special_ts_tokens.sum(dim=0)
410
+ patch_index = 0
411
+ num_patches_per_batch = []
412
+ for i in range(batch_size):
413
+ num_ts_in_batch = num_special_ts_tokens[i] # 每个batch多少个ts
414
+ num_patches_per_batch.append(patch_counts[patch_index : patch_index + num_ts_in_batch].sum())
415
+ patch_index = patch_index + num_ts_in_batch
416
+
417
+ # complete_q = self.complete_query.expand(num_ts, -1, -1).to(ts_features.device)
418
+ # trend_q = self.trend_query.expand(num_ts, -1, -1).to(ts_features.device)
419
+ # seasonal_q = self.seasonal_query.expand(num_ts, -1, -1).to(ts_features.device)
420
+ # complete_q = self.complete_query.expand(batch_size, -1, -1).to(text_embeddings.device)
421
+ # trend_q = self.trend_query.expand(batch_size, -1, -1).to(text_embeddings.device)
422
+ # seasonal_q = self.seasonal_query.expand(batch_size, -1, -1).to(text_embeddings.device)
423
+ # complete_q = self.complete_query(torch.eye(self.num_align_tokens, dtype=text_embeddings.dtype, device=text_embeddings.device)).unsqueeze(0).expand(batch_size, -1, -1)
424
+ # trend_q = self.trend_query(torch.eye(self.num_align_tokens, dtype=text_embeddings.dtype, device=text_embeddings.device)).unsqueeze(0).expand(batch_size, -1, -1)
425
+ # seasonal_q = self.seasonal_query(torch.eye(self.num_align_tokens, dtype=text_embeddings.dtype, device=text_embeddings.device)).unsqueeze(0).expand(batch_size, -1, -1)
426
+ complete_q = self.complete_query(torch.eye(self.num_align_tokens, dtype=self.complete_query.weight.dtype, device=text_embeddings.device)).unsqueeze(0).expand(batch_size, -1, -1)
427
+ trend_q = self.trend_query(torch.eye(self.num_align_tokens, dtype=self.trend_query.weight.dtype, device=text_embeddings.device)).unsqueeze(0).expand(batch_size, -1, -1)
428
+ seasonal_q = self.seasonal_query(torch.eye(self.num_align_tokens, dtype=self.seasonal_query.weight.dtype, device=text_embeddings.device)).unsqueeze(0).expand(batch_size, -1, -1)
429
+
430
+ # text_embeddings = torch.repeat_interleave(text_embeddings, repeats=num_special_ts_tokens, dim=0)
431
+
432
+ # 3. 文本以 ts level 分解,输出的shape为 (num_ts, n_token, dim)
433
+ text_complete, _ = self.complete_text_attn(
434
+ query=complete_q,
435
+ key=text_embeddings,
436
+ value=text_embeddings
437
+ )
438
+
439
+ text_trend, _ = self.trend_text_attn(
440
+ query=trend_q,
441
+ key=text_embeddings,
442
+ value=text_embeddings
443
+ )
444
+
445
+ text_seasonal, _ = self.seasonal_text_attn(
446
+ query=seasonal_q,
447
+ key=text_embeddings,
448
+ value=text_embeddings
449
+ )
450
+
451
+ # text_complete = torch.repeat_interleave(text_complete, repeats=num_special_ts_tokens, dim=0)
452
+ # text_trend = torch.repeat_interleave(text_trend, repeats=num_special_ts_tokens, dim=0)
453
+ # text_seasonal = torch.repeat_interleave(text_seasonal, repeats=num_special_ts_tokens, dim=0)
454
+
455
+ # 4. ts分解 (1, patch_num, dim)
456
+ ts_features = ts_features.unsqueeze(0)
457
+ ts_seasonal, ts_trend = self.ts_decomposer(ts_features)
458
+ index_patch = 0
459
+ aligned_features_list = []
460
+ for i in range(batch_size):
461
+ complite_kv = ts_features[:, index_patch: index_patch + num_patches_per_batch[i]]
462
+ seasonal_kv = ts_seasonal[:, index_patch: index_patch + num_patches_per_batch[i]]
463
+ trend_kv = ts_trend[:, index_patch: index_patch + num_patches_per_batch[i]]
464
+ index_patch = index_patch + num_patches_per_batch[i]
465
+
466
+ complite_qkv = torch.cat([text_complete[i:i+1], complite_kv], dim=1)
467
+ # seasonal_qkv = torch.cat([text_trend[i:i+1], seasonal_kv], dim=1)
468
+ # trend_qkv = torch.cat([text_seasonal[i:i+1], trend_kv], dim=1)
469
+
470
+ trend_qkv = torch.cat([text_trend[i:i+1], seasonal_kv], dim=1)
471
+ seasonal_qkv = torch.cat([text_seasonal[i:i+1], trend_kv], dim=1)
472
+
473
+ aligned_complete, _ = self.complete_cross_attn(
474
+ query=complite_qkv,
475
+ key=complite_qkv,
476
+ value=complite_qkv
477
+ )
478
+
479
+ aligned_trend, _ = self.trend_cross_attn(
480
+ query=trend_qkv,
481
+ key=trend_qkv,
482
+ value=trend_qkv
483
+ )
484
+
485
+ aligned_seasonal, _ = self.seasonal_cross_attn(
486
+ query=seasonal_qkv,
487
+ key=seasonal_qkv,
488
+ value=seasonal_qkv
489
+ )
490
+
491
+ aligned_features = (aligned_complete + aligned_trend + aligned_seasonal) / 3
492
+ aligned_features_list.append(aligned_features.reshape(-1, self.hidden_size)[self.num_align_tokens:])
493
+
494
+ aligned_features = torch.cat(aligned_features_list, dim=0)
495
+ assert aligned_features.shape == ts_features.squeeze(0).shape, f"{aligned_features.shape}, {ts_features.shape}"
496
+
497
+ # 5. 三部分文本reshape为 (1, bs * n_token, dim)
498
+ # n_token = text_complete.shape[1]
499
+ # text_complete = text_complete.reshape(-1, self.hidden_size).unsqueeze(0)
500
+ # text_trend = text_complete.reshape(-1, self.hidden_size).unsqueeze(0)
501
+ # text_seasonal = text_complete.reshape(-1, self.hidden_size).unsqueeze(0)
502
+
503
+ # mask = torch.ones((num_ts * n_token, ts_features.shape[1]), dtype=torch.bool).to(ts_features.device)
504
+ # index_ts = 0
505
+ # index_patch = 0
506
+ # for i in range(batch_size):
507
+ # num_ts_in_batch = num_special_ts_tokens[i]
508
+ # num_patch_in_batch = num_patches_per_batch[i]
509
+ # mask[index_ts * n_token: (index_ts + num_ts_in_batch) * n_token, index_patch: index_patch + num_patch_in_batch] = False
510
+ # index_ts = index_ts + num_ts_in_batch
511
+ # index_patch = index_patch + num_patch_in_batch
512
+
513
+ # aligned_complete, _ = self.complete_cross_attn(
514
+ # query=text_complete,
515
+ # key=ts_features,
516
+ # value=ts_features,
517
+ # attn_mask = mask
518
+ # )
519
+
520
+ # aligned_trend, _ = self.trend_cross_attn(
521
+ # query=text_trend,
522
+ # key=ts_trend,
523
+ # value=ts_trend,
524
+ # attn_mask = mask
525
+ # )
526
+
527
+ # aligned_seasonal, _ = self.seasonal_cross_attn(
528
+ # query=text_seasonal,
529
+ # key=ts_seasonal,
530
+ # value=ts_seasonal,
531
+ # attn_mask = mask
532
+ # )
533
+
534
+ # # 6. Fuse into final representation,输出shape为(1, num_ts * n_token, dim)
535
+ # # fused_features = self.fusion_layer(concatenated)
536
+ # aligned_features = (aligned_complete + aligned_trend + aligned_seasonal) / 3
537
+ # aligned_features = aligned_features.reshape(-1, self.hidden_size)
538
+
539
+ # # 7. 重新给出patch_cnt
540
+ aligned_patch_cnt = torch.full_like(patch_counts, self.num_align_tokens)
541
+
542
+ return aligned_features, patch_counts
543
+
544
+
545
+ ########################QWEN2###################################
546
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
547
+ def _get_unpad_data(attention_mask):
548
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
549
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
550
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
551
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
552
+ return (
553
+ indices,
554
+ cu_seqlens,
555
+ max_seqlen_in_batch,
556
+ )
557
+
558
+
559
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Qwen2
560
+ class Qwen2RMSNorm(nn.Module):
561
+ def __init__(self, hidden_size, eps=1e-6):
562
+ """
563
+ Qwen2RMSNorm is equivalent to T5LayerNorm
564
+ """
565
+ super().__init__()
566
+ self.weight = nn.Parameter(torch.ones(hidden_size))
567
+ self.variance_epsilon = eps
568
+
569
+ def forward(self, hidden_states):
570
+ input_dtype = hidden_states.dtype
571
+ hidden_states = hidden_states.to(torch.float32)
572
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
573
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
574
+ return self.weight * hidden_states.to(input_dtype)
575
+
576
+
577
+ # Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->Qwen2
578
+ class Qwen2RotaryEmbedding(nn.Module):
579
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
580
+ super().__init__()
581
+
582
+ self.dim = dim
583
+ self.max_position_embeddings = max_position_embeddings
584
+ self.base = base
585
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
586
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
587
+
588
+ # Build here to make `torch.jit.trace` work.
589
+ self._set_cos_sin_cache(
590
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
591
+ )
592
+
593
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
594
+ self.max_seq_len_cached = seq_len
595
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
596
+
597
+ freqs = torch.outer(t, self.inv_freq)
598
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
599
+ emb = torch.cat((freqs, freqs), dim=-1)
600
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
601
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
602
+
603
+ def forward(self, x, seq_len=None):
604
+ # x: [bs, num_attention_heads, seq_len, head_size]
605
+ if seq_len > self.max_seq_len_cached:
606
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
607
+
608
+ return (
609
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
610
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
611
+ )
612
+
613
+
614
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
615
+ def rotate_half(x):
616
+ """Rotates half the hidden dims of the input."""
617
+ x1 = x[..., : x.shape[-1] // 2]
618
+ x2 = x[..., x.shape[-1] // 2 :]
619
+ return torch.cat((-x2, x1), dim=-1)
620
+
621
+
622
+ # Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
623
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
624
+ """Applies Rotary Position Embedding to the query and key tensors.
625
+
626
+ Args:
627
+ q (`torch.Tensor`): The query tensor.
628
+ k (`torch.Tensor`): The key tensor.
629
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
630
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
631
+ position_ids (`torch.Tensor`):
632
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
633
+ used to pass offsetted position ids when working with a KV-cache.
634
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
635
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
636
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
637
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
638
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
639
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
640
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
641
+ Returns:
642
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
643
+ """
644
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
645
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
646
+ q_embed = (q * cos) + (rotate_half(q) * sin)
647
+ k_embed = (k * cos) + (rotate_half(k) * sin)
648
+ return q_embed, k_embed
649
+
650
+
651
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Qwen2
652
+ class Qwen2MLP(nn.Module):
653
+ def __init__(self, config):
654
+ super().__init__()
655
+ self.config = config
656
+ self.hidden_size = config.hidden_size
657
+ self.intermediate_size = config.intermediate_size
658
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
659
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
660
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
661
+ self.act_fn = ACT2FN[config.hidden_act]
662
+
663
+ def forward(self, x):
664
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
665
+
666
+
667
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
668
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
669
+ """
670
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
671
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
672
+ """
673
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
674
+ if n_rep == 1:
675
+ return hidden_states
676
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
677
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
678
+
679
+
680
+ class Qwen2Attention(nn.Module):
681
+ """
682
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
683
+ and "Generating Long Sequences with Sparse Transformers".
684
+ """
685
+
686
+ def __init__(self, config: Qwen2TSConfig, layer_idx: Optional[int] = None):
687
+ super().__init__()
688
+ self.config = config
689
+ self.layer_idx = layer_idx
690
+ if layer_idx is None:
691
+ logger.warning_once(
692
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
693
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
694
+ "when creating this class."
695
+ )
696
+
697
+ self.hidden_size = config.hidden_size
698
+ self.num_heads = config.num_attention_heads
699
+ self.head_dim = self.hidden_size // self.num_heads
700
+ self.num_key_value_heads = config.num_key_value_heads
701
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
702
+ self.max_position_embeddings = config.max_position_embeddings
703
+ self.rope_theta = config.rope_theta
704
+ self.is_causal = True
705
+ self.attention_dropout = config.attention_dropout
706
+
707
+ if (self.head_dim * self.num_heads) != self.hidden_size:
708
+ raise ValueError(
709
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
710
+ f" and `num_heads`: {self.num_heads})."
711
+ )
712
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
713
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
714
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
715
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
716
+
717
+ self.rotary_emb = Qwen2RotaryEmbedding(
718
+ self.head_dim,
719
+ max_position_embeddings=self.max_position_embeddings,
720
+ base=self.rope_theta,
721
+ )
722
+
723
+ def forward(
724
+ self,
725
+ hidden_states: torch.Tensor,
726
+ attention_mask: Optional[torch.Tensor] = None,
727
+ position_ids: Optional[torch.LongTensor] = None,
728
+ past_key_value: Optional[Cache] = None,
729
+ output_attentions: bool = False,
730
+ use_cache: bool = False,
731
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
732
+ bsz, q_len, _ = hidden_states.size()
733
+
734
+ query_states = self.q_proj(hidden_states)
735
+ key_states = self.k_proj(hidden_states)
736
+ value_states = self.v_proj(hidden_states)
737
+
738
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
739
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
740
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
741
+
742
+ kv_seq_len = key_states.shape[-2]
743
+ if past_key_value is not None:
744
+ if self.layer_idx is None:
745
+ raise ValueError(
746
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
747
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
748
+ "with a layer index."
749
+ )
750
+ kv_seq_len += past_key_value.get_seq_length(self.layer_idx)
751
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
752
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
753
+
754
+ if past_key_value is not None:
755
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
756
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
757
+
758
+ # repeat k/v heads if n_kv_heads < n_heads
759
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
760
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
761
+
762
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
763
+
764
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
765
+ raise ValueError(
766
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
767
+ f" {attn_weights.size()}"
768
+ )
769
+
770
+ if attention_mask is not None:
771
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
772
+ raise ValueError(
773
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
774
+ )
775
+
776
+ attn_weights = attn_weights + attention_mask
777
+
778
+ # upcast attention to fp32
779
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
780
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
781
+ attn_output = torch.matmul(attn_weights, value_states)
782
+
783
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
784
+ raise ValueError(
785
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
786
+ f" {attn_output.size()}"
787
+ )
788
+
789
+ attn_output = attn_output.transpose(1, 2).contiguous()
790
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
791
+
792
+ attn_output = self.o_proj(attn_output)
793
+
794
+ if not output_attentions:
795
+ attn_weights = None
796
+
797
+ return attn_output, attn_weights, past_key_value
798
+
799
+
800
+ class Qwen2FlashAttention2(Qwen2Attention):
801
+ """
802
+ Qwen2 flash attention module, following Qwen2 attention module. This module inherits from `Qwen2Attention`
803
+ as the weights of the module stays untouched. The only required change would be on the forward pass
804
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
805
+ in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
806
+ config.max_window_layers layers.
807
+ """
808
+
809
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
810
+ def __init__(self, *args, **kwargs):
811
+ super().__init__(*args, **kwargs)
812
+
813
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
814
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
815
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
816
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
817
+
818
+ def forward(
819
+ self,
820
+ hidden_states: torch.Tensor,
821
+ attention_mask: Optional[torch.Tensor] = None,
822
+ position_ids: Optional[torch.LongTensor] = None,
823
+ past_key_value: Optional[Cache] = None,
824
+ output_attentions: bool = False,
825
+ use_cache: bool = False,
826
+ ):
827
+ bsz, q_len, _ = hidden_states.size()
828
+
829
+ query_states = self.q_proj(hidden_states)
830
+ key_states = self.k_proj(hidden_states)
831
+ value_states = self.v_proj(hidden_states)
832
+
833
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
834
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
835
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
836
+
837
+ kv_seq_len = key_states.shape[-2]
838
+ if past_key_value is not None:
839
+ if self.layer_idx is None:
840
+ raise ValueError(
841
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
842
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
843
+ "with a layer index."
844
+ )
845
+ kv_seq_len += past_key_value.get_seq_length(self.layer_idx)
846
+
847
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
848
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
849
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
850
+
851
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
852
+
853
+ use_sliding_windows = (
854
+ _flash_supports_window_size
855
+ and getattr(self.config, "sliding_window", None) is not None
856
+ and kv_seq_len > self.config.sliding_window
857
+ and self.config.use_sliding_window
858
+ )
859
+
860
+ if not _flash_supports_window_size:
861
+ logger.warning_once(
862
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
863
+ " make sure to upgrade flash-attn library."
864
+ )
865
+
866
+ if past_key_value is not None:
867
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
868
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
869
+ if (
870
+ getattr(self.config, "sliding_window", None) is not None
871
+ and kv_seq_len > self.config.sliding_window
872
+ and cache_has_contents
873
+ ):
874
+ slicing_tokens = 1 - self.config.sliding_window
875
+
876
+ past_key = past_key_value[self.layer_idx][0]
877
+ past_value = past_key_value[self.layer_idx][1]
878
+
879
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
880
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
881
+
882
+ if past_key.shape[-2] != self.config.sliding_window - 1:
883
+ raise ValueError(
884
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
885
+ f" {past_key.shape}"
886
+ )
887
+
888
+ if attention_mask is not None:
889
+ attention_mask = attention_mask[:, slicing_tokens:]
890
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
891
+
892
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
893
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
894
+
895
+ # repeat k/v heads if n_kv_heads < n_heads
896
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
897
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
898
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
899
+
900
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
901
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
902
+ # cast them back in float16 just to be sure everything works as expected.
903
+ input_dtype = query_states.dtype
904
+ if input_dtype == torch.float32:
905
+ if torch.is_autocast_enabled():
906
+ target_dtype = torch.get_autocast_gpu_dtype()
907
+ # Handle the case where the model is quantized
908
+ elif hasattr(self.config, "_pre_quantization_dtype"):
909
+ target_dtype = self.config._pre_quantization_dtype
910
+ else:
911
+ target_dtype = self.q_proj.weight.dtype
912
+
913
+ logger.warning_once(
914
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
915
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
916
+ f" {target_dtype}."
917
+ )
918
+
919
+ query_states = query_states.to(target_dtype)
920
+ key_states = key_states.to(target_dtype)
921
+ value_states = value_states.to(target_dtype)
922
+
923
+ # Reashape to the expected shape for Flash Attention
924
+ query_states = query_states.transpose(1, 2)
925
+ key_states = key_states.transpose(1, 2)
926
+ value_states = value_states.transpose(1, 2)
927
+
928
+ attn_output = self._flash_attention_forward(
929
+ query_states,
930
+ key_states,
931
+ value_states,
932
+ attention_mask,
933
+ q_len,
934
+ dropout=dropout_rate,
935
+ use_sliding_windows=use_sliding_windows,
936
+ )
937
+
938
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
939
+ attn_output = self.o_proj(attn_output)
940
+
941
+ if not output_attentions:
942
+ attn_weights = None
943
+
944
+ return attn_output, attn_weights, past_key_value
945
+
946
+ def _flash_attention_forward(
947
+ self,
948
+ query_states,
949
+ key_states,
950
+ value_states,
951
+ attention_mask,
952
+ query_length,
953
+ dropout=0.0,
954
+ softmax_scale=None,
955
+ use_sliding_windows=False,
956
+ ):
957
+ """
958
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
959
+ first unpad the input, then computes the attention scores and pad the final attention scores.
960
+
961
+ Args:
962
+ query_states (`torch.Tensor`):
963
+ Input query states to be passed to Flash Attention API
964
+ key_states (`torch.Tensor`):
965
+ Input key states to be passed to Flash Attention API
966
+ value_states (`torch.Tensor`):
967
+ Input value states to be passed to Flash Attention API
968
+ attention_mask (`torch.Tensor`):
969
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
970
+ position of padding tokens and 1 for the position of non-padding tokens.
971
+ dropout (`float`):
972
+ Attention dropout
973
+ softmax_scale (`float`, *optional*):
974
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
975
+ use_sliding_windows (`bool`, *optional*):
976
+ Whether to activate sliding window attention.
977
+ """
978
+ if not self._flash_attn_uses_top_left_mask:
979
+ causal = self.is_causal
980
+ else:
981
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
982
+ causal = self.is_causal and query_length != 1
983
+
984
+ # Decide whether to use SWA or not by layer index.
985
+ if use_sliding_windows and self.layer_idx >= self.config.max_window_layers:
986
+ use_sliding_windows = False
987
+
988
+ # Contains at least one padding token in the sequence
989
+ if attention_mask is not None:
990
+ batch_size = query_states.shape[0]
991
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
992
+ query_states, key_states, value_states, attention_mask, query_length
993
+ )
994
+
995
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
996
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
997
+
998
+ if not use_sliding_windows:
999
+ attn_output_unpad = flash_attn_varlen_func(
1000
+ query_states,
1001
+ key_states,
1002
+ value_states,
1003
+ cu_seqlens_q=cu_seqlens_q,
1004
+ cu_seqlens_k=cu_seqlens_k,
1005
+ max_seqlen_q=max_seqlen_in_batch_q,
1006
+ max_seqlen_k=max_seqlen_in_batch_k,
1007
+ dropout_p=dropout,
1008
+ softmax_scale=softmax_scale,
1009
+ causal=causal,
1010
+ )
1011
+ else:
1012
+ attn_output_unpad = flash_attn_varlen_func(
1013
+ query_states,
1014
+ key_states,
1015
+ value_states,
1016
+ cu_seqlens_q=cu_seqlens_q,
1017
+ cu_seqlens_k=cu_seqlens_k,
1018
+ max_seqlen_q=max_seqlen_in_batch_q,
1019
+ max_seqlen_k=max_seqlen_in_batch_k,
1020
+ dropout_p=dropout,
1021
+ softmax_scale=softmax_scale,
1022
+ causal=causal,
1023
+ window_size=(self.config.sliding_window, self.config.sliding_window),
1024
+ )
1025
+
1026
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
1027
+ else:
1028
+ if not use_sliding_windows:
1029
+ attn_output = flash_attn_func(
1030
+ query_states,
1031
+ key_states,
1032
+ value_states,
1033
+ dropout,
1034
+ softmax_scale=softmax_scale,
1035
+ causal=causal,
1036
+ )
1037
+ else:
1038
+ attn_output = flash_attn_func(
1039
+ query_states,
1040
+ key_states,
1041
+ value_states,
1042
+ dropout,
1043
+ softmax_scale=softmax_scale,
1044
+ causal=causal,
1045
+ window_size=(self.config.sliding_window, self.config.sliding_window),
1046
+ )
1047
+
1048
+ return attn_output
1049
+
1050
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
1051
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
1052
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
1053
+
1054
+ # On the first iteration we need to properly re-create the padding mask
1055
+ # by slicing it on the proper place
1056
+ if kv_seq_len != attention_mask.shape[-1]:
1057
+ attention_mask_num_tokens = attention_mask.shape[-1]
1058
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
1059
+
1060
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
1061
+
1062
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
1063
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
1064
+
1065
+ if query_length == kv_seq_len:
1066
+ query_layer = index_first_axis(
1067
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
1068
+ )
1069
+ cu_seqlens_q = cu_seqlens_k
1070
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
1071
+ indices_q = indices_k
1072
+ elif query_length == 1:
1073
+ max_seqlen_in_batch_q = 1
1074
+ cu_seqlens_q = torch.arange(
1075
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
1076
+ ) # There is a memcpy here, that is very bad.
1077
+ indices_q = cu_seqlens_q[:-1]
1078
+ query_layer = query_layer.squeeze(1)
1079
+ else:
1080
+ # The -q_len: slice assumes left padding.
1081
+ attention_mask = attention_mask[:, -query_length:]
1082
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
1083
+
1084
+ return (
1085
+ query_layer,
1086
+ key_layer,
1087
+ value_layer,
1088
+ indices_q,
1089
+ (cu_seqlens_q, cu_seqlens_k),
1090
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1091
+ )
1092
+
1093
+
1094
+ # Copied from transformers.models.mistral.modeling_mistral.MistralSdpaAttention with Mistral->Qwen2
1095
+ class Qwen2SdpaAttention(Qwen2Attention):
1096
+ """
1097
+ Qwen2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
1098
+ `Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
1099
+ SDPA API.
1100
+ """
1101
+
1102
+ # Adapted from Qwen2Attention.forward
1103
+ def forward(
1104
+ self,
1105
+ hidden_states: torch.Tensor,
1106
+ attention_mask: Optional[torch.Tensor] = None,
1107
+ position_ids: Optional[torch.LongTensor] = None,
1108
+ past_key_value: Optional[Cache] = None,
1109
+ output_attentions: bool = False,
1110
+ use_cache: bool = False,
1111
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
1112
+ if output_attentions:
1113
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
1114
+ logger.warning_once(
1115
+ "Qwen2Model is using Qwen2SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
1116
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
1117
+ )
1118
+ return super().forward(
1119
+ hidden_states=hidden_states,
1120
+ attention_mask=attention_mask,
1121
+ position_ids=position_ids,
1122
+ past_key_value=past_key_value,
1123
+ output_attentions=output_attentions,
1124
+ use_cache=use_cache,
1125
+ )
1126
+
1127
+ bsz, q_len, _ = hidden_states.size()
1128
+
1129
+ query_states = self.q_proj(hidden_states)
1130
+ key_states = self.k_proj(hidden_states)
1131
+ value_states = self.v_proj(hidden_states)
1132
+
1133
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
1134
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1135
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1136
+
1137
+ kv_seq_len = key_states.shape[-2]
1138
+ if past_key_value is not None:
1139
+ kv_seq_len += past_key_value.get_seq_length(self.layer_idx)
1140
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
1141
+
1142
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
1143
+
1144
+ if past_key_value is not None:
1145
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1146
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
1147
+
1148
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
1149
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
1150
+
1151
+ if attention_mask is not None:
1152
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
1153
+ raise ValueError(
1154
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
1155
+ )
1156
+
1157
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
1158
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
1159
+ if query_states.device.type == "cuda" and attention_mask is not None:
1160
+ query_states = query_states.contiguous()
1161
+ key_states = key_states.contiguous()
1162
+ value_states = value_states.contiguous()
1163
+
1164
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
1165
+ query_states,
1166
+ key_states,
1167
+ value_states,
1168
+ attn_mask=attention_mask,
1169
+ dropout_p=self.attention_dropout if self.training else 0.0,
1170
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
1171
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
1172
+ )
1173
+
1174
+ attn_output = attn_output.transpose(1, 2).contiguous()
1175
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
1176
+
1177
+ attn_output = self.o_proj(attn_output)
1178
+
1179
+ return attn_output, None, past_key_value
1180
+
1181
+
1182
+ QWEN2_ATTENTION_CLASSES = {
1183
+ "eager": Qwen2Attention,
1184
+ "flash_attention_2": Qwen2FlashAttention2,
1185
+ "sdpa": Qwen2SdpaAttention,
1186
+ }
1187
+
1188
+
1189
+ class Qwen2DecoderLayer(nn.Module):
1190
+ def __init__(self, config: Qwen2TSConfig, layer_idx: int):
1191
+ super().__init__()
1192
+ self.hidden_size = config.hidden_size
1193
+
1194
+ if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
1195
+ logger.warning_once(
1196
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
1197
+ "unexpected results may be encountered."
1198
+ )
1199
+ self.self_attn = QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
1200
+
1201
+ self.mlp = Qwen2MLP(config)
1202
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1203
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1204
+
1205
+ def forward(
1206
+ self,
1207
+ hidden_states: torch.Tensor,
1208
+ attention_mask: Optional[torch.Tensor] = None,
1209
+ position_ids: Optional[torch.LongTensor] = None,
1210
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1211
+ output_attentions: Optional[bool] = False,
1212
+ use_cache: Optional[bool] = False,
1213
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
1214
+ """
1215
+ Args:
1216
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1217
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
1218
+ `(batch, sequence_length)` where padding elements are indicated by 0.
1219
+ output_attentions (`bool`, *optional*):
1220
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1221
+ returned tensors for more detail.
1222
+ use_cache (`bool`, *optional*):
1223
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1224
+ (see `past_key_values`).
1225
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1226
+ """
1227
+
1228
+ residual = hidden_states
1229
+
1230
+ hidden_states = self.input_layernorm(hidden_states)
1231
+
1232
+ # Self Attention
1233
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1234
+ hidden_states=hidden_states,
1235
+ attention_mask=attention_mask,
1236
+ position_ids=position_ids,
1237
+ past_key_value=past_key_value,
1238
+ output_attentions=output_attentions,
1239
+ use_cache=use_cache,
1240
+ )
1241
+ hidden_states = residual + hidden_states
1242
+
1243
+ # Fully Connected
1244
+ residual = hidden_states
1245
+ hidden_states = self.post_attention_layernorm(hidden_states)
1246
+ hidden_states = self.mlp(hidden_states)
1247
+ hidden_states = residual + hidden_states
1248
+
1249
+ outputs = (hidden_states,)
1250
+
1251
+ if output_attentions:
1252
+ outputs += (self_attn_weights,)
1253
+
1254
+ if use_cache:
1255
+ outputs += (present_key_value,)
1256
+
1257
+ return outputs
1258
+
1259
+
1260
+ QWEN2_START_DOCSTRING = r"""
1261
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1262
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1263
+ etc.)
1264
+
1265
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1266
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1267
+ and behavior.
1268
+
1269
+ Parameters:
1270
+ config ([`Qwen2TSConfig`]):
1271
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1272
+ load the weights associated with the model, only the configuration. Check out the
1273
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1274
+ """
1275
+
1276
+
1277
+ @add_start_docstrings(
1278
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
1279
+ QWEN2_START_DOCSTRING,
1280
+ )
1281
+ class Qwen2PreTrainedModel(PreTrainedModel):
1282
+ config_class = Qwen2TSConfig
1283
+ base_model_prefix = "model"
1284
+ supports_gradient_checkpointing = True
1285
+ _no_split_modules = ["Qwen2DecoderLayer"]
1286
+ _skip_keys_device_placement = "past_key_values"
1287
+ _supports_flash_attn_2 = True
1288
+ _supports_sdpa = True
1289
+ _supports_cache_class = True
1290
+
1291
+ def _init_weights(self, module):
1292
+ std = self.config.initializer_range
1293
+ if isinstance(module, nn.Linear):
1294
+ module.weight.data.normal_(mean=0.0, std=std)
1295
+ if module.bias is not None:
1296
+ module.bias.data.zero_()
1297
+ elif isinstance(module, nn.Embedding):
1298
+ module.weight.data.normal_(mean=0.0, std=std)
1299
+ if module.padding_idx is not None:
1300
+ module.weight.data[module.padding_idx].zero_()
1301
+
1302
+
1303
+ class TSProjector(nn.Module):
1304
+ def __init__(self, config: Qwen2TSConfig):
1305
+ super().__init__()
1306
+ self.config = config
1307
+ self.linear_1 = nn.Linear(config.ts['d_model'], config.hidden_size, bias=True)
1308
+ self.linear_2 = nn.LayerNorm(config.hidden_size, bias=True)
1309
+ self.linear_3 = nn.Linear(config.hidden_size, config.hidden_size * 4, bias=True)
1310
+ self.linear_4 = nn.LayerNorm(config.hidden_size * 4, bias=True)
1311
+ self.act = nn.GELU()
1312
+
1313
+ def forward(self, ts_features):
1314
+ hidden_states = self.linear_1(ts_features)
1315
+ hidden_states = self.linear_2(hidden_states)
1316
+ hidden_states = self.act(hidden_states)
1317
+ hidden_states = self.linear_3(hidden_states)
1318
+ hidden_states = self.linear_4(hidden_states)
1319
+ hidden_states = hidden_states.reshape(hidden_states.size(0), -1, self.config.hidden_size)
1320
+ return hidden_states
1321
+
1322
+
1323
+ QWEN2_INPUTS_DOCSTRING = r"""
1324
+ Args:
1325
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1326
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1327
+ it.
1328
+
1329
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1330
+ [`PreTrainedTokenizer.__call__`] for details.
1331
+
1332
+ [What are input IDs?](../glossary#input-ids)
1333
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1334
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1335
+
1336
+ - 1 for tokens that are **not masked**,
1337
+ - 0 for tokens that are **masked**.
1338
+
1339
+ [What are attention masks?](../glossary#attention-mask)
1340
+
1341
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1342
+ [`PreTrainedTokenizer.__call__`] for details.
1343
+
1344
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
1345
+ `past_key_values`).
1346
+
1347
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1348
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1349
+ information on the default strategy.
1350
+
1351
+ - 1 indicates the head is **not masked**,
1352
+ - 0 indicates the head is **masked**.
1353
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1354
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1355
+ config.n_positions - 1]`.
1356
+
1357
+ [What are position IDs?](../glossary#position-ids)
1358
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1359
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1360
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1361
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1362
+
1363
+ Two formats are allowed:
1364
+ - a [`~cache_utils.Cache`] instance;
1365
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1366
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1367
+ cache format.
1368
+
1369
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1370
+ legacy cache format will be returned.
1371
+
1372
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1373
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1374
+ of shape `(batch_size, sequence_length)`.
1375
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1376
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1377
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1378
+ model's internal embedding lookup matrix.
1379
+ use_cache (`bool`, *optional*):
1380
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1381
+ `past_key_values`).
1382
+ output_attentions (`bool`, *optional*):
1383
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1384
+ tensors for more detail.
1385
+ output_hidden_states (`bool`, *optional*):
1386
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1387
+ more detail.
1388
+ return_dict (`bool`, *optional*):
1389
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1390
+ """
1391
+
1392
+
1393
+ @add_start_docstrings(
1394
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
1395
+ QWEN2_START_DOCSTRING,
1396
+ )
1397
+ class Qwen2Model(Qwen2PreTrainedModel):
1398
+ """
1399
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
1400
+
1401
+ Args:
1402
+ config: Qwen2TSConfig
1403
+ """
1404
+
1405
+ def __init__(self, config: Qwen2TSConfig):
1406
+ super().__init__(config)
1407
+ self.padding_idx = config.pad_token_id
1408
+ self.vocab_size = config.vocab_size
1409
+
1410
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1411
+ self.layers = nn.ModuleList(
1412
+ [Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1413
+ )
1414
+ self._attn_implementation = config._attn_implementation
1415
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1416
+
1417
+ self.gradient_checkpointing = False
1418
+
1419
+ # Initialize weights and apply final processing
1420
+ self.post_init()
1421
+
1422
+ def get_input_embeddings(self):
1423
+ return self.embed_tokens
1424
+
1425
+ def set_input_embeddings(self, value):
1426
+ self.embed_tokens = value
1427
+
1428
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1429
+ def forward(
1430
+ self,
1431
+ input_ids: torch.LongTensor = None,
1432
+ attention_mask: Optional[torch.Tensor] = None,
1433
+ position_ids: Optional[torch.LongTensor] = None,
1434
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1435
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1436
+ use_cache: Optional[bool] = None,
1437
+ output_attentions: Optional[bool] = None,
1438
+ output_hidden_states: Optional[bool] = None,
1439
+ return_dict: Optional[bool] = None,
1440
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1441
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1442
+ output_hidden_states = (
1443
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1444
+ )
1445
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1446
+
1447
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1448
+
1449
+ # retrieve input_ids and inputs_embeds
1450
+ if input_ids is not None and inputs_embeds is not None:
1451
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
1452
+ elif input_ids is not None:
1453
+ batch_size, seq_length = input_ids.shape
1454
+ elif inputs_embeds is not None:
1455
+ batch_size, seq_length, _ = inputs_embeds.shape
1456
+ else:
1457
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
1458
+
1459
+ if self.gradient_checkpointing and self.training:
1460
+ if use_cache:
1461
+ logger.warning_once(
1462
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1463
+ )
1464
+ use_cache = False
1465
+
1466
+ past_key_values_length = 0
1467
+
1468
+ if use_cache:
1469
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1470
+ if use_legacy_cache:
1471
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1472
+ past_key_values_length = past_key_values.get_seq_length()
1473
+
1474
+ if position_ids is None:
1475
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1476
+ position_ids = torch.arange(
1477
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1478
+ )
1479
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1480
+ else:
1481
+ position_ids = position_ids.view(-1, seq_length).long()
1482
+
1483
+ if inputs_embeds is None:
1484
+ inputs_embeds = self.embed_tokens(input_ids)
1485
+
1486
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1487
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1488
+ if is_padding_right:
1489
+ raise ValueError(
1490
+ "You are attempting to perform batched generation with padding_side='right'"
1491
+ " this may lead to unexpected behaviour for Flash Attention version of Qwen2. Make sure to "
1492
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1493
+ )
1494
+
1495
+ if self._attn_implementation == "flash_attention_2":
1496
+ # 2d mask is passed through the layers
1497
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1498
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1499
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1500
+ # the manual implementation that requires a 4D causal mask in all cases.
1501
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1502
+ attention_mask,
1503
+ (batch_size, seq_length),
1504
+ inputs_embeds,
1505
+ past_key_values_length,
1506
+ sliding_window=self.config.sliding_window,
1507
+ )
1508
+ else:
1509
+ # 4d mask is passed through the layers
1510
+ attention_mask = _prepare_4d_causal_attention_mask(
1511
+ attention_mask,
1512
+ (batch_size, seq_length),
1513
+ inputs_embeds,
1514
+ past_key_values_length,
1515
+ sliding_window=self.config.sliding_window,
1516
+ )
1517
+
1518
+ hidden_states = inputs_embeds
1519
+
1520
+ # decoder layers
1521
+ all_hidden_states = () if output_hidden_states else None
1522
+ all_self_attns = () if output_attentions else None
1523
+ next_decoder_cache = None
1524
+
1525
+ for decoder_layer in self.layers:
1526
+ if output_hidden_states:
1527
+ all_hidden_states += (hidden_states,)
1528
+
1529
+ if self.gradient_checkpointing and self.training:
1530
+ layer_outputs = self._gradient_checkpointing_func(
1531
+ decoder_layer.__call__,
1532
+ hidden_states,
1533
+ attention_mask,
1534
+ position_ids,
1535
+ past_key_values,
1536
+ output_attentions,
1537
+ use_cache,
1538
+ )
1539
+ else:
1540
+ layer_outputs = decoder_layer(
1541
+ hidden_states,
1542
+ attention_mask=attention_mask,
1543
+ position_ids=position_ids,
1544
+ past_key_value=past_key_values,
1545
+ output_attentions=output_attentions,
1546
+ use_cache=use_cache,
1547
+ )
1548
+
1549
+ hidden_states = layer_outputs[0]
1550
+
1551
+ if use_cache:
1552
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1553
+
1554
+ if output_attentions:
1555
+ all_self_attns += (layer_outputs[1],)
1556
+
1557
+ hidden_states = self.norm(hidden_states)
1558
+
1559
+ # add hidden states from the last decoder layer
1560
+ if output_hidden_states:
1561
+ all_hidden_states += (hidden_states,)
1562
+
1563
+ next_cache = None
1564
+ if use_cache:
1565
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1566
+
1567
+ if not return_dict:
1568
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1569
+ return BaseModelOutputWithPast(
1570
+ last_hidden_state=hidden_states,
1571
+ past_key_values=next_cache,
1572
+ hidden_states=all_hidden_states,
1573
+ attentions=all_self_attns,
1574
+ )
1575
+
1576
+ class Qwen2TSForCausalLM(Qwen2PreTrainedModel):
1577
+ _tied_weights_keys = ["lm_head.weight"]
1578
+
1579
+ def __init__(self, config):
1580
+ super().__init__(config)
1581
+ self.config = config
1582
+
1583
+ self.model = Qwen2Model(config)
1584
+ self.vocab_size = config.vocab_size
1585
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1586
+
1587
+ # TS embedding
1588
+ self.ts_encoder = TimeSeriesEmbedding(config.ts)
1589
+ self.align = MultiModalAlignment(config)
1590
+
1591
+ # Initialize weights and apply final processing
1592
+ self.post_init()
1593
+
1594
+ def get_input_embeddings(self):
1595
+ return self.model.embed_tokens
1596
+
1597
+ def set_input_embeddings(self, value):
1598
+ self.model.embed_tokens = value
1599
+
1600
+ def get_output_embeddings(self):
1601
+ return self.lm_head
1602
+
1603
+ def set_output_embeddings(self, new_embeddings):
1604
+ self.lm_head = new_embeddings
1605
+
1606
+ def set_decoder(self, decoder):
1607
+ self.model = decoder
1608
+
1609
+ def get_decoder(self):
1610
+ return self.model
1611
+ def _merge_input_ids_with_time_series_features(
1612
+ self, time_series_features, inputs_embeds, input_ids, attention_mask, labels, patch_cnt
1613
+ ):
1614
+ batch_size, sequence_length = input_ids.shape
1615
+ # _left_padding = torch.any(attention_mask[:, 0] == 0)
1616
+ # _right_padding = torch.any(attention_mask[:, -1] == 0)
1617
+ left_padding = False
1618
+ # if batch_size > 1:
1619
+ # if _left_padding and not _right_padding:
1620
+ # left_padding = True
1621
+ # elif not _left_padding and _right_padding:
1622
+ # left_padding = False
1623
+ # elif not _left_padding and not _right_padding:
1624
+ # left_padding = False
1625
+ # else:
1626
+ # raise ValueError(f"both side of attention_mask has zero, invalid. {attention_mask}")
1627
+ # else:
1628
+ # if _left_padding and not _right_padding:
1629
+ # left_padding = True
1630
+ # else:
1631
+ # left_padding = False
1632
+
1633
+ # 1. Create a mask to know where special time series tokens are
1634
+ special_ts_token_mask_start = input_ids == self.config.ts_token_start_index
1635
+ special_ts_token_mask_end = input_ids == self.config.ts_token_end_index
1636
+ special_ts_token_mask = special_ts_token_mask_start | special_ts_token_mask_end
1637
+
1638
+ # 2. Calculate patch count
1639
+ num_special_ts_tokens = torch.sum(special_ts_token_mask_start, dim=-1)
1640
+ total_time_steps, embed_dim = time_series_features.shape
1641
+
1642
+ # Correctly calculate the total number of patches per batch
1643
+ patch_index = 0
1644
+ num_total_patches = torch.zeros(batch_size, dtype=patch_cnt.dtype, device=patch_cnt.device)
1645
+ special_ts_token_mask_start_nonzero = special_ts_token_mask_start.nonzero()
1646
+ special_ts_token_mask_start_with_size = special_ts_token_mask_start.clone().long()
1647
+
1648
+ attn_mask_cnt = attention_mask.sum(dim=-1)
1649
+ for i in range(batch_size):
1650
+ num_ts_in_batch = num_special_ts_tokens[i]
1651
+ num_total_patches[i] = patch_cnt[patch_index : patch_index + num_ts_in_batch].sum() - 2 * num_ts_in_batch
1652
+ for idx in range(patch_index, patch_index + num_ts_in_batch):
1653
+ b_idx, pos = special_ts_token_mask_start_nonzero[idx]
1654
+ special_ts_token_mask_start_with_size[b_idx, pos] *= (patch_cnt[idx].item() - 2)
1655
+ patch_index += num_ts_in_batch
1656
+ attn_mask_cnt[i] += num_total_patches[i].item()
1657
+
1658
+ # 3. Embeding length
1659
+ max_embed_dim = sequence_length + num_total_patches.max()
1660
+
1661
+ # 4. Non ts tokens
1662
+ batch_indices, non_ts_indices = torch.where(~special_ts_token_mask)
1663
+
1664
+ # 5. Text token in final text positions
1665
+ new_token_positions = torch.cumsum((special_ts_token_mask_start_with_size + 1), dim=-1) - 1
1666
+
1667
+ # nb_ts_pad
1668
+ nb_ts_pad = max_embed_dim - 1 - new_token_positions[:, -1]
1669
+ if left_padding:
1670
+ new_token_positions += nb_ts_pad[:, None]
1671
+
1672
+ text_to_overwrite = new_token_positions[batch_indices, non_ts_indices]
1673
+
1674
+ # 6. Final embedding and attention masks
1675
+ final_embedding = torch.zeros(
1676
+ batch_size, max_embed_dim, embed_dim, dtype=inputs_embeds.dtype, device=inputs_embeds.device
1677
+ )
1678
+
1679
+ final_attention_mask = torch.zeros(batch_size, max_embed_dim, dtype=attention_mask.dtype, device=inputs_embeds.device)
1680
+ for i in range(attention_mask.size(0)):
1681
+ if left_padding:
1682
+ final_attention_mask[i, max_embed_dim - attn_mask_cnt[i] :] = 1
1683
+ else:
1684
+ final_attention_mask[i, : attn_mask_cnt[i]] = 1
1685
+
1686
+ final_labels = None
1687
+ if labels is not None:
1688
+ final_labels = torch.full(
1689
+ (batch_size, max_embed_dim), self.config.ignore_index, dtype=input_ids.dtype, device=input_ids.device
1690
+ )
1691
+
1692
+ target_device = inputs_embeds.device
1693
+ batch_indices, non_ts_indices, text_to_overwrite = (
1694
+ batch_indices.to(target_device),
1695
+ non_ts_indices.to(target_device),
1696
+ text_to_overwrite.to(target_device),
1697
+ )
1698
+
1699
+ # 7. Move embedding and labels to final positions
1700
+ final_embedding[batch_indices, text_to_overwrite] = inputs_embeds[batch_indices, non_ts_indices]
1701
+ if labels is not None:
1702
+ final_labels[batch_indices, text_to_overwrite] = labels[batch_indices, non_ts_indices]
1703
+
1704
+ # 8. Move time series to final positions
1705
+ ts_to_overwrite = torch.full(
1706
+ (batch_size, max_embed_dim), True, dtype=torch.bool, device=inputs_embeds.device
1707
+ )
1708
+ ts_to_overwrite[batch_indices, text_to_overwrite] = False
1709
+
1710
+ reversed_cumsum = ts_to_overwrite.flip(dims=[-1]).cumsum(-1).flip(dims=[-1]) - 1
1711
+ ts_to_overwrite &= reversed_cumsum >= nb_ts_pad[:, None].to(target_device)
1712
+
1713
+ # Check that the number of time series tokens is correct
1714
+ if ts_to_overwrite.sum() != time_series_features.shape[:-1].numel():
1715
+ if ts_to_overwrite.sum() < time_series_features.shape[:-1].numel():
1716
+ time_series_features = time_series_features[:ts_to_overwrite.sum()]
1717
+ else:
1718
+ print(ts_to_overwrite.sum(), time_series_features.shape[:-1])
1719
+ raise ValueError(
1720
+ f"The input provided to the model are wrong. The number of time series tokens is {torch.sum(special_ts_token_mask_start)} while"
1721
+ f" the number of time series given to the model is {len(patch_cnt)}. This prevents correct indexing and breaks batch generation."
1722
+ )
1723
+ final_embedding[ts_to_overwrite] = time_series_features.contiguous().reshape(-1, embed_dim).to(target_device)
1724
+
1725
+ # 9. Calculate position ids
1726
+ position_ids = (final_attention_mask.cumsum(-1) - 1).masked_fill_((final_attention_mask == 0), 1)
1727
+ if position_ids.size(-1) < input_ids.size(-1):
1728
+ position_ids = position_ids[:, -input_ids.size(-1) :]
1729
+
1730
+ # 10. Move attention mask to final positions
1731
+ pad_batch_indices, pad_indices = torch.where(input_ids == self.config.pad_token_id)
1732
+ if len(pad_batch_indices) > 0:
1733
+ indices_to_mask = new_token_positions[pad_batch_indices, pad_indices]
1734
+ final_embedding[pad_batch_indices, indices_to_mask] = 0
1735
+
1736
+ return final_embedding, final_attention_mask, position_ids, final_labels
1737
+
1738
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1739
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1740
+ def forward(
1741
+ self,
1742
+ input_ids: torch.LongTensor = None,
1743
+ timeseries: torch.FloatTensor = None,
1744
+ attention_mask: Optional[torch.Tensor] = None,
1745
+ position_ids: Optional[torch.LongTensor] = None,
1746
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1747
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1748
+ labels: Optional[torch.LongTensor] = None,
1749
+ use_cache: Optional[bool] = None,
1750
+ output_attentions: Optional[bool] = None,
1751
+ output_hidden_states: Optional[bool] = None,
1752
+ logits_to_keep: int = 0,
1753
+ return_dict: Optional[bool] = None,
1754
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1755
+ r"""
1756
+ Args:
1757
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1758
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1759
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1760
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1761
+
1762
+ Returns:
1763
+
1764
+ Example:
1765
+
1766
+ ```python
1767
+ >>> from transformers import AutoTokenizer, Qwen2ForCausalLM
1768
+
1769
+ >>> model = Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1770
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1771
+
1772
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1773
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1774
+
1775
+ >>> # Generate
1776
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1777
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1778
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1779
+ ```"""
1780
+
1781
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1782
+ output_hidden_states = (
1783
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1784
+ )
1785
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1786
+
1787
+ if inputs_embeds is None:
1788
+ inputs_embeds = self.get_input_embeddings()(input_ids)
1789
+
1790
+ if timeseries is not None and timeseries.shape[0] > 0:
1791
+ # use_cache = False
1792
+ ts_features, patch_cnt = self.ts_encoder(timeseries)
1793
+ inputs_embeds = inputs_embeds.to(ts_features.dtype)
1794
+ align_ts_features, align_patch_cnt = self.align(input_ids, inputs_embeds, ts_features, patch_cnt)
1795
+ # align_ts_features, _ = self.align(ts_features.unsqueeze(0), ts_features.unsqueeze(0), ts_features.unsqueeze(0))
1796
+ # align_patch_cnt = patch_cnt
1797
+ align_ts_features = align_ts_features.reshape(-1, align_ts_features.shape[-1])
1798
+ inputs_embeds, attention_mask, position_ids, labels = self._merge_input_ids_with_time_series_features(
1799
+ align_ts_features, inputs_embeds, input_ids, attention_mask, labels, align_patch_cnt
1800
+ )
1801
+
1802
+ outputs = self.model(
1803
+ attention_mask=attention_mask,
1804
+ position_ids=position_ids,
1805
+ past_key_values=past_key_values,
1806
+ inputs_embeds=inputs_embeds,
1807
+ use_cache=use_cache,
1808
+ output_attentions=output_attentions,
1809
+ output_hidden_states=output_hidden_states,
1810
+ return_dict=return_dict,
1811
+ )
1812
+
1813
+ hidden_states = outputs[0]
1814
+ logits = self.lm_head(hidden_states[:, -logits_to_keep:, :])
1815
+ logits = logits.float()
1816
+
1817
+ loss = None
1818
+ if labels is not None:
1819
+ # Shift so that tokens < n predict n
1820
+ shift_logits = logits[..., :-1, :].contiguous()
1821
+ shift_labels = labels[..., 1:].contiguous()
1822
+ # Flatten the tokens
1823
+ loss_fct = CrossEntropyLoss()
1824
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1825
+ shift_labels = shift_labels.view(-1)
1826
+ # Enable model parallelism
1827
+ shift_labels = shift_labels.to(shift_logits.device)
1828
+ loss = loss_fct(shift_logits, shift_labels)
1829
+
1830
+ if not return_dict:
1831
+ output = (logits,) + outputs[1:]
1832
+ return (loss,) + output if loss is not None else output
1833
+ return Qwen2TSCausalLMOutputWithPast(
1834
+ loss=loss,
1835
+ logits=logits,
1836
+ labels=labels,
1837
+ past_key_values=outputs.past_key_values,
1838
+ hidden_states=outputs.hidden_states,
1839
+ attentions=outputs.attentions,
1840
+ attention_mask=attention_mask
1841
+ )
1842
+
1843
+ def _extract_past_from_model_output(self, outputs: ModelOutput):
1844
+ return "past_key_values", outputs.past_key_values
1845
+
1846
+ def _update_model_kwargs_for_generation(
1847
+ self,
1848
+ outputs: ModelOutput,
1849
+ model_kwargs: Dict[str, Any],
1850
+ is_encoder_decoder: bool = False,
1851
+ num_new_tokens: int = 1,
1852
+ ) -> Dict[str, Any]:
1853
+ # update past_key_values keeping its naming used in model code
1854
+ cache_name, cache = self._extract_past_from_model_output(outputs)
1855
+ model_kwargs[cache_name] = cache
1856
+ if getattr(outputs, "state", None) is not None:
1857
+ model_kwargs["state"] = outputs.state
1858
+
1859
+ # update attention_mask
1860
+ if getattr(outputs, "attention_mask", None) is not None:
1861
+ model_kwargs["attention_mask"] = outputs.attention_mask
1862
+
1863
+ # update token_type_ids with last value
1864
+ if "token_type_ids" in model_kwargs:
1865
+ token_type_ids = model_kwargs["token_type_ids"]
1866
+ model_kwargs["token_type_ids"] = torch.cat([token_type_ids, token_type_ids[:, -1].unsqueeze(-1)], dim=-1)
1867
+
1868
+ if not is_encoder_decoder:
1869
+ # update attention mask
1870
+ if "attention_mask" in model_kwargs:
1871
+ attention_mask = model_kwargs["attention_mask"]
1872
+ model_kwargs["attention_mask"] = torch.cat(
1873
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
1874
+ )
1875
+ else:
1876
+ # update decoder attention mask
1877
+ if "decoder_attention_mask" in model_kwargs:
1878
+ decoder_attention_mask = model_kwargs["decoder_attention_mask"]
1879
+ model_kwargs["decoder_attention_mask"] = torch.cat(
1880
+ [decoder_attention_mask, decoder_attention_mask.new_ones((decoder_attention_mask.shape[0], 1))],
1881
+ dim=-1,
1882
+ )
1883
+
1884
+ if model_kwargs.get("use_cache", True):
1885
+ if "cache_position" not in model_kwargs or model_kwargs["cache_position"] is None:
1886
+ # transformers >= 5.x no longer auto-injects cache_position into
1887
+ # model_kwargs on every step; reconstruct from attention_mask.
1888
+ attn = model_kwargs.get("attention_mask")
1889
+ if attn is not None:
1890
+ seq_len = attn.shape[1]
1891
+ else:
1892
+ seq_len = num_new_tokens
1893
+ model_kwargs["cache_position"] = torch.arange(
1894
+ seq_len - num_new_tokens, seq_len, dtype=torch.long, device=attn.device if attn is not None else "cpu"
1895
+ )
1896
+ else:
1897
+ model_kwargs["cache_position"] = model_kwargs["cache_position"][-1:] + num_new_tokens
1898
+ else:
1899
+ past_positions = model_kwargs.pop("cache_position", None)
1900
+ if past_positions is None:
1901
+ attn = model_kwargs.get("attention_mask")
1902
+ seq_len = attn.shape[1] if attn is not None else num_new_tokens
1903
+ past_positions = torch.arange(
1904
+ 0, seq_len - num_new_tokens, dtype=torch.long,
1905
+ device=attn.device if attn is not None else "cpu",
1906
+ )
1907
+ new_positions = torch.arange(
1908
+ past_positions[-1] + 1, past_positions[-1] + num_new_tokens + 1, dtype=past_positions.dtype
1909
+ ).to(past_positions.device)
1910
+ model_kwargs["cache_position"] = torch.cat((past_positions, new_positions))
1911
+ return model_kwargs
1912
+
1913
+ def prepare_inputs_for_generation(
1914
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, timeseries=None, **kwargs
1915
+ ):
1916
+ # Omit tokens covered by past_key_values
1917
+ if past_key_values is not None:
1918
+ if isinstance(past_key_values, Cache):
1919
+ cache_length = past_key_values.get_seq_length()
1920
+ past_length = past_key_values.get_seq_length()
1921
+ # past_length = past_key_values.get_seq_length()
1922
+ max_cache_length = (
1923
+ past_key_values.get_max_length()
1924
+ if hasattr(past_key_values, "get_max_length")
1925
+ else past_key_values.get_max_cache_shape()
1926
+ )
1927
+ else:
1928
+ cache_length = past_length = past_key_values[0][0].shape[2]
1929
+ max_cache_length = None
1930
+
1931
+ has_ts = timeseries is not None and len(timeseries) > 0
1932
+
1933
+ if has_ts and kwargs.get("attention_mask") is not None:
1934
+ attention_mask = kwargs["attention_mask"]
1935
+ attention_mask = torch.cat(
1936
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
1937
+ )
1938
+
1939
+ # Set attention mask and input_ids
1940
+ if has_ts and past_length > 0:
1941
+ # We have only one token added and timeseries are already inferenced
1942
+ input_ids = input_ids[:, -1:]
1943
+ timeseries = None
1944
+ elif attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1945
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1946
+ elif past_length < input_ids.shape[1]:
1947
+ input_ids = input_ids[:, past_length:]
1948
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1949
+
1950
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1951
+ if (
1952
+ max_cache_length is not None
1953
+ and attention_mask is not None
1954
+ and cache_length + input_ids.size(1) > max_cache_length
1955
+ ):
1956
+ attention_mask = attention_mask[:, -max_cache_length:]
1957
+
1958
+ position_ids = kwargs.get("position_ids", None)
1959
+ if attention_mask is not None and position_ids is None:
1960
+ # create position_ids on the fly for batch generation
1961
+ position_ids = attention_mask.long().cumsum(-1) - 1
1962
+ position_ids.masked_fill_(attention_mask == 0, 1)
1963
+ if past_key_values:
1964
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1965
+
1966
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1967
+ if inputs_embeds is not None and past_key_values is None:
1968
+ model_inputs = {"inputs_embeds": inputs_embeds}
1969
+ else:
1970
+ model_inputs = {"input_ids": input_ids}
1971
+
1972
+ model_inputs.update(
1973
+ {
1974
+ "position_ids": position_ids,
1975
+ "past_key_values": past_key_values,
1976
+ "use_cache": kwargs.get("use_cache"),
1977
+ "attention_mask": attention_mask,
1978
+ "timeseries": timeseries
1979
+ }
1980
+ )
1981
+ return model_inputs
1982
+
1983
+ @staticmethod
1984
+ def _reorder_cache(past_key_values, beam_idx):
1985
+ reordered_past = ()
1986
+ for layer_past in past_key_values:
1987
+ reordered_past += (
1988
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1989
+ )
1990
+ return reordered_past
1991
+
1992
+
1993
+ @add_start_docstrings(
1994
+ """
1995
+ The Qwen2 Model transformer with a sequence classification head on top (linear layer).
1996
+
1997
+ [`Qwen2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1998
+ (e.g. GPT-2) do.
1999
+
2000
+ Since it does classification on the last token, it requires to know the position of the last token. If a
2001
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
2002
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
2003
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
2004
+ each row of the batch).
2005
+ """,
2006
+ QWEN2_START_DOCSTRING,
2007
+ )
2008
+ class Qwen2ForSequenceClassification(Qwen2PreTrainedModel):
2009
+ def __init__(self, config):
2010
+ super().__init__(config)
2011
+ self.num_labels = config.num_labels
2012
+ self.model = Qwen2Model(config)
2013
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
2014
+
2015
+ # Initialize weights and apply final processing
2016
+ self.post_init()
2017
+
2018
+ def get_input_embeddings(self):
2019
+ return self.model.embed_tokens
2020
+
2021
+ def set_input_embeddings(self, value):
2022
+ self.model.embed_tokens = value
2023
+
2024
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
2025
+ def forward(
2026
+ self,
2027
+ input_ids: torch.LongTensor = None,
2028
+ attention_mask: Optional[torch.Tensor] = None,
2029
+ position_ids: Optional[torch.LongTensor] = None,
2030
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
2031
+ inputs_embeds: Optional[torch.FloatTensor] = None,
2032
+ labels: Optional[torch.LongTensor] = None,
2033
+ use_cache: Optional[bool] = None,
2034
+ output_attentions: Optional[bool] = None,
2035
+ output_hidden_states: Optional[bool] = None,
2036
+ return_dict: Optional[bool] = None,
2037
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
2038
+ r"""
2039
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
2040
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
2041
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
2042
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
2043
+ """
2044
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
2045
+
2046
+ transformer_outputs = self.model(
2047
+ input_ids,
2048
+ attention_mask=attention_mask,
2049
+ position_ids=position_ids,
2050
+ past_key_values=past_key_values,
2051
+ inputs_embeds=inputs_embeds,
2052
+ use_cache=use_cache,
2053
+ output_attentions=output_attentions,
2054
+ output_hidden_states=output_hidden_states,
2055
+ return_dict=return_dict,
2056
+ )
2057
+ hidden_states = transformer_outputs[0]
2058
+ logits = self.score(hidden_states)
2059
+
2060
+ if input_ids is not None:
2061
+ batch_size = input_ids.shape[0]
2062
+ else:
2063
+ batch_size = inputs_embeds.shape[0]
2064
+
2065
+ if self.config.pad_token_id is None and batch_size != 1:
2066
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
2067
+ if self.config.pad_token_id is None:
2068
+ sequence_lengths = -1
2069
+ else:
2070
+ if input_ids is not None:
2071
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
2072
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
2073
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
2074
+ sequence_lengths = sequence_lengths.to(logits.device)
2075
+ else:
2076
+ sequence_lengths = -1
2077
+
2078
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
2079
+
2080
+ loss = None
2081
+ if labels is not None:
2082
+ labels = labels.to(logits.device)
2083
+ if self.config.problem_type is None:
2084
+ if self.num_labels == 1:
2085
+ self.config.problem_type = "regression"
2086
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
2087
+ self.config.problem_type = "single_label_classification"
2088
+ else:
2089
+ self.config.problem_type = "multi_label_classification"
2090
+
2091
+ if self.config.problem_type == "regression":
2092
+ loss_fct = MSELoss()
2093
+ if self.num_labels == 1:
2094
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
2095
+ else:
2096
+ loss = loss_fct(pooled_logits, labels)
2097
+ elif self.config.problem_type == "single_label_classification":
2098
+ loss_fct = CrossEntropyLoss()
2099
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
2100
+ elif self.config.problem_type == "multi_label_classification":
2101
+ loss_fct = BCEWithLogitsLoss()
2102
+ loss = loss_fct(pooled_logits, labels)
2103
+ if not return_dict:
2104
+ output = (pooled_logits,) + transformer_outputs[1:]
2105
+ return ((loss,) + output) if loss is not None else output
2106
+
2107
+ return SequenceClassifierOutputWithPast(
2108
+ loss=loss,
2109
+ logits=pooled_logits,
2110
+ past_key_values=transformer_outputs.past_key_values,
2111
+ hidden_states=transformer_outputs.hidden_states,
2112
+ attentions=transformer_outputs.attentions,
2113
+ )
processing_qwen2_ts.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Tsinghua University and ByteDance.
3
+ #
4
+ # Licensed under the MIT License (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # https://opensource.org/license/mit
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import numpy as np
17
+ from typing import List, Union, Tuple, Optional
18
+ import torch
19
+
20
+ from transformers.feature_extraction_utils import BatchFeature
21
+ from transformers.processing_utils import ProcessorMixin
22
+ from transformers.tokenization_utils_base import PaddingStrategy
23
+
24
+ def sp_encoding(timeseries: np.ndarray, eots_token: bool = True) -> Tuple[np.ndarray, str, dict]:
25
+ """
26
+ Encodes a time series with scalar normalization.
27
+
28
+ Args:
29
+ timeseries (np.ndarray): The raw time series data (1D or 2D).
30
+
31
+ Returns:
32
+ result_timeseries (np.ndarray): The encoded time series, shape [seq_len, 1].
33
+ prompt (str): The placeholder string with offset and scaling info.
34
+ metadata (dict): Metadata containing the offset and scaling factor.
35
+ """
36
+ mean = np.mean(timeseries)
37
+ scaled_timeseries = timeseries - mean
38
+ scale_factor = 1.0
39
+ if np.any(np.abs(scaled_timeseries) >= 3.0):
40
+ scale_factor = np.max(np.abs(scaled_timeseries)) / 3.0
41
+ scaled_timeseries /= scale_factor
42
+
43
+ # prompt = f"[Value Offset: {-mean:.4f}|Value Scaling: {scale_factor:.4f}]<ts>"
44
+ prompt = '<ts>'
45
+ if eots_token:
46
+ prompt += '<ts/>'
47
+
48
+ result_timeseries = np.stack([scaled_timeseries, np.ones_like(scaled_timeseries)], axis=-1).reshape(-1, 1)
49
+
50
+ return result_timeseries, prompt, {"offset": float(-mean), "scale_factor": float(scale_factor)}
51
+
52
+ class Qwen2TSProcessor(ProcessorMixin):
53
+ """
54
+ A processor for PATRA that integrates text prompt processing and time series encoding.
55
+ """
56
+
57
+ attributes = ["tokenizer"]
58
+ feature_extractor_class = None # You can add a feature extractor if needed
59
+ tokenizer_class = "AutoTokenizer"
60
+
61
+ def __init__(self, tokenizer=None, **kwargs):
62
+ """
63
+ Args:
64
+ tokenizer: An optional tokenizer to process text prompts.
65
+ **kwargs: swallowed for forward-compat (e.g. transformers 4.52+
66
+ passes `chat_template=` when loading via AutoProcessor).
67
+ """
68
+ super().__init__(tokenizer=tokenizer)
69
+
70
+ def __call__(
71
+ self,
72
+ text: Union[str, List[str]],
73
+ timeseries: Optional[List[List[np.ndarray]]] = None,
74
+ padding: Union[bool, str, PaddingStrategy] = False,
75
+ padding_side: str = 'left',
76
+ vllm_flag: bool = False,
77
+ **kwargs,
78
+ ) -> BatchFeature:
79
+ """
80
+ Encodes a prompt and its associated time series.
81
+
82
+ Args:
83
+ prompt (List[str]): The input prompt containing <ts><ts/> placeholders.
84
+ timeseries (List[np.ndarray]): A list of time series matched to placeholders in the prompt.
85
+ padding (bool or str or PaddingStrategy, optional): Passed to the tokenizer for text padding.
86
+ return_tensors (str, optional): "pt" to return PyTorch tensors; None to return NumPy arrays.
87
+ **kwargs: Additional tokenizer parameters.
88
+
89
+ Returns:
90
+ BatchFeature: Contains processed prompt, encoded time series, and tokenizer outputs.
91
+ """
92
+ if type(text) == str:
93
+ text = [text]
94
+ if timeseries is None:
95
+ timeseries = []
96
+
97
+ reconstructed_prompts = []
98
+ concatenated_ts = None
99
+ ts_tokens = []
100
+
101
+ if vllm_flag:
102
+ # All prompt modifications have to be done inside of the vLLM
103
+ # to work correctly with its caching mechanism.
104
+ reconstructed_prompts = text
105
+
106
+ # Process timeseries data
107
+ encoded_ts_arrays = []
108
+ for ts in timeseries:
109
+ # Get the normalized data and prompt text
110
+ encoded_ts, ts_prompt, _ = sp_encoding(ts, eots_token=False)
111
+ # Tokenize the ts_prompt and add to the tokens list
112
+ if self.tokenizer is not None:
113
+ tokens = self.tokenizer.encode(ts_prompt, add_special_tokens=False)
114
+ ts_tokens.append(tokens)
115
+ encoded_ts_arrays.append(encoded_ts[None, ...])
116
+ else:
117
+ encoded_ts_arrays = []
118
+ total_ts_cnt = 0
119
+ for idx, prompt in enumerate(text):
120
+ # Split prompt by <ts><ts/> placeholders
121
+ last_ts_cnt = total_ts_cnt
122
+ prompt_segments = prompt.split("<ts><ts/>")
123
+ total_ts_cnt = total_ts_cnt + len(prompt_segments) - 1
124
+
125
+ # Encode each time series and rebuild the prompt
126
+ reconstructed_prompt = prompt_segments[0]
127
+
128
+ for i, ts in enumerate(timeseries[last_ts_cnt:total_ts_cnt]):
129
+ encoded_ts, ts_prompt, _ = sp_encoding(ts, eots_token=not vllm_flag)
130
+ reconstructed_prompt += ts_prompt + prompt_segments[i + 1]
131
+ # Ensure time series shape [1, seq_len, feature_dim] for batch concatenation
132
+ encoded_ts_arrays.append(encoded_ts[None, ...])
133
+
134
+ reconstructed_prompts.append(reconstructed_prompt)
135
+
136
+ if len(timeseries) != len(encoded_ts_arrays):
137
+ raise ValueError(
138
+ f"Mismatch between <ts><ts/> placeholders ({total_ts_cnt}) "
139
+ f"and time series ({len(encoded_ts_arrays)})."
140
+ )
141
+
142
+ if len(encoded_ts_arrays) > 0:
143
+ # Pad time series to the same length
144
+ max_length = max(ts.shape[1] for ts in encoded_ts_arrays)
145
+ padded_ts_arrays = [
146
+ np.pad(ts, ((0, 0), (0, max_length - ts.shape[1]), (0, 0)), mode="constant", constant_values=0.0)
147
+ for ts in encoded_ts_arrays
148
+ ]
149
+ concatenated_ts = np.concatenate(padded_ts_arrays, axis=0) # Shape: [batch_size, max_length, feature_dim]
150
+
151
+ # Convert to torch
152
+ concatenated_ts = torch.from_numpy(concatenated_ts).half()
153
+
154
+ # Tokenize the processed prompt
155
+ tokenizer_outputs = {}
156
+ if self.tokenizer is not None:
157
+ tokenizer_outputs = self.tokenizer(reconstructed_prompts, padding=padding, padding_side=padding_side, **kwargs)
158
+
159
+ # Create the final output
160
+ outputs = tokenizer_outputs
161
+ if vllm_flag:
162
+ outputs["timeseries"] = zip(ts_tokens, encoded_ts_arrays)
163
+ elif concatenated_ts is not None:
164
+ outputs["timeseries"] = concatenated_ts
165
+
166
+ return BatchFeature(data=outputs)
167
+
168
+ @property
169
+ def model_input_names(self):
170
+ """
171
+ Define the input names expected by the model.
172
+ """
173
+ tokenizer_input_names = []
174
+ if self.tokenizer and hasattr(self.tokenizer, "model_input_names"):
175
+ tokenizer_input_names = self.tokenizer.model_input_names
176
+ return list(dict.fromkeys(["processed_prompt", "time_series"] + tokenizer_input_names))
177
+
178
+ def batch_decode(self, *args, **kwargs):
179
+ """
180
+ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
181
+ refer to the docstring of this method for more information.
182
+ """
183
+ return self.tokenizer.batch_decode(*args, **kwargs)
184
+
185
+ def decode(self, *args, **kwargs):
186
+ """
187
+ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
188
+ the docstring of this method for more information.
189
+ """
190
+ return self.tokenizer.decode(*args, **kwargs)
processor_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoProcessor": "processing_qwen2_ts.Qwen2TSProcessor"
4
+ },
5
+ "processor_class": "Qwen2TSProcessor"
6
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<ts>",
4
+ "<ts/>",
5
+ "<|im_end|>"
6
+ ],
7
+ "eos_token": {
8
+ "content": "<|im_end|>",
9
+ "lstrip": false,
10
+ "normalized": false,
11
+ "rstrip": false,
12
+ "single_word": false
13
+ },
14
+ "pad_token": {
15
+ "content": "<|endoftext|>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false
20
+ }
21
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:309a7f94e51f1104e6687b31284915a0349755302b483d851f466650dc2ebc67
3
+ size 11422259
tokenizer_config.json ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ },
181
+ "151665": {
182
+ "content": "<ts>",
183
+ "lstrip": false,
184
+ "normalized": false,
185
+ "rstrip": false,
186
+ "single_word": false,
187
+ "special": true
188
+ },
189
+ "151666": {
190
+ "content": "<ts/>",
191
+ "lstrip": false,
192
+ "normalized": false,
193
+ "rstrip": false,
194
+ "single_word": false,
195
+ "special": true
196
+ }
197
+ },
198
+ "additional_special_tokens": [
199
+ "<ts>",
200
+ "<ts/>",
201
+ "<|im_end|>"
202
+ ],
203
+ "auto_map": {
204
+ "AutoProcessor": "processing_qwen2_ts.Qwen2TSProcessor"
205
+ },
206
+ "bos_token": null,
207
+ "clean_up_tokenization_spaces": false,
208
+ "eos_token": "<|im_end|>",
209
+ "errors": "replace",
210
+ "extra_special_tokens": {},
211
+ "model_max_length": 131072,
212
+ "pad_token": "<|endoftext|>",
213
+ "padding_side": "left",
214
+ "processor_class": "Qwen2TSProcessor",
215
+ "split_special_tokens": false,
216
+ "tokenizer_class": "Qwen2Tokenizer",
217
+ "unk_token": null,
218
+ "chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0]['role'] == 'system' %}\n {{- messages[0]['content'] }}\n {%- else %}\n {{- 'You are Qwen, created by Alibaba Cloud. You are a helpful assistant.' }}\n {%- endif %}\n {{- \"\\n\\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 {%- else %}\n {{- '<|im_start|>system\\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- for message in messages %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) or (message.role == \"assistant\" and not message.tool_calls) %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {{- '<|im_start|>' + message.role }}\n {%- if message.content %}\n {{- '\\n' + message.content }}\n {%- endif %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '\\n<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {{- tool_call.arguments | tojson }}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if (loop.index0 == 0) 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{%- endif %}\n"
219
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff