ParadiseYu commited on
Commit
808dbb6
·
verified ·
1 Parent(s): 0b5d438

Upload folder using huggingface_hub

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
README.md ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ license: other
4
+ tags:
5
+ - llama-factory
6
+ - full
7
+ - generated_from_trainer
8
+ model-index:
9
+ - name: stage_2_align_120K_sft_25K
10
+ results: []
11
+ ---
12
+
13
+ <!-- This model card has been generated automatically according to the information the Trainer had access to. You
14
+ should probably proofread and complete it, then remove this comment. -->
15
+
16
+ # stage_2_align_120K_sft_25K
17
+
18
+ This model is a fine-tuned version of [/data/fangxu/output/stage_1_gpt_chrono_unfreeze](https://huggingface.co//data/fangxu/output/stage_1_gpt_chrono_unfreeze) on the stage_2_25K dataset.
19
+
20
+ ## Model description
21
+
22
+ More information needed
23
+
24
+ ## Intended uses & limitations
25
+
26
+ More information needed
27
+
28
+ ## Training and evaluation data
29
+
30
+ More information needed
31
+
32
+ ## Training procedure
33
+
34
+ ### Training hyperparameters
35
+
36
+ The following hyperparameters were used during training:
37
+ - learning_rate: 2e-05
38
+ - train_batch_size: 1
39
+ - eval_batch_size: 8
40
+ - seed: 42
41
+ - distributed_type: multi-GPU
42
+ - num_devices: 8
43
+ - gradient_accumulation_steps: 8
44
+ - total_train_batch_size: 64
45
+ - total_eval_batch_size: 64
46
+ - optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-08
47
+ - lr_scheduler_type: cosine
48
+ - lr_scheduler_warmup_ratio: 0.02
49
+ - num_epochs: 2.0
50
+
51
+ ### Training results
52
+
53
+
54
+
55
+ ### Framework versions
56
+
57
+ - Transformers 4.45.0
58
+ - Pytorch 2.6.0+cu124
59
+ - Datasets 2.20.0
60
+ - Tokenizers 0.20.3
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
+ }
all_results.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "epoch": 1.9968,
3
+ "total_flos": 440534549233664.0,
4
+ "train_loss": 0.46617485760496213,
5
+ "train_runtime": 27454.835,
6
+ "train_samples_per_second": 1.821,
7
+ "train_steps_per_second": 0.028
8
+ }
config.json ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/data/fangxu/output/stage_1_gpt_chrono_unfreeze",
3
+ "architectures": [
4
+ "Qwen2TSForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_qwen2.Qwen2TSConfig",
9
+ "AutoModel": "modeling_qwen2.Qwen2TSForCausalLM",
10
+ "AutoModelForCausalLM": "modeling_qwen2.Qwen2TSForCausalLM",
11
+ "AutoProcessor": "processing_qwen2_ts.Qwen2TSProcessor"
12
+ },
13
+ "bos_token_id": 151643,
14
+ "eos_token_id": 151645,
15
+ "hidden_act": "silu",
16
+ "hidden_size": 3584,
17
+ "ignore_index": -100,
18
+ "initializer_range": 0.02,
19
+ "intermediate_size": 18944,
20
+ "max_position_embeddings": 32768,
21
+ "max_window_layers": 28,
22
+ "model_type": "qwen2",
23
+ "num_attention_heads": 28,
24
+ "num_hidden_layers": 28,
25
+ "num_key_value_heads": 4,
26
+ "pad_token_id": 151643,
27
+ "rms_norm_eps": 1e-06,
28
+ "rope_theta": 1000000.0,
29
+ "sliding_window": 131072,
30
+ "stage_2": true,
31
+ "tie_word_embeddings": false,
32
+ "torch_dtype": "float32",
33
+ "train_from_scratch": true,
34
+ "transformers_version": "4.45.0",
35
+ "ts": {
36
+ "hidden_size": 3584,
37
+ "max_length": 2048,
38
+ "num_features": 2,
39
+ "num_layers": 2,
40
+ "patch_size": 32
41
+ },
42
+ "ts_config": {
43
+ "d_model": null,
44
+ "device": "cpu",
45
+ "model_kwargs": {},
46
+ "model_name": "MOMENT",
47
+ "patch_len": 8,
48
+ "patch_stride_len": 8,
49
+ "seq_len": 512,
50
+ "t5_config": {
51
+ "architectures": [
52
+ "T5ForConditionalGeneration"
53
+ ],
54
+ "d_ff": 2816,
55
+ "d_kv": 64,
56
+ "d_model": 1024,
57
+ "decoder_start_token_id": 0,
58
+ "dropout_rate": 0.1,
59
+ "eos_token_id": 1,
60
+ "feed_forward_proj": "gated-gelu",
61
+ "initializer_factor": 1.0,
62
+ "is_encoder_decoder": true,
63
+ "layer_norm_epsilon": 1e-06,
64
+ "model_type": "t5",
65
+ "n_positions": 512,
66
+ "num_decoder_layers": 24,
67
+ "num_heads": 16,
68
+ "num_layers": 24,
69
+ "output_past": true,
70
+ "pad_token_id": 0,
71
+ "relative_attention_max_distance": 128,
72
+ "relative_attention_num_buckets": 32,
73
+ "tie_word_embeddings": false,
74
+ "use_cache": true,
75
+ "vocab_size": 32128
76
+ },
77
+ "task_name": "reconstruction",
78
+ "transformer_backbone": "google/flan-t5-large",
79
+ "transformer_type": "encoder_only"
80
+ },
81
+ "ts_path": "AutonLab/MOMENT-1-large",
82
+ "ts_token_end_index": 151666,
83
+ "ts_token_start_index": 151665,
84
+ "use_cache": false,
85
+ "use_sliding_window": false,
86
+ "vocab_size": 152064
87
+ }
configuration_qwen2.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ train_from_scratch=False,
119
+ **kwargs,
120
+ ):
121
+ self.vocab_size = vocab_size
122
+ self.max_position_embeddings = max_position_embeddings
123
+ self.hidden_size = hidden_size
124
+ self.intermediate_size = intermediate_size
125
+ self.num_hidden_layers = num_hidden_layers
126
+ self.num_attention_heads = num_attention_heads
127
+ self.use_sliding_window = use_sliding_window
128
+ self.sliding_window = sliding_window
129
+ self.max_window_layers = max_window_layers
130
+
131
+ # for backward compatibility
132
+ if num_key_value_heads is None:
133
+ num_key_value_heads = num_attention_heads
134
+
135
+ self.num_key_value_heads = num_key_value_heads
136
+ self.hidden_act = hidden_act
137
+ self.initializer_range = initializer_range
138
+ self.rms_norm_eps = rms_norm_eps
139
+ self.use_cache = use_cache
140
+ self.rope_theta = rope_theta
141
+ self.attention_dropout = attention_dropout
142
+ self.train_from_scratch = train_from_scratch
143
+ super().__init__(
144
+ tie_word_embeddings=tie_word_embeddings,
145
+ **kwargs,
146
+ )
generation_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 151645,
6
+ 151643
7
+ ],
8
+ "pad_token_id": 151643,
9
+ "repetition_penalty": 1.05,
10
+ "temperature": 0.7,
11
+ "top_k": 20,
12
+ "top_p": 0.8,
13
+ "transformers_version": "4.45.0"
14
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
modeling_qwen2.py ADDED
@@ -0,0 +1,1988 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
30
+ from typing import List, Optional, Tuple, Union, Dict, Any
31
+ from dataclasses import dataclass
32
+ from matplotlib.dviread import Tfm
33
+ import timesfm
34
+ import torch
35
+ import torch.nn.functional as F
36
+ import torch.utils.checkpoint
37
+ from torch import nn
38
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
39
+
40
+ from transformers.activations import ACT2FN
41
+ from transformers.cache_utils import Cache, DynamicCache
42
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa
43
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
44
+ from transformers.modeling_utils import PreTrainedModel
45
+ from transformers import AutoConfig, CLIPVisionModel
46
+ from transformers.utils import (
47
+ add_start_docstrings,
48
+ add_start_docstrings_to_model_forward,
49
+ is_flash_attn_2_available,
50
+ is_flash_attn_greater_or_equal_2_10,
51
+ logging,
52
+ replace_return_docstrings,
53
+ ModelOutput
54
+ )
55
+ from .configuration_qwen2 import Qwen2TSConfig
56
+ from momentfm import MOMENTPipeline
57
+ # from .modeling_tinytimemixer import TinyTimeMixerForPrediction
58
+ # from .configuration_tinytimemixer import TinyTimeMixerConfig
59
+
60
+ if is_flash_attn_2_available():
61
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
62
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
63
+
64
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
65
+
66
+
67
+ logger = logging.get_logger(__name__)
68
+
69
+ _CHECKPOINT_FOR_DOC = "Qwen/Qwen2-7B-beta"
70
+ _CONFIG_FOR_DOC = "Qwen2TSConfig"
71
+
72
+
73
+ @dataclass
74
+ class Qwen2TSCausalLMOutputWithPast(ModelOutput):
75
+ """
76
+ Base class for Qwen2TS causal language model (or autoregressive) outputs.
77
+
78
+ Args:
79
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
80
+ Language modeling loss (for next-token prediction).
81
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
82
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
83
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
84
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
85
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
86
+
87
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
88
+ `past_key_values` input) to speed up sequential decoding.
89
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
90
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
91
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
92
+
93
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
94
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
95
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
96
+ sequence_length)`.
97
+
98
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
99
+ heads.
100
+ attention_mask (`torch.FloatTensor`, *optional*):
101
+ Attentions mask, used to update attention mask and position_ids.
102
+ """
103
+
104
+ loss: Optional[torch.FloatTensor] = None
105
+ logits: torch.FloatTensor = None
106
+ past_key_values: Optional[List[torch.FloatTensor]] = None
107
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
108
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
109
+ attention_mask: Optional[torch.FloatTensor] = None
110
+
111
+ ########################Naive TS Embedding#####################
112
+ class TimeSeriesEmbedding(nn.Module):
113
+ def __init__(self, config):
114
+ super(TimeSeriesEmbedding, self).__init__()
115
+ self.patch_size = config['patch_size']
116
+ # self.patch_size = 64
117
+ self.num_layers = config['num_layers']
118
+ # self.num_layers = 2
119
+ self.hidden_size = config['hidden_size']
120
+ self.num_features = config['num_features']
121
+ # self.tfm = tfm
122
+ layers = []
123
+ # input_size = 1 * self.patch_size
124
+ # input_size = 1024
125
+ input_size = 1280
126
+
127
+ for _ in range(self.num_layers - 1):
128
+ layers.append(nn.Linear(input_size, self.hidden_size))
129
+ layers.append(nn.GELU())
130
+ input_size = self.hidden_size
131
+ layers.append(nn.Linear(input_size, self.hidden_size))
132
+
133
+ self.mlp = nn.Sequential(*layers)
134
+ # self.mlp.to(torch.bfloat16)
135
+
136
+ # def forward(self, x: torch.Tensor):
137
+ # device = x.device
138
+ # if next(self.timesfm.parameters()).device != device:
139
+ # # self.timesfm = self.timesfm.to(device, dtype=x.dtype)
140
+ # self.timesfm.to(device, dtype=x.dtype)
141
+ # batch_size = x.size(0)
142
+ # x = x.reshape(batch_size, -1, self.num_features)
143
+ # # print(x.shape)
144
+ # mask = x[:, :, -1]
145
+ # valid_lengths = mask.sum(dim=1).long() # Shape: (batch_size)
146
+
147
+ # patch_cnt = (valid_lengths + self.patch_size - 1) // self.patch_size # 向上取整
148
+
149
+ # patches_list = []
150
+ # mask_list = []
151
+ # for i in range(batch_size):
152
+ # vl = valid_lengths[i].item()
153
+ # pc = patch_cnt[i].item()
154
+ # if pc == 0:
155
+ # continue
156
+ # xi = x[i, :vl, :1]
157
+ # mask_i = x[i, :vl, 1:]
158
+ # # total_padded_length = pc * self.patch_size
159
+ # total_padded_length = valid_lengths.max()
160
+ # padding_length = total_padded_length - vl
161
+ # if padding_length > 0:
162
+ # padding = torch.zeros(padding_length, 1, device=x.device, dtype=x.dtype)
163
+ # xi = torch.cat([xi, padding], dim=0)
164
+ # mask_i = torch.cat([mask_i, padding], dim=0)
165
+ # # mask = torch.ones_like()
166
+ # # xi = xi.reshape(pc, self.patch_size * 1) # 几个patch * patch_size
167
+ # # print(xi.shape)
168
+ # mask_list.append(mask_i.squeeze().unsqueeze(0).unsqueeze(0))
169
+ # patches_list.append(xi.squeeze().unsqueeze(0).unsqueeze(0))
170
+
171
+ # if patches_list:
172
+ # min_patch_size = min([patches_list[i].shape[2] for i in range(len(patches_list))])
173
+ # patches_list = [patches_list[i][:, :, :min_patch_size] for i in range(len(patches_list))]
174
+ # mask_list = [mask_list[i][:, :, :min_patch_size] for i in range(len(mask_list))]
175
+ # # for i in range(len(patches_list)):
176
+ # # print(f"patches_list[{i}].shape", patches_list[i].shape)
177
+ # x_patches = torch.cat(patches_list, dim=0) # Shape: (total_patch_cnt, patch_size * num_features)
178
+ # mask = torch.cat(mask_list, dim=0)
179
+ # # x = self.mlp(x_patches)
180
+ # # print("x_patches.shape", x_patches.shape)
181
+ # # print("mask", mask.shape)
182
+ # x_patches = x_patches.to(x.device, dtype=next(self.timesfm.parameters()).dtype)
183
+ # x_patches.requires_grad_(True)
184
+ # mask = mask.squeeze(1).to(x.device, dtype=next(self.timesfm.parameters()).dtype)
185
+ # mask.requires_grad_(True)
186
+ # # for name, param in self.timesfm.patch_embedding.named_parameters():
187
+ # # print(f"[timesfm param] {name}: {param.dtype}")
188
+ # output = self.timesfm(x_enc=x_patches, input_mask=mask, reduction="none")
189
+ # # print(output)
190
+ # embeddings = output.embeddings
191
+ # embeddings = embeddings.squeeze(1)
192
+ # real_embeddings = []
193
+ # for i in range(embeddings.shape[0]):
194
+ # if patch_cnt[i] > embeddings.shape[1]:
195
+ # patch_cnt[i] = embeddings.shape[1]
196
+ # real_embeddings.append(embeddings[i, :patch_cnt[i], :])
197
+ # real_embeddings = torch.cat(real_embeddings, dim=0)
198
+ # # if sum(patch_cnt) != real_embeddings.shape[0]:
199
+ # # print("sum(patch_cnt)", sum(patch_cnt))
200
+ # # print("embeddings.shape[0]", real_embeddings.shape[0])
201
+ # # print("embeddings.shape", embeddings.shape)
202
+ # # for j in range(patch_cnt.shape[0]):
203
+ # # print("patch_cnt[j]", patch_cnt[j])
204
+ # # print("embeddings[j, :patch_cnt[j], :].shape", embeddings[j, :patch_cnt[j], :].shape)
205
+ # # for j in range(patch_cnt.shape[0]):
206
+ # # patch_cnt[j] = x_patches.shape[1]
207
+ # # print("before reshape", x.shape)
208
+ # # embeddings = embeddings.reshape(-1, 1024)
209
+ # # print("after reshape", x.shape)
210
+ # # print("output.dtype", embeddings.dtype)
211
+ # # print("self.mlp.parameters().dtype", next(self.mlp.parameters()).dtype)
212
+ # # print("real_embeddings.shape", real_embeddings.shape)
213
+ # real_embeddings = real_embeddings.to(next(self.mlp.parameters()).dtype)
214
+ # x = self.mlp(real_embeddings)
215
+ # else:
216
+ # x = torch.empty(0, self.hidden_size, device=x.device)
217
+ # # print("x.shape, patch_cnt", x.shape, patch_cnt)
218
+ # return x, patch_cnt
219
+
220
+ def forward(self, x: torch.Tensor):
221
+ self.timesfm._model.to(x.device)
222
+ self.timesfm._device = x.device
223
+ batch_size = x.size(0)
224
+ x = x.reshape(batch_size, -1, self.num_features)
225
+ # print(x.shape)
226
+ mask = x[:, :, -1]
227
+ valid_lengths = mask.sum(dim=1).long() # Shape: (batch_size)
228
+
229
+ patch_cnt = (valid_lengths + self.patch_size - 1) // self.patch_size # 向上取整
230
+
231
+ patches_list = []
232
+ embedding_list = []
233
+ xi_s = []
234
+ for i in range(batch_size):
235
+ vl = valid_lengths[i].item()
236
+ pc = patch_cnt[i].item()
237
+ if pc == 0:
238
+ continue
239
+ xi = x[i, :vl, 0].cpu().numpy()
240
+ xi_s.append(xi)
241
+ patch_cnt[i] = 512 // self.patch_size
242
+
243
+ embedding, t_input_ts, t_input_padding = self.timesfm.forecast(xi_s)
244
+ embedding = [emb.squeeze(0) for emb in embedding]
245
+ embedding_list = torch.cat(embedding, dim=0) # Shape: (total_patch_cnt, patch_size * num_features)
246
+ embedding_list = embedding_list.to(x.device, dtype=x.dtype)
247
+ x = self.mlp(embedding_list)
248
+ return x, patch_cnt
249
+
250
+ # def forward(self, x: torch.Tensor):
251
+
252
+ # batch_size = x.size(0)
253
+ # x = x.reshape(batch_size, -1, self.num_features)
254
+ # # print(x.shape)
255
+ # mask = x[:, :, -1]
256
+ # valid_lengths = mask.sum(dim=1).long() # Shape: (batch_size)
257
+
258
+ # patch_cnt = (valid_lengths + self.patch_size - 1) // self.patch_size # 向上取整
259
+
260
+ # patches_list = []
261
+ # for i in range(batch_size):
262
+ # vl = valid_lengths[i].item()
263
+ # pc = patch_cnt[i].item()
264
+ # if pc == 0:
265
+ # continue
266
+ # xi = x[i, :vl, :1]
267
+ # total_padded_length = pc * self.patch_size
268
+ # padding_length = total_padded_length - vl
269
+ # if padding_length > 0:
270
+ # padding = torch.zeros(padding_length, 1, device=x.device, dtype=x.dtype)
271
+ # xi = torch.cat([xi, padding], dim=0)
272
+ # xi = xi.reshape(pc, self.patch_size * 1) # 几个patch * patch_size
273
+ # patches_list.append(xi)
274
+
275
+ # if patches_list:
276
+ # x_patches = torch.cat(patches_list, dim=0) # Shape: (total_patch_cnt, patch_size * num_features)
277
+ # print("x_patches.shape", x_patches.shape)
278
+ # x = self.mlp(x_patches)
279
+ # print("x.shape", x.shape)
280
+ # else:
281
+ # x = torch.empty(0, self.hidden_size, device=x.device)
282
+ # # print("x.shape, patch_cnt", x.shape, patch_cnt)
283
+ # return x, patch_cnt
284
+
285
+
286
+ ########################QWEN2###################################
287
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
288
+ def _get_unpad_data(attention_mask):
289
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
290
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
291
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
292
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
293
+ return (
294
+ indices,
295
+ cu_seqlens,
296
+ max_seqlen_in_batch,
297
+ )
298
+
299
+
300
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Qwen2
301
+ class Qwen2RMSNorm(nn.Module):
302
+ def __init__(self, hidden_size, eps=1e-6):
303
+ """
304
+ Qwen2RMSNorm is equivalent to T5LayerNorm
305
+ """
306
+ super().__init__()
307
+ self.weight = nn.Parameter(torch.ones(hidden_size))
308
+ self.variance_epsilon = eps
309
+
310
+ def forward(self, hidden_states):
311
+ input_dtype = hidden_states.dtype
312
+ hidden_states = hidden_states.to(torch.float32)
313
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
314
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
315
+ return self.weight * hidden_states.to(input_dtype)
316
+
317
+
318
+ # Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->Qwen2
319
+ class Qwen2RotaryEmbedding(nn.Module):
320
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
321
+ super().__init__()
322
+
323
+ self.dim = dim
324
+ self.max_position_embeddings = max_position_embeddings
325
+ self.base = base
326
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
327
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
328
+
329
+ # Build here to make `torch.jit.trace` work.
330
+ self._set_cos_sin_cache(
331
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
332
+ )
333
+
334
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
335
+ self.max_seq_len_cached = seq_len
336
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
337
+
338
+ freqs = torch.outer(t, self.inv_freq)
339
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
340
+ emb = torch.cat((freqs, freqs), dim=-1)
341
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
342
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
343
+
344
+ def forward(self, x, seq_len=None):
345
+ # x: [bs, num_attention_heads, seq_len, head_size]
346
+ if seq_len > self.max_seq_len_cached:
347
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
348
+
349
+ return (
350
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
351
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
352
+ )
353
+
354
+
355
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
356
+ def rotate_half(x):
357
+ """Rotates half the hidden dims of the input."""
358
+ x1 = x[..., : x.shape[-1] // 2]
359
+ x2 = x[..., x.shape[-1] // 2 :]
360
+ return torch.cat((-x2, x1), dim=-1)
361
+
362
+
363
+ # Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
364
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
365
+ """Applies Rotary Position Embedding to the query and key tensors.
366
+
367
+ Args:
368
+ q (`torch.Tensor`): The query tensor.
369
+ k (`torch.Tensor`): The key tensor.
370
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
371
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
372
+ position_ids (`torch.Tensor`):
373
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
374
+ used to pass offsetted position ids when working with a KV-cache.
375
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
376
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
377
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
378
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
379
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
380
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
381
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
382
+ Returns:
383
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
384
+ """
385
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
386
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
387
+ q_embed = (q * cos) + (rotate_half(q) * sin)
388
+ k_embed = (k * cos) + (rotate_half(k) * sin)
389
+ return q_embed, k_embed
390
+
391
+
392
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Qwen2
393
+ class Qwen2MLP(nn.Module):
394
+ def __init__(self, config):
395
+ super().__init__()
396
+ self.config = config
397
+ self.hidden_size = config.hidden_size
398
+ self.intermediate_size = config.intermediate_size
399
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
400
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
401
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
402
+ self.act_fn = ACT2FN[config.hidden_act]
403
+
404
+ def forward(self, x):
405
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
406
+
407
+
408
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
409
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
410
+ """
411
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
412
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
413
+ """
414
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
415
+ if n_rep == 1:
416
+ return hidden_states
417
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
418
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
419
+
420
+
421
+ class Qwen2Attention(nn.Module):
422
+ """
423
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
424
+ and "Generating Long Sequences with Sparse Transformers".
425
+ """
426
+
427
+ def __init__(self, config: Qwen2TSConfig, layer_idx: Optional[int] = None):
428
+ super().__init__()
429
+ self.config = config
430
+ self.layer_idx = layer_idx
431
+ if layer_idx is None:
432
+ logger.warning_once(
433
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
434
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
435
+ "when creating this class."
436
+ )
437
+
438
+ self.hidden_size = config.hidden_size
439
+ self.num_heads = config.num_attention_heads
440
+ self.head_dim = self.hidden_size // self.num_heads
441
+ self.num_key_value_heads = config.num_key_value_heads
442
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
443
+ self.max_position_embeddings = config.max_position_embeddings
444
+ self.rope_theta = config.rope_theta
445
+ self.is_causal = True
446
+ self.attention_dropout = config.attention_dropout
447
+
448
+ if (self.head_dim * self.num_heads) != self.hidden_size:
449
+ raise ValueError(
450
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
451
+ f" and `num_heads`: {self.num_heads})."
452
+ )
453
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
454
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
455
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
456
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
457
+
458
+ self.rotary_emb = Qwen2RotaryEmbedding(
459
+ self.head_dim,
460
+ max_position_embeddings=self.max_position_embeddings,
461
+ base=self.rope_theta,
462
+ )
463
+
464
+ def forward(
465
+ self,
466
+ hidden_states: torch.Tensor,
467
+ attention_mask: Optional[torch.Tensor] = None,
468
+ position_ids: Optional[torch.LongTensor] = None,
469
+ past_key_value: Optional[Cache] = None,
470
+ output_attentions: bool = False,
471
+ use_cache: bool = False,
472
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
473
+ bsz, q_len, _ = hidden_states.size()
474
+
475
+ query_states = self.q_proj(hidden_states)
476
+ key_states = self.k_proj(hidden_states)
477
+ value_states = self.v_proj(hidden_states)
478
+
479
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
480
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
481
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
482
+
483
+ kv_seq_len = key_states.shape[-2]
484
+ if past_key_value is not None:
485
+ if self.layer_idx is None:
486
+ raise ValueError(
487
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
488
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
489
+ "with a layer index."
490
+ )
491
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
492
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
493
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
494
+
495
+ if past_key_value is not None:
496
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
497
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
498
+
499
+ # repeat k/v heads if n_kv_heads < n_heads
500
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
501
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
502
+
503
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
504
+
505
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
506
+ raise ValueError(
507
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
508
+ f" {attn_weights.size()}"
509
+ )
510
+
511
+ if attention_mask is not None:
512
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
513
+ raise ValueError(
514
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
515
+ )
516
+
517
+ attn_weights = attn_weights + attention_mask
518
+
519
+ # upcast attention to fp32
520
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
521
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
522
+ attn_output = torch.matmul(attn_weights, value_states)
523
+
524
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
525
+ raise ValueError(
526
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
527
+ f" {attn_output.size()}"
528
+ )
529
+
530
+ attn_output = attn_output.transpose(1, 2).contiguous()
531
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
532
+
533
+ attn_output = self.o_proj(attn_output)
534
+
535
+ if not output_attentions:
536
+ attn_weights = None
537
+
538
+ return attn_output, attn_weights, past_key_value
539
+
540
+
541
+ class Qwen2FlashAttention2(Qwen2Attention):
542
+ """
543
+ Qwen2 flash attention module, following Qwen2 attention module. This module inherits from `Qwen2Attention`
544
+ as the weights of the module stays untouched. The only required change would be on the forward pass
545
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
546
+ in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
547
+ config.max_window_layers layers.
548
+ """
549
+
550
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
551
+ def __init__(self, *args, **kwargs):
552
+ super().__init__(*args, **kwargs)
553
+
554
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
555
+ # 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.
556
+ # 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).
557
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
558
+
559
+ def forward(
560
+ self,
561
+ hidden_states: torch.Tensor,
562
+ attention_mask: Optional[torch.Tensor] = None,
563
+ position_ids: Optional[torch.LongTensor] = None,
564
+ past_key_value: Optional[Cache] = None,
565
+ output_attentions: bool = False,
566
+ use_cache: bool = False,
567
+ ):
568
+ bsz, q_len, _ = hidden_states.size()
569
+
570
+ query_states = self.q_proj(hidden_states)
571
+ key_states = self.k_proj(hidden_states)
572
+ value_states = self.v_proj(hidden_states)
573
+
574
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
575
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
576
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
577
+
578
+ kv_seq_len = key_states.shape[-2]
579
+ if past_key_value is not None:
580
+ if self.layer_idx is None:
581
+ raise ValueError(
582
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
583
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
584
+ "with a layer index."
585
+ )
586
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
587
+
588
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
589
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
590
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
591
+
592
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
593
+
594
+ use_sliding_windows = (
595
+ _flash_supports_window_size
596
+ and getattr(self.config, "sliding_window", None) is not None
597
+ and kv_seq_len > self.config.sliding_window
598
+ and self.config.use_sliding_window
599
+ )
600
+
601
+ if not _flash_supports_window_size:
602
+ logger.warning_once(
603
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
604
+ " make sure to upgrade flash-attn library."
605
+ )
606
+
607
+ if past_key_value is not None:
608
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
609
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
610
+ if (
611
+ getattr(self.config, "sliding_window", None) is not None
612
+ and kv_seq_len > self.config.sliding_window
613
+ and cache_has_contents
614
+ ):
615
+ slicing_tokens = 1 - self.config.sliding_window
616
+
617
+ past_key = past_key_value[self.layer_idx][0]
618
+ past_value = past_key_value[self.layer_idx][1]
619
+
620
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
621
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
622
+
623
+ if past_key.shape[-2] != self.config.sliding_window - 1:
624
+ raise ValueError(
625
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
626
+ f" {past_key.shape}"
627
+ )
628
+
629
+ if attention_mask is not None:
630
+ attention_mask = attention_mask[:, slicing_tokens:]
631
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
632
+
633
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
634
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
635
+
636
+ # repeat k/v heads if n_kv_heads < n_heads
637
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
638
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
639
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
640
+
641
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
642
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
643
+ # cast them back in float16 just to be sure everything works as expected.
644
+ input_dtype = query_states.dtype
645
+ if input_dtype == torch.float32:
646
+ if torch.is_autocast_enabled():
647
+ target_dtype = torch.get_autocast_gpu_dtype()
648
+ # Handle the case where the model is quantized
649
+ elif hasattr(self.config, "_pre_quantization_dtype"):
650
+ target_dtype = self.config._pre_quantization_dtype
651
+ else:
652
+ target_dtype = self.q_proj.weight.dtype
653
+
654
+ logger.warning_once(
655
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
656
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
657
+ f" {target_dtype}."
658
+ )
659
+
660
+ query_states = query_states.to(target_dtype)
661
+ key_states = key_states.to(target_dtype)
662
+ value_states = value_states.to(target_dtype)
663
+
664
+ # Reashape to the expected shape for Flash Attention
665
+ query_states = query_states.transpose(1, 2)
666
+ key_states = key_states.transpose(1, 2)
667
+ value_states = value_states.transpose(1, 2)
668
+
669
+ attn_output = self._flash_attention_forward(
670
+ query_states,
671
+ key_states,
672
+ value_states,
673
+ attention_mask,
674
+ q_len,
675
+ dropout=dropout_rate,
676
+ use_sliding_windows=use_sliding_windows,
677
+ )
678
+
679
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
680
+ attn_output = self.o_proj(attn_output)
681
+
682
+ if not output_attentions:
683
+ attn_weights = None
684
+
685
+ return attn_output, attn_weights, past_key_value
686
+
687
+ def _flash_attention_forward(
688
+ self,
689
+ query_states,
690
+ key_states,
691
+ value_states,
692
+ attention_mask,
693
+ query_length,
694
+ dropout=0.0,
695
+ softmax_scale=None,
696
+ use_sliding_windows=False,
697
+ ):
698
+ """
699
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
700
+ first unpad the input, then computes the attention scores and pad the final attention scores.
701
+
702
+ Args:
703
+ query_states (`torch.Tensor`):
704
+ Input query states to be passed to Flash Attention API
705
+ key_states (`torch.Tensor`):
706
+ Input key states to be passed to Flash Attention API
707
+ value_states (`torch.Tensor`):
708
+ Input value states to be passed to Flash Attention API
709
+ attention_mask (`torch.Tensor`):
710
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
711
+ position of padding tokens and 1 for the position of non-padding tokens.
712
+ dropout (`float`):
713
+ Attention dropout
714
+ softmax_scale (`float`, *optional*):
715
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
716
+ use_sliding_windows (`bool`, *optional*):
717
+ Whether to activate sliding window attention.
718
+ """
719
+ if not self._flash_attn_uses_top_left_mask:
720
+ causal = self.is_causal
721
+ else:
722
+ # 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__.
723
+ causal = self.is_causal and query_length != 1
724
+
725
+ # Decide whether to use SWA or not by layer index.
726
+ if use_sliding_windows and self.layer_idx >= self.config.max_window_layers:
727
+ use_sliding_windows = False
728
+
729
+ # Contains at least one padding token in the sequence
730
+ if attention_mask is not None:
731
+ batch_size = query_states.shape[0]
732
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
733
+ query_states, key_states, value_states, attention_mask, query_length
734
+ )
735
+
736
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
737
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
738
+
739
+ if not use_sliding_windows:
740
+ attn_output_unpad = flash_attn_varlen_func(
741
+ query_states,
742
+ key_states,
743
+ value_states,
744
+ cu_seqlens_q=cu_seqlens_q,
745
+ cu_seqlens_k=cu_seqlens_k,
746
+ max_seqlen_q=max_seqlen_in_batch_q,
747
+ max_seqlen_k=max_seqlen_in_batch_k,
748
+ dropout_p=dropout,
749
+ softmax_scale=softmax_scale,
750
+ causal=causal,
751
+ )
752
+ else:
753
+ attn_output_unpad = flash_attn_varlen_func(
754
+ query_states,
755
+ key_states,
756
+ value_states,
757
+ cu_seqlens_q=cu_seqlens_q,
758
+ cu_seqlens_k=cu_seqlens_k,
759
+ max_seqlen_q=max_seqlen_in_batch_q,
760
+ max_seqlen_k=max_seqlen_in_batch_k,
761
+ dropout_p=dropout,
762
+ softmax_scale=softmax_scale,
763
+ causal=causal,
764
+ window_size=(self.config.sliding_window, self.config.sliding_window),
765
+ )
766
+
767
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
768
+ else:
769
+ if not use_sliding_windows:
770
+ attn_output = flash_attn_func(
771
+ query_states,
772
+ key_states,
773
+ value_states,
774
+ dropout,
775
+ softmax_scale=softmax_scale,
776
+ causal=causal,
777
+ )
778
+ else:
779
+ attn_output = flash_attn_func(
780
+ query_states,
781
+ key_states,
782
+ value_states,
783
+ dropout,
784
+ softmax_scale=softmax_scale,
785
+ causal=causal,
786
+ window_size=(self.config.sliding_window, self.config.sliding_window),
787
+ )
788
+
789
+ return attn_output
790
+
791
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
792
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
793
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
794
+
795
+ # On the first iteration we need to properly re-create the padding mask
796
+ # by slicing it on the proper place
797
+ if kv_seq_len != attention_mask.shape[-1]:
798
+ attention_mask_num_tokens = attention_mask.shape[-1]
799
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
800
+
801
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
802
+
803
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
804
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
805
+
806
+ if query_length == kv_seq_len:
807
+ query_layer = index_first_axis(
808
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
809
+ )
810
+ cu_seqlens_q = cu_seqlens_k
811
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
812
+ indices_q = indices_k
813
+ elif query_length == 1:
814
+ max_seqlen_in_batch_q = 1
815
+ cu_seqlens_q = torch.arange(
816
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
817
+ ) # There is a memcpy here, that is very bad.
818
+ indices_q = cu_seqlens_q[:-1]
819
+ query_layer = query_layer.squeeze(1)
820
+ else:
821
+ # The -q_len: slice assumes left padding.
822
+ attention_mask = attention_mask[:, -query_length:]
823
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
824
+
825
+ return (
826
+ query_layer,
827
+ key_layer,
828
+ value_layer,
829
+ indices_q,
830
+ (cu_seqlens_q, cu_seqlens_k),
831
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
832
+ )
833
+
834
+
835
+ # Copied from transformers.models.mistral.modeling_mistral.MistralSdpaAttention with Mistral->Qwen2
836
+ class Qwen2SdpaAttention(Qwen2Attention):
837
+ """
838
+ Qwen2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
839
+ `Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
840
+ SDPA API.
841
+ """
842
+
843
+ # Adapted from Qwen2Attention.forward
844
+ def forward(
845
+ self,
846
+ hidden_states: torch.Tensor,
847
+ attention_mask: Optional[torch.Tensor] = None,
848
+ position_ids: Optional[torch.LongTensor] = None,
849
+ past_key_value: Optional[Cache] = None,
850
+ output_attentions: bool = False,
851
+ use_cache: bool = False,
852
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
853
+ if output_attentions:
854
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
855
+ logger.warning_once(
856
+ "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, "
857
+ '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.'
858
+ )
859
+ return super().forward(
860
+ hidden_states=hidden_states,
861
+ attention_mask=attention_mask,
862
+ position_ids=position_ids,
863
+ past_key_value=past_key_value,
864
+ output_attentions=output_attentions,
865
+ use_cache=use_cache,
866
+ )
867
+
868
+ bsz, q_len, _ = hidden_states.size()
869
+
870
+ query_states = self.q_proj(hidden_states)
871
+ key_states = self.k_proj(hidden_states)
872
+ value_states = self.v_proj(hidden_states)
873
+
874
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
875
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
876
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
877
+
878
+ kv_seq_len = key_states.shape[-2]
879
+ if past_key_value is not None:
880
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
881
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
882
+
883
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
884
+
885
+ if past_key_value is not None:
886
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
887
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
888
+
889
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
890
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
891
+
892
+ if attention_mask is not None:
893
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
894
+ raise ValueError(
895
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
896
+ )
897
+
898
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
899
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
900
+ if query_states.device.type == "cuda" and attention_mask is not None:
901
+ query_states = query_states.contiguous()
902
+ key_states = key_states.contiguous()
903
+ value_states = value_states.contiguous()
904
+
905
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
906
+ query_states,
907
+ key_states,
908
+ value_states,
909
+ attn_mask=attention_mask,
910
+ dropout_p=self.attention_dropout if self.training else 0.0,
911
+ # 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.
912
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
913
+ )
914
+
915
+ attn_output = attn_output.transpose(1, 2).contiguous()
916
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
917
+
918
+ attn_output = self.o_proj(attn_output)
919
+
920
+ return attn_output, None, past_key_value
921
+
922
+
923
+ QWEN2_ATTENTION_CLASSES = {
924
+ "eager": Qwen2Attention,
925
+ "flash_attention_2": Qwen2FlashAttention2,
926
+ "sdpa": Qwen2SdpaAttention,
927
+ }
928
+
929
+
930
+ class Qwen2DecoderLayer(nn.Module):
931
+ def __init__(self, config: Qwen2TSConfig, layer_idx: int):
932
+ super().__init__()
933
+ self.hidden_size = config.hidden_size
934
+
935
+ if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
936
+ logger.warning_once(
937
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
938
+ "unexpected results may be encountered."
939
+ )
940
+ self.self_attn = QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
941
+
942
+ self.mlp = Qwen2MLP(config)
943
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
944
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
945
+
946
+ def forward(
947
+ self,
948
+ hidden_states: torch.Tensor,
949
+ attention_mask: Optional[torch.Tensor] = None,
950
+ position_ids: Optional[torch.LongTensor] = None,
951
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
952
+ output_attentions: Optional[bool] = False,
953
+ use_cache: Optional[bool] = False,
954
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
955
+ """
956
+ Args:
957
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
958
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
959
+ `(batch, sequence_length)` where padding elements are indicated by 0.
960
+ output_attentions (`bool`, *optional*):
961
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
962
+ returned tensors for more detail.
963
+ use_cache (`bool`, *optional*):
964
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
965
+ (see `past_key_values`).
966
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
967
+ """
968
+
969
+ residual = hidden_states
970
+
971
+ hidden_states = self.input_layernorm(hidden_states)
972
+
973
+ # Self Attention
974
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
975
+ hidden_states=hidden_states,
976
+ attention_mask=attention_mask,
977
+ position_ids=position_ids,
978
+ past_key_value=past_key_value,
979
+ output_attentions=output_attentions,
980
+ use_cache=use_cache,
981
+ )
982
+ hidden_states = residual + hidden_states
983
+
984
+ # Fully Connected
985
+ residual = hidden_states
986
+ hidden_states = self.post_attention_layernorm(hidden_states)
987
+ hidden_states = self.mlp(hidden_states)
988
+ hidden_states = residual + hidden_states
989
+
990
+ outputs = (hidden_states,)
991
+
992
+ if output_attentions:
993
+ outputs += (self_attn_weights,)
994
+
995
+ if use_cache:
996
+ outputs += (present_key_value,)
997
+
998
+ return outputs
999
+
1000
+
1001
+ QWEN2_START_DOCSTRING = r"""
1002
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1003
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1004
+ etc.)
1005
+
1006
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1007
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1008
+ and behavior.
1009
+
1010
+ Parameters:
1011
+ config ([`Qwen2TSConfig`]):
1012
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1013
+ load the weights associated with the model, only the configuration. Check out the
1014
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1015
+ """
1016
+
1017
+
1018
+ @add_start_docstrings(
1019
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
1020
+ QWEN2_START_DOCSTRING,
1021
+ )
1022
+ class Qwen2PreTrainedModel(PreTrainedModel):
1023
+ config_class = Qwen2TSConfig
1024
+ base_model_prefix = "model"
1025
+ supports_gradient_checkpointing = True
1026
+ _no_split_modules = ["Qwen2DecoderLayer"]
1027
+ _skip_keys_device_placement = "past_key_values"
1028
+ _supports_flash_attn_2 = True
1029
+ _supports_sdpa = True
1030
+ _supports_cache_class = True
1031
+
1032
+ def _init_weights(self, module):
1033
+ std = self.config.initializer_range
1034
+ if isinstance(module, nn.Linear):
1035
+ module.weight.data.normal_(mean=0.0, std=std)
1036
+ if module.bias is not None:
1037
+ module.bias.data.zero_()
1038
+ elif isinstance(module, nn.Embedding):
1039
+ module.weight.data.normal_(mean=0.0, std=std)
1040
+ if module.padding_idx is not None:
1041
+ module.weight.data[module.padding_idx].zero_()
1042
+
1043
+
1044
+ class TSProjector(nn.Module):
1045
+ def __init__(self, config: Qwen2TSConfig):
1046
+ super().__init__()
1047
+ self.config = config
1048
+ self.linear_1 = nn.Linear(config.ts['d_model'], config.hidden_size, bias=True)
1049
+ self.linear_2 = nn.LayerNorm(config.hidden_size, bias=True)
1050
+ self.linear_3 = nn.Linear(config.hidden_size, config.hidden_size * 4, bias=True)
1051
+ self.linear_4 = nn.LayerNorm(config.hidden_size * 4, bias=True)
1052
+ self.act = nn.GELU()
1053
+
1054
+ def forward(self, ts_features):
1055
+ hidden_states = self.linear_1(ts_features)
1056
+ hidden_states = self.linear_2(hidden_states)
1057
+ hidden_states = self.act(hidden_states)
1058
+ hidden_states = self.linear_3(hidden_states)
1059
+ hidden_states = self.linear_4(hidden_states)
1060
+ hidden_states = hidden_states.reshape(hidden_states.size(0), -1, self.config.hidden_size)
1061
+ return hidden_states
1062
+
1063
+
1064
+ QWEN2_INPUTS_DOCSTRING = r"""
1065
+ Args:
1066
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1067
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1068
+ it.
1069
+
1070
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1071
+ [`PreTrainedTokenizer.__call__`] for details.
1072
+
1073
+ [What are input IDs?](../glossary#input-ids)
1074
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1075
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1076
+
1077
+ - 1 for tokens that are **not masked**,
1078
+ - 0 for tokens that are **masked**.
1079
+
1080
+ [What are attention masks?](../glossary#attention-mask)
1081
+
1082
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1083
+ [`PreTrainedTokenizer.__call__`] for details.
1084
+
1085
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
1086
+ `past_key_values`).
1087
+
1088
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1089
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1090
+ information on the default strategy.
1091
+
1092
+ - 1 indicates the head is **not masked**,
1093
+ - 0 indicates the head is **masked**.
1094
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1095
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1096
+ config.n_positions - 1]`.
1097
+
1098
+ [What are position IDs?](../glossary#position-ids)
1099
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1100
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1101
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1102
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1103
+
1104
+ Two formats are allowed:
1105
+ - a [`~cache_utils.Cache`] instance;
1106
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1107
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1108
+ cache format.
1109
+
1110
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1111
+ legacy cache format will be returned.
1112
+
1113
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1114
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1115
+ of shape `(batch_size, sequence_length)`.
1116
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1117
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1118
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1119
+ model's internal embedding lookup matrix.
1120
+ use_cache (`bool`, *optional*):
1121
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1122
+ `past_key_values`).
1123
+ output_attentions (`bool`, *optional*):
1124
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1125
+ tensors for more detail.
1126
+ output_hidden_states (`bool`, *optional*):
1127
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1128
+ more detail.
1129
+ return_dict (`bool`, *optional*):
1130
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1131
+ """
1132
+
1133
+
1134
+ @add_start_docstrings(
1135
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
1136
+ QWEN2_START_DOCSTRING,
1137
+ )
1138
+ class Qwen2Model(Qwen2PreTrainedModel):
1139
+ """
1140
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
1141
+
1142
+ Args:
1143
+ config: Qwen2TSConfig
1144
+ """
1145
+
1146
+ def __init__(self, config: Qwen2TSConfig):
1147
+ super().__init__(config)
1148
+ self.padding_idx = config.pad_token_id
1149
+ self.vocab_size = config.vocab_size
1150
+
1151
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1152
+ self.layers = nn.ModuleList(
1153
+ [Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1154
+ )
1155
+ self._attn_implementation = config._attn_implementation
1156
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1157
+
1158
+ self.gradient_checkpointing = False
1159
+
1160
+ # Initialize weights and apply final processing
1161
+ self.post_init()
1162
+
1163
+ def get_input_embeddings(self):
1164
+ return self.embed_tokens
1165
+
1166
+ def set_input_embeddings(self, value):
1167
+ self.embed_tokens = value
1168
+
1169
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1170
+ def forward(
1171
+ self,
1172
+ input_ids: torch.LongTensor = None,
1173
+ attention_mask: Optional[torch.Tensor] = None,
1174
+ position_ids: Optional[torch.LongTensor] = None,
1175
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1176
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1177
+ use_cache: Optional[bool] = None,
1178
+ output_attentions: Optional[bool] = None,
1179
+ output_hidden_states: Optional[bool] = None,
1180
+ return_dict: Optional[bool] = None,
1181
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1182
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1183
+ output_hidden_states = (
1184
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1185
+ )
1186
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1187
+
1188
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1189
+
1190
+ # retrieve input_ids and inputs_embeds
1191
+ if input_ids is not None and inputs_embeds is not None:
1192
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
1193
+ elif input_ids is not None:
1194
+ batch_size, seq_length = input_ids.shape
1195
+ elif inputs_embeds is not None:
1196
+ batch_size, seq_length, _ = inputs_embeds.shape
1197
+ else:
1198
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
1199
+
1200
+ if self.gradient_checkpointing and self.training:
1201
+ if use_cache:
1202
+ logger.warning_once(
1203
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1204
+ )
1205
+ use_cache = False
1206
+
1207
+ past_key_values_length = 0
1208
+
1209
+ if use_cache:
1210
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1211
+ if use_legacy_cache:
1212
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1213
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1214
+
1215
+ if position_ids is None:
1216
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1217
+ position_ids = torch.arange(
1218
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1219
+ )
1220
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1221
+ else:
1222
+ position_ids = position_ids.view(-1, seq_length).long()
1223
+
1224
+ if inputs_embeds is None:
1225
+ inputs_embeds = self.embed_tokens(input_ids)
1226
+
1227
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1228
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1229
+ if is_padding_right:
1230
+ raise ValueError(
1231
+ "You are attempting to perform batched generation with padding_side='right'"
1232
+ " this may lead to unexpected behaviour for Flash Attention version of Qwen2. Make sure to "
1233
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1234
+ )
1235
+
1236
+ if self._attn_implementation == "flash_attention_2":
1237
+ # 2d mask is passed through the layers
1238
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1239
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1240
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1241
+ # the manual implementation that requires a 4D causal mask in all cases.
1242
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1243
+ attention_mask,
1244
+ (batch_size, seq_length),
1245
+ inputs_embeds,
1246
+ past_key_values_length,
1247
+ sliding_window=self.config.sliding_window,
1248
+ )
1249
+ else:
1250
+ # 4d mask is passed through the layers
1251
+ attention_mask = _prepare_4d_causal_attention_mask(
1252
+ attention_mask,
1253
+ (batch_size, seq_length),
1254
+ inputs_embeds,
1255
+ past_key_values_length,
1256
+ sliding_window=self.config.sliding_window,
1257
+ )
1258
+
1259
+ hidden_states = inputs_embeds
1260
+
1261
+ # decoder layers
1262
+ all_hidden_states = () if output_hidden_states else None
1263
+ all_self_attns = () if output_attentions else None
1264
+ next_decoder_cache = None
1265
+
1266
+ for decoder_layer in self.layers:
1267
+ if output_hidden_states:
1268
+ all_hidden_states += (hidden_states,)
1269
+
1270
+ if self.gradient_checkpointing and self.training:
1271
+ layer_outputs = self._gradient_checkpointing_func(
1272
+ decoder_layer.__call__,
1273
+ hidden_states,
1274
+ attention_mask,
1275
+ position_ids,
1276
+ past_key_values,
1277
+ output_attentions,
1278
+ use_cache,
1279
+ )
1280
+ else:
1281
+ layer_outputs = decoder_layer(
1282
+ hidden_states,
1283
+ attention_mask=attention_mask,
1284
+ position_ids=position_ids,
1285
+ past_key_value=past_key_values,
1286
+ output_attentions=output_attentions,
1287
+ use_cache=use_cache,
1288
+ )
1289
+
1290
+ hidden_states = layer_outputs[0]
1291
+
1292
+ if use_cache:
1293
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1294
+
1295
+ if output_attentions:
1296
+ all_self_attns += (layer_outputs[1],)
1297
+
1298
+ hidden_states = self.norm(hidden_states)
1299
+
1300
+ # add hidden states from the last decoder layer
1301
+ if output_hidden_states:
1302
+ all_hidden_states += (hidden_states,)
1303
+
1304
+ next_cache = None
1305
+ if use_cache:
1306
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1307
+
1308
+ if not return_dict:
1309
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1310
+ return BaseModelOutputWithPast(
1311
+ last_hidden_state=hidden_states,
1312
+ past_key_values=next_cache,
1313
+ hidden_states=all_hidden_states,
1314
+ attentions=all_self_attns,
1315
+ )
1316
+
1317
+
1318
+ class Qwen2TSForCausalLM(Qwen2PreTrainedModel):
1319
+ _tied_weights_keys = ["lm_head.weight"]
1320
+
1321
+ def __init__(self, config):
1322
+ super().__init__(config)
1323
+ self.config = config
1324
+
1325
+ self.model = Qwen2Model(config)
1326
+ # self.model.gradient_checkpointing = True
1327
+ # self.model.eval()
1328
+
1329
+ if not config.stage_2:
1330
+ self.model.train()
1331
+ for param in self.model.parameters():
1332
+ param.requires_grad = True
1333
+ else:
1334
+ for param in self.model.parameters():
1335
+ param.requires_grad = True
1336
+ self.vocab_size = config.vocab_size
1337
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1338
+ # TS embedding
1339
+ if not config.stage_2:
1340
+ for param in self.lm_head.parameters():
1341
+ param.requires_grad = True
1342
+ else:
1343
+ for param in self.lm_head.parameters():
1344
+ param.requires_grad = True
1345
+ self.ts_encoder = TimeSeriesEmbedding(config.ts)
1346
+ # if config.train_from_scratch:
1347
+ # logger.info("loading vision model from pretrained")
1348
+ # # self.vision_tower = CLIPVisionModel.from_pretrained("openai/clip-vit-large-patch14-336")
1349
+ # self.tfm = MOMENTPipeline.from_pretrained(
1350
+ # config.ts_path,
1351
+ # model_kwargs={'task_name': 'embedding'}, # We are loading the model in `embedding` mode to learn representations
1352
+ # # local_files_only=True, # Whether or not to only look at local files (i.e., do not try to download the model).
1353
+ # )
1354
+ # self.tfm.init()
1355
+
1356
+ # else:
1357
+ # self.tfm = MOMENTPipeline(
1358
+ # config.ts_config,
1359
+ # model_kwargs={'task_name': 'embedding'}, # We are loading the model in `embedding` mode to learn representations
1360
+ # # local_files_only=True, # Whether or not to only look at local files (i.e., do not try to download the model).
1361
+ # )
1362
+ # self.tfm.init()
1363
+ # self.ts_encoder.tfm = Tfm
1364
+ # Initialize weights and apply final processing
1365
+ self.post_init()
1366
+
1367
+ def get_input_embeddings(self):
1368
+ return self.model.embed_tokens
1369
+
1370
+ def set_input_embeddings(self, value):
1371
+ self.model.embed_tokens = value
1372
+
1373
+ def get_output_embeddings(self):
1374
+ return self.lm_head
1375
+
1376
+ def set_output_embeddings(self, new_embeddings):
1377
+ self.lm_head = new_embeddings
1378
+
1379
+ def set_decoder(self, decoder):
1380
+ self.model = decoder
1381
+
1382
+ def get_decoder(self):
1383
+ return self.model
1384
+ # def _merge_input_ids_with_time_series_features(
1385
+ # self, time_series_features, inputs_embeds, input_ids, attention_mask, labels, patch_cnt
1386
+ # ):
1387
+ # batch_size, sequence_length = input_ids.shape
1388
+ # _left_padding = torch.any(attention_mask[:, 0] == 0)
1389
+ # _right_padding = torch.any(attention_mask[:, -1] == 0)
1390
+ # left_padding = False
1391
+ # if batch_size > 1:
1392
+ # if _left_padding and not _right_padding:
1393
+ # left_padding = True
1394
+ # elif not _left_padding and _right_padding:
1395
+ # left_padding = False
1396
+ # elif not _left_padding and not _right_padding:
1397
+ # left_padding = False
1398
+ # else:
1399
+ # raise ValueError(f"both side of attention_mask has zero, invalid. {attention_mask}")
1400
+ # else:
1401
+ # if _left_padding and not _right_padding:
1402
+ # left_padding = True
1403
+ # else:
1404
+ # left_padding = False
1405
+
1406
+ # # 1. Create a mask to know where special time series tokens are
1407
+ # special_ts_token_mask_start = input_ids == self.config.ts_token_start_index
1408
+ # special_ts_token_mask_end = input_ids == self.config.ts_token_end_index
1409
+ # special_ts_token_mask = special_ts_token_mask_start | special_ts_token_mask_end
1410
+
1411
+ # # 2. Calculate patch count
1412
+ # num_special_ts_tokens = torch.sum(special_ts_token_mask_start, dim=-1)
1413
+ # total_time_steps, embed_dim = time_series_features.shape
1414
+
1415
+ # # Correctly calculate the total number of patches per batch
1416
+ # patch_index = 0
1417
+ # num_total_patches = torch.zeros(batch_size, dtype=patch_cnt.dtype, device=patch_cnt.device)
1418
+ # special_ts_token_mask_start_nonzero = special_ts_token_mask_start.nonzero()
1419
+ # special_ts_token_mask_start_with_size = special_ts_token_mask_start.clone().long()
1420
+
1421
+ # attn_mask_cnt = attention_mask.sum(dim=-1)
1422
+ # for i in range(batch_size):
1423
+ # num_ts_in_batch = num_special_ts_tokens[i]
1424
+ # num_total_patches[i] = patch_cnt[patch_index : patch_index + num_ts_in_batch].sum() - 2 * num_ts_in_batch
1425
+ # for idx in range(patch_index, patch_index + num_ts_in_batch):
1426
+ # b_idx, pos = special_ts_token_mask_start_nonzero[idx]
1427
+ # special_ts_token_mask_start_with_size[b_idx, pos] *= (patch_cnt[idx].item() - 2)
1428
+ # patch_index += num_ts_in_batch
1429
+ # attn_mask_cnt[i] += num_total_patches[i].item()
1430
+
1431
+ # # 3. Embeding length
1432
+ # max_embed_dim = sequence_length + num_total_patches.max()
1433
+
1434
+ # # 4. Non ts tokens
1435
+ # batch_indices, non_ts_indices = torch.where(~special_ts_token_mask)
1436
+
1437
+ # # 5. Text token in final text positions
1438
+ # new_token_positions = torch.cumsum((special_ts_token_mask_start_with_size + 1), dim=-1) - 1
1439
+
1440
+ # # nb_ts_pad
1441
+ # nb_ts_pad = max_embed_dim - 1 - new_token_positions[:, -1]
1442
+ # if left_padding:
1443
+ # new_token_positions += nb_ts_pad[:, None]
1444
+
1445
+ # text_to_overwrite = new_token_positions[batch_indices, non_ts_indices]
1446
+
1447
+ # # 6. Final embedding and attention masks
1448
+ # final_embedding = torch.zeros(
1449
+ # batch_size, max_embed_dim, embed_dim, dtype=inputs_embeds.dtype, device=inputs_embeds.device
1450
+ # )
1451
+
1452
+ # final_attention_mask = torch.zeros(batch_size, max_embed_dim, dtype=attention_mask.dtype, device=inputs_embeds.device)
1453
+ # for i in range(attention_mask.size(0)):
1454
+ # if left_padding:
1455
+ # final_attention_mask[i, max_embed_dim - attn_mask_cnt[i] :] = 1
1456
+ # else:
1457
+ # final_attention_mask[i, : attn_mask_cnt[i]] = 1
1458
+
1459
+ # final_labels = None
1460
+ # if labels is not None:
1461
+ # final_labels = torch.full(
1462
+ # (batch_size, max_embed_dim), self.config.ignore_index, dtype=input_ids.dtype, device=input_ids.device
1463
+ # )
1464
+
1465
+ # target_device = inputs_embeds.device
1466
+ # batch_indices, non_ts_indices, text_to_overwrite = (
1467
+ # batch_indices.to(target_device),
1468
+ # non_ts_indices.to(target_device),
1469
+ # text_to_overwrite.to(target_device),
1470
+ # )
1471
+
1472
+ # # 7. Move embedding and labels to final positions
1473
+ # final_embedding[batch_indices, text_to_overwrite] = inputs_embeds[batch_indices, non_ts_indices]
1474
+ # if labels is not None:
1475
+ # final_labels[batch_indices, text_to_overwrite] = labels[batch_indices, non_ts_indices]
1476
+
1477
+ # # 8. Move time series to final positions
1478
+ # ts_to_overwrite = torch.full(
1479
+ # (batch_size, max_embed_dim), True, dtype=torch.bool, device=inputs_embeds.device
1480
+ # )
1481
+ # ts_to_overwrite[batch_indices, text_to_overwrite] = False
1482
+
1483
+ # reversed_cumsum = ts_to_overwrite.flip(dims=[-1]).cumsum(-1).flip(dims=[-1]) - 1
1484
+ # ts_to_overwrite &= reversed_cumsum >= nb_ts_pad[:, None].to(target_device)
1485
+
1486
+ # # Check that the number of time series tokens is correct
1487
+ # if ts_to_overwrite.sum() != time_series_features.shape[:-1].numel():
1488
+ # raise ValueError(
1489
+ # f"The input provided to the model are wrong. The number of time series tokens is {torch.sum(special_ts_token_mask_start)} while"
1490
+ # f" the number of time series given to the model is {len(patch_cnt)}. This prevents correct indexing and breaks batch generation."
1491
+ # )
1492
+ # final_embedding[ts_to_overwrite] = time_series_features.contiguous().reshape(-1, embed_dim).to(target_device)
1493
+
1494
+ # # 9. Calculate position ids
1495
+ # position_ids = (final_attention_mask.cumsum(-1) - 1).masked_fill_((final_attention_mask == 0), 1)
1496
+ # if position_ids.size(-1) < input_ids.size(-1):
1497
+ # position_ids = position_ids[:, -input_ids.size(-1) :]
1498
+
1499
+ # # 10. Move attention mask to final positions
1500
+ # pad_batch_indices, pad_indices = torch.where(input_ids == self.config.pad_token_id)
1501
+ # if len(pad_batch_indices) > 0:
1502
+ # indices_to_mask = new_token_positions[pad_batch_indices, pad_indices]
1503
+ # final_embedding[pad_batch_indices, indices_to_mask] = 0
1504
+
1505
+ # return final_embedding, final_attention_mask, position_ids, final_labels
1506
+
1507
+ def _merge_input_ids_with_time_series_features(
1508
+ self, time_series_features, inputs_embeds, input_ids, attention_mask, labels, patch_cnt
1509
+ ):
1510
+ # print("inputs_embeds.shape, cuda:{}".format(inputs_embeds.device), inputs_embeds.shape)
1511
+ # print("patch_cnt, cuda:{}".format(patch_cnt.device), patch_cnt)
1512
+ # print("time_series_features.shape, cuda:{}".format(time_series_features.device), time_series_features.shape)
1513
+
1514
+ batch_size, sequence_length = input_ids.shape
1515
+ _left_padding = torch.any(attention_mask[:, 0] == 0)
1516
+ _right_padding = torch.any(attention_mask[:, -1] == 0)
1517
+ left_padding = False
1518
+ if batch_size > 1:
1519
+ if _left_padding and not _right_padding:
1520
+ left_padding = True
1521
+ elif not _left_padding and _right_padding:
1522
+ left_padding = False
1523
+ elif not _left_padding and not _right_padding:
1524
+ left_padding = False
1525
+ else:
1526
+ raise ValueError(f"both side of attention_mask has zero, invalid. {attention_mask}")
1527
+ else:
1528
+ if _left_padding and not _right_padding:
1529
+ left_padding = True
1530
+ else:
1531
+ left_padding = False
1532
+
1533
+ # 1. Create a mask to know where special time series tokens are
1534
+ special_ts_token_mask_start = input_ids == self.config.ts_token_start_index # Batchsize * sequence_length
1535
+ special_ts_token_mask_end = input_ids == self.config.ts_token_end_index
1536
+ special_ts_token_mask = special_ts_token_mask_start | special_ts_token_mask_end # True -> ts_token
1537
+ # 2. Calculate patch count
1538
+ num_special_ts_tokens = torch.sum(special_ts_token_mask_start, dim=-1)
1539
+ total_time_steps, embed_dim = time_series_features.shape # num_patches, token_embedding
1540
+
1541
+ # Correctly calculate the total number of patches per batch
1542
+ patch_index = 0
1543
+ num_total_patches = torch.zeros(batch_size, dtype=patch_cnt.dtype, device=patch_cnt.device)
1544
+ special_ts_token_mask_start_nonzero = special_ts_token_mask_start.nonzero() # [num_ts_tokens, 2] <ts>位置的索引
1545
+ special_ts_token_mask_start_with_size = special_ts_token_mask_start.clone().long() # <ts>的位置,True False表示
1546
+
1547
+ attn_mask_cnt = attention_mask.sum(dim=-1)
1548
+ for i in range(batch_size):
1549
+ num_ts_in_batch = num_special_ts_tokens[i] # 当前batch有几个<ts>
1550
+ num_total_patches[i] = patch_cnt[patch_index : patch_index + num_ts_in_batch].sum() - 2 * num_ts_in_batch # 当前batch有几个patch
1551
+ for idx in range(patch_index, patch_index + num_ts_in_batch):
1552
+ b_idx, pos = special_ts_token_mask_start_nonzero[idx]
1553
+ special_ts_token_mask_start_with_size[b_idx, pos] *= (patch_cnt[idx].item() - 2) # 当前这一个<ts>需要插入多少个patch
1554
+
1555
+ patch_index += num_ts_in_batch
1556
+ attn_mask_cnt[i] += num_total_patches[i].item()
1557
+
1558
+ # 3. Embeding length
1559
+ max_embed_dim = sequence_length + num_total_patches.max()
1560
+
1561
+ # 4. Non ts tokens
1562
+ batch_indices, non_ts_indices = torch.where(~special_ts_token_mask)
1563
+
1564
+ # 5. Text token in final text positions
1565
+ new_token_positions = torch.cumsum((special_ts_token_mask_start_with_size + 1), dim=-1) - 1
1566
+
1567
+ # nb_ts_pad
1568
+ nb_ts_pad = max_embed_dim - 1 - new_token_positions[:, -1]
1569
+ if left_padding:
1570
+ new_token_positions += nb_ts_pad[:, None]
1571
+
1572
+ text_to_overwrite = new_token_positions[batch_indices, non_ts_indices]
1573
+
1574
+ # 6. Final embedding and attention masks
1575
+ final_embedding = torch.zeros(
1576
+ batch_size, max_embed_dim, embed_dim, dtype=inputs_embeds.dtype, device=inputs_embeds.device
1577
+ )
1578
+
1579
+ final_attention_mask = torch.zeros(batch_size, max_embed_dim, dtype=attention_mask.dtype, device=inputs_embeds.device)
1580
+ for i in range(attention_mask.size(0)):
1581
+ if left_padding:
1582
+ final_attention_mask[i, max_embed_dim - attn_mask_cnt[i] :] = 1
1583
+ else:
1584
+ final_attention_mask[i, : attn_mask_cnt[i]] = 1
1585
+
1586
+ final_labels = None
1587
+ if labels is not None:
1588
+ final_labels = torch.full(
1589
+ (batch_size, max_embed_dim), self.config.ignore_index, dtype=input_ids.dtype, device=input_ids.device
1590
+ )
1591
+
1592
+ target_device = inputs_embeds.device
1593
+ batch_indices, non_ts_indices, text_to_overwrite = (
1594
+ batch_indices.to(target_device),
1595
+ non_ts_indices.to(target_device),
1596
+ text_to_overwrite.to(target_device),
1597
+ )
1598
+
1599
+ # 7. Move embedding and labels to final positions
1600
+ final_embedding[batch_indices, text_to_overwrite] = inputs_embeds[batch_indices, non_ts_indices]
1601
+ if labels is not None:
1602
+ final_labels[batch_indices, text_to_overwrite] = labels[batch_indices, non_ts_indices]
1603
+
1604
+ # 8. Move time series to final positions
1605
+ ts_to_overwrite = torch.full(
1606
+ (batch_size, max_embed_dim), True, dtype=torch.bool, device=inputs_embeds.device
1607
+ )
1608
+ ts_to_overwrite[batch_indices, text_to_overwrite] = False
1609
+
1610
+ reversed_cumsum = ts_to_overwrite.flip(dims=[-1]).cumsum(-1).flip(dims=[-1]) - 1
1611
+ ts_to_overwrite &= reversed_cumsum >= nb_ts_pad[:, None].to(target_device)
1612
+
1613
+ # Check that the number of time series tokens is correct
1614
+ # print("ts_to_overwrite.sum(), time_series_features.shape[:-1].numel()", ts_to_overwrite.sum(), time_series_features.shape[:-1].numel())
1615
+ # print("ts_to_overwrite.sum(), len(patch_cnt)", ts_to_overwrite.sum(), len(patch_cnt))
1616
+ if ts_to_overwrite.sum() != time_series_features.shape[:-1].numel():
1617
+ raise ValueError(
1618
+ f"The input provided to the model are wrong. The number of time series tokens is {torch.sum(special_ts_token_mask_start)} while"
1619
+ f" the number of time series given to the model is {len(patch_cnt)}. This prevents correct indexing and breaks batch generation."
1620
+ )
1621
+ final_embedding[ts_to_overwrite] = time_series_features.contiguous().reshape(-1, embed_dim).to(target_device)
1622
+
1623
+ # 9. Calculate position ids
1624
+ position_ids = (final_attention_mask.cumsum(-1) - 1).masked_fill_((final_attention_mask == 0), 1)
1625
+ if position_ids.size(-1) < input_ids.size(-1):
1626
+ position_ids = position_ids[:, -input_ids.size(-1) :]
1627
+
1628
+ # 10. Move attention mask to final positions
1629
+ pad_batch_indices, pad_indices = torch.where(input_ids == self.config.pad_token_id)
1630
+ if len(pad_batch_indices) > 0:
1631
+ indices_to_mask = new_token_positions[pad_batch_indices, pad_indices]
1632
+ final_embedding[pad_batch_indices, indices_to_mask] = 0
1633
+
1634
+ # print("final_embedding.shape, cuda:{}".format(final_embedding.device), final_embedding.shape)
1635
+ # print("final_attention_mask.shape, cuda:{}".format(final_attention_mask.device), final_attention_mask.shape)
1636
+ # print("position_ids.shape, cuda:{}".format(position_ids.device), position_ids.shape)
1637
+ # print("final_labels.shape, cuda:{}".format(final_labels.device), final_labels.shape)
1638
+
1639
+ return final_embedding, final_attention_mask, position_ids, final_labels
1640
+
1641
+ # print(decoded_text)
1642
+
1643
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1644
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1645
+ def forward(
1646
+ self,
1647
+ input_ids: torch.LongTensor = None,
1648
+ timeseries: torch.FloatTensor = None,
1649
+ attention_mask: Optional[torch.Tensor] = None,
1650
+ position_ids: Optional[torch.LongTensor] = None,
1651
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1652
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1653
+ labels: Optional[torch.LongTensor] = None,
1654
+ use_cache: Optional[bool] = None,
1655
+ output_attentions: Optional[bool] = None,
1656
+ output_hidden_states: Optional[bool] = None,
1657
+ return_dict: Optional[bool] = None,
1658
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1659
+ r"""
1660
+ Args:
1661
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1662
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1663
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1664
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1665
+
1666
+ Returns:
1667
+
1668
+ Example:
1669
+
1670
+ ```python
1671
+ >>> from transformers import AutoTokenizer, Qwen2ForCausalLM
1672
+
1673
+ >>> model = Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1674
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1675
+
1676
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1677
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1678
+
1679
+ >>> # Generate
1680
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1681
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1682
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1683
+ ```"""
1684
+
1685
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1686
+ output_hidden_states = (
1687
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1688
+ )
1689
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1690
+
1691
+ if inputs_embeds is None:
1692
+ inputs_embeds = self.get_input_embeddings()(input_ids)
1693
+
1694
+ if timeseries is not None and timeseries.shape[0] > 0:
1695
+ # use_cache = False
1696
+ ts_features, patch_cnt = self.ts_encoder(timeseries)
1697
+ inputs_embeds = inputs_embeds.to(ts_features.dtype)
1698
+
1699
+ inputs_embeds, attention_mask, position_ids, labels = self._merge_input_ids_with_time_series_features(
1700
+ ts_features, inputs_embeds, input_ids, attention_mask, labels, patch_cnt
1701
+ )
1702
+
1703
+ outputs = self.model(
1704
+ attention_mask=attention_mask,
1705
+ position_ids=position_ids,
1706
+ past_key_values=past_key_values,
1707
+ inputs_embeds=inputs_embeds,
1708
+ use_cache=use_cache,
1709
+ output_attentions=output_attentions,
1710
+ output_hidden_states=output_hidden_states,
1711
+ return_dict=return_dict,
1712
+ )
1713
+
1714
+ hidden_states = outputs[0]
1715
+ logits = self.lm_head(hidden_states)
1716
+ logits = logits.float()
1717
+
1718
+ loss = None
1719
+ if labels is not None:
1720
+ # Shift so that tokens < n predict n
1721
+ shift_logits = logits[..., :-1, :].contiguous()
1722
+ shift_labels = labels[..., 1:].contiguous()
1723
+ # Flatten the tokens
1724
+ loss_fct = CrossEntropyLoss()
1725
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1726
+ shift_labels = shift_labels.view(-1)
1727
+ # Enable model parallelism
1728
+ shift_labels = shift_labels.to(shift_logits.device)
1729
+ loss = loss_fct(shift_logits, shift_labels)
1730
+
1731
+ if not return_dict:
1732
+ output = (logits,) + outputs[1:]
1733
+ return (loss,) + output if loss is not None else output
1734
+
1735
+
1736
+ return Qwen2TSCausalLMOutputWithPast(
1737
+ loss=loss,
1738
+ logits=logits,
1739
+ past_key_values=outputs.past_key_values,
1740
+ hidden_states=outputs.hidden_states,
1741
+ attentions=outputs.attentions,
1742
+ attention_mask=attention_mask
1743
+ )
1744
+
1745
+ def _update_model_kwargs_for_generation(
1746
+ self,
1747
+ outputs: ModelOutput,
1748
+ model_kwargs: Dict[str, Any],
1749
+ is_encoder_decoder: bool = False,
1750
+ num_new_tokens: int = 1,
1751
+ ) -> Dict[str, Any]:
1752
+ # update past_key_values keeping its naming used in model code
1753
+ cache_name, cache = self._extract_past_from_model_output(outputs)
1754
+ model_kwargs[cache_name] = cache
1755
+ if getattr(outputs, "state", None) is not None:
1756
+ model_kwargs["state"] = outputs.state
1757
+
1758
+ # update attention_mask
1759
+ if getattr(outputs, "attention_mask", None) is not None:
1760
+ model_kwargs["attention_mask"] = outputs.attention_mask
1761
+
1762
+ # update token_type_ids with last value
1763
+ if "token_type_ids" in model_kwargs:
1764
+ token_type_ids = model_kwargs["token_type_ids"]
1765
+ model_kwargs["token_type_ids"] = torch.cat([token_type_ids, token_type_ids[:, -1].unsqueeze(-1)], dim=-1)
1766
+
1767
+ if not is_encoder_decoder:
1768
+ # update attention mask
1769
+ if "attention_mask" in model_kwargs:
1770
+ attention_mask = model_kwargs["attention_mask"]
1771
+ model_kwargs["attention_mask"] = torch.cat(
1772
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
1773
+ )
1774
+ else:
1775
+ # update decoder attention mask
1776
+ if "decoder_attention_mask" in model_kwargs:
1777
+ decoder_attention_mask = model_kwargs["decoder_attention_mask"]
1778
+ model_kwargs["decoder_attention_mask"] = torch.cat(
1779
+ [decoder_attention_mask, decoder_attention_mask.new_ones((decoder_attention_mask.shape[0], 1))],
1780
+ dim=-1,
1781
+ )
1782
+
1783
+ if model_kwargs.get("use_cache", True):
1784
+ model_kwargs["cache_position"] = model_kwargs["cache_position"][-1:] + num_new_tokens
1785
+ else:
1786
+ past_positions = model_kwargs.pop("cache_position")
1787
+ new_positions = torch.arange(
1788
+ past_positions[-1] + 1, past_positions[-1] + num_new_tokens + 1, dtype=past_positions.dtype
1789
+ ).to(past_positions.device)
1790
+ model_kwargs["cache_position"] = torch.cat((past_positions, new_positions))
1791
+ return model_kwargs
1792
+
1793
+ def prepare_inputs_for_generation(
1794
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, timeseries=None, **kwargs
1795
+ ):
1796
+ # Omit tokens covered by past_key_values
1797
+ if past_key_values is not None:
1798
+ if isinstance(past_key_values, Cache):
1799
+ cache_length = past_key_values.get_seq_length()
1800
+ past_length = past_key_values.get_seq_length() # Fixed for transformers 4.44.2
1801
+ max_cache_length = None # Fixed: get_max_length() does not exist in DynamicCache
1802
+ else:
1803
+ cache_length = past_length = past_key_values[0][0].shape[2]
1804
+ max_cache_length = None
1805
+
1806
+ has_ts = timeseries is not None and len(timeseries) > 0
1807
+
1808
+ if has_ts and kwargs.get("attention_mask") is not None:
1809
+ attention_mask = kwargs["attention_mask"]
1810
+ attention_mask = torch.cat(
1811
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
1812
+ )
1813
+
1814
+ # Set attention mask and input_ids
1815
+ if has_ts and past_length > 0:
1816
+ # We have only one token added and timeseries are already inferenced
1817
+ input_ids = input_ids[:, -1:]
1818
+ timeseries = None
1819
+ elif attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1820
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1821
+ elif past_length < input_ids.shape[1]:
1822
+ input_ids = input_ids[:, past_length:]
1823
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1824
+
1825
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1826
+ if (
1827
+ max_cache_length is not None
1828
+ and attention_mask is not None
1829
+ and cache_length + input_ids.size(1) > max_cache_length
1830
+ ):
1831
+ attention_mask = attention_mask[:, -max_cache_length:]
1832
+
1833
+ position_ids = kwargs.get("position_ids", None)
1834
+ if attention_mask is not None and position_ids is None:
1835
+ # create position_ids on the fly for batch generation
1836
+ position_ids = attention_mask.long().cumsum(-1) - 1
1837
+ position_ids.masked_fill_(attention_mask == 0, 1)
1838
+ if past_key_values:
1839
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1840
+
1841
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1842
+ if inputs_embeds is not None and past_key_values is None:
1843
+ model_inputs = {"inputs_embeds": inputs_embeds}
1844
+ else:
1845
+ model_inputs = {"input_ids": input_ids}
1846
+
1847
+ model_inputs.update(
1848
+ {
1849
+ "position_ids": position_ids,
1850
+ "past_key_values": past_key_values,
1851
+ "use_cache": kwargs.get("use_cache"),
1852
+ "attention_mask": attention_mask,
1853
+ "timeseries": timeseries
1854
+ }
1855
+ )
1856
+ return model_inputs
1857
+
1858
+ @staticmethod
1859
+ def _reorder_cache(past_key_values, beam_idx):
1860
+ reordered_past = ()
1861
+ for layer_past in past_key_values:
1862
+ reordered_past += (
1863
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1864
+ )
1865
+ return reordered_past
1866
+
1867
+
1868
+ @add_start_docstrings(
1869
+ """
1870
+ The Qwen2 Model transformer with a sequence classification head on top (linear layer).
1871
+
1872
+ [`Qwen2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1873
+ (e.g. GPT-2) do.
1874
+
1875
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1876
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1877
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1878
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1879
+ each row of the batch).
1880
+ """,
1881
+ QWEN2_START_DOCSTRING,
1882
+ )
1883
+ class Qwen2ForSequenceClassification(Qwen2PreTrainedModel):
1884
+ def __init__(self, config):
1885
+ super().__init__(config)
1886
+ self.num_labels = config.num_labels
1887
+ self.model = Qwen2Model(config)
1888
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1889
+
1890
+ # Initialize weights and apply final processing
1891
+ self.post_init()
1892
+
1893
+ def get_input_embeddings(self):
1894
+ return self.model.embed_tokens
1895
+
1896
+ def set_input_embeddings(self, value):
1897
+ self.model.embed_tokens = value
1898
+
1899
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1900
+ def forward(
1901
+ self,
1902
+ input_ids: torch.LongTensor = None,
1903
+ attention_mask: Optional[torch.Tensor] = None,
1904
+ position_ids: Optional[torch.LongTensor] = None,
1905
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1906
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1907
+ labels: Optional[torch.LongTensor] = None,
1908
+ use_cache: Optional[bool] = None,
1909
+ output_attentions: Optional[bool] = None,
1910
+ output_hidden_states: Optional[bool] = None,
1911
+ return_dict: Optional[bool] = None,
1912
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1913
+ r"""
1914
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1915
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1916
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1917
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1918
+ """
1919
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1920
+
1921
+ transformer_outputs = self.model(
1922
+ input_ids,
1923
+ attention_mask=attention_mask,
1924
+ position_ids=position_ids,
1925
+ past_key_values=past_key_values,
1926
+ inputs_embeds=inputs_embeds,
1927
+ use_cache=use_cache,
1928
+ output_attentions=output_attentions,
1929
+ output_hidden_states=output_hidden_states,
1930
+ return_dict=return_dict,
1931
+ )
1932
+ hidden_states = transformer_outputs[0]
1933
+ logits = self.score(hidden_states)
1934
+
1935
+ if input_ids is not None:
1936
+ batch_size = input_ids.shape[0]
1937
+ else:
1938
+ batch_size = inputs_embeds.shape[0]
1939
+
1940
+ if self.config.pad_token_id is None and batch_size != 1:
1941
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1942
+ if self.config.pad_token_id is None:
1943
+ sequence_lengths = -1
1944
+ else:
1945
+ if input_ids is not None:
1946
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1947
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1948
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1949
+ sequence_lengths = sequence_lengths.to(logits.device)
1950
+ else:
1951
+ sequence_lengths = -1
1952
+
1953
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1954
+
1955
+ loss = None
1956
+ if labels is not None:
1957
+ labels = labels.to(logits.device)
1958
+ if self.config.problem_type is None:
1959
+ if self.num_labels == 1:
1960
+ self.config.problem_type = "regression"
1961
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1962
+ self.config.problem_type = "single_label_classification"
1963
+ else:
1964
+ self.config.problem_type = "multi_label_classification"
1965
+
1966
+ if self.config.problem_type == "regression":
1967
+ loss_fct = MSELoss()
1968
+ if self.num_labels == 1:
1969
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1970
+ else:
1971
+ loss = loss_fct(pooled_logits, labels)
1972
+ elif self.config.problem_type == "single_label_classification":
1973
+ loss_fct = CrossEntropyLoss()
1974
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1975
+ elif self.config.problem_type == "multi_label_classification":
1976
+ loss_fct = BCEWithLogitsLoss()
1977
+ loss = loss_fct(pooled_logits, labels)
1978
+ if not return_dict:
1979
+ output = (pooled_logits,) + transformer_outputs[1:]
1980
+ return ((loss,) + output) if loss is not None else output
1981
+
1982
+ return SequenceClassifierOutputWithPast(
1983
+ loss=loss,
1984
+ logits=pooled_logits,
1985
+ past_key_values=transformer_outputs.past_key_values,
1986
+ hidden_states=transformer_outputs.hidden_states,
1987
+ attentions=transformer_outputs.attentions,
1988
+ )
pytorch_model-00001-of-00007.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7831f8f0872650b92795355b9810e36f5d99ed8918b0ddc7365576d432a5b1ff
3
+ size 4976695876
pytorch_model-00002-of-00007.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:091c991a49b44da7feef5695998fe8e551d74e0de252fef1fe8642151486f568
3
+ size 4778637580
pytorch_model-00003-of-00007.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4f1dd4361f1b00cabab4e8b2b19d3d3cc7e3b82198a8330009c952c1c8c7f721
3
+ size 4932758012
pytorch_model-00004-of-00007.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c7b366ce577080cbcd942490f2f04c3a638a8712290324bf513ea06dabee5c84
3
+ size 4932758052
pytorch_model-00005-of-00007.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d2f3c4cb11a7e748bdb6016d3c17d225582194d12f577d891f88d1c3593a81a7
3
+ size 4998868108
pytorch_model-00006-of-00007.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9d02da284acf9bcfb84a29ed08200868d3f1138853cfa26b8b225c2b904ef30f
3
+ size 3662875056
pytorch_model-00007-of-00007.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bb7d426c5f5fec1777af79eda51a5e80db602ec34e389356c8bbd337f1ba879f
3
+ size 2249751049
pytorch_model.bin.index.json ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 30532225024
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "pytorch_model-00007-of-00007.bin",
7
+ "model.embed_tokens.weight": "pytorch_model-00001-of-00007.bin",
8
+ "model.layers.0.input_layernorm.weight": "pytorch_model-00001-of-00007.bin",
9
+ "model.layers.0.mlp.down_proj.weight": "pytorch_model-00001-of-00007.bin",
10
+ "model.layers.0.mlp.gate_proj.weight": "pytorch_model-00001-of-00007.bin",
11
+ "model.layers.0.mlp.up_proj.weight": "pytorch_model-00001-of-00007.bin",
12
+ "model.layers.0.post_attention_layernorm.weight": "pytorch_model-00001-of-00007.bin",
13
+ "model.layers.0.self_attn.k_proj.bias": "pytorch_model-00001-of-00007.bin",
14
+ "model.layers.0.self_attn.k_proj.weight": "pytorch_model-00001-of-00007.bin",
15
+ "model.layers.0.self_attn.o_proj.weight": "pytorch_model-00001-of-00007.bin",
16
+ "model.layers.0.self_attn.q_proj.bias": "pytorch_model-00001-of-00007.bin",
17
+ "model.layers.0.self_attn.q_proj.weight": "pytorch_model-00001-of-00007.bin",
18
+ "model.layers.0.self_attn.v_proj.bias": "pytorch_model-00001-of-00007.bin",
19
+ "model.layers.0.self_attn.v_proj.weight": "pytorch_model-00001-of-00007.bin",
20
+ "model.layers.1.input_layernorm.weight": "pytorch_model-00001-of-00007.bin",
21
+ "model.layers.1.mlp.down_proj.weight": "pytorch_model-00001-of-00007.bin",
22
+ "model.layers.1.mlp.gate_proj.weight": "pytorch_model-00001-of-00007.bin",
23
+ "model.layers.1.mlp.up_proj.weight": "pytorch_model-00001-of-00007.bin",
24
+ "model.layers.1.post_attention_layernorm.weight": "pytorch_model-00001-of-00007.bin",
25
+ "model.layers.1.self_attn.k_proj.bias": "pytorch_model-00001-of-00007.bin",
26
+ "model.layers.1.self_attn.k_proj.weight": "pytorch_model-00001-of-00007.bin",
27
+ "model.layers.1.self_attn.o_proj.weight": "pytorch_model-00001-of-00007.bin",
28
+ "model.layers.1.self_attn.q_proj.bias": "pytorch_model-00001-of-00007.bin",
29
+ "model.layers.1.self_attn.q_proj.weight": "pytorch_model-00001-of-00007.bin",
30
+ "model.layers.1.self_attn.v_proj.bias": "pytorch_model-00001-of-00007.bin",
31
+ "model.layers.1.self_attn.v_proj.weight": "pytorch_model-00001-of-00007.bin",
32
+ "model.layers.10.input_layernorm.weight": "pytorch_model-00003-of-00007.bin",
33
+ "model.layers.10.mlp.down_proj.weight": "pytorch_model-00003-of-00007.bin",
34
+ "model.layers.10.mlp.gate_proj.weight": "pytorch_model-00003-of-00007.bin",
35
+ "model.layers.10.mlp.up_proj.weight": "pytorch_model-00003-of-00007.bin",
36
+ "model.layers.10.post_attention_layernorm.weight": "pytorch_model-00003-of-00007.bin",
37
+ "model.layers.10.self_attn.k_proj.bias": "pytorch_model-00003-of-00007.bin",
38
+ "model.layers.10.self_attn.k_proj.weight": "pytorch_model-00003-of-00007.bin",
39
+ "model.layers.10.self_attn.o_proj.weight": "pytorch_model-00003-of-00007.bin",
40
+ "model.layers.10.self_attn.q_proj.bias": "pytorch_model-00003-of-00007.bin",
41
+ "model.layers.10.self_attn.q_proj.weight": "pytorch_model-00003-of-00007.bin",
42
+ "model.layers.10.self_attn.v_proj.bias": "pytorch_model-00003-of-00007.bin",
43
+ "model.layers.10.self_attn.v_proj.weight": "pytorch_model-00003-of-00007.bin",
44
+ "model.layers.11.input_layernorm.weight": "pytorch_model-00003-of-00007.bin",
45
+ "model.layers.11.mlp.down_proj.weight": "pytorch_model-00003-of-00007.bin",
46
+ "model.layers.11.mlp.gate_proj.weight": "pytorch_model-00003-of-00007.bin",
47
+ "model.layers.11.mlp.up_proj.weight": "pytorch_model-00003-of-00007.bin",
48
+ "model.layers.11.post_attention_layernorm.weight": "pytorch_model-00003-of-00007.bin",
49
+ "model.layers.11.self_attn.k_proj.bias": "pytorch_model-00003-of-00007.bin",
50
+ "model.layers.11.self_attn.k_proj.weight": "pytorch_model-00003-of-00007.bin",
51
+ "model.layers.11.self_attn.o_proj.weight": "pytorch_model-00003-of-00007.bin",
52
+ "model.layers.11.self_attn.q_proj.bias": "pytorch_model-00003-of-00007.bin",
53
+ "model.layers.11.self_attn.q_proj.weight": "pytorch_model-00003-of-00007.bin",
54
+ "model.layers.11.self_attn.v_proj.bias": "pytorch_model-00003-of-00007.bin",
55
+ "model.layers.11.self_attn.v_proj.weight": "pytorch_model-00003-of-00007.bin",
56
+ "model.layers.12.input_layernorm.weight": "pytorch_model-00003-of-00007.bin",
57
+ "model.layers.12.mlp.down_proj.weight": "pytorch_model-00003-of-00007.bin",
58
+ "model.layers.12.mlp.gate_proj.weight": "pytorch_model-00003-of-00007.bin",
59
+ "model.layers.12.mlp.up_proj.weight": "pytorch_model-00003-of-00007.bin",
60
+ "model.layers.12.post_attention_layernorm.weight": "pytorch_model-00003-of-00007.bin",
61
+ "model.layers.12.self_attn.k_proj.bias": "pytorch_model-00003-of-00007.bin",
62
+ "model.layers.12.self_attn.k_proj.weight": "pytorch_model-00003-of-00007.bin",
63
+ "model.layers.12.self_attn.o_proj.weight": "pytorch_model-00003-of-00007.bin",
64
+ "model.layers.12.self_attn.q_proj.bias": "pytorch_model-00003-of-00007.bin",
65
+ "model.layers.12.self_attn.q_proj.weight": "pytorch_model-00003-of-00007.bin",
66
+ "model.layers.12.self_attn.v_proj.bias": "pytorch_model-00003-of-00007.bin",
67
+ "model.layers.12.self_attn.v_proj.weight": "pytorch_model-00003-of-00007.bin",
68
+ "model.layers.13.input_layernorm.weight": "pytorch_model-00004-of-00007.bin",
69
+ "model.layers.13.mlp.down_proj.weight": "pytorch_model-00004-of-00007.bin",
70
+ "model.layers.13.mlp.gate_proj.weight": "pytorch_model-00003-of-00007.bin",
71
+ "model.layers.13.mlp.up_proj.weight": "pytorch_model-00004-of-00007.bin",
72
+ "model.layers.13.post_attention_layernorm.weight": "pytorch_model-00004-of-00007.bin",
73
+ "model.layers.13.self_attn.k_proj.bias": "pytorch_model-00003-of-00007.bin",
74
+ "model.layers.13.self_attn.k_proj.weight": "pytorch_model-00003-of-00007.bin",
75
+ "model.layers.13.self_attn.o_proj.weight": "pytorch_model-00003-of-00007.bin",
76
+ "model.layers.13.self_attn.q_proj.bias": "pytorch_model-00003-of-00007.bin",
77
+ "model.layers.13.self_attn.q_proj.weight": "pytorch_model-00003-of-00007.bin",
78
+ "model.layers.13.self_attn.v_proj.bias": "pytorch_model-00003-of-00007.bin",
79
+ "model.layers.13.self_attn.v_proj.weight": "pytorch_model-00003-of-00007.bin",
80
+ "model.layers.14.input_layernorm.weight": "pytorch_model-00004-of-00007.bin",
81
+ "model.layers.14.mlp.down_proj.weight": "pytorch_model-00004-of-00007.bin",
82
+ "model.layers.14.mlp.gate_proj.weight": "pytorch_model-00004-of-00007.bin",
83
+ "model.layers.14.mlp.up_proj.weight": "pytorch_model-00004-of-00007.bin",
84
+ "model.layers.14.post_attention_layernorm.weight": "pytorch_model-00004-of-00007.bin",
85
+ "model.layers.14.self_attn.k_proj.bias": "pytorch_model-00004-of-00007.bin",
86
+ "model.layers.14.self_attn.k_proj.weight": "pytorch_model-00004-of-00007.bin",
87
+ "model.layers.14.self_attn.o_proj.weight": "pytorch_model-00004-of-00007.bin",
88
+ "model.layers.14.self_attn.q_proj.bias": "pytorch_model-00004-of-00007.bin",
89
+ "model.layers.14.self_attn.q_proj.weight": "pytorch_model-00004-of-00007.bin",
90
+ "model.layers.14.self_attn.v_proj.bias": "pytorch_model-00004-of-00007.bin",
91
+ "model.layers.14.self_attn.v_proj.weight": "pytorch_model-00004-of-00007.bin",
92
+ "model.layers.15.input_layernorm.weight": "pytorch_model-00004-of-00007.bin",
93
+ "model.layers.15.mlp.down_proj.weight": "pytorch_model-00004-of-00007.bin",
94
+ "model.layers.15.mlp.gate_proj.weight": "pytorch_model-00004-of-00007.bin",
95
+ "model.layers.15.mlp.up_proj.weight": "pytorch_model-00004-of-00007.bin",
96
+ "model.layers.15.post_attention_layernorm.weight": "pytorch_model-00004-of-00007.bin",
97
+ "model.layers.15.self_attn.k_proj.bias": "pytorch_model-00004-of-00007.bin",
98
+ "model.layers.15.self_attn.k_proj.weight": "pytorch_model-00004-of-00007.bin",
99
+ "model.layers.15.self_attn.o_proj.weight": "pytorch_model-00004-of-00007.bin",
100
+ "model.layers.15.self_attn.q_proj.bias": "pytorch_model-00004-of-00007.bin",
101
+ "model.layers.15.self_attn.q_proj.weight": "pytorch_model-00004-of-00007.bin",
102
+ "model.layers.15.self_attn.v_proj.bias": "pytorch_model-00004-of-00007.bin",
103
+ "model.layers.15.self_attn.v_proj.weight": "pytorch_model-00004-of-00007.bin",
104
+ "model.layers.16.input_layernorm.weight": "pytorch_model-00004-of-00007.bin",
105
+ "model.layers.16.mlp.down_proj.weight": "pytorch_model-00004-of-00007.bin",
106
+ "model.layers.16.mlp.gate_proj.weight": "pytorch_model-00004-of-00007.bin",
107
+ "model.layers.16.mlp.up_proj.weight": "pytorch_model-00004-of-00007.bin",
108
+ "model.layers.16.post_attention_layernorm.weight": "pytorch_model-00004-of-00007.bin",
109
+ "model.layers.16.self_attn.k_proj.bias": "pytorch_model-00004-of-00007.bin",
110
+ "model.layers.16.self_attn.k_proj.weight": "pytorch_model-00004-of-00007.bin",
111
+ "model.layers.16.self_attn.o_proj.weight": "pytorch_model-00004-of-00007.bin",
112
+ "model.layers.16.self_attn.q_proj.bias": "pytorch_model-00004-of-00007.bin",
113
+ "model.layers.16.self_attn.q_proj.weight": "pytorch_model-00004-of-00007.bin",
114
+ "model.layers.16.self_attn.v_proj.bias": "pytorch_model-00004-of-00007.bin",
115
+ "model.layers.16.self_attn.v_proj.weight": "pytorch_model-00004-of-00007.bin",
116
+ "model.layers.17.input_layernorm.weight": "pytorch_model-00004-of-00007.bin",
117
+ "model.layers.17.mlp.down_proj.weight": "pytorch_model-00004-of-00007.bin",
118
+ "model.layers.17.mlp.gate_proj.weight": "pytorch_model-00004-of-00007.bin",
119
+ "model.layers.17.mlp.up_proj.weight": "pytorch_model-00004-of-00007.bin",
120
+ "model.layers.17.post_attention_layernorm.weight": "pytorch_model-00004-of-00007.bin",
121
+ "model.layers.17.self_attn.k_proj.bias": "pytorch_model-00004-of-00007.bin",
122
+ "model.layers.17.self_attn.k_proj.weight": "pytorch_model-00004-of-00007.bin",
123
+ "model.layers.17.self_attn.o_proj.weight": "pytorch_model-00004-of-00007.bin",
124
+ "model.layers.17.self_attn.q_proj.bias": "pytorch_model-00004-of-00007.bin",
125
+ "model.layers.17.self_attn.q_proj.weight": "pytorch_model-00004-of-00007.bin",
126
+ "model.layers.17.self_attn.v_proj.bias": "pytorch_model-00004-of-00007.bin",
127
+ "model.layers.17.self_attn.v_proj.weight": "pytorch_model-00004-of-00007.bin",
128
+ "model.layers.18.input_layernorm.weight": "pytorch_model-00005-of-00007.bin",
129
+ "model.layers.18.mlp.down_proj.weight": "pytorch_model-00005-of-00007.bin",
130
+ "model.layers.18.mlp.gate_proj.weight": "pytorch_model-00004-of-00007.bin",
131
+ "model.layers.18.mlp.up_proj.weight": "pytorch_model-00004-of-00007.bin",
132
+ "model.layers.18.post_attention_layernorm.weight": "pytorch_model-00005-of-00007.bin",
133
+ "model.layers.18.self_attn.k_proj.bias": "pytorch_model-00004-of-00007.bin",
134
+ "model.layers.18.self_attn.k_proj.weight": "pytorch_model-00004-of-00007.bin",
135
+ "model.layers.18.self_attn.o_proj.weight": "pytorch_model-00004-of-00007.bin",
136
+ "model.layers.18.self_attn.q_proj.bias": "pytorch_model-00004-of-00007.bin",
137
+ "model.layers.18.self_attn.q_proj.weight": "pytorch_model-00004-of-00007.bin",
138
+ "model.layers.18.self_attn.v_proj.bias": "pytorch_model-00004-of-00007.bin",
139
+ "model.layers.18.self_attn.v_proj.weight": "pytorch_model-00004-of-00007.bin",
140
+ "model.layers.19.input_layernorm.weight": "pytorch_model-00005-of-00007.bin",
141
+ "model.layers.19.mlp.down_proj.weight": "pytorch_model-00005-of-00007.bin",
142
+ "model.layers.19.mlp.gate_proj.weight": "pytorch_model-00005-of-00007.bin",
143
+ "model.layers.19.mlp.up_proj.weight": "pytorch_model-00005-of-00007.bin",
144
+ "model.layers.19.post_attention_layernorm.weight": "pytorch_model-00005-of-00007.bin",
145
+ "model.layers.19.self_attn.k_proj.bias": "pytorch_model-00005-of-00007.bin",
146
+ "model.layers.19.self_attn.k_proj.weight": "pytorch_model-00005-of-00007.bin",
147
+ "model.layers.19.self_attn.o_proj.weight": "pytorch_model-00005-of-00007.bin",
148
+ "model.layers.19.self_attn.q_proj.bias": "pytorch_model-00005-of-00007.bin",
149
+ "model.layers.19.self_attn.q_proj.weight": "pytorch_model-00005-of-00007.bin",
150
+ "model.layers.19.self_attn.v_proj.bias": "pytorch_model-00005-of-00007.bin",
151
+ "model.layers.19.self_attn.v_proj.weight": "pytorch_model-00005-of-00007.bin",
152
+ "model.layers.2.input_layernorm.weight": "pytorch_model-00001-of-00007.bin",
153
+ "model.layers.2.mlp.down_proj.weight": "pytorch_model-00001-of-00007.bin",
154
+ "model.layers.2.mlp.gate_proj.weight": "pytorch_model-00001-of-00007.bin",
155
+ "model.layers.2.mlp.up_proj.weight": "pytorch_model-00001-of-00007.bin",
156
+ "model.layers.2.post_attention_layernorm.weight": "pytorch_model-00001-of-00007.bin",
157
+ "model.layers.2.self_attn.k_proj.bias": "pytorch_model-00001-of-00007.bin",
158
+ "model.layers.2.self_attn.k_proj.weight": "pytorch_model-00001-of-00007.bin",
159
+ "model.layers.2.self_attn.o_proj.weight": "pytorch_model-00001-of-00007.bin",
160
+ "model.layers.2.self_attn.q_proj.bias": "pytorch_model-00001-of-00007.bin",
161
+ "model.layers.2.self_attn.q_proj.weight": "pytorch_model-00001-of-00007.bin",
162
+ "model.layers.2.self_attn.v_proj.bias": "pytorch_model-00001-of-00007.bin",
163
+ "model.layers.2.self_attn.v_proj.weight": "pytorch_model-00001-of-00007.bin",
164
+ "model.layers.20.input_layernorm.weight": "pytorch_model-00005-of-00007.bin",
165
+ "model.layers.20.mlp.down_proj.weight": "pytorch_model-00005-of-00007.bin",
166
+ "model.layers.20.mlp.gate_proj.weight": "pytorch_model-00005-of-00007.bin",
167
+ "model.layers.20.mlp.up_proj.weight": "pytorch_model-00005-of-00007.bin",
168
+ "model.layers.20.post_attention_layernorm.weight": "pytorch_model-00005-of-00007.bin",
169
+ "model.layers.20.self_attn.k_proj.bias": "pytorch_model-00005-of-00007.bin",
170
+ "model.layers.20.self_attn.k_proj.weight": "pytorch_model-00005-of-00007.bin",
171
+ "model.layers.20.self_attn.o_proj.weight": "pytorch_model-00005-of-00007.bin",
172
+ "model.layers.20.self_attn.q_proj.bias": "pytorch_model-00005-of-00007.bin",
173
+ "model.layers.20.self_attn.q_proj.weight": "pytorch_model-00005-of-00007.bin",
174
+ "model.layers.20.self_attn.v_proj.bias": "pytorch_model-00005-of-00007.bin",
175
+ "model.layers.20.self_attn.v_proj.weight": "pytorch_model-00005-of-00007.bin",
176
+ "model.layers.21.input_layernorm.weight": "pytorch_model-00005-of-00007.bin",
177
+ "model.layers.21.mlp.down_proj.weight": "pytorch_model-00005-of-00007.bin",
178
+ "model.layers.21.mlp.gate_proj.weight": "pytorch_model-00005-of-00007.bin",
179
+ "model.layers.21.mlp.up_proj.weight": "pytorch_model-00005-of-00007.bin",
180
+ "model.layers.21.post_attention_layernorm.weight": "pytorch_model-00005-of-00007.bin",
181
+ "model.layers.21.self_attn.k_proj.bias": "pytorch_model-00005-of-00007.bin",
182
+ "model.layers.21.self_attn.k_proj.weight": "pytorch_model-00005-of-00007.bin",
183
+ "model.layers.21.self_attn.o_proj.weight": "pytorch_model-00005-of-00007.bin",
184
+ "model.layers.21.self_attn.q_proj.bias": "pytorch_model-00005-of-00007.bin",
185
+ "model.layers.21.self_attn.q_proj.weight": "pytorch_model-00005-of-00007.bin",
186
+ "model.layers.21.self_attn.v_proj.bias": "pytorch_model-00005-of-00007.bin",
187
+ "model.layers.21.self_attn.v_proj.weight": "pytorch_model-00005-of-00007.bin",
188
+ "model.layers.22.input_layernorm.weight": "pytorch_model-00005-of-00007.bin",
189
+ "model.layers.22.mlp.down_proj.weight": "pytorch_model-00005-of-00007.bin",
190
+ "model.layers.22.mlp.gate_proj.weight": "pytorch_model-00005-of-00007.bin",
191
+ "model.layers.22.mlp.up_proj.weight": "pytorch_model-00005-of-00007.bin",
192
+ "model.layers.22.post_attention_layernorm.weight": "pytorch_model-00005-of-00007.bin",
193
+ "model.layers.22.self_attn.k_proj.bias": "pytorch_model-00005-of-00007.bin",
194
+ "model.layers.22.self_attn.k_proj.weight": "pytorch_model-00005-of-00007.bin",
195
+ "model.layers.22.self_attn.o_proj.weight": "pytorch_model-00005-of-00007.bin",
196
+ "model.layers.22.self_attn.q_proj.bias": "pytorch_model-00005-of-00007.bin",
197
+ "model.layers.22.self_attn.q_proj.weight": "pytorch_model-00005-of-00007.bin",
198
+ "model.layers.22.self_attn.v_proj.bias": "pytorch_model-00005-of-00007.bin",
199
+ "model.layers.22.self_attn.v_proj.weight": "pytorch_model-00005-of-00007.bin",
200
+ "model.layers.23.input_layernorm.weight": "pytorch_model-00005-of-00007.bin",
201
+ "model.layers.23.mlp.down_proj.weight": "pytorch_model-00005-of-00007.bin",
202
+ "model.layers.23.mlp.gate_proj.weight": "pytorch_model-00005-of-00007.bin",
203
+ "model.layers.23.mlp.up_proj.weight": "pytorch_model-00005-of-00007.bin",
204
+ "model.layers.23.post_attention_layernorm.weight": "pytorch_model-00005-of-00007.bin",
205
+ "model.layers.23.self_attn.k_proj.bias": "pytorch_model-00005-of-00007.bin",
206
+ "model.layers.23.self_attn.k_proj.weight": "pytorch_model-00005-of-00007.bin",
207
+ "model.layers.23.self_attn.o_proj.weight": "pytorch_model-00005-of-00007.bin",
208
+ "model.layers.23.self_attn.q_proj.bias": "pytorch_model-00005-of-00007.bin",
209
+ "model.layers.23.self_attn.q_proj.weight": "pytorch_model-00005-of-00007.bin",
210
+ "model.layers.23.self_attn.v_proj.bias": "pytorch_model-00005-of-00007.bin",
211
+ "model.layers.23.self_attn.v_proj.weight": "pytorch_model-00005-of-00007.bin",
212
+ "model.layers.24.input_layernorm.weight": "pytorch_model-00006-of-00007.bin",
213
+ "model.layers.24.mlp.down_proj.weight": "pytorch_model-00006-of-00007.bin",
214
+ "model.layers.24.mlp.gate_proj.weight": "pytorch_model-00006-of-00007.bin",
215
+ "model.layers.24.mlp.up_proj.weight": "pytorch_model-00006-of-00007.bin",
216
+ "model.layers.24.post_attention_layernorm.weight": "pytorch_model-00006-of-00007.bin",
217
+ "model.layers.24.self_attn.k_proj.bias": "pytorch_model-00005-of-00007.bin",
218
+ "model.layers.24.self_attn.k_proj.weight": "pytorch_model-00005-of-00007.bin",
219
+ "model.layers.24.self_attn.o_proj.weight": "pytorch_model-00006-of-00007.bin",
220
+ "model.layers.24.self_attn.q_proj.bias": "pytorch_model-00005-of-00007.bin",
221
+ "model.layers.24.self_attn.q_proj.weight": "pytorch_model-00005-of-00007.bin",
222
+ "model.layers.24.self_attn.v_proj.bias": "pytorch_model-00005-of-00007.bin",
223
+ "model.layers.24.self_attn.v_proj.weight": "pytorch_model-00005-of-00007.bin",
224
+ "model.layers.25.input_layernorm.weight": "pytorch_model-00006-of-00007.bin",
225
+ "model.layers.25.mlp.down_proj.weight": "pytorch_model-00006-of-00007.bin",
226
+ "model.layers.25.mlp.gate_proj.weight": "pytorch_model-00006-of-00007.bin",
227
+ "model.layers.25.mlp.up_proj.weight": "pytorch_model-00006-of-00007.bin",
228
+ "model.layers.25.post_attention_layernorm.weight": "pytorch_model-00006-of-00007.bin",
229
+ "model.layers.25.self_attn.k_proj.bias": "pytorch_model-00006-of-00007.bin",
230
+ "model.layers.25.self_attn.k_proj.weight": "pytorch_model-00006-of-00007.bin",
231
+ "model.layers.25.self_attn.o_proj.weight": "pytorch_model-00006-of-00007.bin",
232
+ "model.layers.25.self_attn.q_proj.bias": "pytorch_model-00006-of-00007.bin",
233
+ "model.layers.25.self_attn.q_proj.weight": "pytorch_model-00006-of-00007.bin",
234
+ "model.layers.25.self_attn.v_proj.bias": "pytorch_model-00006-of-00007.bin",
235
+ "model.layers.25.self_attn.v_proj.weight": "pytorch_model-00006-of-00007.bin",
236
+ "model.layers.26.input_layernorm.weight": "pytorch_model-00006-of-00007.bin",
237
+ "model.layers.26.mlp.down_proj.weight": "pytorch_model-00006-of-00007.bin",
238
+ "model.layers.26.mlp.gate_proj.weight": "pytorch_model-00006-of-00007.bin",
239
+ "model.layers.26.mlp.up_proj.weight": "pytorch_model-00006-of-00007.bin",
240
+ "model.layers.26.post_attention_layernorm.weight": "pytorch_model-00006-of-00007.bin",
241
+ "model.layers.26.self_attn.k_proj.bias": "pytorch_model-00006-of-00007.bin",
242
+ "model.layers.26.self_attn.k_proj.weight": "pytorch_model-00006-of-00007.bin",
243
+ "model.layers.26.self_attn.o_proj.weight": "pytorch_model-00006-of-00007.bin",
244
+ "model.layers.26.self_attn.q_proj.bias": "pytorch_model-00006-of-00007.bin",
245
+ "model.layers.26.self_attn.q_proj.weight": "pytorch_model-00006-of-00007.bin",
246
+ "model.layers.26.self_attn.v_proj.bias": "pytorch_model-00006-of-00007.bin",
247
+ "model.layers.26.self_attn.v_proj.weight": "pytorch_model-00006-of-00007.bin",
248
+ "model.layers.27.input_layernorm.weight": "pytorch_model-00006-of-00007.bin",
249
+ "model.layers.27.mlp.down_proj.weight": "pytorch_model-00006-of-00007.bin",
250
+ "model.layers.27.mlp.gate_proj.weight": "pytorch_model-00006-of-00007.bin",
251
+ "model.layers.27.mlp.up_proj.weight": "pytorch_model-00006-of-00007.bin",
252
+ "model.layers.27.post_attention_layernorm.weight": "pytorch_model-00006-of-00007.bin",
253
+ "model.layers.27.self_attn.k_proj.bias": "pytorch_model-00006-of-00007.bin",
254
+ "model.layers.27.self_attn.k_proj.weight": "pytorch_model-00006-of-00007.bin",
255
+ "model.layers.27.self_attn.o_proj.weight": "pytorch_model-00006-of-00007.bin",
256
+ "model.layers.27.self_attn.q_proj.bias": "pytorch_model-00006-of-00007.bin",
257
+ "model.layers.27.self_attn.q_proj.weight": "pytorch_model-00006-of-00007.bin",
258
+ "model.layers.27.self_attn.v_proj.bias": "pytorch_model-00006-of-00007.bin",
259
+ "model.layers.27.self_attn.v_proj.weight": "pytorch_model-00006-of-00007.bin",
260
+ "model.layers.3.input_layernorm.weight": "pytorch_model-00002-of-00007.bin",
261
+ "model.layers.3.mlp.down_proj.weight": "pytorch_model-00002-of-00007.bin",
262
+ "model.layers.3.mlp.gate_proj.weight": "pytorch_model-00002-of-00007.bin",
263
+ "model.layers.3.mlp.up_proj.weight": "pytorch_model-00002-of-00007.bin",
264
+ "model.layers.3.post_attention_layernorm.weight": "pytorch_model-00002-of-00007.bin",
265
+ "model.layers.3.self_attn.k_proj.bias": "pytorch_model-00002-of-00007.bin",
266
+ "model.layers.3.self_attn.k_proj.weight": "pytorch_model-00002-of-00007.bin",
267
+ "model.layers.3.self_attn.o_proj.weight": "pytorch_model-00002-of-00007.bin",
268
+ "model.layers.3.self_attn.q_proj.bias": "pytorch_model-00002-of-00007.bin",
269
+ "model.layers.3.self_attn.q_proj.weight": "pytorch_model-00002-of-00007.bin",
270
+ "model.layers.3.self_attn.v_proj.bias": "pytorch_model-00002-of-00007.bin",
271
+ "model.layers.3.self_attn.v_proj.weight": "pytorch_model-00002-of-00007.bin",
272
+ "model.layers.4.input_layernorm.weight": "pytorch_model-00002-of-00007.bin",
273
+ "model.layers.4.mlp.down_proj.weight": "pytorch_model-00002-of-00007.bin",
274
+ "model.layers.4.mlp.gate_proj.weight": "pytorch_model-00002-of-00007.bin",
275
+ "model.layers.4.mlp.up_proj.weight": "pytorch_model-00002-of-00007.bin",
276
+ "model.layers.4.post_attention_layernorm.weight": "pytorch_model-00002-of-00007.bin",
277
+ "model.layers.4.self_attn.k_proj.bias": "pytorch_model-00002-of-00007.bin",
278
+ "model.layers.4.self_attn.k_proj.weight": "pytorch_model-00002-of-00007.bin",
279
+ "model.layers.4.self_attn.o_proj.weight": "pytorch_model-00002-of-00007.bin",
280
+ "model.layers.4.self_attn.q_proj.bias": "pytorch_model-00002-of-00007.bin",
281
+ "model.layers.4.self_attn.q_proj.weight": "pytorch_model-00002-of-00007.bin",
282
+ "model.layers.4.self_attn.v_proj.bias": "pytorch_model-00002-of-00007.bin",
283
+ "model.layers.4.self_attn.v_proj.weight": "pytorch_model-00002-of-00007.bin",
284
+ "model.layers.5.input_layernorm.weight": "pytorch_model-00002-of-00007.bin",
285
+ "model.layers.5.mlp.down_proj.weight": "pytorch_model-00002-of-00007.bin",
286
+ "model.layers.5.mlp.gate_proj.weight": "pytorch_model-00002-of-00007.bin",
287
+ "model.layers.5.mlp.up_proj.weight": "pytorch_model-00002-of-00007.bin",
288
+ "model.layers.5.post_attention_layernorm.weight": "pytorch_model-00002-of-00007.bin",
289
+ "model.layers.5.self_attn.k_proj.bias": "pytorch_model-00002-of-00007.bin",
290
+ "model.layers.5.self_attn.k_proj.weight": "pytorch_model-00002-of-00007.bin",
291
+ "model.layers.5.self_attn.o_proj.weight": "pytorch_model-00002-of-00007.bin",
292
+ "model.layers.5.self_attn.q_proj.bias": "pytorch_model-00002-of-00007.bin",
293
+ "model.layers.5.self_attn.q_proj.weight": "pytorch_model-00002-of-00007.bin",
294
+ "model.layers.5.self_attn.v_proj.bias": "pytorch_model-00002-of-00007.bin",
295
+ "model.layers.5.self_attn.v_proj.weight": "pytorch_model-00002-of-00007.bin",
296
+ "model.layers.6.input_layernorm.weight": "pytorch_model-00002-of-00007.bin",
297
+ "model.layers.6.mlp.down_proj.weight": "pytorch_model-00002-of-00007.bin",
298
+ "model.layers.6.mlp.gate_proj.weight": "pytorch_model-00002-of-00007.bin",
299
+ "model.layers.6.mlp.up_proj.weight": "pytorch_model-00002-of-00007.bin",
300
+ "model.layers.6.post_attention_layernorm.weight": "pytorch_model-00002-of-00007.bin",
301
+ "model.layers.6.self_attn.k_proj.bias": "pytorch_model-00002-of-00007.bin",
302
+ "model.layers.6.self_attn.k_proj.weight": "pytorch_model-00002-of-00007.bin",
303
+ "model.layers.6.self_attn.o_proj.weight": "pytorch_model-00002-of-00007.bin",
304
+ "model.layers.6.self_attn.q_proj.bias": "pytorch_model-00002-of-00007.bin",
305
+ "model.layers.6.self_attn.q_proj.weight": "pytorch_model-00002-of-00007.bin",
306
+ "model.layers.6.self_attn.v_proj.bias": "pytorch_model-00002-of-00007.bin",
307
+ "model.layers.6.self_attn.v_proj.weight": "pytorch_model-00002-of-00007.bin",
308
+ "model.layers.7.input_layernorm.weight": "pytorch_model-00002-of-00007.bin",
309
+ "model.layers.7.mlp.down_proj.weight": "pytorch_model-00002-of-00007.bin",
310
+ "model.layers.7.mlp.gate_proj.weight": "pytorch_model-00002-of-00007.bin",
311
+ "model.layers.7.mlp.up_proj.weight": "pytorch_model-00002-of-00007.bin",
312
+ "model.layers.7.post_attention_layernorm.weight": "pytorch_model-00002-of-00007.bin",
313
+ "model.layers.7.self_attn.k_proj.bias": "pytorch_model-00002-of-00007.bin",
314
+ "model.layers.7.self_attn.k_proj.weight": "pytorch_model-00002-of-00007.bin",
315
+ "model.layers.7.self_attn.o_proj.weight": "pytorch_model-00002-of-00007.bin",
316
+ "model.layers.7.self_attn.q_proj.bias": "pytorch_model-00002-of-00007.bin",
317
+ "model.layers.7.self_attn.q_proj.weight": "pytorch_model-00002-of-00007.bin",
318
+ "model.layers.7.self_attn.v_proj.bias": "pytorch_model-00002-of-00007.bin",
319
+ "model.layers.7.self_attn.v_proj.weight": "pytorch_model-00002-of-00007.bin",
320
+ "model.layers.8.input_layernorm.weight": "pytorch_model-00003-of-00007.bin",
321
+ "model.layers.8.mlp.down_proj.weight": "pytorch_model-00003-of-00007.bin",
322
+ "model.layers.8.mlp.gate_proj.weight": "pytorch_model-00003-of-00007.bin",
323
+ "model.layers.8.mlp.up_proj.weight": "pytorch_model-00003-of-00007.bin",
324
+ "model.layers.8.post_attention_layernorm.weight": "pytorch_model-00003-of-00007.bin",
325
+ "model.layers.8.self_attn.k_proj.bias": "pytorch_model-00002-of-00007.bin",
326
+ "model.layers.8.self_attn.k_proj.weight": "pytorch_model-00002-of-00007.bin",
327
+ "model.layers.8.self_attn.o_proj.weight": "pytorch_model-00002-of-00007.bin",
328
+ "model.layers.8.self_attn.q_proj.bias": "pytorch_model-00002-of-00007.bin",
329
+ "model.layers.8.self_attn.q_proj.weight": "pytorch_model-00002-of-00007.bin",
330
+ "model.layers.8.self_attn.v_proj.bias": "pytorch_model-00002-of-00007.bin",
331
+ "model.layers.8.self_attn.v_proj.weight": "pytorch_model-00002-of-00007.bin",
332
+ "model.layers.9.input_layernorm.weight": "pytorch_model-00003-of-00007.bin",
333
+ "model.layers.9.mlp.down_proj.weight": "pytorch_model-00003-of-00007.bin",
334
+ "model.layers.9.mlp.gate_proj.weight": "pytorch_model-00003-of-00007.bin",
335
+ "model.layers.9.mlp.up_proj.weight": "pytorch_model-00003-of-00007.bin",
336
+ "model.layers.9.post_attention_layernorm.weight": "pytorch_model-00003-of-00007.bin",
337
+ "model.layers.9.self_attn.k_proj.bias": "pytorch_model-00003-of-00007.bin",
338
+ "model.layers.9.self_attn.k_proj.weight": "pytorch_model-00003-of-00007.bin",
339
+ "model.layers.9.self_attn.o_proj.weight": "pytorch_model-00003-of-00007.bin",
340
+ "model.layers.9.self_attn.q_proj.bias": "pytorch_model-00003-of-00007.bin",
341
+ "model.layers.9.self_attn.q_proj.weight": "pytorch_model-00003-of-00007.bin",
342
+ "model.layers.9.self_attn.v_proj.bias": "pytorch_model-00003-of-00007.bin",
343
+ "model.layers.9.self_attn.v_proj.weight": "pytorch_model-00003-of-00007.bin",
344
+ "model.norm.weight": "pytorch_model-00006-of-00007.bin",
345
+ "ts_encoder.mlp.0.bias": "pytorch_model-00007-of-00007.bin",
346
+ "ts_encoder.mlp.0.weight": "pytorch_model-00007-of-00007.bin",
347
+ "ts_encoder.mlp.2.bias": "pytorch_model-00007-of-00007.bin",
348
+ "ts_encoder.mlp.2.weight": "pytorch_model-00007-of-00007.bin"
349
+ }
350
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<ts>",
4
+ "<ts/>",
5
+ "<|im_end|>"
6
+ ],
7
+ "eos_token": {
8
+ "content": "<|im_end|>",
9
+ "lstrip": false,
10
+ "normalized": false,
11
+ "rstrip": false,
12
+ "single_word": false
13
+ },
14
+ "pad_token": {
15
+ "content": "<|endoftext|>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false
20
+ }
21
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:309a7f94e51f1104e6687b31284915a0349755302b483d851f466650dc2ebc67
3
+ size 11422259
tokenizer_config.json ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ },
181
+ "151665": {
182
+ "content": "<ts>",
183
+ "lstrip": false,
184
+ "normalized": false,
185
+ "rstrip": false,
186
+ "single_word": false,
187
+ "special": true
188
+ },
189
+ "151666": {
190
+ "content": "<ts/>",
191
+ "lstrip": false,
192
+ "normalized": false,
193
+ "rstrip": false,
194
+ "single_word": false,
195
+ "special": true
196
+ }
197
+ },
198
+ "additional_special_tokens": [
199
+ "<ts>",
200
+ "<ts/>",
201
+ "<|im_end|>"
202
+ ],
203
+ "bos_token": null,
204
+ "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 %}",
205
+ "clean_up_tokenization_spaces": false,
206
+ "eos_token": "<|im_end|>",
207
+ "errors": "replace",
208
+ "model_max_length": 131072,
209
+ "pad_token": "<|endoftext|>",
210
+ "padding_side": "right",
211
+ "split_special_tokens": false,
212
+ "tokenizer_class": "Qwen2Tokenizer",
213
+ "unk_token": null
214
+ }
train_results.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "epoch": 1.9968,
3
+ "total_flos": 440534549233664.0,
4
+ "train_loss": 0.46617485760496213,
5
+ "train_runtime": 27454.835,
6
+ "train_samples_per_second": 1.821,
7
+ "train_steps_per_second": 0.028
8
+ }
trainer_log.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
trainer_state.json ADDED
The diff for this file is too large to render. See raw diff
 
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:91c4d83a7fc10064d9c3afd307c0629a3a3c950bb7ddfd5fbab6de6a0c3224b0
3
+ size 7096
training_loss.png ADDED
vocab.json ADDED
The diff for this file is too large to render. See raw diff