xiezhe24 commited on
Commit
76f51da
·
verified ·
1 Parent(s): 6d73c5d

Upload 16 files

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
+ }
config.json ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen2TSForCausalLM"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_qwen2.Qwen2TSConfig",
8
+ "AutoModel": "modeling_qwen2.Qwen2TSForCausalLM",
9
+ "AutoModelForCausalLM": "modeling_qwen2.Qwen2TSForCausalLM",
10
+ "AutoProcessor": "processing_qwen2_ts.Qwen2TSProcessor"
11
+ },
12
+ "bos_token_id": 151643,
13
+ "eos_token_id": 151645,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 5120,
16
+ "ignore_index": -100,
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 13824,
19
+ "max_position_embeddings": 32768,
20
+ "max_window_layers": 70,
21
+ "model_type": "qwen2",
22
+ "num_attention_heads": 40,
23
+ "num_hidden_layers": 48,
24
+ "num_key_value_heads": 8,
25
+ "pad_token_id": 151643,
26
+ "quantization_config": {
27
+ "config_groups": {
28
+ "group_0": {
29
+ "input_activations": null,
30
+ "output_activations": null,
31
+ "targets": [
32
+ "Linear"
33
+ ],
34
+ "weights": {
35
+ "actorder": null,
36
+ "block_structure": null,
37
+ "dynamic": false,
38
+ "group_size": 128,
39
+ "num_bits": 4,
40
+ "observer": "minmax",
41
+ "observer_kwargs": {},
42
+ "strategy": "group",
43
+ "symmetric": true,
44
+ "type": "int"
45
+ }
46
+ }
47
+ },
48
+ "format": "pack-quantized",
49
+ "global_compression_ratio": null,
50
+ "ignore": [
51
+ "lm_head",
52
+ "ts_encoder.mlp.0",
53
+ "ts_encoder.mlp.2",
54
+ "ts_encoder.mlp.4",
55
+ "ts_encoder.mlp.6",
56
+ "ts_encoder.mlp.8"
57
+ ],
58
+ "kv_cache_scheme": null,
59
+ "quant_method": "compressed-tensors",
60
+ "quantization_status": "compressed"
61
+ },
62
+ "rms_norm_eps": 1e-06,
63
+ "rope_theta": 1000000.0,
64
+ "sliding_window": 131072,
65
+ "tie_word_embeddings": false,
66
+ "torch_dtype": "float16",
67
+ "transformers_version": "4.52.4",
68
+ "ts": {
69
+ "hidden_size": 5120,
70
+ "max_length": 2048,
71
+ "num_features": 2,
72
+ "num_layers": 5,
73
+ "patch_size": 16
74
+ },
75
+ "ts_token_end_index": 151666,
76
+ "ts_token_start_index": 151665,
77
+ "use_cache": false,
78
+ "use_sliding_window": false,
79
+ "vocab_size": 152064
80
+ }
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 = "qwen2"
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.0,
11
+ "top_k": 1,
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-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:90d6867d28372adb063c7786ea407367c6237468f73e15e6fb30e34ce5e75f54
3
+ size 4996734536
model-00002-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2b45261f1039a8ac6e2824e933ca829b3f95efd5dbcb13f13d71e32a7b00b6e0
3
+ size 4984445528
model-00003-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:012d40889a942c5bf7701222d064de53dc3d06d0a30eecbbc164972102f2e4c1
3
+ size 157317720
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_qwen2.py ADDED
@@ -0,0 +1,1703 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ past_key_values: Optional[List[torch.FloatTensor]] = None
105
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
106
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
107
+ attention_mask: Optional[torch.FloatTensor] = None
108
+
109
+ ########################Naive TS Embedding#####################
110
+ class TimeSeriesEmbedding(nn.Module):
111
+ def __init__(self, config):
112
+ super(TimeSeriesEmbedding, self).__init__()
113
+ self.patch_size = config['patch_size']
114
+ self.num_layers = config['num_layers']
115
+ self.hidden_size = config['hidden_size']
116
+ self.num_features = config['num_features']
117
+
118
+ layers = []
119
+ input_size = 1 * self.patch_size
120
+
121
+ for _ in range(self.num_layers - 1):
122
+ layers.append(nn.Linear(input_size, self.hidden_size))
123
+ layers.append(nn.GELU())
124
+ input_size = self.hidden_size
125
+ layers.append(nn.Linear(input_size, self.hidden_size))
126
+
127
+ self.mlp = nn.Sequential(*layers)
128
+
129
+ def forward(self, x: torch.Tensor):
130
+ batch_size = x.size(0)
131
+ x = x.reshape(batch_size, -1, self.num_features)
132
+
133
+ mask = x[:, :, -1].long()
134
+ valid_lengths = mask.sum(dim=1).long() # Shape: (batch_size)
135
+
136
+ patch_cnt = (valid_lengths + self.patch_size - 1) // self.patch_size # 向上取整
137
+
138
+ patches_list = []
139
+ for i in range(batch_size):
140
+ vl = valid_lengths[i].item()
141
+ pc = patch_cnt[i].item()
142
+ if pc == 0:
143
+ continue
144
+ xi = x[i, :vl, :1]
145
+ total_padded_length = pc * self.patch_size
146
+ padding_length = total_padded_length - vl
147
+ if padding_length > 0:
148
+ padding = torch.zeros(padding_length, 1, device=x.device, dtype=x.dtype)
149
+ xi = torch.cat([xi, padding], dim=0)
150
+ xi = xi.reshape(pc, self.patch_size * 1)
151
+ patches_list.append(xi)
152
+
153
+ if patches_list:
154
+ x_patches = torch.cat(patches_list, dim=0) # Shape: (total_patch_cnt, patch_size * num_features)
155
+ x = self.mlp(x_patches)
156
+ else:
157
+ x = torch.empty(0, self.hidden_size, device=x.device)
158
+
159
+ return x, patch_cnt
160
+
161
+
162
+ ########################QWEN2###################################
163
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
164
+ def _get_unpad_data(attention_mask):
165
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
166
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
167
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
168
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
169
+ return (
170
+ indices,
171
+ cu_seqlens,
172
+ max_seqlen_in_batch,
173
+ )
174
+
175
+
176
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Qwen2
177
+ class Qwen2RMSNorm(nn.Module):
178
+ def __init__(self, hidden_size, eps=1e-6):
179
+ """
180
+ Qwen2RMSNorm is equivalent to T5LayerNorm
181
+ """
182
+ super().__init__()
183
+ self.weight = nn.Parameter(torch.ones(hidden_size))
184
+ self.variance_epsilon = eps
185
+
186
+ def forward(self, hidden_states):
187
+ input_dtype = hidden_states.dtype
188
+ hidden_states = hidden_states.to(torch.float32)
189
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
190
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
191
+ return self.weight * hidden_states.to(input_dtype)
192
+
193
+
194
+ # Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->Qwen2
195
+ class Qwen2RotaryEmbedding(nn.Module):
196
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
197
+ super().__init__()
198
+
199
+ self.dim = dim
200
+ self.max_position_embeddings = max_position_embeddings
201
+ self.base = base
202
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
203
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
204
+
205
+ # Build here to make `torch.jit.trace` work.
206
+ self._set_cos_sin_cache(
207
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
208
+ )
209
+
210
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
211
+ self.max_seq_len_cached = seq_len
212
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
213
+
214
+ freqs = torch.outer(t, self.inv_freq)
215
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
216
+ emb = torch.cat((freqs, freqs), dim=-1)
217
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
218
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
219
+
220
+ def forward(self, x, seq_len=None):
221
+ # x: [bs, num_attention_heads, seq_len, head_size]
222
+ if seq_len > self.max_seq_len_cached:
223
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
224
+
225
+ return (
226
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
227
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
228
+ )
229
+
230
+
231
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
232
+ def rotate_half(x):
233
+ """Rotates half the hidden dims of the input."""
234
+ x1 = x[..., : x.shape[-1] // 2]
235
+ x2 = x[..., x.shape[-1] // 2 :]
236
+ return torch.cat((-x2, x1), dim=-1)
237
+
238
+
239
+ # Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
240
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
241
+ """Applies Rotary Position Embedding to the query and key tensors.
242
+
243
+ Args:
244
+ q (`torch.Tensor`): The query tensor.
245
+ k (`torch.Tensor`): The key tensor.
246
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
247
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
248
+ position_ids (`torch.Tensor`):
249
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
250
+ used to pass offsetted position ids when working with a KV-cache.
251
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
252
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
253
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
254
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
255
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
256
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
257
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
258
+ Returns:
259
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
260
+ """
261
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
262
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
263
+ q_embed = (q * cos) + (rotate_half(q) * sin)
264
+ k_embed = (k * cos) + (rotate_half(k) * sin)
265
+ return q_embed, k_embed
266
+
267
+
268
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Qwen2
269
+ class Qwen2MLP(nn.Module):
270
+ def __init__(self, config):
271
+ super().__init__()
272
+ self.config = config
273
+ self.hidden_size = config.hidden_size
274
+ self.intermediate_size = config.intermediate_size
275
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
276
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
277
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
278
+ self.act_fn = ACT2FN[config.hidden_act]
279
+
280
+ def forward(self, x):
281
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
282
+
283
+
284
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
285
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
286
+ """
287
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
288
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
289
+ """
290
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
291
+ if n_rep == 1:
292
+ return hidden_states
293
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
294
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
295
+
296
+
297
+ class Qwen2Attention(nn.Module):
298
+ """
299
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
300
+ and "Generating Long Sequences with Sparse Transformers".
301
+ """
302
+
303
+ def __init__(self, config: Qwen2TSConfig, layer_idx: Optional[int] = None):
304
+ super().__init__()
305
+ self.config = config
306
+ self.layer_idx = layer_idx
307
+ if layer_idx is None:
308
+ logger.warning_once(
309
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
310
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
311
+ "when creating this class."
312
+ )
313
+
314
+ self.hidden_size = config.hidden_size
315
+ self.num_heads = config.num_attention_heads
316
+ self.head_dim = self.hidden_size // self.num_heads
317
+ self.num_key_value_heads = config.num_key_value_heads
318
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
319
+ self.max_position_embeddings = config.max_position_embeddings
320
+ self.rope_theta = config.rope_theta
321
+ self.is_causal = True
322
+ self.attention_dropout = config.attention_dropout
323
+
324
+ if (self.head_dim * self.num_heads) != self.hidden_size:
325
+ raise ValueError(
326
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
327
+ f" and `num_heads`: {self.num_heads})."
328
+ )
329
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
330
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
331
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
332
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
333
+
334
+ self.rotary_emb = Qwen2RotaryEmbedding(
335
+ self.head_dim,
336
+ max_position_embeddings=self.max_position_embeddings,
337
+ base=self.rope_theta,
338
+ )
339
+
340
+ def forward(
341
+ self,
342
+ hidden_states: torch.Tensor,
343
+ attention_mask: Optional[torch.Tensor] = None,
344
+ position_ids: Optional[torch.LongTensor] = None,
345
+ past_key_value: Optional[Cache] = None,
346
+ output_attentions: bool = False,
347
+ use_cache: bool = False,
348
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
349
+ bsz, q_len, _ = hidden_states.size()
350
+
351
+ query_states = self.q_proj(hidden_states)
352
+ key_states = self.k_proj(hidden_states)
353
+ value_states = self.v_proj(hidden_states)
354
+
355
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
356
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
357
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
358
+
359
+ kv_seq_len = key_states.shape[-2]
360
+ if past_key_value is not None:
361
+ if self.layer_idx is None:
362
+ raise ValueError(
363
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
364
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
365
+ "with a layer index."
366
+ )
367
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
368
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
369
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
370
+
371
+ if past_key_value is not None:
372
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
373
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
374
+
375
+ # repeat k/v heads if n_kv_heads < n_heads
376
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
377
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
378
+
379
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
380
+
381
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
382
+ raise ValueError(
383
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
384
+ f" {attn_weights.size()}"
385
+ )
386
+
387
+ if attention_mask is not None:
388
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
389
+ raise ValueError(
390
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
391
+ )
392
+
393
+ attn_weights = attn_weights + attention_mask
394
+
395
+ # upcast attention to fp32
396
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
397
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
398
+ attn_output = torch.matmul(attn_weights, value_states)
399
+
400
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
401
+ raise ValueError(
402
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
403
+ f" {attn_output.size()}"
404
+ )
405
+
406
+ attn_output = attn_output.transpose(1, 2).contiguous()
407
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
408
+
409
+ attn_output = self.o_proj(attn_output)
410
+
411
+ if not output_attentions:
412
+ attn_weights = None
413
+
414
+ return attn_output, attn_weights, past_key_value
415
+
416
+
417
+ class Qwen2FlashAttention2(Qwen2Attention):
418
+ """
419
+ Qwen2 flash attention module, following Qwen2 attention module. This module inherits from `Qwen2Attention`
420
+ as the weights of the module stays untouched. The only required change would be on the forward pass
421
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
422
+ in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
423
+ config.max_window_layers layers.
424
+ """
425
+
426
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
427
+ def __init__(self, *args, **kwargs):
428
+ super().__init__(*args, **kwargs)
429
+
430
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
431
+ # 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.
432
+ # 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).
433
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
434
+
435
+ def forward(
436
+ self,
437
+ hidden_states: torch.Tensor,
438
+ attention_mask: Optional[torch.Tensor] = None,
439
+ position_ids: Optional[torch.LongTensor] = None,
440
+ past_key_value: Optional[Cache] = None,
441
+ output_attentions: bool = False,
442
+ use_cache: bool = False,
443
+ ):
444
+ bsz, q_len, _ = hidden_states.size()
445
+
446
+ query_states = self.q_proj(hidden_states)
447
+ key_states = self.k_proj(hidden_states)
448
+ value_states = self.v_proj(hidden_states)
449
+
450
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
451
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
452
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
453
+
454
+ kv_seq_len = key_states.shape[-2]
455
+ if past_key_value is not None:
456
+ if self.layer_idx is None:
457
+ raise ValueError(
458
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
459
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
460
+ "with a layer index."
461
+ )
462
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
463
+
464
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
465
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
466
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
467
+
468
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
469
+
470
+ use_sliding_windows = (
471
+ _flash_supports_window_size
472
+ and getattr(self.config, "sliding_window", None) is not None
473
+ and kv_seq_len > self.config.sliding_window
474
+ and self.config.use_sliding_window
475
+ )
476
+
477
+ if not _flash_supports_window_size:
478
+ logger.warning_once(
479
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
480
+ " make sure to upgrade flash-attn library."
481
+ )
482
+
483
+ if past_key_value is not None:
484
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
485
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
486
+ if (
487
+ getattr(self.config, "sliding_window", None) is not None
488
+ and kv_seq_len > self.config.sliding_window
489
+ and cache_has_contents
490
+ ):
491
+ slicing_tokens = 1 - self.config.sliding_window
492
+
493
+ past_key = past_key_value[self.layer_idx][0]
494
+ past_value = past_key_value[self.layer_idx][1]
495
+
496
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
497
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
498
+
499
+ if past_key.shape[-2] != self.config.sliding_window - 1:
500
+ raise ValueError(
501
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
502
+ f" {past_key.shape}"
503
+ )
504
+
505
+ if attention_mask is not None:
506
+ attention_mask = attention_mask[:, slicing_tokens:]
507
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
508
+
509
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
510
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
511
+
512
+ # repeat k/v heads if n_kv_heads < n_heads
513
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
514
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
515
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
516
+
517
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
518
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
519
+ # cast them back in float16 just to be sure everything works as expected.
520
+ input_dtype = query_states.dtype
521
+ if input_dtype == torch.float32:
522
+ if torch.is_autocast_enabled():
523
+ target_dtype = torch.get_autocast_gpu_dtype()
524
+ # Handle the case where the model is quantized
525
+ elif hasattr(self.config, "_pre_quantization_dtype"):
526
+ target_dtype = self.config._pre_quantization_dtype
527
+ else:
528
+ target_dtype = self.q_proj.weight.dtype
529
+
530
+ logger.warning_once(
531
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
532
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
533
+ f" {target_dtype}."
534
+ )
535
+
536
+ query_states = query_states.to(target_dtype)
537
+ key_states = key_states.to(target_dtype)
538
+ value_states = value_states.to(target_dtype)
539
+
540
+ # Reashape to the expected shape for Flash Attention
541
+ query_states = query_states.transpose(1, 2)
542
+ key_states = key_states.transpose(1, 2)
543
+ value_states = value_states.transpose(1, 2)
544
+
545
+ attn_output = self._flash_attention_forward(
546
+ query_states,
547
+ key_states,
548
+ value_states,
549
+ attention_mask,
550
+ q_len,
551
+ dropout=dropout_rate,
552
+ use_sliding_windows=use_sliding_windows,
553
+ )
554
+
555
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
556
+ attn_output = self.o_proj(attn_output)
557
+
558
+ if not output_attentions:
559
+ attn_weights = None
560
+
561
+ return attn_output, attn_weights, past_key_value
562
+
563
+ def _flash_attention_forward(
564
+ self,
565
+ query_states,
566
+ key_states,
567
+ value_states,
568
+ attention_mask,
569
+ query_length,
570
+ dropout=0.0,
571
+ softmax_scale=None,
572
+ use_sliding_windows=False,
573
+ ):
574
+ """
575
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
576
+ first unpad the input, then computes the attention scores and pad the final attention scores.
577
+
578
+ Args:
579
+ query_states (`torch.Tensor`):
580
+ Input query states to be passed to Flash Attention API
581
+ key_states (`torch.Tensor`):
582
+ Input key states to be passed to Flash Attention API
583
+ value_states (`torch.Tensor`):
584
+ Input value states to be passed to Flash Attention API
585
+ attention_mask (`torch.Tensor`):
586
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
587
+ position of padding tokens and 1 for the position of non-padding tokens.
588
+ dropout (`float`):
589
+ Attention dropout
590
+ softmax_scale (`float`, *optional*):
591
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
592
+ use_sliding_windows (`bool`, *optional*):
593
+ Whether to activate sliding window attention.
594
+ """
595
+ if not self._flash_attn_uses_top_left_mask:
596
+ causal = self.is_causal
597
+ else:
598
+ # 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__.
599
+ causal = self.is_causal and query_length != 1
600
+
601
+ # Decide whether to use SWA or not by layer index.
602
+ if use_sliding_windows and self.layer_idx >= self.config.max_window_layers:
603
+ use_sliding_windows = False
604
+
605
+ # Contains at least one padding token in the sequence
606
+ if attention_mask is not None:
607
+ batch_size = query_states.shape[0]
608
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
609
+ query_states, key_states, value_states, attention_mask, query_length
610
+ )
611
+
612
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
613
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
614
+
615
+ if not use_sliding_windows:
616
+ attn_output_unpad = flash_attn_varlen_func(
617
+ query_states,
618
+ key_states,
619
+ value_states,
620
+ cu_seqlens_q=cu_seqlens_q,
621
+ cu_seqlens_k=cu_seqlens_k,
622
+ max_seqlen_q=max_seqlen_in_batch_q,
623
+ max_seqlen_k=max_seqlen_in_batch_k,
624
+ dropout_p=dropout,
625
+ softmax_scale=softmax_scale,
626
+ causal=causal,
627
+ )
628
+ else:
629
+ attn_output_unpad = flash_attn_varlen_func(
630
+ query_states,
631
+ key_states,
632
+ value_states,
633
+ cu_seqlens_q=cu_seqlens_q,
634
+ cu_seqlens_k=cu_seqlens_k,
635
+ max_seqlen_q=max_seqlen_in_batch_q,
636
+ max_seqlen_k=max_seqlen_in_batch_k,
637
+ dropout_p=dropout,
638
+ softmax_scale=softmax_scale,
639
+ causal=causal,
640
+ window_size=(self.config.sliding_window, self.config.sliding_window),
641
+ )
642
+
643
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
644
+ else:
645
+ if not use_sliding_windows:
646
+ attn_output = flash_attn_func(
647
+ query_states,
648
+ key_states,
649
+ value_states,
650
+ dropout,
651
+ softmax_scale=softmax_scale,
652
+ causal=causal,
653
+ )
654
+ else:
655
+ attn_output = flash_attn_func(
656
+ query_states,
657
+ key_states,
658
+ value_states,
659
+ dropout,
660
+ softmax_scale=softmax_scale,
661
+ causal=causal,
662
+ window_size=(self.config.sliding_window, self.config.sliding_window),
663
+ )
664
+
665
+ return attn_output
666
+
667
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
668
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
669
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
670
+
671
+ # On the first iteration we need to properly re-create the padding mask
672
+ # by slicing it on the proper place
673
+ if kv_seq_len != attention_mask.shape[-1]:
674
+ attention_mask_num_tokens = attention_mask.shape[-1]
675
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
676
+
677
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
678
+
679
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
680
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
681
+
682
+ if query_length == kv_seq_len:
683
+ query_layer = index_first_axis(
684
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
685
+ )
686
+ cu_seqlens_q = cu_seqlens_k
687
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
688
+ indices_q = indices_k
689
+ elif query_length == 1:
690
+ max_seqlen_in_batch_q = 1
691
+ cu_seqlens_q = torch.arange(
692
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
693
+ ) # There is a memcpy here, that is very bad.
694
+ indices_q = cu_seqlens_q[:-1]
695
+ query_layer = query_layer.squeeze(1)
696
+ else:
697
+ # The -q_len: slice assumes left padding.
698
+ attention_mask = attention_mask[:, -query_length:]
699
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
700
+
701
+ return (
702
+ query_layer,
703
+ key_layer,
704
+ value_layer,
705
+ indices_q,
706
+ (cu_seqlens_q, cu_seqlens_k),
707
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
708
+ )
709
+
710
+
711
+ # Copied from transformers.models.mistral.modeling_mistral.MistralSdpaAttention with Mistral->Qwen2
712
+ class Qwen2SdpaAttention(Qwen2Attention):
713
+ """
714
+ Qwen2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
715
+ `Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
716
+ SDPA API.
717
+ """
718
+
719
+ # Adapted from Qwen2Attention.forward
720
+ def forward(
721
+ self,
722
+ hidden_states: torch.Tensor,
723
+ attention_mask: Optional[torch.Tensor] = None,
724
+ position_ids: Optional[torch.LongTensor] = None,
725
+ past_key_value: Optional[Cache] = None,
726
+ output_attentions: bool = False,
727
+ use_cache: bool = False,
728
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
729
+ if output_attentions:
730
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
731
+ logger.warning_once(
732
+ "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, "
733
+ '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.'
734
+ )
735
+ return super().forward(
736
+ hidden_states=hidden_states,
737
+ attention_mask=attention_mask,
738
+ position_ids=position_ids,
739
+ past_key_value=past_key_value,
740
+ output_attentions=output_attentions,
741
+ use_cache=use_cache,
742
+ )
743
+
744
+ bsz, q_len, _ = hidden_states.size()
745
+
746
+ query_states = self.q_proj(hidden_states)
747
+ key_states = self.k_proj(hidden_states)
748
+ value_states = self.v_proj(hidden_states)
749
+
750
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
751
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
752
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
753
+
754
+ kv_seq_len = key_states.shape[-2]
755
+ if past_key_value is not None:
756
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
757
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
758
+
759
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
760
+
761
+ if past_key_value is not None:
762
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
763
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
764
+
765
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
766
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
767
+
768
+ if attention_mask is not None:
769
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
770
+ raise ValueError(
771
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
772
+ )
773
+
774
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
775
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
776
+ if query_states.device.type == "cuda" and attention_mask is not None:
777
+ query_states = query_states.contiguous()
778
+ key_states = key_states.contiguous()
779
+ value_states = value_states.contiguous()
780
+
781
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
782
+ query_states,
783
+ key_states,
784
+ value_states,
785
+ attn_mask=attention_mask,
786
+ dropout_p=self.attention_dropout if self.training else 0.0,
787
+ # 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.
788
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
789
+ )
790
+
791
+ attn_output = attn_output.transpose(1, 2).contiguous()
792
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
793
+
794
+ attn_output = self.o_proj(attn_output)
795
+
796
+ return attn_output, None, past_key_value
797
+
798
+
799
+ QWEN2_ATTENTION_CLASSES = {
800
+ "eager": Qwen2Attention,
801
+ "flash_attention_2": Qwen2FlashAttention2,
802
+ "sdpa": Qwen2SdpaAttention,
803
+ }
804
+
805
+
806
+ class Qwen2DecoderLayer(nn.Module):
807
+ def __init__(self, config: Qwen2TSConfig, layer_idx: int):
808
+ super().__init__()
809
+ self.hidden_size = config.hidden_size
810
+
811
+ if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
812
+ logger.warning_once(
813
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
814
+ "unexpected results may be encountered."
815
+ )
816
+ self.self_attn = QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
817
+
818
+ self.mlp = Qwen2MLP(config)
819
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
820
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
821
+
822
+ def forward(
823
+ self,
824
+ hidden_states: torch.Tensor,
825
+ attention_mask: Optional[torch.Tensor] = None,
826
+ position_ids: Optional[torch.LongTensor] = None,
827
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
828
+ output_attentions: Optional[bool] = False,
829
+ use_cache: Optional[bool] = False,
830
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
831
+ """
832
+ Args:
833
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
834
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
835
+ `(batch, sequence_length)` where padding elements are indicated by 0.
836
+ output_attentions (`bool`, *optional*):
837
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
838
+ returned tensors for more detail.
839
+ use_cache (`bool`, *optional*):
840
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
841
+ (see `past_key_values`).
842
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
843
+ """
844
+
845
+ residual = hidden_states
846
+
847
+ hidden_states = self.input_layernorm(hidden_states)
848
+
849
+ # Self Attention
850
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
851
+ hidden_states=hidden_states,
852
+ attention_mask=attention_mask,
853
+ position_ids=position_ids,
854
+ past_key_value=past_key_value,
855
+ output_attentions=output_attentions,
856
+ use_cache=use_cache,
857
+ )
858
+ hidden_states = residual + hidden_states
859
+
860
+ # Fully Connected
861
+ residual = hidden_states
862
+ hidden_states = self.post_attention_layernorm(hidden_states)
863
+ hidden_states = self.mlp(hidden_states)
864
+ hidden_states = residual + hidden_states
865
+
866
+ outputs = (hidden_states,)
867
+
868
+ if output_attentions:
869
+ outputs += (self_attn_weights,)
870
+
871
+ if use_cache:
872
+ outputs += (present_key_value,)
873
+
874
+ return outputs
875
+
876
+
877
+ QWEN2_START_DOCSTRING = r"""
878
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
879
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
880
+ etc.)
881
+
882
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
883
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
884
+ and behavior.
885
+
886
+ Parameters:
887
+ config ([`Qwen2TSConfig`]):
888
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
889
+ load the weights associated with the model, only the configuration. Check out the
890
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
891
+ """
892
+
893
+
894
+ @add_start_docstrings(
895
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
896
+ QWEN2_START_DOCSTRING,
897
+ )
898
+ class Qwen2PreTrainedModel(PreTrainedModel):
899
+ config_class = Qwen2TSConfig
900
+ base_model_prefix = "model"
901
+ supports_gradient_checkpointing = True
902
+ _no_split_modules = ["Qwen2DecoderLayer"]
903
+ _skip_keys_device_placement = "past_key_values"
904
+ _supports_flash_attn_2 = True
905
+ _supports_sdpa = True
906
+ _supports_cache_class = True
907
+
908
+ def _init_weights(self, module):
909
+ std = self.config.initializer_range
910
+ if isinstance(module, nn.Linear):
911
+ module.weight.data.normal_(mean=0.0, std=std)
912
+ if module.bias is not None:
913
+ module.bias.data.zero_()
914
+ elif isinstance(module, nn.Embedding):
915
+ module.weight.data.normal_(mean=0.0, std=std)
916
+ if module.padding_idx is not None:
917
+ module.weight.data[module.padding_idx].zero_()
918
+
919
+
920
+ class TSProjector(nn.Module):
921
+ def __init__(self, config: Qwen2TSConfig):
922
+ super().__init__()
923
+ self.config = config
924
+ self.linear_1 = nn.Linear(config.ts['d_model'], config.hidden_size, bias=True)
925
+ self.linear_2 = nn.LayerNorm(config.hidden_size, bias=True)
926
+ self.linear_3 = nn.Linear(config.hidden_size, config.hidden_size * 4, bias=True)
927
+ self.linear_4 = nn.LayerNorm(config.hidden_size * 4, bias=True)
928
+ self.act = nn.GELU()
929
+
930
+ def forward(self, ts_features):
931
+ hidden_states = self.linear_1(ts_features)
932
+ hidden_states = self.linear_2(hidden_states)
933
+ hidden_states = self.act(hidden_states)
934
+ hidden_states = self.linear_3(hidden_states)
935
+ hidden_states = self.linear_4(hidden_states)
936
+ hidden_states = hidden_states.reshape(hidden_states.size(0), -1, self.config.hidden_size)
937
+ return hidden_states
938
+
939
+
940
+ QWEN2_INPUTS_DOCSTRING = r"""
941
+ Args:
942
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
943
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
944
+ it.
945
+
946
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
947
+ [`PreTrainedTokenizer.__call__`] for details.
948
+
949
+ [What are input IDs?](../glossary#input-ids)
950
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
951
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
952
+
953
+ - 1 for tokens that are **not masked**,
954
+ - 0 for tokens that are **masked**.
955
+
956
+ [What are attention masks?](../glossary#attention-mask)
957
+
958
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
959
+ [`PreTrainedTokenizer.__call__`] for details.
960
+
961
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
962
+ `past_key_values`).
963
+
964
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
965
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
966
+ information on the default strategy.
967
+
968
+ - 1 indicates the head is **not masked**,
969
+ - 0 indicates the head is **masked**.
970
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
971
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
972
+ config.n_positions - 1]`.
973
+
974
+ [What are position IDs?](../glossary#position-ids)
975
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
976
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
977
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
978
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
979
+
980
+ Two formats are allowed:
981
+ - a [`~cache_utils.Cache`] instance;
982
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
983
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
984
+ cache format.
985
+
986
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
987
+ legacy cache format will be returned.
988
+
989
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
990
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
991
+ of shape `(batch_size, sequence_length)`.
992
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
993
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
994
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
995
+ model's internal embedding lookup matrix.
996
+ use_cache (`bool`, *optional*):
997
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
998
+ `past_key_values`).
999
+ output_attentions (`bool`, *optional*):
1000
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1001
+ tensors for more detail.
1002
+ output_hidden_states (`bool`, *optional*):
1003
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1004
+ more detail.
1005
+ return_dict (`bool`, *optional*):
1006
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1007
+ """
1008
+
1009
+
1010
+ @add_start_docstrings(
1011
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
1012
+ QWEN2_START_DOCSTRING,
1013
+ )
1014
+ class Qwen2Model(Qwen2PreTrainedModel):
1015
+ """
1016
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
1017
+
1018
+ Args:
1019
+ config: Qwen2TSConfig
1020
+ """
1021
+
1022
+ def __init__(self, config: Qwen2TSConfig):
1023
+ super().__init__(config)
1024
+ self.padding_idx = config.pad_token_id
1025
+ self.vocab_size = config.vocab_size
1026
+
1027
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1028
+ self.layers = nn.ModuleList(
1029
+ [Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1030
+ )
1031
+ self._attn_implementation = config._attn_implementation
1032
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1033
+
1034
+ self.gradient_checkpointing = False
1035
+
1036
+ # Initialize weights and apply final processing
1037
+ self.post_init()
1038
+
1039
+ def get_input_embeddings(self):
1040
+ return self.embed_tokens
1041
+
1042
+ def set_input_embeddings(self, value):
1043
+ self.embed_tokens = value
1044
+
1045
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1046
+ def forward(
1047
+ self,
1048
+ input_ids: torch.LongTensor = None,
1049
+ attention_mask: Optional[torch.Tensor] = None,
1050
+ position_ids: Optional[torch.LongTensor] = None,
1051
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1052
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1053
+ use_cache: Optional[bool] = None,
1054
+ output_attentions: Optional[bool] = None,
1055
+ output_hidden_states: Optional[bool] = None,
1056
+ return_dict: Optional[bool] = None,
1057
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1058
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1059
+ output_hidden_states = (
1060
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1061
+ )
1062
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1063
+
1064
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1065
+
1066
+ # retrieve input_ids and inputs_embeds
1067
+ if input_ids is not None and inputs_embeds is not None:
1068
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
1069
+ elif input_ids is not None:
1070
+ batch_size, seq_length = input_ids.shape
1071
+ elif inputs_embeds is not None:
1072
+ batch_size, seq_length, _ = inputs_embeds.shape
1073
+ else:
1074
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
1075
+
1076
+ if self.gradient_checkpointing and self.training:
1077
+ if use_cache:
1078
+ logger.warning_once(
1079
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1080
+ )
1081
+ use_cache = False
1082
+
1083
+ past_key_values_length = 0
1084
+
1085
+ if use_cache:
1086
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1087
+ if use_legacy_cache:
1088
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1089
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1090
+
1091
+ if position_ids is None:
1092
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1093
+ position_ids = torch.arange(
1094
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1095
+ )
1096
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1097
+ else:
1098
+ position_ids = position_ids.view(-1, seq_length).long()
1099
+
1100
+ if inputs_embeds is None:
1101
+ inputs_embeds = self.embed_tokens(input_ids)
1102
+
1103
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1104
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1105
+ if is_padding_right:
1106
+ raise ValueError(
1107
+ "You are attempting to perform batched generation with padding_side='right'"
1108
+ " this may lead to unexpected behaviour for Flash Attention version of Qwen2. Make sure to "
1109
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1110
+ )
1111
+
1112
+ if self._attn_implementation == "flash_attention_2":
1113
+ # 2d mask is passed through the layers
1114
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1115
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1116
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1117
+ # the manual implementation that requires a 4D causal mask in all cases.
1118
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1119
+ attention_mask,
1120
+ (batch_size, seq_length),
1121
+ inputs_embeds,
1122
+ past_key_values_length,
1123
+ sliding_window=self.config.sliding_window,
1124
+ )
1125
+ else:
1126
+ # 4d mask is passed through the layers
1127
+ attention_mask = _prepare_4d_causal_attention_mask(
1128
+ attention_mask,
1129
+ (batch_size, seq_length),
1130
+ inputs_embeds,
1131
+ past_key_values_length,
1132
+ sliding_window=self.config.sliding_window,
1133
+ )
1134
+
1135
+ hidden_states = inputs_embeds
1136
+
1137
+ # decoder layers
1138
+ all_hidden_states = () if output_hidden_states else None
1139
+ all_self_attns = () if output_attentions else None
1140
+ next_decoder_cache = None
1141
+
1142
+ for decoder_layer in self.layers:
1143
+ if output_hidden_states:
1144
+ all_hidden_states += (hidden_states,)
1145
+
1146
+ if self.gradient_checkpointing and self.training:
1147
+ layer_outputs = self._gradient_checkpointing_func(
1148
+ decoder_layer.__call__,
1149
+ hidden_states,
1150
+ attention_mask,
1151
+ position_ids,
1152
+ past_key_values,
1153
+ output_attentions,
1154
+ use_cache,
1155
+ )
1156
+ else:
1157
+ layer_outputs = decoder_layer(
1158
+ hidden_states,
1159
+ attention_mask=attention_mask,
1160
+ position_ids=position_ids,
1161
+ past_key_value=past_key_values,
1162
+ output_attentions=output_attentions,
1163
+ use_cache=use_cache,
1164
+ )
1165
+
1166
+ hidden_states = layer_outputs[0]
1167
+
1168
+ if use_cache:
1169
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1170
+
1171
+ if output_attentions:
1172
+ all_self_attns += (layer_outputs[1],)
1173
+
1174
+ hidden_states = self.norm(hidden_states)
1175
+
1176
+ # add hidden states from the last decoder layer
1177
+ if output_hidden_states:
1178
+ all_hidden_states += (hidden_states,)
1179
+
1180
+ next_cache = None
1181
+ if use_cache:
1182
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1183
+
1184
+ if not return_dict:
1185
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1186
+ return BaseModelOutputWithPast(
1187
+ last_hidden_state=hidden_states,
1188
+ past_key_values=next_cache,
1189
+ hidden_states=all_hidden_states,
1190
+ attentions=all_self_attns,
1191
+ )
1192
+
1193
+
1194
+ class Qwen2TSForCausalLM(Qwen2PreTrainedModel):
1195
+ _tied_weights_keys = ["lm_head.weight"]
1196
+
1197
+ def __init__(self, config):
1198
+ super().__init__(config)
1199
+ self.config = config
1200
+
1201
+ self.model = Qwen2Model(config)
1202
+ self.vocab_size = config.vocab_size
1203
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1204
+
1205
+ # TS embedding
1206
+ self.ts_encoder = TimeSeriesEmbedding(config.ts)
1207
+
1208
+ # Initialize weights and apply final processing
1209
+ self.post_init()
1210
+
1211
+ def get_input_embeddings(self):
1212
+ return self.model.embed_tokens
1213
+
1214
+ def set_input_embeddings(self, value):
1215
+ self.model.embed_tokens = value
1216
+
1217
+ def get_output_embeddings(self):
1218
+ return self.lm_head
1219
+
1220
+ def set_output_embeddings(self, new_embeddings):
1221
+ self.lm_head = new_embeddings
1222
+
1223
+ def set_decoder(self, decoder):
1224
+ self.model = decoder
1225
+
1226
+ def get_decoder(self):
1227
+ return self.model
1228
+ def _merge_input_ids_with_time_series_features(
1229
+ self, time_series_features, inputs_embeds, input_ids, attention_mask, labels, patch_cnt
1230
+ ):
1231
+ batch_size, sequence_length = input_ids.shape
1232
+ _left_padding = torch.any(attention_mask[:, 0] == 0)
1233
+ _right_padding = torch.any(attention_mask[:, -1] == 0)
1234
+ left_padding = False
1235
+ if batch_size > 1:
1236
+ if _left_padding and not _right_padding:
1237
+ left_padding = True
1238
+ elif not _left_padding and _right_padding:
1239
+ left_padding = False
1240
+ elif not _left_padding and not _right_padding:
1241
+ left_padding = False
1242
+ else:
1243
+ raise ValueError(f"both side of attention_mask has zero, invalid. {attention_mask}")
1244
+ else:
1245
+ if _left_padding and not _right_padding:
1246
+ left_padding = True
1247
+ else:
1248
+ left_padding = False
1249
+
1250
+ # 1. Create a mask to know where special time series tokens are
1251
+ special_ts_token_mask_start = input_ids == self.config.ts_token_start_index
1252
+ special_ts_token_mask_end = input_ids == self.config.ts_token_end_index
1253
+ special_ts_token_mask = special_ts_token_mask_start | special_ts_token_mask_end
1254
+
1255
+ # 2. Calculate patch count
1256
+ num_special_ts_tokens = torch.sum(special_ts_token_mask_start, dim=-1)
1257
+ total_time_steps, embed_dim = time_series_features.shape
1258
+
1259
+ # Correctly calculate the total number of patches per batch
1260
+ patch_index = 0
1261
+ num_total_patches = torch.zeros(batch_size, dtype=patch_cnt.dtype, device=patch_cnt.device)
1262
+ special_ts_token_mask_start_nonzero = special_ts_token_mask_start.nonzero()
1263
+ special_ts_token_mask_start_with_size = special_ts_token_mask_start.clone().long()
1264
+
1265
+ attn_mask_cnt = attention_mask.sum(dim=-1)
1266
+ for i in range(batch_size):
1267
+ num_ts_in_batch = num_special_ts_tokens[i]
1268
+ num_total_patches[i] = patch_cnt[patch_index : patch_index + num_ts_in_batch].sum() - 2 * num_ts_in_batch
1269
+ for idx in range(patch_index, patch_index + num_ts_in_batch):
1270
+ b_idx, pos = special_ts_token_mask_start_nonzero[idx]
1271
+ special_ts_token_mask_start_with_size[b_idx, pos] *= (patch_cnt[idx].item() - 2)
1272
+ patch_index += num_ts_in_batch
1273
+ attn_mask_cnt[i] += num_total_patches[i].item()
1274
+
1275
+ # 3. Embeding length
1276
+ max_embed_dim = sequence_length + num_total_patches.max()
1277
+
1278
+ # 4. Non ts tokens
1279
+ batch_indices, non_ts_indices = torch.where(~special_ts_token_mask)
1280
+
1281
+ # 5. Text token in final text positions
1282
+ new_token_positions = torch.cumsum((special_ts_token_mask_start_with_size + 1), dim=-1) - 1
1283
+
1284
+ # nb_ts_pad
1285
+ nb_ts_pad = max_embed_dim - 1 - new_token_positions[:, -1]
1286
+ if left_padding:
1287
+ new_token_positions += nb_ts_pad[:, None]
1288
+
1289
+ text_to_overwrite = new_token_positions[batch_indices, non_ts_indices]
1290
+
1291
+ # 6. Final embedding and attention masks
1292
+ final_embedding = torch.zeros(
1293
+ batch_size, max_embed_dim, embed_dim, dtype=inputs_embeds.dtype, device=inputs_embeds.device
1294
+ )
1295
+
1296
+ final_attention_mask = torch.zeros(batch_size, max_embed_dim, dtype=attention_mask.dtype, device=inputs_embeds.device)
1297
+ for i in range(attention_mask.size(0)):
1298
+ if left_padding:
1299
+ final_attention_mask[i, max_embed_dim - attn_mask_cnt[i] :] = 1
1300
+ else:
1301
+ final_attention_mask[i, : attn_mask_cnt[i]] = 1
1302
+
1303
+ final_labels = None
1304
+ if labels is not None:
1305
+ final_labels = torch.full(
1306
+ (batch_size, max_embed_dim), self.config.ignore_index, dtype=input_ids.dtype, device=input_ids.device
1307
+ )
1308
+
1309
+ target_device = inputs_embeds.device
1310
+ batch_indices, non_ts_indices, text_to_overwrite = (
1311
+ batch_indices.to(target_device),
1312
+ non_ts_indices.to(target_device),
1313
+ text_to_overwrite.to(target_device),
1314
+ )
1315
+
1316
+ # 7. Move embedding and labels to final positions
1317
+ final_embedding[batch_indices, text_to_overwrite] = inputs_embeds[batch_indices, non_ts_indices]
1318
+ if labels is not None:
1319
+ final_labels[batch_indices, text_to_overwrite] = labels[batch_indices, non_ts_indices]
1320
+
1321
+ # 8. Move time series to final positions
1322
+ ts_to_overwrite = torch.full(
1323
+ (batch_size, max_embed_dim), True, dtype=torch.bool, device=inputs_embeds.device
1324
+ )
1325
+ ts_to_overwrite[batch_indices, text_to_overwrite] = False
1326
+
1327
+ reversed_cumsum = ts_to_overwrite.flip(dims=[-1]).cumsum(-1).flip(dims=[-1]) - 1
1328
+ ts_to_overwrite &= reversed_cumsum >= nb_ts_pad[:, None].to(target_device)
1329
+
1330
+ # Check that the number of time series tokens is correct
1331
+ if ts_to_overwrite.sum() != time_series_features.shape[:-1].numel():
1332
+ raise ValueError(
1333
+ f"The input provided to the model are wrong. The number of time series tokens is {torch.sum(special_ts_token_mask_start)} while"
1334
+ f" the number of time series given to the model is {len(patch_cnt)}. This prevents correct indexing and breaks batch generation."
1335
+ )
1336
+ final_embedding[ts_to_overwrite] = time_series_features.contiguous().reshape(-1, embed_dim).to(target_device)
1337
+
1338
+ # 9. Calculate position ids
1339
+ position_ids = (final_attention_mask.cumsum(-1) - 1).masked_fill_((final_attention_mask == 0), 1)
1340
+ if position_ids.size(-1) < input_ids.size(-1):
1341
+ position_ids = position_ids[:, -input_ids.size(-1) :]
1342
+
1343
+ # 10. Move attention mask to final positions
1344
+ pad_batch_indices, pad_indices = torch.where(input_ids == self.config.pad_token_id)
1345
+ if len(pad_batch_indices) > 0:
1346
+ indices_to_mask = new_token_positions[pad_batch_indices, pad_indices]
1347
+ final_embedding[pad_batch_indices, indices_to_mask] = 0
1348
+
1349
+ return final_embedding, final_attention_mask, position_ids, final_labels
1350
+
1351
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1352
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1353
+ def forward(
1354
+ self,
1355
+ input_ids: torch.LongTensor = None,
1356
+ timeseries: torch.FloatTensor = None,
1357
+ attention_mask: Optional[torch.Tensor] = None,
1358
+ position_ids: Optional[torch.LongTensor] = None,
1359
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1360
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1361
+ labels: Optional[torch.LongTensor] = None,
1362
+ use_cache: Optional[bool] = None,
1363
+ output_attentions: Optional[bool] = None,
1364
+ output_hidden_states: Optional[bool] = None,
1365
+ return_dict: Optional[bool] = None,
1366
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1367
+ r"""
1368
+ Args:
1369
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1370
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1371
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1372
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1373
+
1374
+ Returns:
1375
+
1376
+ Example:
1377
+
1378
+ ```python
1379
+ >>> from transformers import AutoTokenizer, Qwen2ForCausalLM
1380
+
1381
+ >>> model = Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1382
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1383
+
1384
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1385
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1386
+
1387
+ >>> # Generate
1388
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1389
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1390
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1391
+ ```"""
1392
+
1393
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1394
+ output_hidden_states = (
1395
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1396
+ )
1397
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1398
+
1399
+ if inputs_embeds is None:
1400
+ inputs_embeds = self.get_input_embeddings()(input_ids)
1401
+
1402
+ if timeseries is not None and timeseries.shape[0] > 0:
1403
+ # use_cache = False
1404
+ ts_features, patch_cnt = self.ts_encoder(timeseries)
1405
+ inputs_embeds = inputs_embeds.to(ts_features.dtype)
1406
+
1407
+ inputs_embeds, attention_mask, position_ids, labels = self._merge_input_ids_with_time_series_features(
1408
+ ts_features, inputs_embeds, input_ids, attention_mask, labels, patch_cnt
1409
+ )
1410
+
1411
+ outputs = self.model(
1412
+ attention_mask=attention_mask,
1413
+ position_ids=position_ids,
1414
+ past_key_values=past_key_values,
1415
+ inputs_embeds=inputs_embeds,
1416
+ use_cache=use_cache,
1417
+ output_attentions=output_attentions,
1418
+ output_hidden_states=output_hidden_states,
1419
+ return_dict=return_dict,
1420
+ )
1421
+
1422
+ hidden_states = outputs[0]
1423
+ logits = self.lm_head(hidden_states)
1424
+ logits = logits.float()
1425
+
1426
+ loss = None
1427
+ if labels is not None:
1428
+ # Shift so that tokens < n predict n
1429
+ shift_logits = logits[..., :-1, :].contiguous()
1430
+ shift_labels = labels[..., 1:].contiguous()
1431
+ # Flatten the tokens
1432
+ loss_fct = CrossEntropyLoss()
1433
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1434
+ shift_labels = shift_labels.view(-1)
1435
+ # Enable model parallelism
1436
+ shift_labels = shift_labels.to(shift_logits.device)
1437
+ loss = loss_fct(shift_logits, shift_labels)
1438
+
1439
+ if not return_dict:
1440
+ output = (logits,) + outputs[1:]
1441
+ return (loss,) + output if loss is not None else output
1442
+
1443
+
1444
+ return Qwen2TSCausalLMOutputWithPast(
1445
+ loss=loss,
1446
+ logits=logits,
1447
+ past_key_values=outputs.past_key_values,
1448
+ hidden_states=outputs.hidden_states,
1449
+ attentions=outputs.attentions,
1450
+ attention_mask=attention_mask
1451
+ )
1452
+
1453
+ def _extract_past_from_model_output(self, outputs: ModelOutput):
1454
+ return "past_key_values", outputs.past_key_values
1455
+
1456
+ def _update_model_kwargs_for_generation(
1457
+ self,
1458
+ outputs: ModelOutput,
1459
+ model_kwargs: Dict[str, Any],
1460
+ is_encoder_decoder: bool = False,
1461
+ num_new_tokens: int = 1,
1462
+ ) -> Dict[str, Any]:
1463
+ # update past_key_values keeping its naming used in model code
1464
+ cache_name, cache = self._extract_past_from_model_output(outputs)
1465
+ model_kwargs[cache_name] = cache
1466
+ if getattr(outputs, "state", None) is not None:
1467
+ model_kwargs["state"] = outputs.state
1468
+
1469
+ # update attention_mask
1470
+ if getattr(outputs, "attention_mask", None) is not None:
1471
+ model_kwargs["attention_mask"] = outputs.attention_mask
1472
+
1473
+ # update token_type_ids with last value
1474
+ if "token_type_ids" in model_kwargs:
1475
+ token_type_ids = model_kwargs["token_type_ids"]
1476
+ model_kwargs["token_type_ids"] = torch.cat([token_type_ids, token_type_ids[:, -1].unsqueeze(-1)], dim=-1)
1477
+
1478
+ if not is_encoder_decoder:
1479
+ # update attention mask
1480
+ if "attention_mask" in model_kwargs:
1481
+ attention_mask = model_kwargs["attention_mask"]
1482
+ model_kwargs["attention_mask"] = torch.cat(
1483
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
1484
+ )
1485
+ else:
1486
+ # update decoder attention mask
1487
+ if "decoder_attention_mask" in model_kwargs:
1488
+ decoder_attention_mask = model_kwargs["decoder_attention_mask"]
1489
+ model_kwargs["decoder_attention_mask"] = torch.cat(
1490
+ [decoder_attention_mask, decoder_attention_mask.new_ones((decoder_attention_mask.shape[0], 1))],
1491
+ dim=-1,
1492
+ )
1493
+
1494
+ if model_kwargs.get("use_cache", True):
1495
+ model_kwargs["cache_position"] = model_kwargs["cache_position"][-1:] + num_new_tokens
1496
+ else:
1497
+ past_positions = model_kwargs.pop("cache_position")
1498
+ new_positions = torch.arange(
1499
+ past_positions[-1] + 1, past_positions[-1] + num_new_tokens + 1, dtype=past_positions.dtype
1500
+ ).to(past_positions.device)
1501
+ model_kwargs["cache_position"] = torch.cat((past_positions, new_positions))
1502
+ return model_kwargs
1503
+
1504
+ def prepare_inputs_for_generation(
1505
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, timeseries=None, **kwargs
1506
+ ):
1507
+ # Omit tokens covered by past_key_values
1508
+ if past_key_values is not None:
1509
+ if isinstance(past_key_values, Cache):
1510
+ cache_length = past_key_values.get_seq_length()
1511
+ past_length = past_key_values.seen_tokens
1512
+ max_cache_length = (
1513
+ past_key_values.get_max_length()
1514
+ if hasattr(past_key_values, "get_max_length")
1515
+ else past_key_values.get_max_cache_shape()
1516
+ )
1517
+ else:
1518
+ cache_length = past_length = past_key_values[0][0].shape[2]
1519
+ max_cache_length = None
1520
+
1521
+ has_ts = timeseries is not None and len(timeseries) > 0
1522
+
1523
+ if has_ts and kwargs.get("attention_mask") is not None:
1524
+ attention_mask = kwargs["attention_mask"]
1525
+ attention_mask = torch.cat(
1526
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
1527
+ )
1528
+
1529
+ # Set attention mask and input_ids
1530
+ if has_ts and past_length > 0:
1531
+ # We have only one token added and timeseries are already inferenced
1532
+ input_ids = input_ids[:, -1:]
1533
+ timeseries = None
1534
+ elif attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1535
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1536
+ elif past_length < input_ids.shape[1]:
1537
+ input_ids = input_ids[:, past_length:]
1538
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1539
+
1540
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1541
+ if (
1542
+ max_cache_length is not None
1543
+ and attention_mask is not None
1544
+ and cache_length + input_ids.size(1) > max_cache_length
1545
+ ):
1546
+ attention_mask = attention_mask[:, -max_cache_length:]
1547
+
1548
+ position_ids = kwargs.get("position_ids", None)
1549
+ if attention_mask is not None and position_ids is None:
1550
+ # create position_ids on the fly for batch generation
1551
+ position_ids = attention_mask.long().cumsum(-1) - 1
1552
+ position_ids.masked_fill_(attention_mask == 0, 1)
1553
+ if past_key_values:
1554
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1555
+
1556
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1557
+ if inputs_embeds is not None and past_key_values is None:
1558
+ model_inputs = {"inputs_embeds": inputs_embeds}
1559
+ else:
1560
+ model_inputs = {"input_ids": input_ids}
1561
+
1562
+ model_inputs.update(
1563
+ {
1564
+ "position_ids": position_ids,
1565
+ "past_key_values": past_key_values,
1566
+ "use_cache": kwargs.get("use_cache"),
1567
+ "attention_mask": attention_mask,
1568
+ "timeseries": timeseries
1569
+ }
1570
+ )
1571
+ return model_inputs
1572
+
1573
+ @staticmethod
1574
+ def _reorder_cache(past_key_values, beam_idx):
1575
+ reordered_past = ()
1576
+ for layer_past in past_key_values:
1577
+ reordered_past += (
1578
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1579
+ )
1580
+ return reordered_past
1581
+
1582
+
1583
+ @add_start_docstrings(
1584
+ """
1585
+ The Qwen2 Model transformer with a sequence classification head on top (linear layer).
1586
+
1587
+ [`Qwen2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1588
+ (e.g. GPT-2) do.
1589
+
1590
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1591
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1592
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1593
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1594
+ each row of the batch).
1595
+ """,
1596
+ QWEN2_START_DOCSTRING,
1597
+ )
1598
+ class Qwen2ForSequenceClassification(Qwen2PreTrainedModel):
1599
+ def __init__(self, config):
1600
+ super().__init__(config)
1601
+ self.num_labels = config.num_labels
1602
+ self.model = Qwen2Model(config)
1603
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1604
+
1605
+ # Initialize weights and apply final processing
1606
+ self.post_init()
1607
+
1608
+ def get_input_embeddings(self):
1609
+ return self.model.embed_tokens
1610
+
1611
+ def set_input_embeddings(self, value):
1612
+ self.model.embed_tokens = value
1613
+
1614
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1615
+ def forward(
1616
+ self,
1617
+ input_ids: torch.LongTensor = None,
1618
+ attention_mask: Optional[torch.Tensor] = None,
1619
+ position_ids: Optional[torch.LongTensor] = None,
1620
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1621
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1622
+ labels: Optional[torch.LongTensor] = None,
1623
+ use_cache: Optional[bool] = None,
1624
+ output_attentions: Optional[bool] = None,
1625
+ output_hidden_states: Optional[bool] = None,
1626
+ return_dict: Optional[bool] = None,
1627
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1628
+ r"""
1629
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1630
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1631
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1632
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1633
+ """
1634
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1635
+
1636
+ transformer_outputs = self.model(
1637
+ input_ids,
1638
+ attention_mask=attention_mask,
1639
+ position_ids=position_ids,
1640
+ past_key_values=past_key_values,
1641
+ inputs_embeds=inputs_embeds,
1642
+ use_cache=use_cache,
1643
+ output_attentions=output_attentions,
1644
+ output_hidden_states=output_hidden_states,
1645
+ return_dict=return_dict,
1646
+ )
1647
+ hidden_states = transformer_outputs[0]
1648
+ logits = self.score(hidden_states)
1649
+
1650
+ if input_ids is not None:
1651
+ batch_size = input_ids.shape[0]
1652
+ else:
1653
+ batch_size = inputs_embeds.shape[0]
1654
+
1655
+ if self.config.pad_token_id is None and batch_size != 1:
1656
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1657
+ if self.config.pad_token_id is None:
1658
+ sequence_lengths = -1
1659
+ else:
1660
+ if input_ids is not None:
1661
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1662
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1663
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1664
+ sequence_lengths = sequence_lengths.to(logits.device)
1665
+ else:
1666
+ sequence_lengths = -1
1667
+
1668
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1669
+
1670
+ loss = None
1671
+ if labels is not None:
1672
+ labels = labels.to(logits.device)
1673
+ if self.config.problem_type is None:
1674
+ if self.num_labels == 1:
1675
+ self.config.problem_type = "regression"
1676
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1677
+ self.config.problem_type = "single_label_classification"
1678
+ else:
1679
+ self.config.problem_type = "multi_label_classification"
1680
+
1681
+ if self.config.problem_type == "regression":
1682
+ loss_fct = MSELoss()
1683
+ if self.num_labels == 1:
1684
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1685
+ else:
1686
+ loss = loss_fct(pooled_logits, labels)
1687
+ elif self.config.problem_type == "single_label_classification":
1688
+ loss_fct = CrossEntropyLoss()
1689
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1690
+ elif self.config.problem_type == "multi_label_classification":
1691
+ loss_fct = BCEWithLogitsLoss()
1692
+ loss = loss_fct(pooled_logits, labels)
1693
+ if not return_dict:
1694
+ output = (pooled_logits,) + transformer_outputs[1:]
1695
+ return ((loss,) + output) if loss is not None else output
1696
+
1697
+ return SequenceClassifierOutputWithPast(
1698
+ loss=loss,
1699
+ logits=pooled_logits,
1700
+ past_key_values=transformer_outputs.past_key_values,
1701
+ hidden_states=transformer_outputs.hidden_states,
1702
+ attentions=transformer_outputs.attentions,
1703
+ )
processing_qwen2_ts.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ if eots_token:
45
+ prompt += '<ts/>'
46
+
47
+ result_timeseries = np.stack([scaled_timeseries, np.ones_like(scaled_timeseries)], axis=-1).reshape(-1, 1)
48
+
49
+ return result_timeseries, prompt, {"offset": float(-mean), "scale_factor": float(scale_factor)}
50
+
51
+ class Qwen2TSProcessor(ProcessorMixin):
52
+ """
53
+ A processor for ChatTS that integrates text prompt processing and time series encoding.
54
+ """
55
+
56
+ attributes = ["tokenizer"]
57
+ feature_extractor_class = None # You can add a feature extractor if needed
58
+ tokenizer_class = "AutoTokenizer"
59
+
60
+ def __init__(self, tokenizer=None):
61
+ """
62
+ Args:
63
+ tokenizer: An optional tokenizer to process text prompts.
64
+ """
65
+ super().__init__(tokenizer=tokenizer)
66
+
67
+ def __call__(
68
+ self,
69
+ text: Union[str, List[str]],
70
+ timeseries: Optional[List[List[np.ndarray]]] = None,
71
+ padding: Union[bool, str, PaddingStrategy] = False,
72
+ padding_side: str = 'left',
73
+ vllm_flag: bool = False,
74
+ **kwargs,
75
+ ) -> BatchFeature:
76
+ """
77
+ Encodes a prompt and its associated time series.
78
+
79
+ Args:
80
+ prompt (List[str]): The input prompt containing <ts><ts/> placeholders.
81
+ timeseries (List[np.ndarray]): A list of time series matched to placeholders in the prompt.
82
+ padding (bool or str or PaddingStrategy, optional): Passed to the tokenizer for text padding.
83
+ return_tensors (str, optional): "pt" to return PyTorch tensors; None to return NumPy arrays.
84
+ **kwargs: Additional tokenizer parameters.
85
+
86
+ Returns:
87
+ BatchFeature: Contains processed prompt, encoded time series, and tokenizer outputs.
88
+ """
89
+ if type(text) == str:
90
+ text = [text]
91
+ if timeseries is None:
92
+ timeseries = []
93
+
94
+ reconstructed_prompts = []
95
+ concatenated_ts = None
96
+ ts_tokens = []
97
+
98
+ if vllm_flag:
99
+ # All prompt modifications have to be done inside of the vLLM
100
+ # to work correctly with its caching mechanism.
101
+ reconstructed_prompts = text
102
+
103
+ # Process timeseries data
104
+ encoded_ts_arrays = []
105
+ for ts in timeseries:
106
+ # Get the normalized data and prompt text
107
+ encoded_ts, ts_prompt, _ = sp_encoding(ts, eots_token=False)
108
+ # Tokenize the ts_prompt and add to the tokens list
109
+ if self.tokenizer is not None:
110
+ tokens = self.tokenizer.encode(ts_prompt, add_special_tokens=False)
111
+ ts_tokens.append(tokens)
112
+ encoded_ts_arrays.append(encoded_ts[None, ...])
113
+ else:
114
+ encoded_ts_arrays = []
115
+ total_ts_cnt = 0
116
+ for idx, prompt in enumerate(text):
117
+ # Split prompt by <ts><ts/> placeholders
118
+ last_ts_cnt = total_ts_cnt
119
+ prompt_segments = prompt.split("<ts><ts/>")
120
+ total_ts_cnt = total_ts_cnt + len(prompt_segments) - 1
121
+
122
+ # Encode each time series and rebuild the prompt
123
+ reconstructed_prompt = prompt_segments[0]
124
+
125
+ for i, ts in enumerate(timeseries[last_ts_cnt:total_ts_cnt]):
126
+ encoded_ts, ts_prompt, _ = sp_encoding(ts, eots_token=not vllm_flag)
127
+ reconstructed_prompt += ts_prompt + prompt_segments[i + 1]
128
+ # Ensure time series shape [1, seq_len, feature_dim] for batch concatenation
129
+ encoded_ts_arrays.append(encoded_ts[None, ...])
130
+
131
+ reconstructed_prompts.append(reconstructed_prompt)
132
+
133
+ if len(timeseries) != len(encoded_ts_arrays):
134
+ raise ValueError(
135
+ f"Mismatch between <ts><ts/> placeholders ({total_ts_cnt}) "
136
+ f"and time series ({len(encoded_ts_arrays)})."
137
+ )
138
+
139
+ if len(encoded_ts_arrays) > 0:
140
+ # Pad time series to the same length
141
+ max_length = max(ts.shape[1] for ts in encoded_ts_arrays)
142
+ padded_ts_arrays = [
143
+ np.pad(ts, ((0, 0), (0, max_length - ts.shape[1]), (0, 0)), mode="constant", constant_values=0.0)
144
+ for ts in encoded_ts_arrays
145
+ ]
146
+ concatenated_ts = np.concatenate(padded_ts_arrays, axis=0) # Shape: [batch_size, max_length, feature_dim]
147
+
148
+ # Convert to torch
149
+ concatenated_ts = torch.from_numpy(concatenated_ts).half()
150
+
151
+ # Tokenize the processed prompt
152
+ tokenizer_outputs = {}
153
+ if self.tokenizer is not None:
154
+ tokenizer_outputs = self.tokenizer(reconstructed_prompts, padding=padding, padding_side=padding_side, **kwargs)
155
+
156
+ # Create the final output
157
+ outputs = tokenizer_outputs
158
+ if vllm_flag:
159
+ outputs["timeseries"] = zip(ts_tokens, encoded_ts_arrays)
160
+ elif concatenated_ts is not None:
161
+ outputs["timeseries"] = concatenated_ts
162
+
163
+ return BatchFeature(data=outputs)
164
+
165
+ @property
166
+ def model_input_names(self):
167
+ """
168
+ Define the input names expected by the model.
169
+ """
170
+ tokenizer_input_names = []
171
+ if self.tokenizer and hasattr(self.tokenizer, "model_input_names"):
172
+ tokenizer_input_names = self.tokenizer.model_input_names
173
+ return list(dict.fromkeys(["processed_prompt", "time_series"] + tokenizer_input_names))
174
+
175
+ def batch_decode(self, *args, **kwargs):
176
+ """
177
+ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
178
+ refer to the docstring of this method for more information.
179
+ """
180
+ return self.tokenizer.batch_decode(*args, **kwargs)
181
+
182
+ def decode(self, *args, **kwargs):
183
+ """
184
+ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
185
+ the docstring of this method for more information.
186
+ """
187
+ return self.tokenizer.decode(*args, **kwargs)
recipe.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ default_stage:
2
+ default_modifiers:
3
+ GPTQModifier:
4
+ targets: [Linear]
5
+ ignore: ['re:.*lm_head', 're:ts_encoder.*']
6
+ scheme: W4A16
7
+ sequential_update: true
8
+ block_size: 128
9
+ dampening_frac: 0.01
10
+ offload_hessians: false
special_tokens_map.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<ts>",
4
+ "<ts/>"
5
+ ],
6
+ "eos_token": {
7
+ "content": "<|im_end|>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false
12
+ },
13
+ "pad_token": {
14
+ "content": "<|endoftext|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false
19
+ }
20
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c678dbd67903d89ef4157de91fbe836a3cd664026f67153e7c136262eea9dc52
3
+ size 11422253
tokenizer_config.json ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ],
202
+ "bos_token": null,
203
+ "chat_template": "{% 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\n' + system_message + '<|im_end|>\n' }}{% endif %}{% for message in messages %}{% set content = message['content'] %}{% if message['role'] == 'user' %}{{ '<|im_start|>user\n' + content + '<|im_end|>\n<|im_start|>assistant\n' }}{% elif message['role'] == 'assistant' %}{{ content + '<|im_end|>' + '\n' }}{% endif %}{% endfor %}",
204
+ "clean_up_tokenization_spaces": false,
205
+ "eos_token": "<|im_end|>",
206
+ "errors": "replace",
207
+ "model_max_length": 131072,
208
+ "pad_token": "<|endoftext|>",
209
+ "padding_side": "right",
210
+ "split_special_tokens": false,
211
+ "tokenizer_class": "Qwen2Tokenizer",
212
+ "unk_token": null
213
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff