sanjay920 commited on
Commit
7d85f82
1 Parent(s): adee55c

Upload folder using huggingface_hub

Browse files
Files changed (34) hide show
  1. function_calling_post_filtering_v4/README.md +57 -0
  2. function_calling_post_filtering_v4/added_tokens.json +13 -0
  3. function_calling_post_filtering_v4/all_results.json +8 -0
  4. function_calling_post_filtering_v4/cache/ds_z2_config.json +28 -0
  5. function_calling_post_filtering_v4/cache/ds_z2_offload_config.json +32 -0
  6. function_calling_post_filtering_v4/cache/ds_z3_config.json +30 -0
  7. function_calling_post_filtering_v4/cache/ds_z3_offload_config.json +38 -0
  8. function_calling_post_filtering_v4/cache/user_config.yaml +4 -0
  9. function_calling_post_filtering_v4/config.json +138 -0
  10. function_calling_post_filtering_v4/configuration_phi3.py +227 -0
  11. function_calling_post_filtering_v4/generation_config.json +7 -0
  12. function_calling_post_filtering_v4/model-00001-of-00002.safetensors +3 -0
  13. function_calling_post_filtering_v4/model-00002-of-00002.safetensors +3 -0
  14. function_calling_post_filtering_v4/model.safetensors.index.json +226 -0
  15. function_calling_post_filtering_v4/modeling_phi3.py +1572 -0
  16. function_calling_post_filtering_v4/special_tokens_map.json +30 -0
  17. function_calling_post_filtering_v4/tokenizer.json +0 -0
  18. function_calling_post_filtering_v4/tokenizer.model +3 -0
  19. function_calling_post_filtering_v4/tokenizer_config.json +132 -0
  20. function_calling_round2/Function_Calling_Round2-4.3B-F16.gguf +0 -0
  21. function_calling_round2/README.md +53 -0
  22. function_calling_round2/added_tokens.json +13 -0
  23. function_calling_round2/all_results.json +8 -0
  24. function_calling_round2/config.json +137 -0
  25. function_calling_round2/configuration_phi3.py +227 -0
  26. function_calling_round2/generation_config.json +7 -0
  27. function_calling_round2/model-00001-of-00002.safetensors +3 -0
  28. function_calling_round2/model-00002-of-00002.safetensors +3 -0
  29. function_calling_round2/model.safetensors.index.json +226 -0
  30. function_calling_round2/modeling_phi3.py +1572 -0
  31. function_calling_round2/special_tokens_map.json +30 -0
  32. function_calling_round2/tokenizer.json +0 -0
  33. function_calling_round2/tokenizer.model +3 -0
  34. function_calling_round2/tokenizer_config.json +132 -0
function_calling_post_filtering_v4/README.md ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ base_model: models/Phi-3.5-mini-instruct-pro-4
4
+ tags:
5
+ - llama-factory
6
+ - freeze
7
+ - generated_from_trainer
8
+ model-index:
9
+ - name: function_calling_post_filtering_v4
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
+ # function_calling_post_filtering_v4
17
+
18
+ This model is a fine-tuned version of [models/Phi-3.5-mini-instruct-pro-4](https://huggingface.co/models/Phi-3.5-mini-instruct-pro-4) on the function_calling_post_filtering_v4, the function_calling_post_filtering_v4, the function_calling_post_filtering_v4, the function_calling_post_filtering_v4, the function_calling_post_filtering_v4, the mmlu_pro_training and the WildChat_116k_functions datasets.
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: 2
39
+ - eval_batch_size: 8
40
+ - seed: 42
41
+ - gradient_accumulation_steps: 3
42
+ - total_train_batch_size: 6
43
+ - optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-08
44
+ - lr_scheduler_type: cosine_with_restarts
45
+ - lr_scheduler_warmup_ratio: 0.1
46
+ - num_epochs: 2
47
+
48
+ ### Training results
49
+
50
+
51
+
52
+ ### Framework versions
53
+
54
+ - Transformers 4.43.4
55
+ - Pytorch 2.4.0+cu121
56
+ - Datasets 2.20.0
57
+ - Tokenizers 0.19.1
function_calling_post_filtering_v4/added_tokens.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "<|assistant|>": 32001,
3
+ "<|endoftext|>": 32000,
4
+ "<|end|>": 32007,
5
+ "<|placeholder1|>": 32002,
6
+ "<|placeholder2|>": 32003,
7
+ "<|placeholder3|>": 32004,
8
+ "<|placeholder4|>": 32005,
9
+ "<|placeholder5|>": 32008,
10
+ "<|placeholder6|>": 32009,
11
+ "<|system|>": 32006,
12
+ "<|user|>": 32010
13
+ }
function_calling_post_filtering_v4/all_results.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "epoch": 1.9999925446575015,
3
+ "total_flos": 4.406156524096045e+19,
4
+ "train_loss": 0.36868289592002895,
5
+ "train_runtime": 263222.1387,
6
+ "train_samples_per_second": 4.077,
7
+ "train_steps_per_second": 0.679
8
+ }
function_calling_post_filtering_v4/cache/ds_z2_config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "train_batch_size": "auto",
3
+ "train_micro_batch_size_per_gpu": "auto",
4
+ "gradient_accumulation_steps": "auto",
5
+ "gradient_clipping": "auto",
6
+ "zero_allow_untested_optimizer": true,
7
+ "fp16": {
8
+ "enabled": "auto",
9
+ "loss_scale": 0,
10
+ "loss_scale_window": 1000,
11
+ "initial_scale_power": 16,
12
+ "hysteresis": 2,
13
+ "min_loss_scale": 1
14
+ },
15
+ "bf16": {
16
+ "enabled": "auto"
17
+ },
18
+ "zero_optimization": {
19
+ "stage": 2,
20
+ "allgather_partitions": true,
21
+ "allgather_bucket_size": 500000000.0,
22
+ "overlap_comm": true,
23
+ "reduce_scatter": true,
24
+ "reduce_bucket_size": 500000000.0,
25
+ "contiguous_gradients": true,
26
+ "round_robin_gradients": true
27
+ }
28
+ }
function_calling_post_filtering_v4/cache/ds_z2_offload_config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "train_batch_size": "auto",
3
+ "train_micro_batch_size_per_gpu": "auto",
4
+ "gradient_accumulation_steps": "auto",
5
+ "gradient_clipping": "auto",
6
+ "zero_allow_untested_optimizer": true,
7
+ "fp16": {
8
+ "enabled": "auto",
9
+ "loss_scale": 0,
10
+ "loss_scale_window": 1000,
11
+ "initial_scale_power": 16,
12
+ "hysteresis": 2,
13
+ "min_loss_scale": 1
14
+ },
15
+ "bf16": {
16
+ "enabled": "auto"
17
+ },
18
+ "zero_optimization": {
19
+ "stage": 2,
20
+ "allgather_partitions": true,
21
+ "allgather_bucket_size": 500000000.0,
22
+ "overlap_comm": true,
23
+ "reduce_scatter": true,
24
+ "reduce_bucket_size": 500000000.0,
25
+ "contiguous_gradients": true,
26
+ "round_robin_gradients": true,
27
+ "offload_optimizer": {
28
+ "device": "cpu",
29
+ "pin_memory": true
30
+ }
31
+ }
32
+ }
function_calling_post_filtering_v4/cache/ds_z3_config.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "train_batch_size": "auto",
3
+ "train_micro_batch_size_per_gpu": "auto",
4
+ "gradient_accumulation_steps": "auto",
5
+ "gradient_clipping": "auto",
6
+ "zero_allow_untested_optimizer": true,
7
+ "fp16": {
8
+ "enabled": "auto",
9
+ "loss_scale": 0,
10
+ "loss_scale_window": 1000,
11
+ "initial_scale_power": 16,
12
+ "hysteresis": 2,
13
+ "min_loss_scale": 1
14
+ },
15
+ "bf16": {
16
+ "enabled": "auto"
17
+ },
18
+ "zero_optimization": {
19
+ "stage": 3,
20
+ "overlap_comm": true,
21
+ "contiguous_gradients": true,
22
+ "sub_group_size": 1000000000.0,
23
+ "reduce_bucket_size": "auto",
24
+ "stage3_prefetch_bucket_size": "auto",
25
+ "stage3_param_persistence_threshold": "auto",
26
+ "stage3_max_live_parameters": 1000000000.0,
27
+ "stage3_max_reuse_distance": 1000000000.0,
28
+ "stage3_gather_16bit_weights_on_model_save": true
29
+ }
30
+ }
function_calling_post_filtering_v4/cache/ds_z3_offload_config.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "train_batch_size": "auto",
3
+ "train_micro_batch_size_per_gpu": "auto",
4
+ "gradient_accumulation_steps": "auto",
5
+ "gradient_clipping": "auto",
6
+ "zero_allow_untested_optimizer": true,
7
+ "fp16": {
8
+ "enabled": "auto",
9
+ "loss_scale": 0,
10
+ "loss_scale_window": 1000,
11
+ "initial_scale_power": 16,
12
+ "hysteresis": 2,
13
+ "min_loss_scale": 1
14
+ },
15
+ "bf16": {
16
+ "enabled": "auto"
17
+ },
18
+ "zero_optimization": {
19
+ "stage": 3,
20
+ "overlap_comm": true,
21
+ "contiguous_gradients": true,
22
+ "sub_group_size": 1000000000.0,
23
+ "reduce_bucket_size": "auto",
24
+ "stage3_prefetch_bucket_size": "auto",
25
+ "stage3_param_persistence_threshold": "auto",
26
+ "stage3_max_live_parameters": 1000000000.0,
27
+ "stage3_max_reuse_distance": 1000000000.0,
28
+ "stage3_gather_16bit_weights_on_model_save": true,
29
+ "offload_optimizer": {
30
+ "device": "cpu",
31
+ "pin_memory": true
32
+ },
33
+ "offload_param": {
34
+ "device": "cpu",
35
+ "pin_memory": true
36
+ }
37
+ }
38
+ }
function_calling_post_filtering_v4/cache/user_config.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ cache_dir: null
2
+ lang: en
3
+ last_model: null
4
+ path_dict: {}
function_calling_post_filtering_v4/config.json ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "models/Phi-3.5-mini-instruct-pro-4",
3
+ "architectures": [
4
+ "Phi3ForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_phi3.Phi3Config",
10
+ "AutoModelForCausalLM": "modeling_phi3.Phi3ForCausalLM"
11
+ },
12
+ "bos_token_id": 1,
13
+ "embd_pdrop": 0.0,
14
+ "eos_token_id": 32000,
15
+ "hidden_act": "silu",
16
+ "hidden_size": 3072,
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 8192,
19
+ "max_position_embeddings": 131072,
20
+ "model_type": "phi3",
21
+ "num_attention_heads": 32,
22
+ "num_hidden_layers": 36,
23
+ "num_key_value_heads": 32,
24
+ "original_max_position_embeddings": 4096,
25
+ "pad_token_id": 32000,
26
+ "resid_pdrop": 0.0,
27
+ "rms_norm_eps": 1e-05,
28
+ "rope_scaling": {
29
+ "long_factor": [
30
+ 1.0800000429153442,
31
+ 1.1100000143051147,
32
+ 1.1399999856948853,
33
+ 1.340000033378601,
34
+ 1.5899999141693115,
35
+ 1.600000023841858,
36
+ 1.6200000047683716,
37
+ 2.620000123977661,
38
+ 3.2300000190734863,
39
+ 3.2300000190734863,
40
+ 4.789999961853027,
41
+ 7.400000095367432,
42
+ 7.700000286102295,
43
+ 9.09000015258789,
44
+ 12.199999809265137,
45
+ 17.670000076293945,
46
+ 24.46000099182129,
47
+ 28.57000160217285,
48
+ 30.420001983642578,
49
+ 30.840002059936523,
50
+ 32.590003967285156,
51
+ 32.93000411987305,
52
+ 42.320003509521484,
53
+ 44.96000289916992,
54
+ 50.340003967285156,
55
+ 50.45000457763672,
56
+ 57.55000305175781,
57
+ 57.93000411987305,
58
+ 58.21000289916992,
59
+ 60.1400032043457,
60
+ 62.61000442504883,
61
+ 62.62000274658203,
62
+ 62.71000289916992,
63
+ 63.1400032043457,
64
+ 63.1400032043457,
65
+ 63.77000427246094,
66
+ 63.93000411987305,
67
+ 63.96000289916992,
68
+ 63.970001220703125,
69
+ 64.02999877929688,
70
+ 64.06999969482422,
71
+ 64.08000183105469,
72
+ 64.12000274658203,
73
+ 64.41000366210938,
74
+ 64.4800033569336,
75
+ 64.51000213623047,
76
+ 64.52999877929688,
77
+ 64.83999633789062
78
+ ],
79
+ "short_factor": [
80
+ 1.0,
81
+ 1.0199999809265137,
82
+ 1.0299999713897705,
83
+ 1.0299999713897705,
84
+ 1.0499999523162842,
85
+ 1.0499999523162842,
86
+ 1.0499999523162842,
87
+ 1.0499999523162842,
88
+ 1.0499999523162842,
89
+ 1.0699999332427979,
90
+ 1.0999999046325684,
91
+ 1.1099998950958252,
92
+ 1.1599998474121094,
93
+ 1.1599998474121094,
94
+ 1.1699998378753662,
95
+ 1.2899998426437378,
96
+ 1.339999794960022,
97
+ 1.679999828338623,
98
+ 1.7899998426437378,
99
+ 1.8199998140335083,
100
+ 1.8499997854232788,
101
+ 1.8799997568130493,
102
+ 1.9099997282028198,
103
+ 1.9399996995925903,
104
+ 1.9899996519088745,
105
+ 2.0199997425079346,
106
+ 2.0199997425079346,
107
+ 2.0199997425079346,
108
+ 2.0199997425079346,
109
+ 2.0199997425079346,
110
+ 2.0199997425079346,
111
+ 2.0299997329711914,
112
+ 2.0299997329711914,
113
+ 2.0299997329711914,
114
+ 2.0299997329711914,
115
+ 2.0299997329711914,
116
+ 2.0299997329711914,
117
+ 2.0299997329711914,
118
+ 2.0299997329711914,
119
+ 2.0299997329711914,
120
+ 2.0799996852874756,
121
+ 2.0899996757507324,
122
+ 2.189999580383301,
123
+ 2.2199995517730713,
124
+ 2.5899994373321533,
125
+ 2.729999542236328,
126
+ 2.749999523162842,
127
+ 2.8399994373321533
128
+ ],
129
+ "type": "longrope"
130
+ },
131
+ "rope_theta": 10000.0,
132
+ "sliding_window": 262144,
133
+ "tie_word_embeddings": false,
134
+ "torch_dtype": "bfloat16",
135
+ "transformers_version": "4.43.4",
136
+ "use_cache": false,
137
+ "vocab_size": 32064
138
+ }
function_calling_post_filtering_v4/configuration_phi3.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """ Phi-3 model configuration"""
17
+
18
+
19
+ from transformers.configuration_utils import PretrainedConfig
20
+ from transformers.utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+ PHI3_PRETRAINED_CONFIG_ARCHIVE_MAP = {
26
+ "microsoft/Phi-3-mini-4k-instruct": "https://huggingface.co/microsoft/Phi-3-mini-4k-instruct/resolve/main/config.json",
27
+ "microsoft/Phi-3-mini-128k-instruct": "https://huggingface.co/microsoft/Phi-3-mini-128k-instruct/resolve/main/config.json",
28
+ }
29
+
30
+
31
+ class Phi3Config(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration of a [`Phi3Model`]. It is used to instantiate a Phi-3
34
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
35
+ defaults will yield a similar configuration to that of the
36
+ [microsoft/Phi-3-mini-4k-instruct](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct).
37
+
38
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
39
+ documentation from [`PretrainedConfig`] for more information.
40
+
41
+ Args:
42
+ vocab_size (`int`, *optional*, defaults to 32064):
43
+ Vocabulary size of the Phi-3 model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`Phi3Model`].
45
+ hidden_size (`int`, *optional*, defaults to 3072):
46
+ Dimension of the hidden representations.
47
+ intermediate_size (`int`, *optional*, defaults to 8192):
48
+ Dimension of the MLP representations.
49
+ num_hidden_layers (`int`, *optional*, defaults to 32):
50
+ Number of hidden layers in the Transformer decoder.
51
+ num_attention_heads (`int`, *optional*, defaults to 32):
52
+ Number of attention heads for each attention layer in the Transformer decoder.
53
+ num_key_value_heads (`int`, *optional*):
54
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
55
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
56
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
57
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
58
+ by meanpooling all the original heads within that group. For more details checkout [this
59
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
60
+ `num_attention_heads`.
61
+ resid_pdrop (`float`, *optional*, defaults to 0.0):
62
+ Dropout probability for mlp outputs.
63
+ embd_pdrop (`int`, *optional*, defaults to 0.0):
64
+ The dropout ratio for the embeddings.
65
+ attention_dropout (`float`, *optional*, defaults to 0.0):
66
+ The dropout ratio after computing the attention scores.
67
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
68
+ The non-linear activation function (function or string) in the decoder.
69
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
70
+ The maximum sequence length that this model might ever be used with.
71
+ original_max_position_embeddings (`int`, *optional*, defaults to 4096):
72
+ The maximum sequence length that this model was trained with. This is used to determine the size of the
73
+ original RoPE embeddings when using long scaling.
74
+ initializer_range (`float`, *optional*, defaults to 0.02):
75
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
76
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
77
+ The epsilon value used for the RMSNorm.
78
+ use_cache (`bool`, *optional*, defaults to `True`):
79
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
80
+ relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
81
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
82
+ Whether to tie weight embeddings
83
+ rope_theta (`float`, *optional*, defaults to 10000.0):
84
+ The base period of the RoPE embeddings.
85
+ rope_scaling (`dict`, *optional*):
86
+ The scaling strategy for the RoPE embeddings. If `None`, no scaling is applied. If a dictionary, it must
87
+ contain the following keys: `type`, `short_factor` and `long_factor`. The `type` must be `longrope` and
88
+ the `short_factor` and `long_factor` must be lists of numbers with the same length as the hidden size
89
+ divided by the number of attention heads divided by 2.
90
+ bos_token_id (`int`, *optional*, defaults to 1):
91
+ The id of the "beginning-of-sequence" token.
92
+ eos_token_id (`int`, *optional*, defaults to 32000):
93
+ The id of the "end-of-sequence" token.
94
+ pad_token_id (`int`, *optional*, defaults to 32000):
95
+ The id of the padding token.
96
+ sliding_window (`int`, *optional*):
97
+ Sliding window attention window size. If `None`, no sliding window is applied.
98
+
99
+ Example:
100
+
101
+ ```python
102
+ >>> from transformers import Phi3Model, Phi3Config
103
+
104
+ >>> # Initializing a Phi-3 style configuration
105
+ >>> configuration = Phi3Config.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
106
+
107
+ >>> # Initializing a model from the configuration
108
+ >>> model = Phi3Model(configuration)
109
+
110
+ >>> # Accessing the model configuration
111
+ >>> configuration = model.config
112
+ ```"""
113
+
114
+ model_type = "phi3"
115
+ keys_to_ignore_at_inference = ["past_key_values"]
116
+
117
+ def __init__(
118
+ self,
119
+ vocab_size=32064,
120
+ hidden_size=3072,
121
+ intermediate_size=8192,
122
+ num_hidden_layers=32,
123
+ num_attention_heads=32,
124
+ num_key_value_heads=None,
125
+ resid_pdrop=0.0,
126
+ embd_pdrop=0.0,
127
+ attention_dropout=0.0,
128
+ hidden_act="silu",
129
+ max_position_embeddings=4096,
130
+ original_max_position_embeddings=4096,
131
+ initializer_range=0.02,
132
+ rms_norm_eps=1e-5,
133
+ use_cache=True,
134
+ tie_word_embeddings=False,
135
+ rope_theta=10000.0,
136
+ rope_scaling=None,
137
+ bos_token_id=1,
138
+ eos_token_id=32000,
139
+ pad_token_id=32000,
140
+ sliding_window=None,
141
+ **kwargs,
142
+ ):
143
+ self.vocab_size = vocab_size
144
+ self.hidden_size = hidden_size
145
+ self.intermediate_size = intermediate_size
146
+ self.num_hidden_layers = num_hidden_layers
147
+ self.num_attention_heads = num_attention_heads
148
+
149
+ if num_key_value_heads is None:
150
+ num_key_value_heads = num_attention_heads
151
+
152
+ self.num_key_value_heads = num_key_value_heads
153
+ self.resid_pdrop = resid_pdrop
154
+ self.embd_pdrop = embd_pdrop
155
+ self.attention_dropout = attention_dropout
156
+ self.hidden_act = hidden_act
157
+ self.max_position_embeddings = max_position_embeddings
158
+ self.original_max_position_embeddings = original_max_position_embeddings
159
+ self.initializer_range = initializer_range
160
+ self.rms_norm_eps = rms_norm_eps
161
+ self.use_cache = use_cache
162
+ self.rope_theta = rope_theta
163
+ self.rope_scaling = rope_scaling
164
+ self._rope_scaling_adjustment()
165
+ self._rope_scaling_validation()
166
+ self.sliding_window = sliding_window
167
+
168
+ super().__init__(
169
+ bos_token_id=bos_token_id,
170
+ eos_token_id=eos_token_id,
171
+ pad_token_id=pad_token_id,
172
+ tie_word_embeddings=tie_word_embeddings,
173
+ **kwargs,
174
+ )
175
+
176
+ def _rope_scaling_adjustment(self):
177
+ """
178
+ Adjust the `type` of the `rope_scaling` configuration for backward compatibility.
179
+ """
180
+ if self.rope_scaling is None:
181
+ return
182
+
183
+ rope_scaling_type = self.rope_scaling.get("type", None)
184
+
185
+ # For backward compatibility if previous version used "su" or "yarn"
186
+ if rope_scaling_type is not None and rope_scaling_type in ["su", "yarn"]:
187
+ self.rope_scaling["type"] = "longrope"
188
+
189
+ def _rope_scaling_validation(self):
190
+ """
191
+ Validate the `rope_scaling` configuration.
192
+ """
193
+ if self.rope_scaling is None:
194
+ return
195
+
196
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 3:
197
+ raise ValueError(
198
+ "`rope_scaling` must be a dictionary with three fields, `type`, `short_factor` and `long_factor`, "
199
+ f"got {self.rope_scaling}"
200
+ )
201
+ rope_scaling_type = self.rope_scaling.get("type", None)
202
+ rope_scaling_short_factor = self.rope_scaling.get("short_factor", None)
203
+ rope_scaling_long_factor = self.rope_scaling.get("long_factor", None)
204
+ if rope_scaling_type is None or rope_scaling_type not in ["longrope"]:
205
+ raise ValueError(f"`rope_scaling`'s type field must be one of ['longrope'], got {rope_scaling_type}")
206
+ if not (
207
+ isinstance(rope_scaling_short_factor, list)
208
+ and all(isinstance(x, (int, float)) for x in rope_scaling_short_factor)
209
+ ):
210
+ raise ValueError(
211
+ f"`rope_scaling`'s short_factor field must be a list of numbers, got {rope_scaling_short_factor}"
212
+ )
213
+ if not len(rope_scaling_short_factor) == self.hidden_size // self.num_attention_heads // 2:
214
+ raise ValueError(
215
+ f"`rope_scaling`'s short_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_short_factor)}"
216
+ )
217
+ if not (
218
+ isinstance(rope_scaling_long_factor, list)
219
+ and all(isinstance(x, (int, float)) for x in rope_scaling_long_factor)
220
+ ):
221
+ raise ValueError(
222
+ f"`rope_scaling`'s long_factor field must be a list of numbers, got {rope_scaling_long_factor}"
223
+ )
224
+ if not len(rope_scaling_long_factor) == self.hidden_size // self.num_attention_heads // 2:
225
+ raise ValueError(
226
+ f"`rope_scaling`'s long_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_long_factor)}"
227
+ )
function_calling_post_filtering_v4/generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 32000,
5
+ "pad_token_id": 32000,
6
+ "transformers_version": "4.43.4"
7
+ }
function_calling_post_filtering_v4/model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f94eb63495f268942b2ce72a970319a19e65ba853706ec54561e89478f07401d
3
+ size 4972487920
function_calling_post_filtering_v4/model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:57e18ef2343a75ec04f532019dc2add7bbb53608bb4852da44d5dc48d175263a
3
+ size 4481734408
function_calling_post_filtering_v4/model.safetensors.index.json ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 9454196736
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00002-of-00002.safetensors",
7
+ "model.embed_tokens.weight": "model-00001-of-00002.safetensors",
8
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00002.safetensors",
9
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
10
+ "model.layers.0.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
11
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
12
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
13
+ "model.layers.0.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
14
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00002.safetensors",
15
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
16
+ "model.layers.1.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
17
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
18
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
19
+ "model.layers.1.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
20
+ "model.layers.10.input_layernorm.weight": "model-00001-of-00002.safetensors",
21
+ "model.layers.10.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
22
+ "model.layers.10.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
23
+ "model.layers.10.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
24
+ "model.layers.10.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
25
+ "model.layers.10.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
26
+ "model.layers.11.input_layernorm.weight": "model-00001-of-00002.safetensors",
27
+ "model.layers.11.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
28
+ "model.layers.11.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
29
+ "model.layers.11.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
30
+ "model.layers.11.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
31
+ "model.layers.11.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
32
+ "model.layers.12.input_layernorm.weight": "model-00001-of-00002.safetensors",
33
+ "model.layers.12.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
34
+ "model.layers.12.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
35
+ "model.layers.12.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
36
+ "model.layers.12.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
37
+ "model.layers.12.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
38
+ "model.layers.13.input_layernorm.weight": "model-00001-of-00002.safetensors",
39
+ "model.layers.13.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
40
+ "model.layers.13.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
41
+ "model.layers.13.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
42
+ "model.layers.13.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
43
+ "model.layers.13.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
44
+ "model.layers.14.input_layernorm.weight": "model-00001-of-00002.safetensors",
45
+ "model.layers.14.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
46
+ "model.layers.14.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
47
+ "model.layers.14.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
48
+ "model.layers.14.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
49
+ "model.layers.14.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
50
+ "model.layers.15.input_layernorm.weight": "model-00001-of-00002.safetensors",
51
+ "model.layers.15.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
52
+ "model.layers.15.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
53
+ "model.layers.15.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
54
+ "model.layers.15.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
55
+ "model.layers.15.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
56
+ "model.layers.16.input_layernorm.weight": "model-00001-of-00002.safetensors",
57
+ "model.layers.16.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
58
+ "model.layers.16.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
59
+ "model.layers.16.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
60
+ "model.layers.16.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
61
+ "model.layers.16.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
62
+ "model.layers.17.input_layernorm.weight": "model-00001-of-00002.safetensors",
63
+ "model.layers.17.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
64
+ "model.layers.17.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
65
+ "model.layers.17.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
66
+ "model.layers.17.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
67
+ "model.layers.17.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
68
+ "model.layers.18.input_layernorm.weight": "model-00001-of-00002.safetensors",
69
+ "model.layers.18.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
70
+ "model.layers.18.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
71
+ "model.layers.18.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
72
+ "model.layers.18.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
73
+ "model.layers.18.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
74
+ "model.layers.19.input_layernorm.weight": "model-00002-of-00002.safetensors",
75
+ "model.layers.19.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
76
+ "model.layers.19.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
77
+ "model.layers.19.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
78
+ "model.layers.19.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
79
+ "model.layers.19.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
80
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00002.safetensors",
81
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
82
+ "model.layers.2.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
83
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
84
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
85
+ "model.layers.2.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
86
+ "model.layers.20.input_layernorm.weight": "model-00002-of-00002.safetensors",
87
+ "model.layers.20.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
88
+ "model.layers.20.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
89
+ "model.layers.20.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
90
+ "model.layers.20.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
91
+ "model.layers.20.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
92
+ "model.layers.21.input_layernorm.weight": "model-00002-of-00002.safetensors",
93
+ "model.layers.21.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
94
+ "model.layers.21.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
95
+ "model.layers.21.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
96
+ "model.layers.21.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
97
+ "model.layers.21.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
98
+ "model.layers.22.input_layernorm.weight": "model-00002-of-00002.safetensors",
99
+ "model.layers.22.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
100
+ "model.layers.22.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
101
+ "model.layers.22.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
102
+ "model.layers.22.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
103
+ "model.layers.22.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
104
+ "model.layers.23.input_layernorm.weight": "model-00002-of-00002.safetensors",
105
+ "model.layers.23.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
106
+ "model.layers.23.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
107
+ "model.layers.23.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
108
+ "model.layers.23.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
109
+ "model.layers.23.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
110
+ "model.layers.24.input_layernorm.weight": "model-00002-of-00002.safetensors",
111
+ "model.layers.24.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
112
+ "model.layers.24.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
113
+ "model.layers.24.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
114
+ "model.layers.24.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
115
+ "model.layers.24.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
116
+ "model.layers.25.input_layernorm.weight": "model-00002-of-00002.safetensors",
117
+ "model.layers.25.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
118
+ "model.layers.25.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
119
+ "model.layers.25.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
120
+ "model.layers.25.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
121
+ "model.layers.25.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
122
+ "model.layers.26.input_layernorm.weight": "model-00002-of-00002.safetensors",
123
+ "model.layers.26.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
124
+ "model.layers.26.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
125
+ "model.layers.26.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
126
+ "model.layers.26.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
127
+ "model.layers.26.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
128
+ "model.layers.27.input_layernorm.weight": "model-00002-of-00002.safetensors",
129
+ "model.layers.27.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
130
+ "model.layers.27.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
131
+ "model.layers.27.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
132
+ "model.layers.27.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
133
+ "model.layers.27.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
134
+ "model.layers.28.input_layernorm.weight": "model-00002-of-00002.safetensors",
135
+ "model.layers.28.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
136
+ "model.layers.28.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
137
+ "model.layers.28.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
138
+ "model.layers.28.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
139
+ "model.layers.28.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
140
+ "model.layers.29.input_layernorm.weight": "model-00002-of-00002.safetensors",
141
+ "model.layers.29.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
142
+ "model.layers.29.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
143
+ "model.layers.29.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
144
+ "model.layers.29.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
145
+ "model.layers.29.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
146
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00002.safetensors",
147
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
148
+ "model.layers.3.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
149
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
150
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
151
+ "model.layers.3.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
152
+ "model.layers.30.input_layernorm.weight": "model-00002-of-00002.safetensors",
153
+ "model.layers.30.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
154
+ "model.layers.30.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
155
+ "model.layers.30.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
156
+ "model.layers.30.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
157
+ "model.layers.30.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
158
+ "model.layers.31.input_layernorm.weight": "model-00002-of-00002.safetensors",
159
+ "model.layers.31.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
160
+ "model.layers.31.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
161
+ "model.layers.31.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
162
+ "model.layers.31.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
163
+ "model.layers.31.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
164
+ "model.layers.32.input_layernorm.weight": "model-00002-of-00002.safetensors",
165
+ "model.layers.32.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
166
+ "model.layers.32.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
167
+ "model.layers.32.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
168
+ "model.layers.32.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
169
+ "model.layers.32.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
170
+ "model.layers.33.input_layernorm.weight": "model-00002-of-00002.safetensors",
171
+ "model.layers.33.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
172
+ "model.layers.33.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
173
+ "model.layers.33.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
174
+ "model.layers.33.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
175
+ "model.layers.33.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
176
+ "model.layers.34.input_layernorm.weight": "model-00002-of-00002.safetensors",
177
+ "model.layers.34.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
178
+ "model.layers.34.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
179
+ "model.layers.34.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
180
+ "model.layers.34.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
181
+ "model.layers.34.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
182
+ "model.layers.35.input_layernorm.weight": "model-00002-of-00002.safetensors",
183
+ "model.layers.35.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
184
+ "model.layers.35.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
185
+ "model.layers.35.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
186
+ "model.layers.35.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
187
+ "model.layers.35.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
188
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00002.safetensors",
189
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
190
+ "model.layers.4.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
191
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
192
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
193
+ "model.layers.4.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
194
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00002.safetensors",
195
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
196
+ "model.layers.5.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
197
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
198
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
199
+ "model.layers.5.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
200
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00002.safetensors",
201
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
202
+ "model.layers.6.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
203
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
204
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
205
+ "model.layers.6.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
206
+ "model.layers.7.input_layernorm.weight": "model-00001-of-00002.safetensors",
207
+ "model.layers.7.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
208
+ "model.layers.7.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
209
+ "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
210
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
211
+ "model.layers.7.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
212
+ "model.layers.8.input_layernorm.weight": "model-00001-of-00002.safetensors",
213
+ "model.layers.8.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
214
+ "model.layers.8.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
215
+ "model.layers.8.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
216
+ "model.layers.8.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
217
+ "model.layers.8.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
218
+ "model.layers.9.input_layernorm.weight": "model-00001-of-00002.safetensors",
219
+ "model.layers.9.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
220
+ "model.layers.9.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
221
+ "model.layers.9.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
222
+ "model.layers.9.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
223
+ "model.layers.9.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
224
+ "model.norm.weight": "model-00002-of-00002.safetensors"
225
+ }
226
+ }
function_calling_post_filtering_v4/modeling_phi3.py ADDED
@@ -0,0 +1,1572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """ PyTorch Phi-3 model."""
17
+
18
+ #import sys
19
+ #sys.path.append('/home/ubuntu/.cache/huggingface/modules/transformers_modules/microsoft/Phi-3.5-mini-instruct/ccf028fc8e1b3ab750a7c55b22792f57ba69f216/')
20
+ import inspect
21
+ import math
22
+ import warnings
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.cache_utils import Cache, DynamicCache
33
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
34
+ from transformers.modeling_outputs import (
35
+ BaseModelOutputWithPast,
36
+ CausalLMOutputWithPast,
37
+ SequenceClassifierOutputWithPast,
38
+ TokenClassifierOutput,
39
+ )
40
+ from transformers.modeling_utils import PreTrainedModel
41
+ from transformers.utils import (
42
+ add_code_sample_docstrings,
43
+ add_start_docstrings,
44
+ add_start_docstrings_to_model_forward,
45
+ is_flash_attn_2_available,
46
+ is_flash_attn_greater_or_equal_2_10,
47
+ logging,
48
+ replace_return_docstrings,
49
+ )
50
+ from .configuration_phi3 import Phi3Config
51
+
52
+
53
+ logger = logging.get_logger(__name__)
54
+
55
+ # Transformers scans dependencies in the modeling file, causing issues on conditional loading. The regex only ignores try/catch blocks, but not if statements
56
+ # if is_flash_attn_2_available():
57
+ _flash_supports_window_size = False
58
+ try:
59
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
60
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
61
+
62
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
63
+ except ImportError as error:
64
+ logger.warning(
65
+ f"`flash-attention` package not found, consider installing for better performance: {error}."
66
+ )
67
+ if not _flash_supports_window_size:
68
+ logger.warning(
69
+ "Current `flash-attention` does not support `window_size`. Either upgrade or use `attn_implementation='eager'`."
70
+ )
71
+
72
+ _CHECKPOINT_FOR_DOC = "microsoft/Phi-3-mini-4k-instruct"
73
+ _CONFIG_FOR_DOC = "Phi3Config"
74
+
75
+ PHI3_PRETRAINED_MODEL_ARCHIVE_LIST = [
76
+ "microsoft/Phi-3-mini-4k-instruct",
77
+ "microsoft/Phi-3-mini-128k-instruct",
78
+ # See all Phi-3 models at https://huggingface.co/models?filter=Phi-3
79
+ ]
80
+
81
+
82
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Phi3
83
+ class Phi3RMSNorm(nn.Module):
84
+ def __init__(self, hidden_size, eps=1e-6):
85
+ """
86
+ Phi3RMSNorm is equivalent to T5LayerNorm
87
+ """
88
+ super().__init__()
89
+ self.weight = nn.Parameter(torch.ones(hidden_size))
90
+ self.variance_epsilon = eps
91
+
92
+ def forward(self, hidden_states):
93
+ input_dtype = hidden_states.dtype
94
+ hidden_states = hidden_states.to(torch.float32)
95
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
96
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
97
+ return self.weight * hidden_states.to(input_dtype)
98
+
99
+
100
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
101
+ def _get_unpad_data(attention_mask):
102
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
103
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
104
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
105
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
106
+ return (
107
+ indices,
108
+ cu_seqlens,
109
+ max_seqlen_in_batch,
110
+ )
111
+
112
+
113
+ # Copied from transformers.models.gemma.modeling_gemma.GemmaRotaryEmbedding with gemma->phi3, Gemma->Phi3
114
+ class Phi3RotaryEmbedding(nn.Module):
115
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
116
+ super().__init__()
117
+
118
+ self.dim = dim
119
+ self.max_position_embeddings = max_position_embeddings
120
+ self.base = base
121
+ self.register_buffer("inv_freq", None, persistent=False)
122
+
123
+ @torch.no_grad()
124
+ def forward(self, x, position_ids, seq_len=None):
125
+ # x: [bs, num_attention_heads, seq_len, head_size]
126
+ if self.inv_freq is None:
127
+ self.inv_freq = 1.0 / (
128
+ self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim)
129
+ )
130
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
131
+ position_ids_expanded = position_ids[:, None, :].float()
132
+ # Force float32 since bfloat16 loses precision on long contexts
133
+ # See https://github.com/huggingface/transformers/pull/29285
134
+ device_type = x.device.type
135
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
136
+ with torch.autocast(device_type=device_type, enabled=False):
137
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
138
+ emb = torch.cat((freqs, freqs), dim=-1)
139
+ cos = emb.cos()
140
+ sin = emb.sin()
141
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
142
+
143
+
144
+ class Phi3LongRoPEScaledRotaryEmbedding(Phi3RotaryEmbedding):
145
+ def __init__(self, dim, config, device=None):
146
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
147
+
148
+ self.short_factor = config.rope_scaling["short_factor"]
149
+ self.long_factor = config.rope_scaling["long_factor"]
150
+ self.original_max_position_embeddings = config.original_max_position_embeddings
151
+
152
+ @torch.no_grad()
153
+ def forward(self, x, position_ids, seq_len=None):
154
+ seq_len = seq_len or torch.max(position_ids) + 1
155
+ if seq_len > self.original_max_position_embeddings:
156
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
157
+ else:
158
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
159
+
160
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
161
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
162
+
163
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
164
+ position_ids_expanded = position_ids[:, None, :].float()
165
+
166
+ # Force float32 since bfloat16 loses precision on long contexts
167
+ # See https://github.com/huggingface/transformers/pull/29285
168
+ device_type = x.device.type
169
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
170
+ with torch.autocast(device_type=device_type, enabled=False):
171
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
172
+ emb = torch.cat((freqs, freqs), dim=-1)
173
+
174
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
175
+ if scale <= 1.0:
176
+ scaling_factor = 1.0
177
+ else:
178
+ scaling_factor = math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
179
+
180
+ cos = emb.cos() * scaling_factor
181
+ sin = emb.sin() * scaling_factor
182
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
183
+
184
+
185
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
186
+ def rotate_half(x):
187
+ """Rotates half the hidden dims of the input."""
188
+ x1 = x[..., : x.shape[-1] // 2]
189
+ x2 = x[..., x.shape[-1] // 2 :]
190
+ return torch.cat((-x2, x1), dim=-1)
191
+
192
+
193
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
194
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
195
+ """Applies Rotary Position Embedding to the query and key tensors.
196
+
197
+ Args:
198
+ q (`torch.Tensor`): The query tensor.
199
+ k (`torch.Tensor`): The key tensor.
200
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
201
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
202
+ position_ids (`torch.Tensor`, *optional*):
203
+ Deprecated and unused.
204
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
205
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
206
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
207
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
208
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
209
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
210
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
211
+ Returns:
212
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
213
+ """
214
+ cos = cos.unsqueeze(unsqueeze_dim)
215
+ sin = sin.unsqueeze(unsqueeze_dim)
216
+ q_embed = (q * cos) + (rotate_half(q) * sin)
217
+ k_embed = (k * cos) + (rotate_half(k) * sin)
218
+ return q_embed, k_embed
219
+
220
+
221
+ class Phi3MLP(nn.Module):
222
+ def __init__(self, config):
223
+ super().__init__()
224
+
225
+ self.config = config
226
+ self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
227
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
228
+
229
+ self.activation_fn = ACT2FN[config.hidden_act]
230
+
231
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
232
+ up_states = self.gate_up_proj(hidden_states)
233
+
234
+ gate, up_states = up_states.chunk(2, dim=-1)
235
+ up_states = up_states * self.activation_fn(gate)
236
+
237
+ return self.down_proj(up_states)
238
+
239
+
240
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
241
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
242
+ """
243
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
244
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
245
+ """
246
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
247
+ if n_rep == 1:
248
+ return hidden_states
249
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
250
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
251
+
252
+
253
+ class Phi3Attention(nn.Module):
254
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
255
+
256
+ def __init__(self, config: Phi3Config, layer_idx: Optional[int] = None):
257
+ super().__init__()
258
+ self.config = config
259
+ self.layer_idx = layer_idx
260
+ if layer_idx is None:
261
+ logger.warning_once(
262
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
263
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
264
+ "when creating this class."
265
+ )
266
+
267
+ self.attention_dropout = config.attention_dropout
268
+ self.hidden_size = config.hidden_size
269
+ self.num_heads = config.num_attention_heads
270
+ self.head_dim = self.hidden_size // self.num_heads
271
+ self.num_key_value_heads = config.num_key_value_heads
272
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
273
+ self.max_position_embeddings = config.max_position_embeddings
274
+ self.original_max_position_embeddings = config.original_max_position_embeddings
275
+ self.rope_theta = config.rope_theta
276
+ self.rope_scaling = config.rope_scaling
277
+ self.is_causal = True
278
+
279
+ if (self.head_dim * self.num_heads) != self.hidden_size:
280
+ raise ValueError(
281
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
282
+ f" and `num_heads`: {self.num_heads})."
283
+ )
284
+
285
+ op_size = self.num_heads * self.head_dim + 2 * (self.num_key_value_heads * self.head_dim)
286
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
287
+ self.qkv_proj = nn.Linear(self.hidden_size, op_size, bias=False)
288
+ self._init_rope()
289
+
290
+ def _init_rope(self):
291
+ if self.rope_scaling is None:
292
+ self.rotary_emb = Phi3RotaryEmbedding(
293
+ self.head_dim,
294
+ max_position_embeddings=self.max_position_embeddings,
295
+ base=self.rope_theta,
296
+ )
297
+ else:
298
+ scaling_type = self.config.rope_scaling["type"]
299
+ if scaling_type == "longrope":
300
+ self.rotary_emb = Phi3LongRoPEScaledRotaryEmbedding(self.head_dim, self.config)
301
+ else:
302
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
303
+
304
+ def forward(
305
+ self,
306
+ hidden_states: torch.Tensor,
307
+ attention_mask: Optional[torch.Tensor] = None,
308
+ position_ids: Optional[torch.LongTensor] = None,
309
+ past_key_value: Optional[Cache] = None,
310
+ output_attentions: bool = False,
311
+ use_cache: bool = False,
312
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
313
+ logger.warning_once("You are not running the flash-attention implementation, expect numerical differences.")
314
+
315
+ bsz, q_len, _ = hidden_states.size()
316
+
317
+ qkv = self.qkv_proj(hidden_states)
318
+ query_pos = self.num_heads * self.head_dim
319
+ query_states = qkv[..., :query_pos]
320
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
321
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
322
+
323
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
324
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
325
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
326
+
327
+ kv_seq_len = key_states.shape[-2]
328
+ if past_key_value is not None:
329
+ if self.layer_idx is None:
330
+ raise ValueError(
331
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
332
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
333
+ "with a layer index."
334
+ )
335
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
336
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
337
+
338
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
339
+
340
+ if past_key_value is not None:
341
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
342
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
343
+
344
+ # repeat k/v heads if n_kv_heads < n_heads
345
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
346
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
347
+
348
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
349
+
350
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
351
+ raise ValueError(
352
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
353
+ f" {attn_weights.size()}"
354
+ )
355
+
356
+ if attention_mask is not None:
357
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
358
+ raise ValueError(
359
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
360
+ )
361
+ attn_weights = attn_weights + attention_mask
362
+
363
+ # upcast attention to fp32
364
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
365
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
366
+
367
+ attn_output = torch.matmul(attn_weights, value_states)
368
+
369
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
370
+ raise ValueError(
371
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
372
+ f" {attn_output.size()}"
373
+ )
374
+
375
+ attn_output = attn_output.transpose(1, 2).contiguous()
376
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
377
+
378
+ attn_output = self.o_proj(attn_output)
379
+
380
+ if not output_attentions:
381
+ attn_weights = None
382
+
383
+ return attn_output, attn_weights, past_key_value
384
+
385
+
386
+ class Phi3FlashAttention2(Phi3Attention):
387
+ """
388
+ Phi-3 flash attention module. This module inherits from `Phi3Attention` as the weights of the module stays
389
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
390
+ flash attention and deal with padding tokens in case the input contains any of them.
391
+ """
392
+
393
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
394
+ def __init__(self, *args, **kwargs):
395
+ super().__init__(*args, **kwargs)
396
+
397
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
398
+ # 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.
399
+ # 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).
400
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
401
+
402
+ def forward(
403
+ self,
404
+ hidden_states: torch.Tensor,
405
+ attention_mask: Optional[torch.LongTensor] = None,
406
+ position_ids: Optional[torch.LongTensor] = None,
407
+ past_key_value: Optional[Cache] = None,
408
+ output_attentions: bool = False,
409
+ use_cache: bool = False,
410
+ **kwargs,
411
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
412
+ # Phi3FlashAttention2 attention does not support output_attentions
413
+
414
+ if not _flash_supports_window_size:
415
+ logger.warning_once(
416
+ "The current flash attention version does not support sliding window attention. Please use `attn_implementation='eager'` or upgrade flash-attn library."
417
+ )
418
+ raise ValueError("The current flash attention version does not support sliding window attention.")
419
+
420
+ output_attentions = False
421
+
422
+ if "padding_mask" in kwargs:
423
+ warnings.warn(
424
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
425
+ )
426
+
427
+ # overwrite attention_mask with padding_mask
428
+ attention_mask = kwargs.pop("padding_mask")
429
+
430
+ bsz, q_len, _ = hidden_states.size()
431
+
432
+ qkv = self.qkv_proj(hidden_states)
433
+ query_pos = self.num_heads * self.head_dim
434
+ query_states = qkv[..., :query_pos]
435
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
436
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
437
+
438
+ # Flash attention requires the input to have the shape
439
+ # batch_size x seq_length x head_dim x hidden_dim
440
+ # therefore we just need to keep the original shape
441
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
442
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
443
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
444
+
445
+ kv_seq_len = key_states.shape[-2]
446
+ if past_key_value is not None:
447
+ if self.layer_idx is None:
448
+ raise ValueError(
449
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
450
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
451
+ "with a layer index."
452
+ )
453
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
454
+
455
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
456
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item() + 1)
457
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=rotary_seq_len)
458
+
459
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
460
+
461
+ use_sliding_windows = (
462
+ _flash_supports_window_size
463
+ and getattr(self.config, "sliding_window", None) is not None
464
+ and kv_seq_len > self.config.sliding_window
465
+ )
466
+
467
+ if past_key_value is not None:
468
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
469
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
470
+ if (
471
+ getattr(self.config, "sliding_window", None) is not None
472
+ and kv_seq_len > self.config.sliding_window
473
+ and cache_has_contents
474
+ ):
475
+ slicing_tokens = 1 - self.config.sliding_window
476
+
477
+ past_key = past_key_value[self.layer_idx][0]
478
+ past_value = past_key_value[self.layer_idx][1]
479
+
480
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
481
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
482
+
483
+ if past_key.shape[-2] != self.config.sliding_window - 1:
484
+ raise ValueError(
485
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
486
+ f" {past_key.shape}"
487
+ )
488
+
489
+ if attention_mask is not None:
490
+ attention_mask = attention_mask[:, slicing_tokens:]
491
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
492
+
493
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
494
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
495
+
496
+ # repeat k/v heads if n_kv_heads < n_heads
497
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
498
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
499
+
500
+ attn_dropout = self.attention_dropout if self.training else 0.0
501
+
502
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
503
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
504
+ # cast them back in the correct dtype just to be sure everything works as expected.
505
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
506
+ # in fp32.
507
+
508
+ if query_states.dtype == torch.float32:
509
+ if torch.is_autocast_enabled():
510
+ target_dtype = torch.get_autocast_gpu_dtype()
511
+ # Handle the case where the model is quantized
512
+ elif hasattr(self.config, "_pre_quantization_dtype"):
513
+ target_dtype = self.config._pre_quantization_dtype
514
+ else:
515
+ target_dtype = self.qkv_proj.weight.dtype
516
+
517
+ logger.warning_once(
518
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
519
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
520
+ f" {target_dtype}."
521
+ )
522
+
523
+ query_states = query_states.to(target_dtype)
524
+ key_states = key_states.to(target_dtype)
525
+ value_states = value_states.to(target_dtype)
526
+
527
+ # Reashape to the expected shape for Flash Attention
528
+ query_states = query_states.transpose(1, 2)
529
+ key_states = key_states.transpose(1, 2)
530
+ value_states = value_states.transpose(1, 2)
531
+
532
+ attn_output = self._flash_attention_forward(
533
+ query_states,
534
+ key_states,
535
+ value_states,
536
+ attention_mask,
537
+ q_len,
538
+ dropout=attn_dropout,
539
+ use_sliding_windows=use_sliding_windows,
540
+ )
541
+
542
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
543
+ attn_output = self.o_proj(attn_output)
544
+
545
+ if not output_attentions:
546
+ attn_weights = None
547
+
548
+ return attn_output, attn_weights, past_key_value
549
+
550
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._flash_attention_forward
551
+ def _flash_attention_forward(
552
+ self,
553
+ query_states,
554
+ key_states,
555
+ value_states,
556
+ attention_mask,
557
+ query_length,
558
+ dropout=0.0,
559
+ softmax_scale=None,
560
+ use_sliding_windows=False,
561
+ ):
562
+ """
563
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
564
+ first unpad the input, then computes the attention scores and pad the final attention scores.
565
+
566
+ Args:
567
+ query_states (`torch.Tensor`):
568
+ Input query states to be passed to Flash Attention API
569
+ key_states (`torch.Tensor`):
570
+ Input key states to be passed to Flash Attention API
571
+ value_states (`torch.Tensor`):
572
+ Input value states to be passed to Flash Attention API
573
+ attention_mask (`torch.Tensor`):
574
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
575
+ position of padding tokens and 1 for the position of non-padding tokens.
576
+ dropout (`float`):
577
+ Attention dropout
578
+ softmax_scale (`float`, *optional*):
579
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
580
+ use_sliding_windows (`bool`, *optional*):
581
+ Whether to activate sliding window attention.
582
+ """
583
+ if not self._flash_attn_uses_top_left_mask:
584
+ causal = self.is_causal
585
+ else:
586
+ # 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__.
587
+ causal = self.is_causal and query_length != 1
588
+
589
+ # Contains at least one padding token in the sequence
590
+ if attention_mask is not None:
591
+ batch_size = query_states.shape[0]
592
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
593
+ query_states, key_states, value_states, attention_mask, query_length
594
+ )
595
+
596
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
597
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
598
+
599
+ if not use_sliding_windows:
600
+ attn_output_unpad = flash_attn_varlen_func(
601
+ query_states,
602
+ key_states,
603
+ value_states,
604
+ cu_seqlens_q=cu_seqlens_q,
605
+ cu_seqlens_k=cu_seqlens_k,
606
+ max_seqlen_q=max_seqlen_in_batch_q,
607
+ max_seqlen_k=max_seqlen_in_batch_k,
608
+ dropout_p=dropout,
609
+ softmax_scale=softmax_scale,
610
+ causal=causal,
611
+ )
612
+ else:
613
+ attn_output_unpad = flash_attn_varlen_func(
614
+ query_states,
615
+ key_states,
616
+ value_states,
617
+ cu_seqlens_q=cu_seqlens_q,
618
+ cu_seqlens_k=cu_seqlens_k,
619
+ max_seqlen_q=max_seqlen_in_batch_q,
620
+ max_seqlen_k=max_seqlen_in_batch_k,
621
+ dropout_p=dropout,
622
+ softmax_scale=softmax_scale,
623
+ causal=causal,
624
+ window_size=(self.config.sliding_window, self.config.sliding_window),
625
+ )
626
+
627
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
628
+ else:
629
+ if not use_sliding_windows:
630
+ attn_output = flash_attn_func(
631
+ query_states,
632
+ key_states,
633
+ value_states,
634
+ dropout,
635
+ softmax_scale=softmax_scale,
636
+ causal=causal,
637
+ )
638
+ else:
639
+ attn_output = flash_attn_func(
640
+ query_states,
641
+ key_states,
642
+ value_states,
643
+ dropout,
644
+ softmax_scale=softmax_scale,
645
+ causal=causal,
646
+ window_size=(self.config.sliding_window, self.config.sliding_window),
647
+ )
648
+
649
+ return attn_output
650
+
651
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
652
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
653
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
654
+
655
+ # On the first iteration we need to properly re-create the padding mask
656
+ # by slicing it on the proper place
657
+ if kv_seq_len != attention_mask.shape[-1]:
658
+ attention_mask_num_tokens = attention_mask.shape[-1]
659
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
660
+
661
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
662
+
663
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
664
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
665
+
666
+ if query_length == kv_seq_len:
667
+ query_layer = index_first_axis(
668
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
669
+ )
670
+ cu_seqlens_q = cu_seqlens_k
671
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
672
+ indices_q = indices_k
673
+ elif query_length == 1:
674
+ max_seqlen_in_batch_q = 1
675
+ cu_seqlens_q = torch.arange(
676
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
677
+ ) # There is a memcpy here, that is very bad.
678
+ indices_q = cu_seqlens_q[:-1]
679
+ query_layer = query_layer.squeeze(1)
680
+ else:
681
+ # The -q_len: slice assumes left padding.
682
+ attention_mask = attention_mask[:, -query_length:]
683
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
684
+
685
+ return (
686
+ query_layer,
687
+ key_layer,
688
+ value_layer,
689
+ indices_q,
690
+ (cu_seqlens_q, cu_seqlens_k),
691
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
692
+ )
693
+
694
+
695
+ # copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Phi3
696
+ # TODO @Arthur no longer copied from LLama after static cache
697
+ class Phi3SdpaAttention(Phi3Attention):
698
+ """
699
+ Phi3 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
700
+ `Phi3Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
701
+ SDPA API.
702
+ """
703
+
704
+ # Adapted from Phi3Attention.forward
705
+ def forward(
706
+ self,
707
+ hidden_states: torch.Tensor,
708
+ attention_mask: Optional[torch.Tensor] = None,
709
+ position_ids: Optional[torch.LongTensor] = None,
710
+ past_key_value: Optional[Cache] = None,
711
+ output_attentions: bool = False,
712
+ use_cache: bool = False,
713
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
714
+ if output_attentions:
715
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
716
+ logger.warning_once(
717
+ "Phi3Model is using Phi3SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
718
+ '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.'
719
+ )
720
+ return super().forward(
721
+ hidden_states=hidden_states,
722
+ attention_mask=attention_mask,
723
+ position_ids=position_ids,
724
+ past_key_value=past_key_value,
725
+ output_attentions=output_attentions,
726
+ use_cache=use_cache,
727
+ )
728
+
729
+ bsz, q_len, _ = hidden_states.size()
730
+
731
+ qkv = self.qkv_proj(hidden_states)
732
+ query_pos = self.num_heads * self.head_dim
733
+ query_states = qkv[..., :query_pos]
734
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
735
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
736
+
737
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
738
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
739
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
740
+
741
+ kv_seq_len = key_states.shape[-2]
742
+ if past_key_value is not None:
743
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
744
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
745
+
746
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
747
+
748
+ if past_key_value is not None:
749
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
750
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
751
+
752
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
753
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
754
+
755
+ if attention_mask is not None:
756
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
757
+ raise ValueError(
758
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
759
+ )
760
+
761
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
762
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
763
+ if query_states.device.type == "cuda" and attention_mask is not None:
764
+ query_states = query_states.contiguous()
765
+ key_states = key_states.contiguous()
766
+ value_states = value_states.contiguous()
767
+
768
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
769
+ query_states,
770
+ key_states,
771
+ value_states,
772
+ attn_mask=attention_mask,
773
+ dropout_p=self.attention_dropout if self.training else 0.0,
774
+ # 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.
775
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
776
+ )
777
+
778
+ attn_output = attn_output.transpose(1, 2).contiguous()
779
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
780
+
781
+ attn_output = self.o_proj(attn_output)
782
+
783
+ return attn_output, None, past_key_value
784
+
785
+
786
+ PHI3_ATTENTION_CLASSES = {
787
+ "eager": Phi3Attention,
788
+ "flash_attention_2": Phi3FlashAttention2,
789
+ "sdpa": Phi3SdpaAttention,
790
+ }
791
+
792
+
793
+ class Phi3DecoderLayer(nn.Module):
794
+ def __init__(self, config: Phi3Config, layer_idx: int):
795
+ super().__init__()
796
+
797
+ self.config = config
798
+ self.self_attn = PHI3_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
799
+
800
+ self.mlp = Phi3MLP(config)
801
+ self.input_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
802
+
803
+ self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)
804
+ self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)
805
+ self.post_attention_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
806
+
807
+ def forward(
808
+ self,
809
+ hidden_states: torch.Tensor,
810
+ attention_mask: Optional[torch.Tensor] = None,
811
+ position_ids: Optional[torch.LongTensor] = None,
812
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
813
+ output_attentions: Optional[bool] = False,
814
+ use_cache: Optional[bool] = False,
815
+ **kwargs,
816
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
817
+ if "padding_mask" in kwargs:
818
+ warnings.warn(
819
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
820
+ )
821
+ """
822
+ Args:
823
+ hidden_states (`torch.FloatTensor`):
824
+ input to the layer of shape `(batch, seq_len, embed_dim)`
825
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
826
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
827
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
828
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
829
+ `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
830
+ output_attentions (`bool`, *optional*):
831
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
832
+ returned tensors for more detail.
833
+ use_cache (`bool`, *optional*):
834
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
835
+ (see `past_key_values`).
836
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
837
+ """
838
+
839
+ residual = hidden_states
840
+
841
+ hidden_states = self.input_layernorm(hidden_states)
842
+
843
+ # Self Attention
844
+ attn_outputs, self_attn_weights, present_key_value = self.self_attn(
845
+ hidden_states=hidden_states,
846
+ attention_mask=attention_mask,
847
+ position_ids=position_ids,
848
+ past_key_value=past_key_value,
849
+ output_attentions=output_attentions,
850
+ use_cache=use_cache,
851
+ )
852
+
853
+ hidden_states = residual + self.resid_attn_dropout(attn_outputs)
854
+
855
+ residual = hidden_states
856
+ hidden_states = self.post_attention_layernorm(hidden_states)
857
+ hidden_states = self.mlp(hidden_states)
858
+ hidden_states = residual + self.resid_mlp_dropout(hidden_states)
859
+
860
+ outputs = (hidden_states,)
861
+
862
+ if output_attentions:
863
+ outputs += (self_attn_weights,)
864
+
865
+ if use_cache:
866
+ outputs += (present_key_value,)
867
+
868
+ return outputs
869
+
870
+
871
+ PHI3_START_DOCSTRING = r"""
872
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
873
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
874
+ etc.)
875
+
876
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
877
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
878
+ and behavior.
879
+
880
+ Parameters:
881
+ config ([`Phi3Config`]):
882
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
883
+ load the weights associated with the model, only the configuration. Check out the
884
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
885
+ """
886
+
887
+
888
+ @add_start_docstrings(
889
+ "The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
890
+ PHI3_START_DOCSTRING,
891
+ )
892
+ class Phi3PreTrainedModel(PreTrainedModel):
893
+ config_class = Phi3Config
894
+ base_model_prefix = "model"
895
+ supports_gradient_checkpointing = True
896
+ _no_split_modules = ["Phi3DecoderLayer"]
897
+ _skip_keys_device_placement = "past_key_values"
898
+ _supports_flash_attn_2 = True
899
+ _supports_sdpa = False
900
+ _supports_cache_class = True
901
+
902
+ _version = "0.0.5"
903
+
904
+ def _init_weights(self, module):
905
+ std = self.config.initializer_range
906
+ if isinstance(module, nn.Linear):
907
+ module.weight.data.normal_(mean=0.0, std=std)
908
+ if module.bias is not None:
909
+ module.bias.data.zero_()
910
+ elif isinstance(module, nn.Embedding):
911
+ module.weight.data.normal_(mean=0.0, std=std)
912
+ if module.padding_idx is not None:
913
+ module.weight.data[module.padding_idx].zero_()
914
+
915
+
916
+ PHI3_INPUTS_DOCSTRING = r"""
917
+ Args:
918
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
919
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
920
+ it.
921
+
922
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
923
+ [`PreTrainedTokenizer.__call__`] for details.
924
+
925
+ [What are input IDs?](../glossary#input-ids)
926
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
927
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
928
+
929
+ - 1 for tokens that are **not masked**,
930
+ - 0 for tokens that are **masked**.
931
+
932
+ [What are attention masks?](../glossary#attention-mask)
933
+
934
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
935
+ [`PreTrainedTokenizer.__call__`] for details.
936
+
937
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
938
+ `past_key_values`).
939
+
940
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
941
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
942
+ information on the default strategy.
943
+
944
+ - 1 indicates the head is **not masked**,
945
+ - 0 indicates the head is **masked**.
946
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
947
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
948
+ config.n_positions - 1]`.
949
+
950
+ [What are position IDs?](../glossary#position-ids)
951
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
952
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
953
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
954
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
955
+
956
+ Two formats are allowed:
957
+ - a [`~cache_utils.Cache`] instance;
958
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
959
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
960
+ cache format.
961
+
962
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
963
+ legacy cache format will be returned.
964
+
965
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
966
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
967
+ of shape `(batch_size, sequence_length)`.
968
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
969
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
970
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
971
+ model's internal embedding lookup matrix.
972
+ use_cache (`bool`, *optional*):
973
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
974
+ `past_key_values`).
975
+ output_attentions (`bool`, *optional*):
976
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
977
+ tensors for more detail.
978
+ output_hidden_states (`bool`, *optional*):
979
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
980
+ more detail.
981
+ return_dict (`bool`, *optional*):
982
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
983
+ """
984
+
985
+
986
+ @add_start_docstrings(
987
+ "The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
988
+ PHI3_START_DOCSTRING,
989
+ )
990
+ class Phi3Model(Phi3PreTrainedModel):
991
+ """
992
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Phi3DecoderLayer`]
993
+
994
+ Args:
995
+ config: Phi3Config
996
+ """
997
+
998
+ def __init__(self, config: Phi3Config):
999
+ super().__init__(config)
1000
+ self.padding_idx = config.pad_token_id
1001
+ self.vocab_size = config.vocab_size
1002
+
1003
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1004
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
1005
+ self.layers = nn.ModuleList(
1006
+ [Phi3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1007
+ )
1008
+ self._attn_implementation = config._attn_implementation
1009
+ self.norm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1010
+
1011
+ self.gradient_checkpointing = False
1012
+ # Initialize weights and apply final processing
1013
+ self.post_init()
1014
+
1015
+ def get_input_embeddings(self):
1016
+ return self.embed_tokens
1017
+
1018
+ def set_input_embeddings(self, value):
1019
+ self.embed_tokens = value
1020
+
1021
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1022
+ def forward(
1023
+ self,
1024
+ input_ids: torch.LongTensor = None,
1025
+ attention_mask: Optional[torch.Tensor] = None,
1026
+ position_ids: Optional[torch.LongTensor] = None,
1027
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1028
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1029
+ use_cache: Optional[bool] = None,
1030
+ output_attentions: Optional[bool] = None,
1031
+ output_hidden_states: Optional[bool] = None,
1032
+ return_dict: Optional[bool] = None,
1033
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1034
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1035
+ output_hidden_states = (
1036
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1037
+ )
1038
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1039
+
1040
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1041
+
1042
+ # retrieve input_ids and inputs_embeds
1043
+ if input_ids is not None and inputs_embeds is not None:
1044
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1045
+ elif input_ids is not None:
1046
+ batch_size, seq_length = input_ids.shape[:2]
1047
+ elif inputs_embeds is not None:
1048
+ batch_size, seq_length = inputs_embeds.shape[:2]
1049
+ else:
1050
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1051
+
1052
+ past_key_values_length = 0
1053
+
1054
+ if self.gradient_checkpointing and self.training:
1055
+ if use_cache:
1056
+ logger.warning_once(
1057
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1058
+ )
1059
+ use_cache = False
1060
+
1061
+ if use_cache:
1062
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1063
+ if use_legacy_cache:
1064
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1065
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1066
+
1067
+ if position_ids is None:
1068
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1069
+ position_ids = torch.arange(
1070
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1071
+ )
1072
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1073
+ else:
1074
+ position_ids = position_ids.view(-1, seq_length).long()
1075
+
1076
+ if inputs_embeds is None:
1077
+ inputs_embeds = self.embed_tokens(input_ids)
1078
+
1079
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1080
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1081
+ if is_padding_right:
1082
+ raise ValueError(
1083
+ "You are attempting to perform batched generation with padding_side='right'"
1084
+ " this may lead to unexpected behaviour for Flash Attention version of Phi3. Make sure to "
1085
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1086
+ )
1087
+
1088
+ if self._attn_implementation == "flash_attention_2":
1089
+ # 2d mask is passed through the layers
1090
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1091
+ else:
1092
+ # 4d mask is passed through the layers
1093
+ attention_mask = _prepare_4d_causal_attention_mask(
1094
+ attention_mask,
1095
+ (batch_size, seq_length),
1096
+ inputs_embeds,
1097
+ past_key_values_length,
1098
+ sliding_window=self.config.sliding_window,
1099
+ )
1100
+
1101
+ hidden_states = inputs_embeds
1102
+
1103
+ # decoder layers
1104
+ all_hidden_states = () if output_hidden_states else None
1105
+ all_self_attns = () if output_attentions else None
1106
+ next_decoder_cache = None
1107
+
1108
+ for decoder_layer in self.layers:
1109
+ if output_hidden_states:
1110
+ all_hidden_states += (hidden_states,)
1111
+
1112
+ if self.gradient_checkpointing and self.training:
1113
+ layer_outputs = self._gradient_checkpointing_func(
1114
+ decoder_layer.__call__,
1115
+ hidden_states,
1116
+ attention_mask,
1117
+ position_ids,
1118
+ past_key_values,
1119
+ output_attentions,
1120
+ use_cache,
1121
+ )
1122
+ else:
1123
+ layer_outputs = decoder_layer(
1124
+ hidden_states,
1125
+ attention_mask=attention_mask,
1126
+ position_ids=position_ids,
1127
+ past_key_value=past_key_values,
1128
+ output_attentions=output_attentions,
1129
+ use_cache=use_cache,
1130
+ )
1131
+
1132
+ hidden_states = layer_outputs[0]
1133
+
1134
+ if use_cache:
1135
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1136
+
1137
+ if output_attentions:
1138
+ all_self_attns += (layer_outputs[1],)
1139
+
1140
+ hidden_states = self.norm(hidden_states)
1141
+
1142
+ # add hidden states from the last decoder layer
1143
+ if output_hidden_states:
1144
+ all_hidden_states += (hidden_states,)
1145
+
1146
+ next_cache = None
1147
+ if use_cache:
1148
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1149
+ if not return_dict:
1150
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1151
+ return BaseModelOutputWithPast(
1152
+ last_hidden_state=hidden_states,
1153
+ past_key_values=next_cache,
1154
+ hidden_states=all_hidden_states,
1155
+ attentions=all_self_attns,
1156
+ )
1157
+
1158
+
1159
+ class Phi3ForCausalLM(Phi3PreTrainedModel):
1160
+ _tied_weights_keys = ["lm_head.weight"]
1161
+
1162
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi3
1163
+ def __init__(self, config):
1164
+ super().__init__(config)
1165
+ self.model = Phi3Model(config)
1166
+ self.vocab_size = config.vocab_size
1167
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1168
+
1169
+ # Initialize weights and apply final processing
1170
+ self.post_init()
1171
+
1172
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
1173
+ def get_input_embeddings(self):
1174
+ return self.model.embed_tokens
1175
+
1176
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
1177
+ def set_input_embeddings(self, value):
1178
+ self.model.embed_tokens = value
1179
+
1180
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
1181
+ def get_output_embeddings(self):
1182
+ return self.lm_head
1183
+
1184
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
1185
+ def set_output_embeddings(self, new_embeddings):
1186
+ self.lm_head = new_embeddings
1187
+
1188
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
1189
+ def set_decoder(self, decoder):
1190
+ self.model = decoder
1191
+
1192
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
1193
+ def get_decoder(self):
1194
+ return self.model
1195
+
1196
+ # Ignore copy
1197
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1198
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1199
+ def forward(
1200
+ self,
1201
+ input_ids: torch.LongTensor = None,
1202
+ attention_mask: Optional[torch.Tensor] = None,
1203
+ position_ids: Optional[torch.LongTensor] = None,
1204
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1205
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1206
+ labels: Optional[torch.LongTensor] = None,
1207
+ use_cache: Optional[bool] = None,
1208
+ output_attentions: Optional[bool] = None,
1209
+ output_hidden_states: Optional[bool] = None,
1210
+ return_dict: Optional[bool] = None,
1211
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1212
+ r"""
1213
+ Args:
1214
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1215
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1216
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1217
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1218
+
1219
+ Returns:
1220
+
1221
+ Example:
1222
+
1223
+ ```python
1224
+ >>> from transformers import AutoTokenizer, Phi3ForCausalLM
1225
+
1226
+ >>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1227
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1228
+
1229
+ >>> prompt = "This is an example script ."
1230
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1231
+
1232
+ >>> # Generate
1233
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1234
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1235
+ 'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
1236
+ ```"""
1237
+
1238
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1239
+ output_hidden_states = (
1240
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1241
+ )
1242
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1243
+
1244
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1245
+ outputs = self.model(
1246
+ input_ids=input_ids,
1247
+ attention_mask=attention_mask,
1248
+ position_ids=position_ids,
1249
+ past_key_values=past_key_values,
1250
+ inputs_embeds=inputs_embeds,
1251
+ use_cache=use_cache,
1252
+ output_attentions=output_attentions,
1253
+ output_hidden_states=output_hidden_states,
1254
+ return_dict=return_dict,
1255
+ )
1256
+
1257
+ hidden_states = outputs[0]
1258
+ logits = self.lm_head(hidden_states)
1259
+ logits = logits.float()
1260
+
1261
+ loss = None
1262
+ if labels is not None:
1263
+ # Shift so that tokens < n predict n
1264
+ shift_logits = logits[..., :-1, :].contiguous()
1265
+ shift_labels = labels[..., 1:].contiguous()
1266
+ # Flatten the tokens
1267
+ loss_fct = CrossEntropyLoss()
1268
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1269
+ shift_labels = shift_labels.view(-1)
1270
+ # Enable model parallelism
1271
+ shift_labels = shift_labels.to(shift_logits.device)
1272
+ loss = loss_fct(shift_logits, shift_labels)
1273
+
1274
+ if not return_dict:
1275
+ output = (logits,) + outputs[1:]
1276
+ return (loss,) + output if loss is not None else output
1277
+
1278
+ return CausalLMOutputWithPast(
1279
+ loss=loss,
1280
+ logits=logits,
1281
+ past_key_values=outputs.past_key_values,
1282
+ hidden_states=outputs.hidden_states,
1283
+ attentions=outputs.attentions,
1284
+ )
1285
+
1286
+ # Copied from transformers.models.persimmon.modeling_persimmon.PersimmonForCausalLM.prepare_inputs_for_generation
1287
+ def prepare_inputs_for_generation(
1288
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1289
+ ):
1290
+ # When the first time input length reached long and short factor switching point, enforce re-compute cache
1291
+ # It will cause downside of slower at this single token position, however, better than current failure.
1292
+ if past_key_values and self.config.rope_scaling and input_ids.shape[1] >= self.config.original_max_position_embeddings + 1:
1293
+ past_length = past_key_values.seen_tokens if isinstance(past_key_values, Cache) else past_key_values[0][0].shape[2]
1294
+ if past_length <= self.config.original_max_position_embeddings:
1295
+ past_key_values = None
1296
+
1297
+ if past_key_values is not None:
1298
+ if isinstance(past_key_values, Cache):
1299
+ cache_length = past_key_values.get_seq_length()
1300
+ past_length = past_key_values.seen_tokens
1301
+ max_cache_length = past_key_values.get_max_length()
1302
+ else:
1303
+ cache_length = past_length = past_key_values[0][0].shape[2]
1304
+ max_cache_length = None
1305
+
1306
+ # Keep only the unprocessed tokens:
1307
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1308
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1309
+ # input)
1310
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1311
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1312
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1313
+ # input_ids based on the past_length.
1314
+ elif past_length < input_ids.shape[1]:
1315
+ input_ids = input_ids[:, past_length:]
1316
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1317
+
1318
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1319
+ if (
1320
+ max_cache_length is not None
1321
+ and attention_mask is not None
1322
+ and cache_length + input_ids.shape[1] > max_cache_length
1323
+ ):
1324
+ attention_mask = attention_mask[:, -max_cache_length:]
1325
+
1326
+ position_ids = kwargs.get("position_ids", None)
1327
+ if attention_mask is not None and position_ids is None:
1328
+ # create position_ids on the fly for batch generation
1329
+ position_ids = attention_mask.long().cumsum(-1) - 1
1330
+ position_ids.masked_fill_(attention_mask == 0, 1)
1331
+ if past_key_values:
1332
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1333
+
1334
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1335
+ if inputs_embeds is not None and past_key_values is None:
1336
+ model_inputs = {"inputs_embeds": inputs_embeds}
1337
+ else:
1338
+ model_inputs = {"input_ids": input_ids}
1339
+
1340
+ model_inputs.update(
1341
+ {
1342
+ "position_ids": position_ids,
1343
+ "past_key_values": past_key_values,
1344
+ "use_cache": kwargs.get("use_cache"),
1345
+ "attention_mask": attention_mask,
1346
+ }
1347
+ )
1348
+ return model_inputs
1349
+
1350
+ @staticmethod
1351
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM._reorder_cache
1352
+ def _reorder_cache(past_key_values, beam_idx):
1353
+ reordered_past = ()
1354
+ for layer_past in past_key_values:
1355
+ reordered_past += (
1356
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1357
+ )
1358
+ return reordered_past
1359
+
1360
+
1361
+ @add_start_docstrings(
1362
+ """
1363
+ The [`Phi3Model`] with a sequence classification head on top (linear layer).
1364
+
1365
+ [`Phi3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1366
+ (e.g. GPT-2) do.
1367
+
1368
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1369
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1370
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1371
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1372
+ each row of the batch).
1373
+ """,
1374
+ PHI3_START_DOCSTRING,
1375
+ )
1376
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Phi3, LLAMA->PHI3, self.transformer->self.model, transformer_outputs->model_outputs
1377
+ class Phi3ForSequenceClassification(Phi3PreTrainedModel):
1378
+ def __init__(self, config):
1379
+ super().__init__(config)
1380
+ self.num_labels = config.num_labels
1381
+ self.model = Phi3Model(config)
1382
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1383
+
1384
+ # Initialize weights and apply final processing
1385
+ self.post_init()
1386
+
1387
+ def get_input_embeddings(self):
1388
+ return self.model.embed_tokens
1389
+
1390
+ def set_input_embeddings(self, value):
1391
+ self.model.embed_tokens = value
1392
+
1393
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1394
+ def forward(
1395
+ self,
1396
+ input_ids: torch.LongTensor = None,
1397
+ attention_mask: Optional[torch.Tensor] = None,
1398
+ position_ids: Optional[torch.LongTensor] = None,
1399
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1400
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1401
+ labels: Optional[torch.LongTensor] = None,
1402
+ use_cache: Optional[bool] = None,
1403
+ output_attentions: Optional[bool] = None,
1404
+ output_hidden_states: Optional[bool] = None,
1405
+ return_dict: Optional[bool] = None,
1406
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1407
+ r"""
1408
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1409
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1410
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1411
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1412
+ """
1413
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1414
+
1415
+ model_outputs = self.model(
1416
+ input_ids,
1417
+ attention_mask=attention_mask,
1418
+ position_ids=position_ids,
1419
+ past_key_values=past_key_values,
1420
+ inputs_embeds=inputs_embeds,
1421
+ use_cache=use_cache,
1422
+ output_attentions=output_attentions,
1423
+ output_hidden_states=output_hidden_states,
1424
+ return_dict=return_dict,
1425
+ )
1426
+ hidden_states = model_outputs[0]
1427
+ logits = self.score(hidden_states)
1428
+
1429
+ if input_ids is not None:
1430
+ batch_size = input_ids.shape[0]
1431
+ else:
1432
+ batch_size = inputs_embeds.shape[0]
1433
+
1434
+ if self.config.pad_token_id is None and batch_size != 1:
1435
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1436
+ if self.config.pad_token_id is None:
1437
+ sequence_lengths = -1
1438
+ else:
1439
+ if input_ids is not None:
1440
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1441
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1442
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1443
+ sequence_lengths = sequence_lengths.to(logits.device)
1444
+ else:
1445
+ sequence_lengths = -1
1446
+
1447
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1448
+
1449
+ loss = None
1450
+ if labels is not None:
1451
+ labels = labels.to(logits.device)
1452
+ if self.config.problem_type is None:
1453
+ if self.num_labels == 1:
1454
+ self.config.problem_type = "regression"
1455
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1456
+ self.config.problem_type = "single_label_classification"
1457
+ else:
1458
+ self.config.problem_type = "multi_label_classification"
1459
+
1460
+ if self.config.problem_type == "regression":
1461
+ loss_fct = MSELoss()
1462
+ if self.num_labels == 1:
1463
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1464
+ else:
1465
+ loss = loss_fct(pooled_logits, labels)
1466
+ elif self.config.problem_type == "single_label_classification":
1467
+ loss_fct = CrossEntropyLoss()
1468
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1469
+ elif self.config.problem_type == "multi_label_classification":
1470
+ loss_fct = BCEWithLogitsLoss()
1471
+ loss = loss_fct(pooled_logits, labels)
1472
+ if not return_dict:
1473
+ output = (pooled_logits,) + model_outputs[1:]
1474
+ return ((loss,) + output) if loss is not None else output
1475
+
1476
+ return SequenceClassifierOutputWithPast(
1477
+ loss=loss,
1478
+ logits=pooled_logits,
1479
+ past_key_values=model_outputs.past_key_values,
1480
+ hidden_states=model_outputs.hidden_states,
1481
+ attentions=model_outputs.attentions,
1482
+ )
1483
+
1484
+
1485
+ @add_start_docstrings(
1486
+ """
1487
+ [`Phi3Model`] with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1488
+ Named-Entity-Recognition (NER) tasks.
1489
+ """,
1490
+ PHI3_START_DOCSTRING,
1491
+ )
1492
+ # Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with Mpt->Phi3,MPT->PHI3,self.transformer->self.model,transformer_outputs->model_outputs
1493
+ class Phi3ForTokenClassification(Phi3PreTrainedModel):
1494
+ def __init__(self, config: Phi3Config):
1495
+ super().__init__(config)
1496
+ self.num_labels = config.num_labels
1497
+
1498
+ self.model = Phi3Model(config)
1499
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1500
+ classifier_dropout = config.classifier_dropout
1501
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1502
+ classifier_dropout = config.hidden_dropout
1503
+ else:
1504
+ classifier_dropout = 0.1
1505
+ self.dropout = nn.Dropout(classifier_dropout)
1506
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1507
+
1508
+ # Initialize weights and apply final processing
1509
+ self.post_init()
1510
+
1511
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1512
+ @add_code_sample_docstrings(
1513
+ checkpoint=_CHECKPOINT_FOR_DOC,
1514
+ output_type=TokenClassifierOutput,
1515
+ config_class=_CONFIG_FOR_DOC,
1516
+ )
1517
+ def forward(
1518
+ self,
1519
+ input_ids: Optional[torch.LongTensor] = None,
1520
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1521
+ attention_mask: Optional[torch.Tensor] = None,
1522
+ inputs_embeds: Optional[torch.Tensor] = None,
1523
+ labels: Optional[torch.Tensor] = None,
1524
+ use_cache: Optional[bool] = None,
1525
+ output_attentions: Optional[bool] = None,
1526
+ output_hidden_states: Optional[bool] = None,
1527
+ return_dict: Optional[bool] = None,
1528
+ **deprecated_arguments,
1529
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1530
+ r"""
1531
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1532
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1533
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1534
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1535
+ """
1536
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1537
+
1538
+ model_outputs = self.model(
1539
+ input_ids,
1540
+ past_key_values=past_key_values,
1541
+ attention_mask=attention_mask,
1542
+ inputs_embeds=inputs_embeds,
1543
+ use_cache=use_cache,
1544
+ output_attentions=output_attentions,
1545
+ output_hidden_states=output_hidden_states,
1546
+ return_dict=return_dict,
1547
+ )
1548
+
1549
+ hidden_states = model_outputs[0]
1550
+ hidden_states = self.dropout(hidden_states)
1551
+ logits = self.classifier(hidden_states)
1552
+
1553
+ loss = None
1554
+ if labels is not None:
1555
+ # move labels to correct device to enable model parallelism
1556
+ labels = labels.to(logits.device)
1557
+ batch_size, seq_length = labels.shape
1558
+ loss_fct = CrossEntropyLoss()
1559
+ loss = loss_fct(
1560
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
1561
+ )
1562
+
1563
+ if not return_dict:
1564
+ output = (logits,) + model_outputs[2:]
1565
+ return ((loss,) + output) if loss is not None else output
1566
+
1567
+ return TokenClassifierOutput(
1568
+ loss=loss,
1569
+ logits=logits,
1570
+ hidden_states=model_outputs.hidden_states,
1571
+ attentions=model_outputs.attentions,
1572
+ )
function_calling_post_filtering_v4/special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|end|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<|endoftext|>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "unk_token": {
24
+ "content": "<unk>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ }
30
+ }
function_calling_post_filtering_v4/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
function_calling_post_filtering_v4/tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
3
+ size 499723
function_calling_post_filtering_v4/tokenizer_config.json ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": null,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<unk>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "</s>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": true,
27
+ "single_word": false,
28
+ "special": false
29
+ },
30
+ "32000": {
31
+ "content": "<|endoftext|>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ },
38
+ "32001": {
39
+ "content": "<|assistant|>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": true,
43
+ "single_word": false,
44
+ "special": true
45
+ },
46
+ "32002": {
47
+ "content": "<|placeholder1|>",
48
+ "lstrip": false,
49
+ "normalized": false,
50
+ "rstrip": true,
51
+ "single_word": false,
52
+ "special": true
53
+ },
54
+ "32003": {
55
+ "content": "<|placeholder2|>",
56
+ "lstrip": false,
57
+ "normalized": false,
58
+ "rstrip": true,
59
+ "single_word": false,
60
+ "special": true
61
+ },
62
+ "32004": {
63
+ "content": "<|placeholder3|>",
64
+ "lstrip": false,
65
+ "normalized": false,
66
+ "rstrip": true,
67
+ "single_word": false,
68
+ "special": true
69
+ },
70
+ "32005": {
71
+ "content": "<|placeholder4|>",
72
+ "lstrip": false,
73
+ "normalized": false,
74
+ "rstrip": true,
75
+ "single_word": false,
76
+ "special": true
77
+ },
78
+ "32006": {
79
+ "content": "<|system|>",
80
+ "lstrip": false,
81
+ "normalized": false,
82
+ "rstrip": true,
83
+ "single_word": false,
84
+ "special": true
85
+ },
86
+ "32007": {
87
+ "content": "<|end|>",
88
+ "lstrip": false,
89
+ "normalized": false,
90
+ "rstrip": false,
91
+ "single_word": false,
92
+ "special": true
93
+ },
94
+ "32008": {
95
+ "content": "<|placeholder5|>",
96
+ "lstrip": false,
97
+ "normalized": false,
98
+ "rstrip": true,
99
+ "single_word": false,
100
+ "special": true
101
+ },
102
+ "32009": {
103
+ "content": "<|placeholder6|>",
104
+ "lstrip": false,
105
+ "normalized": false,
106
+ "rstrip": true,
107
+ "single_word": false,
108
+ "special": true
109
+ },
110
+ "32010": {
111
+ "content": "<|user|>",
112
+ "lstrip": false,
113
+ "normalized": false,
114
+ "rstrip": true,
115
+ "single_word": false,
116
+ "special": true
117
+ }
118
+ },
119
+ "bos_token": "<s>",
120
+ "chat_template": "{{ '<s>' }}{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% else %}{% set loop_messages = messages %}{% endif %}{% if system_message is defined %}{{ '<|system|>\n' + system_message + '<|end|>\n' }}{% endif %}{% for message in loop_messages %}{% set content = message['content'] %}{% if message['role'] == 'user' %}{{ '<|user|>\n' + content + '<|end|>\n<|assistant|>\n' }}{% elif message['role'] == 'assistant' %}{{ content + '<|end|>' + '\n' }}{% endif %}{% endfor %}",
121
+ "clean_up_tokenization_spaces": false,
122
+ "eos_token": "<|end|>",
123
+ "legacy": false,
124
+ "model_max_length": 131072,
125
+ "pad_token": "<|endoftext|>",
126
+ "padding_side": "right",
127
+ "sp_model_kwargs": {},
128
+ "split_special_tokens": false,
129
+ "tokenizer_class": "LlamaTokenizer",
130
+ "unk_token": "<unk>",
131
+ "use_default_system_prompt": false
132
+ }
function_calling_round2/Function_Calling_Round2-4.3B-F16.gguf ADDED
Binary file (24 Bytes). View file
 
function_calling_round2/README.md ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ tags:
4
+ - llama-factory
5
+ - freeze
6
+ - generated_from_trainer
7
+ model-index:
8
+ - name: function_calling_round2
9
+ results: []
10
+ ---
11
+
12
+ <!-- This model card has been generated automatically according to the information the Trainer had access to. You
13
+ should probably proofread and complete it, then remove this comment. -->
14
+
15
+ # Phi3.5
16
+ ## Model description
17
+
18
+ More information needed
19
+
20
+ ## Intended uses & limitations
21
+
22
+ More information needed
23
+
24
+ ## Training and evaluation data
25
+
26
+ More information needed
27
+
28
+ ## Training procedure
29
+
30
+ ### Training hyperparameters
31
+
32
+ The following hyperparameters were used during training:
33
+ - learning_rate: 2e-05
34
+ - train_batch_size: 2
35
+ - eval_batch_size: 8
36
+ - seed: 42
37
+ - gradient_accumulation_steps: 3
38
+ - total_train_batch_size: 6
39
+ - optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-08
40
+ - lr_scheduler_type: cosine_with_restarts
41
+ - lr_scheduler_warmup_ratio: 0.1
42
+ - num_epochs: 2
43
+
44
+ ### Training results
45
+
46
+
47
+
48
+ ### Framework versions
49
+
50
+ - Transformers 4.43.4
51
+ - Pytorch 2.4.0+cu121
52
+ - Datasets 2.20.0
53
+ - Tokenizers 0.19.1
function_calling_round2/added_tokens.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "<|assistant|>": 32001,
3
+ "<|endoftext|>": 32000,
4
+ "<|end|>": 32007,
5
+ "<|placeholder1|>": 32002,
6
+ "<|placeholder2|>": 32003,
7
+ "<|placeholder3|>": 32004,
8
+ "<|placeholder4|>": 32005,
9
+ "<|placeholder5|>": 32008,
10
+ "<|placeholder6|>": 32009,
11
+ "<|system|>": 32006,
12
+ "<|user|>": 32010
13
+ }
function_calling_round2/all_results.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "epoch": 1.9999747065965197,
3
+ "total_flos": 8.305213564465938e+18,
4
+ "train_loss": 0.19771010399692432,
5
+ "train_runtime": 52111.6605,
6
+ "train_samples_per_second": 6.069,
7
+ "train_steps_per_second": 1.012
8
+ }
function_calling_round2/config.json ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {,
2
+ "architectures": [
3
+ "Phi3ForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_phi3.Phi3Config",
9
+ "AutoModelForCausalLM": "modeling_phi3.Phi3ForCausalLM"
10
+ },
11
+ "bos_token_id": 1,
12
+ "embd_pdrop": 0.0,
13
+ "eos_token_id": 32000,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 3072,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 8192,
18
+ "max_position_embeddings": 131072,
19
+ "model_type": "phi3",
20
+ "num_attention_heads": 32,
21
+ "num_hidden_layers": 36,
22
+ "num_key_value_heads": 32,
23
+ "original_max_position_embeddings": 4096,
24
+ "pad_token_id": 32000,
25
+ "resid_pdrop": 0.0,
26
+ "rms_norm_eps": 1e-05,
27
+ "rope_scaling": {
28
+ "long_factor": [
29
+ 1.0800000429153442,
30
+ 1.1100000143051147,
31
+ 1.1399999856948853,
32
+ 1.340000033378601,
33
+ 1.5899999141693115,
34
+ 1.600000023841858,
35
+ 1.6200000047683716,
36
+ 2.620000123977661,
37
+ 3.2300000190734863,
38
+ 3.2300000190734863,
39
+ 4.789999961853027,
40
+ 7.400000095367432,
41
+ 7.700000286102295,
42
+ 9.09000015258789,
43
+ 12.199999809265137,
44
+ 17.670000076293945,
45
+ 24.46000099182129,
46
+ 28.57000160217285,
47
+ 30.420001983642578,
48
+ 30.840002059936523,
49
+ 32.590003967285156,
50
+ 32.93000411987305,
51
+ 42.320003509521484,
52
+ 44.96000289916992,
53
+ 50.340003967285156,
54
+ 50.45000457763672,
55
+ 57.55000305175781,
56
+ 57.93000411987305,
57
+ 58.21000289916992,
58
+ 60.1400032043457,
59
+ 62.61000442504883,
60
+ 62.62000274658203,
61
+ 62.71000289916992,
62
+ 63.1400032043457,
63
+ 63.1400032043457,
64
+ 63.77000427246094,
65
+ 63.93000411987305,
66
+ 63.96000289916992,
67
+ 63.970001220703125,
68
+ 64.02999877929688,
69
+ 64.06999969482422,
70
+ 64.08000183105469,
71
+ 64.12000274658203,
72
+ 64.41000366210938,
73
+ 64.4800033569336,
74
+ 64.51000213623047,
75
+ 64.52999877929688,
76
+ 64.83999633789062
77
+ ],
78
+ "short_factor": [
79
+ 1.0,
80
+ 1.0199999809265137,
81
+ 1.0299999713897705,
82
+ 1.0299999713897705,
83
+ 1.0499999523162842,
84
+ 1.0499999523162842,
85
+ 1.0499999523162842,
86
+ 1.0499999523162842,
87
+ 1.0499999523162842,
88
+ 1.0699999332427979,
89
+ 1.0999999046325684,
90
+ 1.1099998950958252,
91
+ 1.1599998474121094,
92
+ 1.1599998474121094,
93
+ 1.1699998378753662,
94
+ 1.2899998426437378,
95
+ 1.339999794960022,
96
+ 1.679999828338623,
97
+ 1.7899998426437378,
98
+ 1.8199998140335083,
99
+ 1.8499997854232788,
100
+ 1.8799997568130493,
101
+ 1.9099997282028198,
102
+ 1.9399996995925903,
103
+ 1.9899996519088745,
104
+ 2.0199997425079346,
105
+ 2.0199997425079346,
106
+ 2.0199997425079346,
107
+ 2.0199997425079346,
108
+ 2.0199997425079346,
109
+ 2.0199997425079346,
110
+ 2.0299997329711914,
111
+ 2.0299997329711914,
112
+ 2.0299997329711914,
113
+ 2.0299997329711914,
114
+ 2.0299997329711914,
115
+ 2.0299997329711914,
116
+ 2.0299997329711914,
117
+ 2.0299997329711914,
118
+ 2.0299997329711914,
119
+ 2.0799996852874756,
120
+ 2.0899996757507324,
121
+ 2.189999580383301,
122
+ 2.2199995517730713,
123
+ 2.5899994373321533,
124
+ 2.729999542236328,
125
+ 2.749999523162842,
126
+ 2.8399994373321533
127
+ ],
128
+ "type": "longrope"
129
+ },
130
+ "rope_theta": 10000.0,
131
+ "sliding_window": 262144,
132
+ "tie_word_embeddings": false,
133
+ "torch_dtype": "bfloat16",
134
+ "transformers_version": "4.43.4",
135
+ "use_cache": false,
136
+ "vocab_size": 32064
137
+ }
function_calling_round2/configuration_phi3.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """ Phi-3 model configuration"""
17
+
18
+
19
+ from transformers.configuration_utils import PretrainedConfig
20
+ from transformers.utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+ PHI3_PRETRAINED_CONFIG_ARCHIVE_MAP = {
26
+ "microsoft/Phi-3-mini-4k-instruct": "https://huggingface.co/microsoft/Phi-3-mini-4k-instruct/resolve/main/config.json",
27
+ "microsoft/Phi-3-mini-128k-instruct": "https://huggingface.co/microsoft/Phi-3-mini-128k-instruct/resolve/main/config.json",
28
+ }
29
+
30
+
31
+ class Phi3Config(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration of a [`Phi3Model`]. It is used to instantiate a Phi-3
34
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
35
+ defaults will yield a similar configuration to that of the
36
+ [microsoft/Phi-3-mini-4k-instruct](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct).
37
+
38
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
39
+ documentation from [`PretrainedConfig`] for more information.
40
+
41
+ Args:
42
+ vocab_size (`int`, *optional*, defaults to 32064):
43
+ Vocabulary size of the Phi-3 model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`Phi3Model`].
45
+ hidden_size (`int`, *optional*, defaults to 3072):
46
+ Dimension of the hidden representations.
47
+ intermediate_size (`int`, *optional*, defaults to 8192):
48
+ Dimension of the MLP representations.
49
+ num_hidden_layers (`int`, *optional*, defaults to 32):
50
+ Number of hidden layers in the Transformer decoder.
51
+ num_attention_heads (`int`, *optional*, defaults to 32):
52
+ Number of attention heads for each attention layer in the Transformer decoder.
53
+ num_key_value_heads (`int`, *optional*):
54
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
55
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
56
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
57
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
58
+ by meanpooling all the original heads within that group. For more details checkout [this
59
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
60
+ `num_attention_heads`.
61
+ resid_pdrop (`float`, *optional*, defaults to 0.0):
62
+ Dropout probability for mlp outputs.
63
+ embd_pdrop (`int`, *optional*, defaults to 0.0):
64
+ The dropout ratio for the embeddings.
65
+ attention_dropout (`float`, *optional*, defaults to 0.0):
66
+ The dropout ratio after computing the attention scores.
67
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
68
+ The non-linear activation function (function or string) in the decoder.
69
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
70
+ The maximum sequence length that this model might ever be used with.
71
+ original_max_position_embeddings (`int`, *optional*, defaults to 4096):
72
+ The maximum sequence length that this model was trained with. This is used to determine the size of the
73
+ original RoPE embeddings when using long scaling.
74
+ initializer_range (`float`, *optional*, defaults to 0.02):
75
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
76
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
77
+ The epsilon value used for the RMSNorm.
78
+ use_cache (`bool`, *optional*, defaults to `True`):
79
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
80
+ relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
81
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
82
+ Whether to tie weight embeddings
83
+ rope_theta (`float`, *optional*, defaults to 10000.0):
84
+ The base period of the RoPE embeddings.
85
+ rope_scaling (`dict`, *optional*):
86
+ The scaling strategy for the RoPE embeddings. If `None`, no scaling is applied. If a dictionary, it must
87
+ contain the following keys: `type`, `short_factor` and `long_factor`. The `type` must be `longrope` and
88
+ the `short_factor` and `long_factor` must be lists of numbers with the same length as the hidden size
89
+ divided by the number of attention heads divided by 2.
90
+ bos_token_id (`int`, *optional*, defaults to 1):
91
+ The id of the "beginning-of-sequence" token.
92
+ eos_token_id (`int`, *optional*, defaults to 32000):
93
+ The id of the "end-of-sequence" token.
94
+ pad_token_id (`int`, *optional*, defaults to 32000):
95
+ The id of the padding token.
96
+ sliding_window (`int`, *optional*):
97
+ Sliding window attention window size. If `None`, no sliding window is applied.
98
+
99
+ Example:
100
+
101
+ ```python
102
+ >>> from transformers import Phi3Model, Phi3Config
103
+
104
+ >>> # Initializing a Phi-3 style configuration
105
+ >>> configuration = Phi3Config.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
106
+
107
+ >>> # Initializing a model from the configuration
108
+ >>> model = Phi3Model(configuration)
109
+
110
+ >>> # Accessing the model configuration
111
+ >>> configuration = model.config
112
+ ```"""
113
+
114
+ model_type = "phi3"
115
+ keys_to_ignore_at_inference = ["past_key_values"]
116
+
117
+ def __init__(
118
+ self,
119
+ vocab_size=32064,
120
+ hidden_size=3072,
121
+ intermediate_size=8192,
122
+ num_hidden_layers=32,
123
+ num_attention_heads=32,
124
+ num_key_value_heads=None,
125
+ resid_pdrop=0.0,
126
+ embd_pdrop=0.0,
127
+ attention_dropout=0.0,
128
+ hidden_act="silu",
129
+ max_position_embeddings=4096,
130
+ original_max_position_embeddings=4096,
131
+ initializer_range=0.02,
132
+ rms_norm_eps=1e-5,
133
+ use_cache=True,
134
+ tie_word_embeddings=False,
135
+ rope_theta=10000.0,
136
+ rope_scaling=None,
137
+ bos_token_id=1,
138
+ eos_token_id=32000,
139
+ pad_token_id=32000,
140
+ sliding_window=None,
141
+ **kwargs,
142
+ ):
143
+ self.vocab_size = vocab_size
144
+ self.hidden_size = hidden_size
145
+ self.intermediate_size = intermediate_size
146
+ self.num_hidden_layers = num_hidden_layers
147
+ self.num_attention_heads = num_attention_heads
148
+
149
+ if num_key_value_heads is None:
150
+ num_key_value_heads = num_attention_heads
151
+
152
+ self.num_key_value_heads = num_key_value_heads
153
+ self.resid_pdrop = resid_pdrop
154
+ self.embd_pdrop = embd_pdrop
155
+ self.attention_dropout = attention_dropout
156
+ self.hidden_act = hidden_act
157
+ self.max_position_embeddings = max_position_embeddings
158
+ self.original_max_position_embeddings = original_max_position_embeddings
159
+ self.initializer_range = initializer_range
160
+ self.rms_norm_eps = rms_norm_eps
161
+ self.use_cache = use_cache
162
+ self.rope_theta = rope_theta
163
+ self.rope_scaling = rope_scaling
164
+ self._rope_scaling_adjustment()
165
+ self._rope_scaling_validation()
166
+ self.sliding_window = sliding_window
167
+
168
+ super().__init__(
169
+ bos_token_id=bos_token_id,
170
+ eos_token_id=eos_token_id,
171
+ pad_token_id=pad_token_id,
172
+ tie_word_embeddings=tie_word_embeddings,
173
+ **kwargs,
174
+ )
175
+
176
+ def _rope_scaling_adjustment(self):
177
+ """
178
+ Adjust the `type` of the `rope_scaling` configuration for backward compatibility.
179
+ """
180
+ if self.rope_scaling is None:
181
+ return
182
+
183
+ rope_scaling_type = self.rope_scaling.get("type", None)
184
+
185
+ # For backward compatibility if previous version used "su" or "yarn"
186
+ if rope_scaling_type is not None and rope_scaling_type in ["su", "yarn"]:
187
+ self.rope_scaling["type"] = "longrope"
188
+
189
+ def _rope_scaling_validation(self):
190
+ """
191
+ Validate the `rope_scaling` configuration.
192
+ """
193
+ if self.rope_scaling is None:
194
+ return
195
+
196
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 3:
197
+ raise ValueError(
198
+ "`rope_scaling` must be a dictionary with three fields, `type`, `short_factor` and `long_factor`, "
199
+ f"got {self.rope_scaling}"
200
+ )
201
+ rope_scaling_type = self.rope_scaling.get("type", None)
202
+ rope_scaling_short_factor = self.rope_scaling.get("short_factor", None)
203
+ rope_scaling_long_factor = self.rope_scaling.get("long_factor", None)
204
+ if rope_scaling_type is None or rope_scaling_type not in ["longrope"]:
205
+ raise ValueError(f"`rope_scaling`'s type field must be one of ['longrope'], got {rope_scaling_type}")
206
+ if not (
207
+ isinstance(rope_scaling_short_factor, list)
208
+ and all(isinstance(x, (int, float)) for x in rope_scaling_short_factor)
209
+ ):
210
+ raise ValueError(
211
+ f"`rope_scaling`'s short_factor field must be a list of numbers, got {rope_scaling_short_factor}"
212
+ )
213
+ if not len(rope_scaling_short_factor) == self.hidden_size // self.num_attention_heads // 2:
214
+ raise ValueError(
215
+ f"`rope_scaling`'s short_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_short_factor)}"
216
+ )
217
+ if not (
218
+ isinstance(rope_scaling_long_factor, list)
219
+ and all(isinstance(x, (int, float)) for x in rope_scaling_long_factor)
220
+ ):
221
+ raise ValueError(
222
+ f"`rope_scaling`'s long_factor field must be a list of numbers, got {rope_scaling_long_factor}"
223
+ )
224
+ if not len(rope_scaling_long_factor) == self.hidden_size // self.num_attention_heads // 2:
225
+ raise ValueError(
226
+ f"`rope_scaling`'s long_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_long_factor)}"
227
+ )
function_calling_round2/generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 32000,
5
+ "pad_token_id": 32000,
6
+ "transformers_version": "4.43.4"
7
+ }
function_calling_round2/model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:372568aec2db5e934f859a1fe92383f82d2f4a5fd9659acee35e8d07298f26ad
3
+ size 4972487920
function_calling_round2/model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:395ad5b5c228bd0f1e50a238765dea1f53a05867c3bbe19efe4dfc2200a5b5d4
3
+ size 4481734408
function_calling_round2/model.safetensors.index.json ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 9454196736
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00002-of-00002.safetensors",
7
+ "model.embed_tokens.weight": "model-00001-of-00002.safetensors",
8
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00002.safetensors",
9
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
10
+ "model.layers.0.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
11
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
12
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
13
+ "model.layers.0.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
14
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00002.safetensors",
15
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
16
+ "model.layers.1.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
17
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
18
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
19
+ "model.layers.1.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
20
+ "model.layers.10.input_layernorm.weight": "model-00001-of-00002.safetensors",
21
+ "model.layers.10.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
22
+ "model.layers.10.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
23
+ "model.layers.10.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
24
+ "model.layers.10.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
25
+ "model.layers.10.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
26
+ "model.layers.11.input_layernorm.weight": "model-00001-of-00002.safetensors",
27
+ "model.layers.11.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
28
+ "model.layers.11.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
29
+ "model.layers.11.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
30
+ "model.layers.11.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
31
+ "model.layers.11.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
32
+ "model.layers.12.input_layernorm.weight": "model-00001-of-00002.safetensors",
33
+ "model.layers.12.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
34
+ "model.layers.12.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
35
+ "model.layers.12.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
36
+ "model.layers.12.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
37
+ "model.layers.12.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
38
+ "model.layers.13.input_layernorm.weight": "model-00001-of-00002.safetensors",
39
+ "model.layers.13.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
40
+ "model.layers.13.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
41
+ "model.layers.13.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
42
+ "model.layers.13.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
43
+ "model.layers.13.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
44
+ "model.layers.14.input_layernorm.weight": "model-00001-of-00002.safetensors",
45
+ "model.layers.14.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
46
+ "model.layers.14.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
47
+ "model.layers.14.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
48
+ "model.layers.14.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
49
+ "model.layers.14.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
50
+ "model.layers.15.input_layernorm.weight": "model-00001-of-00002.safetensors",
51
+ "model.layers.15.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
52
+ "model.layers.15.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
53
+ "model.layers.15.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
54
+ "model.layers.15.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
55
+ "model.layers.15.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
56
+ "model.layers.16.input_layernorm.weight": "model-00001-of-00002.safetensors",
57
+ "model.layers.16.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
58
+ "model.layers.16.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
59
+ "model.layers.16.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
60
+ "model.layers.16.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
61
+ "model.layers.16.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
62
+ "model.layers.17.input_layernorm.weight": "model-00001-of-00002.safetensors",
63
+ "model.layers.17.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
64
+ "model.layers.17.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
65
+ "model.layers.17.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
66
+ "model.layers.17.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
67
+ "model.layers.17.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
68
+ "model.layers.18.input_layernorm.weight": "model-00001-of-00002.safetensors",
69
+ "model.layers.18.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
70
+ "model.layers.18.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
71
+ "model.layers.18.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
72
+ "model.layers.18.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
73
+ "model.layers.18.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
74
+ "model.layers.19.input_layernorm.weight": "model-00002-of-00002.safetensors",
75
+ "model.layers.19.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
76
+ "model.layers.19.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
77
+ "model.layers.19.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
78
+ "model.layers.19.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
79
+ "model.layers.19.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
80
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00002.safetensors",
81
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
82
+ "model.layers.2.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
83
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
84
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
85
+ "model.layers.2.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
86
+ "model.layers.20.input_layernorm.weight": "model-00002-of-00002.safetensors",
87
+ "model.layers.20.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
88
+ "model.layers.20.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
89
+ "model.layers.20.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
90
+ "model.layers.20.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
91
+ "model.layers.20.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
92
+ "model.layers.21.input_layernorm.weight": "model-00002-of-00002.safetensors",
93
+ "model.layers.21.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
94
+ "model.layers.21.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
95
+ "model.layers.21.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
96
+ "model.layers.21.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
97
+ "model.layers.21.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
98
+ "model.layers.22.input_layernorm.weight": "model-00002-of-00002.safetensors",
99
+ "model.layers.22.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
100
+ "model.layers.22.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
101
+ "model.layers.22.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
102
+ "model.layers.22.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
103
+ "model.layers.22.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
104
+ "model.layers.23.input_layernorm.weight": "model-00002-of-00002.safetensors",
105
+ "model.layers.23.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
106
+ "model.layers.23.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
107
+ "model.layers.23.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
108
+ "model.layers.23.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
109
+ "model.layers.23.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
110
+ "model.layers.24.input_layernorm.weight": "model-00002-of-00002.safetensors",
111
+ "model.layers.24.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
112
+ "model.layers.24.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
113
+ "model.layers.24.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
114
+ "model.layers.24.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
115
+ "model.layers.24.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
116
+ "model.layers.25.input_layernorm.weight": "model-00002-of-00002.safetensors",
117
+ "model.layers.25.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
118
+ "model.layers.25.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
119
+ "model.layers.25.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
120
+ "model.layers.25.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
121
+ "model.layers.25.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
122
+ "model.layers.26.input_layernorm.weight": "model-00002-of-00002.safetensors",
123
+ "model.layers.26.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
124
+ "model.layers.26.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
125
+ "model.layers.26.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
126
+ "model.layers.26.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
127
+ "model.layers.26.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
128
+ "model.layers.27.input_layernorm.weight": "model-00002-of-00002.safetensors",
129
+ "model.layers.27.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
130
+ "model.layers.27.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
131
+ "model.layers.27.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
132
+ "model.layers.27.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
133
+ "model.layers.27.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
134
+ "model.layers.28.input_layernorm.weight": "model-00002-of-00002.safetensors",
135
+ "model.layers.28.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
136
+ "model.layers.28.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
137
+ "model.layers.28.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
138
+ "model.layers.28.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
139
+ "model.layers.28.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
140
+ "model.layers.29.input_layernorm.weight": "model-00002-of-00002.safetensors",
141
+ "model.layers.29.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
142
+ "model.layers.29.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
143
+ "model.layers.29.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
144
+ "model.layers.29.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
145
+ "model.layers.29.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
146
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00002.safetensors",
147
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
148
+ "model.layers.3.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
149
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
150
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
151
+ "model.layers.3.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
152
+ "model.layers.30.input_layernorm.weight": "model-00002-of-00002.safetensors",
153
+ "model.layers.30.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
154
+ "model.layers.30.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
155
+ "model.layers.30.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
156
+ "model.layers.30.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
157
+ "model.layers.30.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
158
+ "model.layers.31.input_layernorm.weight": "model-00002-of-00002.safetensors",
159
+ "model.layers.31.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
160
+ "model.layers.31.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
161
+ "model.layers.31.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
162
+ "model.layers.31.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
163
+ "model.layers.31.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
164
+ "model.layers.32.input_layernorm.weight": "model-00002-of-00002.safetensors",
165
+ "model.layers.32.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
166
+ "model.layers.32.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
167
+ "model.layers.32.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
168
+ "model.layers.32.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
169
+ "model.layers.32.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
170
+ "model.layers.33.input_layernorm.weight": "model-00002-of-00002.safetensors",
171
+ "model.layers.33.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
172
+ "model.layers.33.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
173
+ "model.layers.33.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
174
+ "model.layers.33.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
175
+ "model.layers.33.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
176
+ "model.layers.34.input_layernorm.weight": "model-00002-of-00002.safetensors",
177
+ "model.layers.34.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
178
+ "model.layers.34.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
179
+ "model.layers.34.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
180
+ "model.layers.34.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
181
+ "model.layers.34.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
182
+ "model.layers.35.input_layernorm.weight": "model-00002-of-00002.safetensors",
183
+ "model.layers.35.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
184
+ "model.layers.35.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
185
+ "model.layers.35.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
186
+ "model.layers.35.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
187
+ "model.layers.35.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
188
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00002.safetensors",
189
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
190
+ "model.layers.4.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
191
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
192
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
193
+ "model.layers.4.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
194
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00002.safetensors",
195
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
196
+ "model.layers.5.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
197
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
198
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
199
+ "model.layers.5.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
200
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00002.safetensors",
201
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
202
+ "model.layers.6.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
203
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
204
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
205
+ "model.layers.6.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
206
+ "model.layers.7.input_layernorm.weight": "model-00001-of-00002.safetensors",
207
+ "model.layers.7.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
208
+ "model.layers.7.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
209
+ "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
210
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
211
+ "model.layers.7.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
212
+ "model.layers.8.input_layernorm.weight": "model-00001-of-00002.safetensors",
213
+ "model.layers.8.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
214
+ "model.layers.8.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
215
+ "model.layers.8.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
216
+ "model.layers.8.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
217
+ "model.layers.8.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
218
+ "model.layers.9.input_layernorm.weight": "model-00001-of-00002.safetensors",
219
+ "model.layers.9.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
220
+ "model.layers.9.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
221
+ "model.layers.9.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
222
+ "model.layers.9.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
223
+ "model.layers.9.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
224
+ "model.norm.weight": "model-00002-of-00002.safetensors"
225
+ }
226
+ }
function_calling_round2/modeling_phi3.py ADDED
@@ -0,0 +1,1572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """ PyTorch Phi-3 model."""
17
+
18
+ #import sys
19
+ #sys.path.append('/home/ubuntu/.cache/huggingface/modules/transformers_modules/microsoft/Phi-3.5-mini-instruct/ccf028fc8e1b3ab750a7c55b22792f57ba69f216/')
20
+ import inspect
21
+ import math
22
+ import warnings
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.cache_utils import Cache, DynamicCache
33
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
34
+ from transformers.modeling_outputs import (
35
+ BaseModelOutputWithPast,
36
+ CausalLMOutputWithPast,
37
+ SequenceClassifierOutputWithPast,
38
+ TokenClassifierOutput,
39
+ )
40
+ from transformers.modeling_utils import PreTrainedModel
41
+ from transformers.utils import (
42
+ add_code_sample_docstrings,
43
+ add_start_docstrings,
44
+ add_start_docstrings_to_model_forward,
45
+ is_flash_attn_2_available,
46
+ is_flash_attn_greater_or_equal_2_10,
47
+ logging,
48
+ replace_return_docstrings,
49
+ )
50
+ from .configuration_phi3 import Phi3Config
51
+
52
+
53
+ logger = logging.get_logger(__name__)
54
+
55
+ # Transformers scans dependencies in the modeling file, causing issues on conditional loading. The regex only ignores try/catch blocks, but not if statements
56
+ # if is_flash_attn_2_available():
57
+ _flash_supports_window_size = False
58
+ try:
59
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
60
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
61
+
62
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
63
+ except ImportError as error:
64
+ logger.warning(
65
+ f"`flash-attention` package not found, consider installing for better performance: {error}."
66
+ )
67
+ if not _flash_supports_window_size:
68
+ logger.warning(
69
+ "Current `flash-attention` does not support `window_size`. Either upgrade or use `attn_implementation='eager'`."
70
+ )
71
+
72
+ _CHECKPOINT_FOR_DOC = "microsoft/Phi-3-mini-4k-instruct"
73
+ _CONFIG_FOR_DOC = "Phi3Config"
74
+
75
+ PHI3_PRETRAINED_MODEL_ARCHIVE_LIST = [
76
+ "microsoft/Phi-3-mini-4k-instruct",
77
+ "microsoft/Phi-3-mini-128k-instruct",
78
+ # See all Phi-3 models at https://huggingface.co/models?filter=Phi-3
79
+ ]
80
+
81
+
82
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Phi3
83
+ class Phi3RMSNorm(nn.Module):
84
+ def __init__(self, hidden_size, eps=1e-6):
85
+ """
86
+ Phi3RMSNorm is equivalent to T5LayerNorm
87
+ """
88
+ super().__init__()
89
+ self.weight = nn.Parameter(torch.ones(hidden_size))
90
+ self.variance_epsilon = eps
91
+
92
+ def forward(self, hidden_states):
93
+ input_dtype = hidden_states.dtype
94
+ hidden_states = hidden_states.to(torch.float32)
95
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
96
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
97
+ return self.weight * hidden_states.to(input_dtype)
98
+
99
+
100
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
101
+ def _get_unpad_data(attention_mask):
102
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
103
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
104
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
105
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
106
+ return (
107
+ indices,
108
+ cu_seqlens,
109
+ max_seqlen_in_batch,
110
+ )
111
+
112
+
113
+ # Copied from transformers.models.gemma.modeling_gemma.GemmaRotaryEmbedding with gemma->phi3, Gemma->Phi3
114
+ class Phi3RotaryEmbedding(nn.Module):
115
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
116
+ super().__init__()
117
+
118
+ self.dim = dim
119
+ self.max_position_embeddings = max_position_embeddings
120
+ self.base = base
121
+ self.register_buffer("inv_freq", None, persistent=False)
122
+
123
+ @torch.no_grad()
124
+ def forward(self, x, position_ids, seq_len=None):
125
+ # x: [bs, num_attention_heads, seq_len, head_size]
126
+ if self.inv_freq is None:
127
+ self.inv_freq = 1.0 / (
128
+ self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim)
129
+ )
130
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
131
+ position_ids_expanded = position_ids[:, None, :].float()
132
+ # Force float32 since bfloat16 loses precision on long contexts
133
+ # See https://github.com/huggingface/transformers/pull/29285
134
+ device_type = x.device.type
135
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
136
+ with torch.autocast(device_type=device_type, enabled=False):
137
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
138
+ emb = torch.cat((freqs, freqs), dim=-1)
139
+ cos = emb.cos()
140
+ sin = emb.sin()
141
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
142
+
143
+
144
+ class Phi3LongRoPEScaledRotaryEmbedding(Phi3RotaryEmbedding):
145
+ def __init__(self, dim, config, device=None):
146
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
147
+
148
+ self.short_factor = config.rope_scaling["short_factor"]
149
+ self.long_factor = config.rope_scaling["long_factor"]
150
+ self.original_max_position_embeddings = config.original_max_position_embeddings
151
+
152
+ @torch.no_grad()
153
+ def forward(self, x, position_ids, seq_len=None):
154
+ seq_len = seq_len or torch.max(position_ids) + 1
155
+ if seq_len > self.original_max_position_embeddings:
156
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
157
+ else:
158
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
159
+
160
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
161
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
162
+
163
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
164
+ position_ids_expanded = position_ids[:, None, :].float()
165
+
166
+ # Force float32 since bfloat16 loses precision on long contexts
167
+ # See https://github.com/huggingface/transformers/pull/29285
168
+ device_type = x.device.type
169
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
170
+ with torch.autocast(device_type=device_type, enabled=False):
171
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
172
+ emb = torch.cat((freqs, freqs), dim=-1)
173
+
174
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
175
+ if scale <= 1.0:
176
+ scaling_factor = 1.0
177
+ else:
178
+ scaling_factor = math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
179
+
180
+ cos = emb.cos() * scaling_factor
181
+ sin = emb.sin() * scaling_factor
182
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
183
+
184
+
185
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
186
+ def rotate_half(x):
187
+ """Rotates half the hidden dims of the input."""
188
+ x1 = x[..., : x.shape[-1] // 2]
189
+ x2 = x[..., x.shape[-1] // 2 :]
190
+ return torch.cat((-x2, x1), dim=-1)
191
+
192
+
193
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
194
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
195
+ """Applies Rotary Position Embedding to the query and key tensors.
196
+
197
+ Args:
198
+ q (`torch.Tensor`): The query tensor.
199
+ k (`torch.Tensor`): The key tensor.
200
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
201
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
202
+ position_ids (`torch.Tensor`, *optional*):
203
+ Deprecated and unused.
204
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
205
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
206
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
207
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
208
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
209
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
210
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
211
+ Returns:
212
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
213
+ """
214
+ cos = cos.unsqueeze(unsqueeze_dim)
215
+ sin = sin.unsqueeze(unsqueeze_dim)
216
+ q_embed = (q * cos) + (rotate_half(q) * sin)
217
+ k_embed = (k * cos) + (rotate_half(k) * sin)
218
+ return q_embed, k_embed
219
+
220
+
221
+ class Phi3MLP(nn.Module):
222
+ def __init__(self, config):
223
+ super().__init__()
224
+
225
+ self.config = config
226
+ self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
227
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
228
+
229
+ self.activation_fn = ACT2FN[config.hidden_act]
230
+
231
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
232
+ up_states = self.gate_up_proj(hidden_states)
233
+
234
+ gate, up_states = up_states.chunk(2, dim=-1)
235
+ up_states = up_states * self.activation_fn(gate)
236
+
237
+ return self.down_proj(up_states)
238
+
239
+
240
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
241
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
242
+ """
243
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
244
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
245
+ """
246
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
247
+ if n_rep == 1:
248
+ return hidden_states
249
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
250
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
251
+
252
+
253
+ class Phi3Attention(nn.Module):
254
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
255
+
256
+ def __init__(self, config: Phi3Config, layer_idx: Optional[int] = None):
257
+ super().__init__()
258
+ self.config = config
259
+ self.layer_idx = layer_idx
260
+ if layer_idx is None:
261
+ logger.warning_once(
262
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
263
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
264
+ "when creating this class."
265
+ )
266
+
267
+ self.attention_dropout = config.attention_dropout
268
+ self.hidden_size = config.hidden_size
269
+ self.num_heads = config.num_attention_heads
270
+ self.head_dim = self.hidden_size // self.num_heads
271
+ self.num_key_value_heads = config.num_key_value_heads
272
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
273
+ self.max_position_embeddings = config.max_position_embeddings
274
+ self.original_max_position_embeddings = config.original_max_position_embeddings
275
+ self.rope_theta = config.rope_theta
276
+ self.rope_scaling = config.rope_scaling
277
+ self.is_causal = True
278
+
279
+ if (self.head_dim * self.num_heads) != self.hidden_size:
280
+ raise ValueError(
281
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
282
+ f" and `num_heads`: {self.num_heads})."
283
+ )
284
+
285
+ op_size = self.num_heads * self.head_dim + 2 * (self.num_key_value_heads * self.head_dim)
286
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
287
+ self.qkv_proj = nn.Linear(self.hidden_size, op_size, bias=False)
288
+ self._init_rope()
289
+
290
+ def _init_rope(self):
291
+ if self.rope_scaling is None:
292
+ self.rotary_emb = Phi3RotaryEmbedding(
293
+ self.head_dim,
294
+ max_position_embeddings=self.max_position_embeddings,
295
+ base=self.rope_theta,
296
+ )
297
+ else:
298
+ scaling_type = self.config.rope_scaling["type"]
299
+ if scaling_type == "longrope":
300
+ self.rotary_emb = Phi3LongRoPEScaledRotaryEmbedding(self.head_dim, self.config)
301
+ else:
302
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
303
+
304
+ def forward(
305
+ self,
306
+ hidden_states: torch.Tensor,
307
+ attention_mask: Optional[torch.Tensor] = None,
308
+ position_ids: Optional[torch.LongTensor] = None,
309
+ past_key_value: Optional[Cache] = None,
310
+ output_attentions: bool = False,
311
+ use_cache: bool = False,
312
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
313
+ logger.warning_once("You are not running the flash-attention implementation, expect numerical differences.")
314
+
315
+ bsz, q_len, _ = hidden_states.size()
316
+
317
+ qkv = self.qkv_proj(hidden_states)
318
+ query_pos = self.num_heads * self.head_dim
319
+ query_states = qkv[..., :query_pos]
320
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
321
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
322
+
323
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
324
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
325
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
326
+
327
+ kv_seq_len = key_states.shape[-2]
328
+ if past_key_value is not None:
329
+ if self.layer_idx is None:
330
+ raise ValueError(
331
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
332
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
333
+ "with a layer index."
334
+ )
335
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
336
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
337
+
338
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
339
+
340
+ if past_key_value is not None:
341
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
342
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
343
+
344
+ # repeat k/v heads if n_kv_heads < n_heads
345
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
346
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
347
+
348
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
349
+
350
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
351
+ raise ValueError(
352
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
353
+ f" {attn_weights.size()}"
354
+ )
355
+
356
+ if attention_mask is not None:
357
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
358
+ raise ValueError(
359
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
360
+ )
361
+ attn_weights = attn_weights + attention_mask
362
+
363
+ # upcast attention to fp32
364
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
365
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
366
+
367
+ attn_output = torch.matmul(attn_weights, value_states)
368
+
369
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
370
+ raise ValueError(
371
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
372
+ f" {attn_output.size()}"
373
+ )
374
+
375
+ attn_output = attn_output.transpose(1, 2).contiguous()
376
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
377
+
378
+ attn_output = self.o_proj(attn_output)
379
+
380
+ if not output_attentions:
381
+ attn_weights = None
382
+
383
+ return attn_output, attn_weights, past_key_value
384
+
385
+
386
+ class Phi3FlashAttention2(Phi3Attention):
387
+ """
388
+ Phi-3 flash attention module. This module inherits from `Phi3Attention` as the weights of the module stays
389
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
390
+ flash attention and deal with padding tokens in case the input contains any of them.
391
+ """
392
+
393
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
394
+ def __init__(self, *args, **kwargs):
395
+ super().__init__(*args, **kwargs)
396
+
397
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
398
+ # 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.
399
+ # 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).
400
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
401
+
402
+ def forward(
403
+ self,
404
+ hidden_states: torch.Tensor,
405
+ attention_mask: Optional[torch.LongTensor] = None,
406
+ position_ids: Optional[torch.LongTensor] = None,
407
+ past_key_value: Optional[Cache] = None,
408
+ output_attentions: bool = False,
409
+ use_cache: bool = False,
410
+ **kwargs,
411
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
412
+ # Phi3FlashAttention2 attention does not support output_attentions
413
+
414
+ if not _flash_supports_window_size:
415
+ logger.warning_once(
416
+ "The current flash attention version does not support sliding window attention. Please use `attn_implementation='eager'` or upgrade flash-attn library."
417
+ )
418
+ raise ValueError("The current flash attention version does not support sliding window attention.")
419
+
420
+ output_attentions = False
421
+
422
+ if "padding_mask" in kwargs:
423
+ warnings.warn(
424
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
425
+ )
426
+
427
+ # overwrite attention_mask with padding_mask
428
+ attention_mask = kwargs.pop("padding_mask")
429
+
430
+ bsz, q_len, _ = hidden_states.size()
431
+
432
+ qkv = self.qkv_proj(hidden_states)
433
+ query_pos = self.num_heads * self.head_dim
434
+ query_states = qkv[..., :query_pos]
435
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
436
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
437
+
438
+ # Flash attention requires the input to have the shape
439
+ # batch_size x seq_length x head_dim x hidden_dim
440
+ # therefore we just need to keep the original shape
441
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
442
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
443
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
444
+
445
+ kv_seq_len = key_states.shape[-2]
446
+ if past_key_value is not None:
447
+ if self.layer_idx is None:
448
+ raise ValueError(
449
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
450
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
451
+ "with a layer index."
452
+ )
453
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
454
+
455
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
456
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item() + 1)
457
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=rotary_seq_len)
458
+
459
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
460
+
461
+ use_sliding_windows = (
462
+ _flash_supports_window_size
463
+ and getattr(self.config, "sliding_window", None) is not None
464
+ and kv_seq_len > self.config.sliding_window
465
+ )
466
+
467
+ if past_key_value is not None:
468
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
469
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
470
+ if (
471
+ getattr(self.config, "sliding_window", None) is not None
472
+ and kv_seq_len > self.config.sliding_window
473
+ and cache_has_contents
474
+ ):
475
+ slicing_tokens = 1 - self.config.sliding_window
476
+
477
+ past_key = past_key_value[self.layer_idx][0]
478
+ past_value = past_key_value[self.layer_idx][1]
479
+
480
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
481
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
482
+
483
+ if past_key.shape[-2] != self.config.sliding_window - 1:
484
+ raise ValueError(
485
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
486
+ f" {past_key.shape}"
487
+ )
488
+
489
+ if attention_mask is not None:
490
+ attention_mask = attention_mask[:, slicing_tokens:]
491
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
492
+
493
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
494
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
495
+
496
+ # repeat k/v heads if n_kv_heads < n_heads
497
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
498
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
499
+
500
+ attn_dropout = self.attention_dropout if self.training else 0.0
501
+
502
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
503
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
504
+ # cast them back in the correct dtype just to be sure everything works as expected.
505
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
506
+ # in fp32.
507
+
508
+ if query_states.dtype == torch.float32:
509
+ if torch.is_autocast_enabled():
510
+ target_dtype = torch.get_autocast_gpu_dtype()
511
+ # Handle the case where the model is quantized
512
+ elif hasattr(self.config, "_pre_quantization_dtype"):
513
+ target_dtype = self.config._pre_quantization_dtype
514
+ else:
515
+ target_dtype = self.qkv_proj.weight.dtype
516
+
517
+ logger.warning_once(
518
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
519
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
520
+ f" {target_dtype}."
521
+ )
522
+
523
+ query_states = query_states.to(target_dtype)
524
+ key_states = key_states.to(target_dtype)
525
+ value_states = value_states.to(target_dtype)
526
+
527
+ # Reashape to the expected shape for Flash Attention
528
+ query_states = query_states.transpose(1, 2)
529
+ key_states = key_states.transpose(1, 2)
530
+ value_states = value_states.transpose(1, 2)
531
+
532
+ attn_output = self._flash_attention_forward(
533
+ query_states,
534
+ key_states,
535
+ value_states,
536
+ attention_mask,
537
+ q_len,
538
+ dropout=attn_dropout,
539
+ use_sliding_windows=use_sliding_windows,
540
+ )
541
+
542
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
543
+ attn_output = self.o_proj(attn_output)
544
+
545
+ if not output_attentions:
546
+ attn_weights = None
547
+
548
+ return attn_output, attn_weights, past_key_value
549
+
550
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._flash_attention_forward
551
+ def _flash_attention_forward(
552
+ self,
553
+ query_states,
554
+ key_states,
555
+ value_states,
556
+ attention_mask,
557
+ query_length,
558
+ dropout=0.0,
559
+ softmax_scale=None,
560
+ use_sliding_windows=False,
561
+ ):
562
+ """
563
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
564
+ first unpad the input, then computes the attention scores and pad the final attention scores.
565
+
566
+ Args:
567
+ query_states (`torch.Tensor`):
568
+ Input query states to be passed to Flash Attention API
569
+ key_states (`torch.Tensor`):
570
+ Input key states to be passed to Flash Attention API
571
+ value_states (`torch.Tensor`):
572
+ Input value states to be passed to Flash Attention API
573
+ attention_mask (`torch.Tensor`):
574
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
575
+ position of padding tokens and 1 for the position of non-padding tokens.
576
+ dropout (`float`):
577
+ Attention dropout
578
+ softmax_scale (`float`, *optional*):
579
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
580
+ use_sliding_windows (`bool`, *optional*):
581
+ Whether to activate sliding window attention.
582
+ """
583
+ if not self._flash_attn_uses_top_left_mask:
584
+ causal = self.is_causal
585
+ else:
586
+ # 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__.
587
+ causal = self.is_causal and query_length != 1
588
+
589
+ # Contains at least one padding token in the sequence
590
+ if attention_mask is not None:
591
+ batch_size = query_states.shape[0]
592
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
593
+ query_states, key_states, value_states, attention_mask, query_length
594
+ )
595
+
596
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
597
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
598
+
599
+ if not use_sliding_windows:
600
+ attn_output_unpad = flash_attn_varlen_func(
601
+ query_states,
602
+ key_states,
603
+ value_states,
604
+ cu_seqlens_q=cu_seqlens_q,
605
+ cu_seqlens_k=cu_seqlens_k,
606
+ max_seqlen_q=max_seqlen_in_batch_q,
607
+ max_seqlen_k=max_seqlen_in_batch_k,
608
+ dropout_p=dropout,
609
+ softmax_scale=softmax_scale,
610
+ causal=causal,
611
+ )
612
+ else:
613
+ attn_output_unpad = flash_attn_varlen_func(
614
+ query_states,
615
+ key_states,
616
+ value_states,
617
+ cu_seqlens_q=cu_seqlens_q,
618
+ cu_seqlens_k=cu_seqlens_k,
619
+ max_seqlen_q=max_seqlen_in_batch_q,
620
+ max_seqlen_k=max_seqlen_in_batch_k,
621
+ dropout_p=dropout,
622
+ softmax_scale=softmax_scale,
623
+ causal=causal,
624
+ window_size=(self.config.sliding_window, self.config.sliding_window),
625
+ )
626
+
627
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
628
+ else:
629
+ if not use_sliding_windows:
630
+ attn_output = flash_attn_func(
631
+ query_states,
632
+ key_states,
633
+ value_states,
634
+ dropout,
635
+ softmax_scale=softmax_scale,
636
+ causal=causal,
637
+ )
638
+ else:
639
+ attn_output = flash_attn_func(
640
+ query_states,
641
+ key_states,
642
+ value_states,
643
+ dropout,
644
+ softmax_scale=softmax_scale,
645
+ causal=causal,
646
+ window_size=(self.config.sliding_window, self.config.sliding_window),
647
+ )
648
+
649
+ return attn_output
650
+
651
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
652
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
653
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
654
+
655
+ # On the first iteration we need to properly re-create the padding mask
656
+ # by slicing it on the proper place
657
+ if kv_seq_len != attention_mask.shape[-1]:
658
+ attention_mask_num_tokens = attention_mask.shape[-1]
659
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
660
+
661
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
662
+
663
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
664
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
665
+
666
+ if query_length == kv_seq_len:
667
+ query_layer = index_first_axis(
668
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
669
+ )
670
+ cu_seqlens_q = cu_seqlens_k
671
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
672
+ indices_q = indices_k
673
+ elif query_length == 1:
674
+ max_seqlen_in_batch_q = 1
675
+ cu_seqlens_q = torch.arange(
676
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
677
+ ) # There is a memcpy here, that is very bad.
678
+ indices_q = cu_seqlens_q[:-1]
679
+ query_layer = query_layer.squeeze(1)
680
+ else:
681
+ # The -q_len: slice assumes left padding.
682
+ attention_mask = attention_mask[:, -query_length:]
683
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
684
+
685
+ return (
686
+ query_layer,
687
+ key_layer,
688
+ value_layer,
689
+ indices_q,
690
+ (cu_seqlens_q, cu_seqlens_k),
691
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
692
+ )
693
+
694
+
695
+ # copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Phi3
696
+ # TODO @Arthur no longer copied from LLama after static cache
697
+ class Phi3SdpaAttention(Phi3Attention):
698
+ """
699
+ Phi3 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
700
+ `Phi3Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
701
+ SDPA API.
702
+ """
703
+
704
+ # Adapted from Phi3Attention.forward
705
+ def forward(
706
+ self,
707
+ hidden_states: torch.Tensor,
708
+ attention_mask: Optional[torch.Tensor] = None,
709
+ position_ids: Optional[torch.LongTensor] = None,
710
+ past_key_value: Optional[Cache] = None,
711
+ output_attentions: bool = False,
712
+ use_cache: bool = False,
713
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
714
+ if output_attentions:
715
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
716
+ logger.warning_once(
717
+ "Phi3Model is using Phi3SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
718
+ '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.'
719
+ )
720
+ return super().forward(
721
+ hidden_states=hidden_states,
722
+ attention_mask=attention_mask,
723
+ position_ids=position_ids,
724
+ past_key_value=past_key_value,
725
+ output_attentions=output_attentions,
726
+ use_cache=use_cache,
727
+ )
728
+
729
+ bsz, q_len, _ = hidden_states.size()
730
+
731
+ qkv = self.qkv_proj(hidden_states)
732
+ query_pos = self.num_heads * self.head_dim
733
+ query_states = qkv[..., :query_pos]
734
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
735
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
736
+
737
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
738
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
739
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
740
+
741
+ kv_seq_len = key_states.shape[-2]
742
+ if past_key_value is not None:
743
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
744
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
745
+
746
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
747
+
748
+ if past_key_value is not None:
749
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
750
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
751
+
752
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
753
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
754
+
755
+ if attention_mask is not None:
756
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
757
+ raise ValueError(
758
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
759
+ )
760
+
761
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
762
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
763
+ if query_states.device.type == "cuda" and attention_mask is not None:
764
+ query_states = query_states.contiguous()
765
+ key_states = key_states.contiguous()
766
+ value_states = value_states.contiguous()
767
+
768
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
769
+ query_states,
770
+ key_states,
771
+ value_states,
772
+ attn_mask=attention_mask,
773
+ dropout_p=self.attention_dropout if self.training else 0.0,
774
+ # 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.
775
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
776
+ )
777
+
778
+ attn_output = attn_output.transpose(1, 2).contiguous()
779
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
780
+
781
+ attn_output = self.o_proj(attn_output)
782
+
783
+ return attn_output, None, past_key_value
784
+
785
+
786
+ PHI3_ATTENTION_CLASSES = {
787
+ "eager": Phi3Attention,
788
+ "flash_attention_2": Phi3FlashAttention2,
789
+ "sdpa": Phi3SdpaAttention,
790
+ }
791
+
792
+
793
+ class Phi3DecoderLayer(nn.Module):
794
+ def __init__(self, config: Phi3Config, layer_idx: int):
795
+ super().__init__()
796
+
797
+ self.config = config
798
+ self.self_attn = PHI3_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
799
+
800
+ self.mlp = Phi3MLP(config)
801
+ self.input_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
802
+
803
+ self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)
804
+ self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)
805
+ self.post_attention_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
806
+
807
+ def forward(
808
+ self,
809
+ hidden_states: torch.Tensor,
810
+ attention_mask: Optional[torch.Tensor] = None,
811
+ position_ids: Optional[torch.LongTensor] = None,
812
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
813
+ output_attentions: Optional[bool] = False,
814
+ use_cache: Optional[bool] = False,
815
+ **kwargs,
816
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
817
+ if "padding_mask" in kwargs:
818
+ warnings.warn(
819
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
820
+ )
821
+ """
822
+ Args:
823
+ hidden_states (`torch.FloatTensor`):
824
+ input to the layer of shape `(batch, seq_len, embed_dim)`
825
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
826
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
827
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
828
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
829
+ `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
830
+ output_attentions (`bool`, *optional*):
831
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
832
+ returned tensors for more detail.
833
+ use_cache (`bool`, *optional*):
834
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
835
+ (see `past_key_values`).
836
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
837
+ """
838
+
839
+ residual = hidden_states
840
+
841
+ hidden_states = self.input_layernorm(hidden_states)
842
+
843
+ # Self Attention
844
+ attn_outputs, self_attn_weights, present_key_value = self.self_attn(
845
+ hidden_states=hidden_states,
846
+ attention_mask=attention_mask,
847
+ position_ids=position_ids,
848
+ past_key_value=past_key_value,
849
+ output_attentions=output_attentions,
850
+ use_cache=use_cache,
851
+ )
852
+
853
+ hidden_states = residual + self.resid_attn_dropout(attn_outputs)
854
+
855
+ residual = hidden_states
856
+ hidden_states = self.post_attention_layernorm(hidden_states)
857
+ hidden_states = self.mlp(hidden_states)
858
+ hidden_states = residual + self.resid_mlp_dropout(hidden_states)
859
+
860
+ outputs = (hidden_states,)
861
+
862
+ if output_attentions:
863
+ outputs += (self_attn_weights,)
864
+
865
+ if use_cache:
866
+ outputs += (present_key_value,)
867
+
868
+ return outputs
869
+
870
+
871
+ PHI3_START_DOCSTRING = r"""
872
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
873
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
874
+ etc.)
875
+
876
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
877
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
878
+ and behavior.
879
+
880
+ Parameters:
881
+ config ([`Phi3Config`]):
882
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
883
+ load the weights associated with the model, only the configuration. Check out the
884
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
885
+ """
886
+
887
+
888
+ @add_start_docstrings(
889
+ "The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
890
+ PHI3_START_DOCSTRING,
891
+ )
892
+ class Phi3PreTrainedModel(PreTrainedModel):
893
+ config_class = Phi3Config
894
+ base_model_prefix = "model"
895
+ supports_gradient_checkpointing = True
896
+ _no_split_modules = ["Phi3DecoderLayer"]
897
+ _skip_keys_device_placement = "past_key_values"
898
+ _supports_flash_attn_2 = True
899
+ _supports_sdpa = False
900
+ _supports_cache_class = True
901
+
902
+ _version = "0.0.5"
903
+
904
+ def _init_weights(self, module):
905
+ std = self.config.initializer_range
906
+ if isinstance(module, nn.Linear):
907
+ module.weight.data.normal_(mean=0.0, std=std)
908
+ if module.bias is not None:
909
+ module.bias.data.zero_()
910
+ elif isinstance(module, nn.Embedding):
911
+ module.weight.data.normal_(mean=0.0, std=std)
912
+ if module.padding_idx is not None:
913
+ module.weight.data[module.padding_idx].zero_()
914
+
915
+
916
+ PHI3_INPUTS_DOCSTRING = r"""
917
+ Args:
918
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
919
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
920
+ it.
921
+
922
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
923
+ [`PreTrainedTokenizer.__call__`] for details.
924
+
925
+ [What are input IDs?](../glossary#input-ids)
926
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
927
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
928
+
929
+ - 1 for tokens that are **not masked**,
930
+ - 0 for tokens that are **masked**.
931
+
932
+ [What are attention masks?](../glossary#attention-mask)
933
+
934
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
935
+ [`PreTrainedTokenizer.__call__`] for details.
936
+
937
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
938
+ `past_key_values`).
939
+
940
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
941
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
942
+ information on the default strategy.
943
+
944
+ - 1 indicates the head is **not masked**,
945
+ - 0 indicates the head is **masked**.
946
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
947
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
948
+ config.n_positions - 1]`.
949
+
950
+ [What are position IDs?](../glossary#position-ids)
951
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
952
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
953
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
954
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
955
+
956
+ Two formats are allowed:
957
+ - a [`~cache_utils.Cache`] instance;
958
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
959
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
960
+ cache format.
961
+
962
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
963
+ legacy cache format will be returned.
964
+
965
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
966
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
967
+ of shape `(batch_size, sequence_length)`.
968
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
969
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
970
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
971
+ model's internal embedding lookup matrix.
972
+ use_cache (`bool`, *optional*):
973
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
974
+ `past_key_values`).
975
+ output_attentions (`bool`, *optional*):
976
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
977
+ tensors for more detail.
978
+ output_hidden_states (`bool`, *optional*):
979
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
980
+ more detail.
981
+ return_dict (`bool`, *optional*):
982
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
983
+ """
984
+
985
+
986
+ @add_start_docstrings(
987
+ "The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
988
+ PHI3_START_DOCSTRING,
989
+ )
990
+ class Phi3Model(Phi3PreTrainedModel):
991
+ """
992
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Phi3DecoderLayer`]
993
+
994
+ Args:
995
+ config: Phi3Config
996
+ """
997
+
998
+ def __init__(self, config: Phi3Config):
999
+ super().__init__(config)
1000
+ self.padding_idx = config.pad_token_id
1001
+ self.vocab_size = config.vocab_size
1002
+
1003
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1004
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
1005
+ self.layers = nn.ModuleList(
1006
+ [Phi3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1007
+ )
1008
+ self._attn_implementation = config._attn_implementation
1009
+ self.norm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1010
+
1011
+ self.gradient_checkpointing = False
1012
+ # Initialize weights and apply final processing
1013
+ self.post_init()
1014
+
1015
+ def get_input_embeddings(self):
1016
+ return self.embed_tokens
1017
+
1018
+ def set_input_embeddings(self, value):
1019
+ self.embed_tokens = value
1020
+
1021
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1022
+ def forward(
1023
+ self,
1024
+ input_ids: torch.LongTensor = None,
1025
+ attention_mask: Optional[torch.Tensor] = None,
1026
+ position_ids: Optional[torch.LongTensor] = None,
1027
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1028
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1029
+ use_cache: Optional[bool] = None,
1030
+ output_attentions: Optional[bool] = None,
1031
+ output_hidden_states: Optional[bool] = None,
1032
+ return_dict: Optional[bool] = None,
1033
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1034
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1035
+ output_hidden_states = (
1036
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1037
+ )
1038
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1039
+
1040
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1041
+
1042
+ # retrieve input_ids and inputs_embeds
1043
+ if input_ids is not None and inputs_embeds is not None:
1044
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1045
+ elif input_ids is not None:
1046
+ batch_size, seq_length = input_ids.shape[:2]
1047
+ elif inputs_embeds is not None:
1048
+ batch_size, seq_length = inputs_embeds.shape[:2]
1049
+ else:
1050
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1051
+
1052
+ past_key_values_length = 0
1053
+
1054
+ if self.gradient_checkpointing and self.training:
1055
+ if use_cache:
1056
+ logger.warning_once(
1057
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1058
+ )
1059
+ use_cache = False
1060
+
1061
+ if use_cache:
1062
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1063
+ if use_legacy_cache:
1064
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1065
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1066
+
1067
+ if position_ids is None:
1068
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1069
+ position_ids = torch.arange(
1070
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1071
+ )
1072
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1073
+ else:
1074
+ position_ids = position_ids.view(-1, seq_length).long()
1075
+
1076
+ if inputs_embeds is None:
1077
+ inputs_embeds = self.embed_tokens(input_ids)
1078
+
1079
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1080
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1081
+ if is_padding_right:
1082
+ raise ValueError(
1083
+ "You are attempting to perform batched generation with padding_side='right'"
1084
+ " this may lead to unexpected behaviour for Flash Attention version of Phi3. Make sure to "
1085
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1086
+ )
1087
+
1088
+ if self._attn_implementation == "flash_attention_2":
1089
+ # 2d mask is passed through the layers
1090
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1091
+ else:
1092
+ # 4d mask is passed through the layers
1093
+ attention_mask = _prepare_4d_causal_attention_mask(
1094
+ attention_mask,
1095
+ (batch_size, seq_length),
1096
+ inputs_embeds,
1097
+ past_key_values_length,
1098
+ sliding_window=self.config.sliding_window,
1099
+ )
1100
+
1101
+ hidden_states = inputs_embeds
1102
+
1103
+ # decoder layers
1104
+ all_hidden_states = () if output_hidden_states else None
1105
+ all_self_attns = () if output_attentions else None
1106
+ next_decoder_cache = None
1107
+
1108
+ for decoder_layer in self.layers:
1109
+ if output_hidden_states:
1110
+ all_hidden_states += (hidden_states,)
1111
+
1112
+ if self.gradient_checkpointing and self.training:
1113
+ layer_outputs = self._gradient_checkpointing_func(
1114
+ decoder_layer.__call__,
1115
+ hidden_states,
1116
+ attention_mask,
1117
+ position_ids,
1118
+ past_key_values,
1119
+ output_attentions,
1120
+ use_cache,
1121
+ )
1122
+ else:
1123
+ layer_outputs = decoder_layer(
1124
+ hidden_states,
1125
+ attention_mask=attention_mask,
1126
+ position_ids=position_ids,
1127
+ past_key_value=past_key_values,
1128
+ output_attentions=output_attentions,
1129
+ use_cache=use_cache,
1130
+ )
1131
+
1132
+ hidden_states = layer_outputs[0]
1133
+
1134
+ if use_cache:
1135
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1136
+
1137
+ if output_attentions:
1138
+ all_self_attns += (layer_outputs[1],)
1139
+
1140
+ hidden_states = self.norm(hidden_states)
1141
+
1142
+ # add hidden states from the last decoder layer
1143
+ if output_hidden_states:
1144
+ all_hidden_states += (hidden_states,)
1145
+
1146
+ next_cache = None
1147
+ if use_cache:
1148
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1149
+ if not return_dict:
1150
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1151
+ return BaseModelOutputWithPast(
1152
+ last_hidden_state=hidden_states,
1153
+ past_key_values=next_cache,
1154
+ hidden_states=all_hidden_states,
1155
+ attentions=all_self_attns,
1156
+ )
1157
+
1158
+
1159
+ class Phi3ForCausalLM(Phi3PreTrainedModel):
1160
+ _tied_weights_keys = ["lm_head.weight"]
1161
+
1162
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi3
1163
+ def __init__(self, config):
1164
+ super().__init__(config)
1165
+ self.model = Phi3Model(config)
1166
+ self.vocab_size = config.vocab_size
1167
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1168
+
1169
+ # Initialize weights and apply final processing
1170
+ self.post_init()
1171
+
1172
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
1173
+ def get_input_embeddings(self):
1174
+ return self.model.embed_tokens
1175
+
1176
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
1177
+ def set_input_embeddings(self, value):
1178
+ self.model.embed_tokens = value
1179
+
1180
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
1181
+ def get_output_embeddings(self):
1182
+ return self.lm_head
1183
+
1184
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
1185
+ def set_output_embeddings(self, new_embeddings):
1186
+ self.lm_head = new_embeddings
1187
+
1188
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
1189
+ def set_decoder(self, decoder):
1190
+ self.model = decoder
1191
+
1192
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
1193
+ def get_decoder(self):
1194
+ return self.model
1195
+
1196
+ # Ignore copy
1197
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1198
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1199
+ def forward(
1200
+ self,
1201
+ input_ids: torch.LongTensor = None,
1202
+ attention_mask: Optional[torch.Tensor] = None,
1203
+ position_ids: Optional[torch.LongTensor] = None,
1204
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1205
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1206
+ labels: Optional[torch.LongTensor] = None,
1207
+ use_cache: Optional[bool] = None,
1208
+ output_attentions: Optional[bool] = None,
1209
+ output_hidden_states: Optional[bool] = None,
1210
+ return_dict: Optional[bool] = None,
1211
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1212
+ r"""
1213
+ Args:
1214
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1215
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1216
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1217
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1218
+
1219
+ Returns:
1220
+
1221
+ Example:
1222
+
1223
+ ```python
1224
+ >>> from transformers import AutoTokenizer, Phi3ForCausalLM
1225
+
1226
+ >>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1227
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1228
+
1229
+ >>> prompt = "This is an example script ."
1230
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1231
+
1232
+ >>> # Generate
1233
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1234
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1235
+ 'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
1236
+ ```"""
1237
+
1238
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1239
+ output_hidden_states = (
1240
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1241
+ )
1242
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1243
+
1244
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1245
+ outputs = self.model(
1246
+ input_ids=input_ids,
1247
+ attention_mask=attention_mask,
1248
+ position_ids=position_ids,
1249
+ past_key_values=past_key_values,
1250
+ inputs_embeds=inputs_embeds,
1251
+ use_cache=use_cache,
1252
+ output_attentions=output_attentions,
1253
+ output_hidden_states=output_hidden_states,
1254
+ return_dict=return_dict,
1255
+ )
1256
+
1257
+ hidden_states = outputs[0]
1258
+ logits = self.lm_head(hidden_states)
1259
+ logits = logits.float()
1260
+
1261
+ loss = None
1262
+ if labels is not None:
1263
+ # Shift so that tokens < n predict n
1264
+ shift_logits = logits[..., :-1, :].contiguous()
1265
+ shift_labels = labels[..., 1:].contiguous()
1266
+ # Flatten the tokens
1267
+ loss_fct = CrossEntropyLoss()
1268
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1269
+ shift_labels = shift_labels.view(-1)
1270
+ # Enable model parallelism
1271
+ shift_labels = shift_labels.to(shift_logits.device)
1272
+ loss = loss_fct(shift_logits, shift_labels)
1273
+
1274
+ if not return_dict:
1275
+ output = (logits,) + outputs[1:]
1276
+ return (loss,) + output if loss is not None else output
1277
+
1278
+ return CausalLMOutputWithPast(
1279
+ loss=loss,
1280
+ logits=logits,
1281
+ past_key_values=outputs.past_key_values,
1282
+ hidden_states=outputs.hidden_states,
1283
+ attentions=outputs.attentions,
1284
+ )
1285
+
1286
+ # Copied from transformers.models.persimmon.modeling_persimmon.PersimmonForCausalLM.prepare_inputs_for_generation
1287
+ def prepare_inputs_for_generation(
1288
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1289
+ ):
1290
+ # When the first time input length reached long and short factor switching point, enforce re-compute cache
1291
+ # It will cause downside of slower at this single token position, however, better than current failure.
1292
+ if past_key_values and self.config.rope_scaling and input_ids.shape[1] >= self.config.original_max_position_embeddings + 1:
1293
+ past_length = past_key_values.seen_tokens if isinstance(past_key_values, Cache) else past_key_values[0][0].shape[2]
1294
+ if past_length <= self.config.original_max_position_embeddings:
1295
+ past_key_values = None
1296
+
1297
+ if past_key_values is not None:
1298
+ if isinstance(past_key_values, Cache):
1299
+ cache_length = past_key_values.get_seq_length()
1300
+ past_length = past_key_values.seen_tokens
1301
+ max_cache_length = past_key_values.get_max_length()
1302
+ else:
1303
+ cache_length = past_length = past_key_values[0][0].shape[2]
1304
+ max_cache_length = None
1305
+
1306
+ # Keep only the unprocessed tokens:
1307
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1308
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1309
+ # input)
1310
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1311
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1312
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1313
+ # input_ids based on the past_length.
1314
+ elif past_length < input_ids.shape[1]:
1315
+ input_ids = input_ids[:, past_length:]
1316
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1317
+
1318
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1319
+ if (
1320
+ max_cache_length is not None
1321
+ and attention_mask is not None
1322
+ and cache_length + input_ids.shape[1] > max_cache_length
1323
+ ):
1324
+ attention_mask = attention_mask[:, -max_cache_length:]
1325
+
1326
+ position_ids = kwargs.get("position_ids", None)
1327
+ if attention_mask is not None and position_ids is None:
1328
+ # create position_ids on the fly for batch generation
1329
+ position_ids = attention_mask.long().cumsum(-1) - 1
1330
+ position_ids.masked_fill_(attention_mask == 0, 1)
1331
+ if past_key_values:
1332
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1333
+
1334
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1335
+ if inputs_embeds is not None and past_key_values is None:
1336
+ model_inputs = {"inputs_embeds": inputs_embeds}
1337
+ else:
1338
+ model_inputs = {"input_ids": input_ids}
1339
+
1340
+ model_inputs.update(
1341
+ {
1342
+ "position_ids": position_ids,
1343
+ "past_key_values": past_key_values,
1344
+ "use_cache": kwargs.get("use_cache"),
1345
+ "attention_mask": attention_mask,
1346
+ }
1347
+ )
1348
+ return model_inputs
1349
+
1350
+ @staticmethod
1351
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM._reorder_cache
1352
+ def _reorder_cache(past_key_values, beam_idx):
1353
+ reordered_past = ()
1354
+ for layer_past in past_key_values:
1355
+ reordered_past += (
1356
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1357
+ )
1358
+ return reordered_past
1359
+
1360
+
1361
+ @add_start_docstrings(
1362
+ """
1363
+ The [`Phi3Model`] with a sequence classification head on top (linear layer).
1364
+
1365
+ [`Phi3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1366
+ (e.g. GPT-2) do.
1367
+
1368
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1369
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1370
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1371
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1372
+ each row of the batch).
1373
+ """,
1374
+ PHI3_START_DOCSTRING,
1375
+ )
1376
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Phi3, LLAMA->PHI3, self.transformer->self.model, transformer_outputs->model_outputs
1377
+ class Phi3ForSequenceClassification(Phi3PreTrainedModel):
1378
+ def __init__(self, config):
1379
+ super().__init__(config)
1380
+ self.num_labels = config.num_labels
1381
+ self.model = Phi3Model(config)
1382
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1383
+
1384
+ # Initialize weights and apply final processing
1385
+ self.post_init()
1386
+
1387
+ def get_input_embeddings(self):
1388
+ return self.model.embed_tokens
1389
+
1390
+ def set_input_embeddings(self, value):
1391
+ self.model.embed_tokens = value
1392
+
1393
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1394
+ def forward(
1395
+ self,
1396
+ input_ids: torch.LongTensor = None,
1397
+ attention_mask: Optional[torch.Tensor] = None,
1398
+ position_ids: Optional[torch.LongTensor] = None,
1399
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1400
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1401
+ labels: Optional[torch.LongTensor] = None,
1402
+ use_cache: Optional[bool] = None,
1403
+ output_attentions: Optional[bool] = None,
1404
+ output_hidden_states: Optional[bool] = None,
1405
+ return_dict: Optional[bool] = None,
1406
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1407
+ r"""
1408
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1409
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1410
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1411
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1412
+ """
1413
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1414
+
1415
+ model_outputs = self.model(
1416
+ input_ids,
1417
+ attention_mask=attention_mask,
1418
+ position_ids=position_ids,
1419
+ past_key_values=past_key_values,
1420
+ inputs_embeds=inputs_embeds,
1421
+ use_cache=use_cache,
1422
+ output_attentions=output_attentions,
1423
+ output_hidden_states=output_hidden_states,
1424
+ return_dict=return_dict,
1425
+ )
1426
+ hidden_states = model_outputs[0]
1427
+ logits = self.score(hidden_states)
1428
+
1429
+ if input_ids is not None:
1430
+ batch_size = input_ids.shape[0]
1431
+ else:
1432
+ batch_size = inputs_embeds.shape[0]
1433
+
1434
+ if self.config.pad_token_id is None and batch_size != 1:
1435
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1436
+ if self.config.pad_token_id is None:
1437
+ sequence_lengths = -1
1438
+ else:
1439
+ if input_ids is not None:
1440
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1441
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1442
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1443
+ sequence_lengths = sequence_lengths.to(logits.device)
1444
+ else:
1445
+ sequence_lengths = -1
1446
+
1447
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1448
+
1449
+ loss = None
1450
+ if labels is not None:
1451
+ labels = labels.to(logits.device)
1452
+ if self.config.problem_type is None:
1453
+ if self.num_labels == 1:
1454
+ self.config.problem_type = "regression"
1455
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1456
+ self.config.problem_type = "single_label_classification"
1457
+ else:
1458
+ self.config.problem_type = "multi_label_classification"
1459
+
1460
+ if self.config.problem_type == "regression":
1461
+ loss_fct = MSELoss()
1462
+ if self.num_labels == 1:
1463
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1464
+ else:
1465
+ loss = loss_fct(pooled_logits, labels)
1466
+ elif self.config.problem_type == "single_label_classification":
1467
+ loss_fct = CrossEntropyLoss()
1468
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1469
+ elif self.config.problem_type == "multi_label_classification":
1470
+ loss_fct = BCEWithLogitsLoss()
1471
+ loss = loss_fct(pooled_logits, labels)
1472
+ if not return_dict:
1473
+ output = (pooled_logits,) + model_outputs[1:]
1474
+ return ((loss,) + output) if loss is not None else output
1475
+
1476
+ return SequenceClassifierOutputWithPast(
1477
+ loss=loss,
1478
+ logits=pooled_logits,
1479
+ past_key_values=model_outputs.past_key_values,
1480
+ hidden_states=model_outputs.hidden_states,
1481
+ attentions=model_outputs.attentions,
1482
+ )
1483
+
1484
+
1485
+ @add_start_docstrings(
1486
+ """
1487
+ [`Phi3Model`] with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1488
+ Named-Entity-Recognition (NER) tasks.
1489
+ """,
1490
+ PHI3_START_DOCSTRING,
1491
+ )
1492
+ # Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with Mpt->Phi3,MPT->PHI3,self.transformer->self.model,transformer_outputs->model_outputs
1493
+ class Phi3ForTokenClassification(Phi3PreTrainedModel):
1494
+ def __init__(self, config: Phi3Config):
1495
+ super().__init__(config)
1496
+ self.num_labels = config.num_labels
1497
+
1498
+ self.model = Phi3Model(config)
1499
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1500
+ classifier_dropout = config.classifier_dropout
1501
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1502
+ classifier_dropout = config.hidden_dropout
1503
+ else:
1504
+ classifier_dropout = 0.1
1505
+ self.dropout = nn.Dropout(classifier_dropout)
1506
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1507
+
1508
+ # Initialize weights and apply final processing
1509
+ self.post_init()
1510
+
1511
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1512
+ @add_code_sample_docstrings(
1513
+ checkpoint=_CHECKPOINT_FOR_DOC,
1514
+ output_type=TokenClassifierOutput,
1515
+ config_class=_CONFIG_FOR_DOC,
1516
+ )
1517
+ def forward(
1518
+ self,
1519
+ input_ids: Optional[torch.LongTensor] = None,
1520
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1521
+ attention_mask: Optional[torch.Tensor] = None,
1522
+ inputs_embeds: Optional[torch.Tensor] = None,
1523
+ labels: Optional[torch.Tensor] = None,
1524
+ use_cache: Optional[bool] = None,
1525
+ output_attentions: Optional[bool] = None,
1526
+ output_hidden_states: Optional[bool] = None,
1527
+ return_dict: Optional[bool] = None,
1528
+ **deprecated_arguments,
1529
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1530
+ r"""
1531
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1532
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1533
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1534
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1535
+ """
1536
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1537
+
1538
+ model_outputs = self.model(
1539
+ input_ids,
1540
+ past_key_values=past_key_values,
1541
+ attention_mask=attention_mask,
1542
+ inputs_embeds=inputs_embeds,
1543
+ use_cache=use_cache,
1544
+ output_attentions=output_attentions,
1545
+ output_hidden_states=output_hidden_states,
1546
+ return_dict=return_dict,
1547
+ )
1548
+
1549
+ hidden_states = model_outputs[0]
1550
+ hidden_states = self.dropout(hidden_states)
1551
+ logits = self.classifier(hidden_states)
1552
+
1553
+ loss = None
1554
+ if labels is not None:
1555
+ # move labels to correct device to enable model parallelism
1556
+ labels = labels.to(logits.device)
1557
+ batch_size, seq_length = labels.shape
1558
+ loss_fct = CrossEntropyLoss()
1559
+ loss = loss_fct(
1560
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
1561
+ )
1562
+
1563
+ if not return_dict:
1564
+ output = (logits,) + model_outputs[2:]
1565
+ return ((loss,) + output) if loss is not None else output
1566
+
1567
+ return TokenClassifierOutput(
1568
+ loss=loss,
1569
+ logits=logits,
1570
+ hidden_states=model_outputs.hidden_states,
1571
+ attentions=model_outputs.attentions,
1572
+ )
function_calling_round2/special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|end|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<|endoftext|>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "unk_token": {
24
+ "content": "<unk>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ }
30
+ }
function_calling_round2/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
function_calling_round2/tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
3
+ size 499723
function_calling_round2/tokenizer_config.json ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": null,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<unk>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "</s>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": true,
27
+ "single_word": false,
28
+ "special": false
29
+ },
30
+ "32000": {
31
+ "content": "<|endoftext|>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ },
38
+ "32001": {
39
+ "content": "<|assistant|>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": true,
43
+ "single_word": false,
44
+ "special": true
45
+ },
46
+ "32002": {
47
+ "content": "<|placeholder1|>",
48
+ "lstrip": false,
49
+ "normalized": false,
50
+ "rstrip": true,
51
+ "single_word": false,
52
+ "special": true
53
+ },
54
+ "32003": {
55
+ "content": "<|placeholder2|>",
56
+ "lstrip": false,
57
+ "normalized": false,
58
+ "rstrip": true,
59
+ "single_word": false,
60
+ "special": true
61
+ },
62
+ "32004": {
63
+ "content": "<|placeholder3|>",
64
+ "lstrip": false,
65
+ "normalized": false,
66
+ "rstrip": true,
67
+ "single_word": false,
68
+ "special": true
69
+ },
70
+ "32005": {
71
+ "content": "<|placeholder4|>",
72
+ "lstrip": false,
73
+ "normalized": false,
74
+ "rstrip": true,
75
+ "single_word": false,
76
+ "special": true
77
+ },
78
+ "32006": {
79
+ "content": "<|system|>",
80
+ "lstrip": false,
81
+ "normalized": false,
82
+ "rstrip": true,
83
+ "single_word": false,
84
+ "special": true
85
+ },
86
+ "32007": {
87
+ "content": "<|end|>",
88
+ "lstrip": false,
89
+ "normalized": false,
90
+ "rstrip": false,
91
+ "single_word": false,
92
+ "special": true
93
+ },
94
+ "32008": {
95
+ "content": "<|placeholder5|>",
96
+ "lstrip": false,
97
+ "normalized": false,
98
+ "rstrip": true,
99
+ "single_word": false,
100
+ "special": true
101
+ },
102
+ "32009": {
103
+ "content": "<|placeholder6|>",
104
+ "lstrip": false,
105
+ "normalized": false,
106
+ "rstrip": true,
107
+ "single_word": false,
108
+ "special": true
109
+ },
110
+ "32010": {
111
+ "content": "<|user|>",
112
+ "lstrip": false,
113
+ "normalized": false,
114
+ "rstrip": true,
115
+ "single_word": false,
116
+ "special": true
117
+ }
118
+ },
119
+ "bos_token": "<s>",
120
+ "chat_template": "{{ '<s>' }}{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% else %}{% set loop_messages = messages %}{% endif %}{% if system_message is defined %}{{ '<|system|>\n' + system_message + '<|end|>\n' }}{% endif %}{% for message in loop_messages %}{% set content = message['content'] %}{% if message['role'] == 'user' %}{{ '<|user|>\n' + content + '<|end|>\n<|assistant|>\n' }}{% elif message['role'] == 'assistant' %}{{ content + '<|end|>' + '\n' }}{% endif %}{% endfor %}",
121
+ "clean_up_tokenization_spaces": false,
122
+ "eos_token": "<|end|>",
123
+ "legacy": false,
124
+ "model_max_length": 131072,
125
+ "pad_token": "<|endoftext|>",
126
+ "padding_side": "right",
127
+ "sp_model_kwargs": {},
128
+ "split_special_tokens": false,
129
+ "tokenizer_class": "LlamaTokenizer",
130
+ "unk_token": "<unk>",
131
+ "use_default_system_prompt": false
132
+ }