MeowFET commited on
Commit
61520b4
·
1 Parent(s): 42e9d10

init: add model checkpoint

Browse files
config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/mnt/kaiwu-group-pp-sh/edge_llm/distill_hf/1118-phi2-tie-emb-unfreeze-decoder-use-qwen-vocab-1.5e-4-2k-seq-tp1/anchor/",
3
+ "architectures": [
4
+ "PhiForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_phi.PhiConfig",
9
+ "AutoModelForCausalLM": "modeling_phi.PhiForCausalLM"
10
+ },
11
+ "bos_token_id": 151643,
12
+ "embd_pdrop": 0.0,
13
+ "eos_token_id": 151645,
14
+ "hidden_act": "gelu",
15
+ "hidden_size": 2560,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 10240,
18
+ "layer_norm_eps": 1e-05,
19
+ "max_position_embeddings": 2048,
20
+ "model_type": "phi",
21
+ "num_attention_heads": 32,
22
+ "num_hidden_layers": 32,
23
+ "num_key_value_heads": 32,
24
+ "partial_rotary_factor": 0.4,
25
+ "qk_layernorm": false,
26
+ "resid_pdrop": 0.1,
27
+ "rope_scaling": null,
28
+ "rope_theta": 10000.0,
29
+ "tie_word_embeddings": true,
30
+ "torch_dtype": "bfloat16",
31
+ "transformers_version": "4.43.3",
32
+ "use_cache": true,
33
+ "vocab_size": 152064
34
+ }
configuration_phi.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 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 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
+ PHI_PRETRAINED_CONFIG_ARCHIVE_MAP = {
26
+ "microsoft/phi-2": "https://huggingface.co/microsoft/phi-2/resolve/main/config.json",
27
+ }
28
+
29
+
30
+ class PhiConfig(PretrainedConfig):
31
+ r"""
32
+ This is the configuration class to store the configuration of a [`PhiModel`]. It is used to instantiate an Phi
33
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
34
+ defaults will yield a similar configuration to that of the Phi
35
+ [microsoft/phi-1](https://huggingface.co/microsoft/phi-1).
36
+
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+
40
+ Args:
41
+ vocab_size (`int`, *optional*, defaults to 51200):
42
+ Vocabulary size of the Phi model. Defines the number of different tokens that can be represented by the
43
+ `inputs_ids` passed when calling [`PhiModel`].
44
+ hidden_size (`int`, *optional*, defaults to 2048):
45
+ Dimension of the hidden representations.
46
+ intermediate_size (`int`, *optional*, defaults to 8192):
47
+ Dimension of the MLP representations.
48
+ num_hidden_layers (`int`, *optional*, defaults to 24):
49
+ Number of hidden layers in the Transformer decoder.
50
+ num_attention_heads (`int`, *optional*, defaults to 32):
51
+ Number of attention heads for each attention layer in the Transformer decoder.
52
+ num_key_value_heads (`int`, *optional*):
53
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
54
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
55
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
56
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
57
+ by meanpooling all the original heads within that group. For more details checkout [this
58
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
59
+ `num_attention_heads`.
60
+ resid_pdrop (`float`, *optional*, defaults to 0.0):
61
+ Dropout probability for mlp outputs.
62
+ embd_pdrop (`int`, *optional*, defaults to 0.0):
63
+ The dropout ratio for the embeddings.
64
+ attention_dropout (`float`, *optional*, defaults to 0.0):
65
+ The dropout ratio after computing the attention scores.
66
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu_new"`):
67
+ The non-linear activation function (function or string) in the decoder.
68
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
69
+ The maximum sequence length that this model might ever be used with. Phi-1 and Phi-1.5 supports up to 2048
70
+ tokens.
71
+ initializer_range (`float`, *optional*, defaults to 0.02):
72
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
73
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
74
+ The epsilon used by the rms normalization layers.
75
+ use_cache (`bool`, *optional*, defaults to `True`):
76
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
77
+ relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
78
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
79
+ Whether to tie weight embeddings
80
+ rope_theta (`float`, *optional*, defaults to 10000.0):
81
+ The base period of the RoPE embeddings.
82
+ rope_scaling (`Dict`, *optional*):
83
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
84
+ strategies: linear and dynamic. Their scaling factor must be an float greater than 1. The expected format
85
+ is `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
86
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
87
+ these scaling strategies behave:
88
+ https://www.reddit.com/r/LocalPersimmon/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This
89
+ is an experimental feature, subject to breaking API changes in future versions.
90
+ partial_rotary_factor (`float`, *optional*, defaults to 0.5):
91
+ Percentage of the query and keys which will have rotary embedding.
92
+ qk_layernorm (`bool`, *optional*, defaults to `False`):
93
+ Whether or not to normalize the Queries and Keys after projecting the hidden states.
94
+ bos_token_id (`int`, *optional*, defaults to 1):
95
+ Denotes beginning of sequences token id.
96
+ eos_token_id (`int`, *optional*, defaults to 2):
97
+ Denotes end of sequences token id.
98
+
99
+ Example:
100
+
101
+ ```python
102
+ >>> from transformers import PhiModel, PhiConfig
103
+
104
+ >>> # Initializing a Phi-1 style configuration
105
+ >>> configuration = PhiConfig.from_pretrained("microsoft/phi-1")
106
+
107
+ >>> # Initializing a model from the configuration
108
+ >>> model = PhiModel(configuration)
109
+
110
+ >>> # Accessing the model configuration
111
+ >>> configuration = model.config
112
+ ```"""
113
+
114
+ model_type = "phi"
115
+ keys_to_ignore_at_inference = ["past_key_values"]
116
+
117
+ def __init__(
118
+ self,
119
+ vocab_size=51200,
120
+ hidden_size=2048,
121
+ intermediate_size=8192,
122
+ num_hidden_layers=24,
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="gelu_new",
129
+ max_position_embeddings=2048,
130
+ initializer_range=0.02,
131
+ layer_norm_eps=1e-5,
132
+ use_cache=True,
133
+ tie_word_embeddings=False,
134
+ rope_theta=10000.0,
135
+ rope_scaling=None,
136
+ partial_rotary_factor=0.5,
137
+ qk_layernorm=False,
138
+ bos_token_id=1,
139
+ eos_token_id=2,
140
+ **kwargs,
141
+ ):
142
+ self.vocab_size = vocab_size
143
+ self.hidden_size = hidden_size
144
+ self.intermediate_size = intermediate_size
145
+ self.num_hidden_layers = num_hidden_layers
146
+ self.num_attention_heads = num_attention_heads
147
+
148
+ if num_key_value_heads is None:
149
+ num_key_value_heads = num_attention_heads
150
+
151
+ self.num_key_value_heads = num_key_value_heads
152
+ self.resid_pdrop = resid_pdrop
153
+ self.embd_pdrop = embd_pdrop
154
+ self.attention_dropout = attention_dropout
155
+ self.hidden_act = hidden_act
156
+ self.max_position_embeddings = max_position_embeddings
157
+ self.initializer_range = initializer_range
158
+ self.layer_norm_eps = layer_norm_eps
159
+ self.use_cache = use_cache
160
+ self.rope_theta = rope_theta
161
+ self.rope_scaling = rope_scaling
162
+ self.partial_rotary_factor = partial_rotary_factor
163
+ self.qk_layernorm = qk_layernorm
164
+ self._rope_scaling_validation()
165
+
166
+ super().__init__(
167
+ bos_token_id=bos_token_id,
168
+ eos_token_id=eos_token_id,
169
+ tie_word_embeddings=tie_word_embeddings,
170
+ **kwargs,
171
+ )
172
+
173
+ # Copied from transformers.models.llama.configuration_llama.LlamaConfig._rope_scaling_validation
174
+ def _rope_scaling_validation(self):
175
+ """
176
+ Validate the `rope_scaling` configuration.
177
+ """
178
+ if self.rope_scaling is None:
179
+ return
180
+
181
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
182
+ raise ValueError(
183
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
184
+ f"got {self.rope_scaling}"
185
+ )
186
+ rope_scaling_type = self.rope_scaling.get("type", None)
187
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
188
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
189
+ raise ValueError(
190
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
191
+ )
192
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
193
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
generation_config.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "pad_token_id": 151643,
4
+ "do_sample": true,
5
+ "eos_token_id": [
6
+ 151645,
7
+ 151643
8
+ ],
9
+ "repetition_penalty": 1.05,
10
+ "_7b_repetition_penalty": 1.1,
11
+ "temperature": 0.7,
12
+ "top_p": 0.8,
13
+ "top_k": 20,
14
+ "transformers_version": "4.37.0"
15
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
modeling_phi.py ADDED
@@ -0,0 +1,1374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 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 model."""
17
+
18
+
19
+ import math
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.nn.functional as F
24
+ import torch.utils.checkpoint
25
+ from torch import nn
26
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
27
+
28
+ from transformers.activations import ACT2FN
29
+ from transformers.cache_utils import Cache, DynamicCache
30
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
31
+ from transformers.modeling_outputs import (
32
+ BaseModelOutputWithPast,
33
+ CausalLMOutputWithPast,
34
+ SequenceClassifierOutputWithPast,
35
+ TokenClassifierOutput,
36
+ )
37
+ from transformers.modeling_utils import PreTrainedModel
38
+ from transformers.utils import (
39
+ add_code_sample_docstrings,
40
+ add_start_docstrings,
41
+ add_start_docstrings_to_model_forward,
42
+ is_flash_attn_2_available,
43
+ is_flash_attn_greater_or_equal_2_10,
44
+ logging,
45
+ replace_return_docstrings,
46
+ )
47
+ from .configuration_phi import PhiConfig
48
+
49
+
50
+ try:
51
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
52
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
53
+ except:
54
+ pass
55
+
56
+
57
+ logger = logging.get_logger(__name__)
58
+
59
+ _CHECKPOINT_FOR_DOC = "microsoft/phi-2"
60
+ _CONFIG_FOR_DOC = "PhiConfig"
61
+
62
+ PHI_PRETRAINED_MODEL_ARCHIVE_LIST = [
63
+ "microsoft/phi-2",
64
+ # See all Phi models at https://huggingface.co/models?filter=phi
65
+ ]
66
+
67
+
68
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
69
+ def _get_unpad_data(attention_mask):
70
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
71
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
72
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
73
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
74
+ return (
75
+ indices,
76
+ cu_seqlens,
77
+ max_seqlen_in_batch,
78
+ )
79
+
80
+
81
+ # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Phi
82
+ class PhiRotaryEmbedding(nn.Module):
83
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
84
+ super().__init__()
85
+
86
+ self.dim = dim
87
+ self.max_position_embeddings = max_position_embeddings
88
+ self.base = base
89
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
90
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
91
+
92
+ # Build here to make `torch.jit.trace` work.
93
+ self._set_cos_sin_cache(
94
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
95
+ )
96
+
97
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
98
+ self.max_seq_len_cached = seq_len
99
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
100
+
101
+ freqs = torch.outer(t, self.inv_freq)
102
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
103
+ emb = torch.cat((freqs, freqs), dim=-1)
104
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
105
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
106
+
107
+ def forward(self, x, seq_len=None):
108
+ # x: [bs, num_attention_heads, seq_len, head_size]
109
+ if seq_len > self.max_seq_len_cached:
110
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
111
+
112
+ return (
113
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
114
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
115
+ )
116
+
117
+
118
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->Phi
119
+ class PhiLinearScalingRotaryEmbedding(PhiRotaryEmbedding):
120
+ """PhiRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
121
+
122
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
123
+ self.scaling_factor = scaling_factor
124
+ super().__init__(dim, max_position_embeddings, base, device)
125
+
126
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
127
+ self.max_seq_len_cached = seq_len
128
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
129
+ t = t / self.scaling_factor
130
+
131
+ freqs = torch.outer(t, self.inv_freq)
132
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
133
+ emb = torch.cat((freqs, freqs), dim=-1)
134
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
135
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
136
+
137
+
138
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->Phi
139
+ class PhiDynamicNTKScalingRotaryEmbedding(PhiRotaryEmbedding):
140
+ """PhiRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
141
+
142
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
143
+ self.scaling_factor = scaling_factor
144
+ super().__init__(dim, max_position_embeddings, base, device)
145
+
146
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
147
+ self.max_seq_len_cached = seq_len
148
+
149
+ if seq_len > self.max_position_embeddings:
150
+ base = self.base * (
151
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
152
+ ) ** (self.dim / (self.dim - 2))
153
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
154
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
155
+
156
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
157
+
158
+ freqs = torch.outer(t, self.inv_freq)
159
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
160
+ emb = torch.cat((freqs, freqs), dim=-1)
161
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
162
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
163
+
164
+
165
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
166
+ def rotate_half(x):
167
+ """Rotates half the hidden dims of the input."""
168
+ x1 = x[..., : x.shape[-1] // 2]
169
+ x2 = x[..., x.shape[-1] // 2 :]
170
+ return torch.cat((-x2, x1), dim=-1)
171
+
172
+
173
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
174
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
175
+ """Applies Rotary Position Embedding to the query and key tensors.
176
+
177
+ Args:
178
+ q (`torch.Tensor`): The query tensor.
179
+ k (`torch.Tensor`): The key tensor.
180
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
181
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
182
+ position_ids (`torch.Tensor`):
183
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
184
+ used to pass offsetted position ids when working with a KV-cache.
185
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
186
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
187
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
188
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
189
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
190
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
191
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
192
+ Returns:
193
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
194
+ """
195
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
196
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
197
+ q_embed = (q * cos) + (rotate_half(q) * sin)
198
+ k_embed = (k * cos) + (rotate_half(k) * sin)
199
+ return q_embed, k_embed
200
+
201
+
202
+ # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Phi
203
+ class PhiMLP(nn.Module):
204
+ def __init__(self, config):
205
+ super().__init__()
206
+ self.config = config
207
+ self.activation_fn = ACT2FN[config.hidden_act]
208
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
209
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
210
+
211
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
212
+ hidden_states = self.fc1(hidden_states)
213
+ hidden_states = self.activation_fn(hidden_states)
214
+ hidden_states = self.fc2(hidden_states)
215
+ return hidden_states
216
+
217
+
218
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
219
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
220
+ """
221
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
222
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
223
+ """
224
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
225
+ if n_rep == 1:
226
+ return hidden_states
227
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
228
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
229
+
230
+
231
+ class PhiAttention(nn.Module):
232
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
233
+
234
+ def __init__(self, config: PhiConfig, layer_idx: Optional[int] = None):
235
+ super().__init__()
236
+ self.config = config
237
+ self.layer_idx = layer_idx
238
+ if layer_idx is None:
239
+ logger.warning_once(
240
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
241
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
242
+ "when creating this class."
243
+ )
244
+
245
+ self.attention_dropout = config.attention_dropout
246
+ self.hidden_size = config.hidden_size
247
+ self.num_heads = config.num_attention_heads
248
+ self.head_dim = self.hidden_size // self.num_heads
249
+ self.num_key_value_heads = config.num_key_value_heads
250
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
251
+ self.max_position_embeddings = config.max_position_embeddings
252
+ self.rope_theta = config.rope_theta
253
+ self.partial_rotary_factor = config.partial_rotary_factor
254
+ self.is_causal = True
255
+
256
+ if (self.head_dim * self.num_heads) != self.hidden_size:
257
+ raise ValueError(
258
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
259
+ f" and `num_heads`: {self.num_heads})."
260
+ )
261
+
262
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
263
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
264
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
265
+ self.dense = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=True)
266
+
267
+ self.qk_layernorm = config.qk_layernorm
268
+ if self.qk_layernorm:
269
+ self.q_layernorm = nn.LayerNorm(
270
+ config.hidden_size // self.num_heads, eps=config.layer_norm_eps, elementwise_affine=True
271
+ )
272
+ self.k_layernorm = nn.LayerNorm(
273
+ config.hidden_size // self.num_heads, eps=config.layer_norm_eps, elementwise_affine=True
274
+ )
275
+
276
+ self._init_rope()
277
+
278
+ def _init_rope(self):
279
+ if self.config.rope_scaling is None:
280
+ self.rotary_emb = PhiRotaryEmbedding(
281
+ int(self.partial_rotary_factor * self.head_dim),
282
+ max_position_embeddings=self.max_position_embeddings,
283
+ base=self.rope_theta,
284
+ )
285
+ else:
286
+ scaling_type = self.config.rope_scaling["type"]
287
+ scaling_factor = self.config.rope_scaling["factor"]
288
+ if scaling_type == "linear":
289
+ self.rotary_emb = PhiLinearScalingRotaryEmbedding(
290
+ int(self.partial_rotary_factor * self.head_dim),
291
+ max_position_embeddings=self.max_position_embeddings,
292
+ scaling_factor=scaling_factor,
293
+ base=self.rope_theta,
294
+ )
295
+ elif scaling_type == "dynamic":
296
+ self.rotary_emb = PhiDynamicNTKScalingRotaryEmbedding(
297
+ int(self.partial_rotary_factor * self.head_dim),
298
+ max_position_embeddings=self.max_position_embeddings,
299
+ scaling_factor=scaling_factor,
300
+ base=self.rope_theta,
301
+ )
302
+ else:
303
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
304
+
305
+ # Phi-2 has an attention overflow issue (with FP16) and requires autocast to be disabled
306
+ @torch.autocast("cpu", enabled=False)
307
+ @torch.autocast("cuda", enabled=False)
308
+ def forward(
309
+ self,
310
+ hidden_states: torch.Tensor,
311
+ attention_mask: Optional[torch.Tensor] = None,
312
+ position_ids: Optional[torch.LongTensor] = None,
313
+ past_key_value: Optional[Cache] = None,
314
+ output_attentions: bool = False,
315
+ use_cache: bool = False,
316
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
317
+ bsz, q_len, _ = hidden_states.size()
318
+
319
+ query_states = self.q_proj(hidden_states)
320
+ key_states = self.k_proj(hidden_states)
321
+ value_states = self.v_proj(hidden_states)
322
+
323
+ if self.qk_layernorm:
324
+ query_states = self.q_layernorm(query_states)
325
+ key_states = self.k_layernorm(key_states)
326
+
327
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
328
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
329
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
330
+
331
+ kv_seq_len = key_states.shape[-2]
332
+ if past_key_value is not None:
333
+ if self.layer_idx is None:
334
+ raise ValueError(
335
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
336
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
337
+ "with a layer index."
338
+ )
339
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
340
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
341
+
342
+ # Partial rotary embedding
343
+ query_rot, query_pass = (
344
+ query_states[..., : self.rotary_emb.dim],
345
+ query_states[..., self.rotary_emb.dim :],
346
+ )
347
+ key_rot, key_pass = (
348
+ key_states[..., : self.rotary_emb.dim],
349
+ key_states[..., self.rotary_emb.dim :],
350
+ )
351
+ # [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
352
+ query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
353
+
354
+ # [batch_size, seq_length, num_heads, head_dim]
355
+ original_query_states = query_states
356
+ query_states = torch.cat((query_rot, query_pass), dim=-1)
357
+ key_states = torch.cat((key_rot, key_pass), dim=-1)
358
+ import os
359
+ if not os.path.isfile('hf.pt'):
360
+ torch.save([query_states, original_query_states], 'hf.pt')
361
+
362
+ if past_key_value is not None:
363
+ cache_kwargs = {"sin": sin, "cos": cos, "partial_rotation_size": self.rotary_emb.dim}
364
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
365
+
366
+
367
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
368
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
369
+
370
+ # Queries and keys upcast to fp32 is required by Phi-2 to avoid overflow
371
+ attn_weights = torch.matmul(
372
+ query_states.to(torch.float32), key_states.to(torch.float32).transpose(2, 3)
373
+ ) / math.sqrt(self.head_dim)
374
+
375
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
376
+ raise ValueError(
377
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
378
+ f" {attn_weights.size()}"
379
+ )
380
+
381
+ if attention_mask is not None:
382
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
383
+ raise ValueError(
384
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
385
+ )
386
+ attn_weights = attn_weights + attention_mask
387
+
388
+ # upcast attention to fp32
389
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
390
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
391
+
392
+ attn_output = torch.matmul(attn_weights, value_states)
393
+
394
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
395
+ raise ValueError(
396
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
397
+ f" {attn_output.size()}"
398
+ )
399
+
400
+ attn_output = attn_output.transpose(1, 2).contiguous()
401
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
402
+
403
+ attn_output = self.dense(attn_output)
404
+
405
+ if not output_attentions:
406
+ attn_weights = None
407
+
408
+ return attn_output, attn_weights, past_key_value
409
+
410
+
411
+ class PhiFlashAttention2(PhiAttention):
412
+ """
413
+ Phi flash attention module. This module inherits from `PhiAttention` as the weights of the module stays
414
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
415
+ flash attention and deal with padding tokens in case the input contains any of them.
416
+ """
417
+
418
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
419
+ def __init__(self, *args, **kwargs):
420
+ super().__init__(*args, **kwargs)
421
+
422
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
423
+ # 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.
424
+ # 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).
425
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
426
+
427
+ def forward(
428
+ self,
429
+ hidden_states: torch.Tensor,
430
+ attention_mask: Optional[torch.LongTensor] = None,
431
+ position_ids: Optional[torch.LongTensor] = None,
432
+ past_key_value: Optional[Cache] = None,
433
+ output_attentions: bool = False,
434
+ use_cache: bool = False,
435
+ **kwargs,
436
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
437
+ # PhiFlashAttention2 attention does not support output_attentions
438
+
439
+ output_attentions = False
440
+
441
+ bsz, q_len, _ = hidden_states.size()
442
+
443
+ query_states = self.q_proj(hidden_states)
444
+ key_states = self.k_proj(hidden_states)
445
+ value_states = self.v_proj(hidden_states)
446
+
447
+ if self.qk_layernorm:
448
+ query_states = self.q_layernorm(query_states)
449
+ key_states = self.k_layernorm(key_states)
450
+
451
+ # Flash attention requires the input to have the shape
452
+ # batch_size x seq_length x head_dim x hidden_dim
453
+ # therefore we just need to keep the original shape
454
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
455
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
456
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
457
+
458
+ kv_seq_len = key_states.shape[-2]
459
+ if past_key_value is not None:
460
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
461
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
462
+
463
+ # Partial rotary embedding
464
+ query_rot, query_pass = (
465
+ query_states[..., : self.rotary_emb.dim],
466
+ query_states[..., self.rotary_emb.dim :],
467
+ )
468
+ key_rot, key_pass = (
469
+ key_states[..., : self.rotary_emb.dim],
470
+ key_states[..., self.rotary_emb.dim :],
471
+ )
472
+ # [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
473
+ query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
474
+
475
+ # [batch_size, seq_length, num_heads, head_dim]
476
+ query_states = torch.cat((query_rot, query_pass), dim=-1)
477
+ key_states = torch.cat((key_rot, key_pass), dim=-1)
478
+
479
+ if past_key_value is not None:
480
+ cache_kwargs = {"sin": sin, "cos": cos, "partial_rotation_size": self.rotary_emb.dim}
481
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
482
+
483
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
484
+ # to be able to avoid many of these transpose/reshape/view.
485
+ query_states = query_states.transpose(1, 2)
486
+ key_states = key_states.transpose(1, 2)
487
+ value_states = value_states.transpose(1, 2)
488
+
489
+ attn_dropout = self.attention_dropout if self.training else 0.0
490
+
491
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
492
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
493
+ # cast them back in the correct dtype just to be sure everything works as expected.
494
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
495
+ # in fp32.
496
+
497
+ if query_states.dtype == torch.float32:
498
+ if torch.is_autocast_enabled():
499
+ target_dtype = torch.get_autocast_gpu_dtype()
500
+ # Handle the case where the model is quantized
501
+ elif hasattr(self.config, "_pre_quantization_dtype"):
502
+ target_dtype = self.config._pre_quantization_dtype
503
+ else:
504
+ target_dtype = self.q_proj.weight.dtype
505
+
506
+ logger.warning_once(
507
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
508
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
509
+ f" {target_dtype}."
510
+ )
511
+
512
+ query_states = query_states.to(target_dtype)
513
+ key_states = key_states.to(target_dtype)
514
+ value_states = value_states.to(target_dtype)
515
+
516
+ attn_output = self._flash_attention_forward(
517
+ query_states, key_states, value_states, attention_mask, q_len, dropout=attn_dropout, softmax_scale=None
518
+ )
519
+
520
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
521
+ attn_output = self.dense(attn_output)
522
+
523
+ if not output_attentions:
524
+ attn_weights = None
525
+
526
+ return attn_output, attn_weights, past_key_value
527
+
528
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._flash_attention_forward
529
+ def _flash_attention_forward(
530
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
531
+ ):
532
+ """
533
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
534
+ first unpad the input, then computes the attention scores and pad the final attention scores.
535
+
536
+ Args:
537
+ query_states (`torch.Tensor`):
538
+ Input query states to be passed to Flash Attention API
539
+ key_states (`torch.Tensor`):
540
+ Input key states to be passed to Flash Attention API
541
+ value_states (`torch.Tensor`):
542
+ Input value states to be passed to Flash Attention API
543
+ attention_mask (`torch.Tensor`):
544
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
545
+ position of padding tokens and 1 for the position of non-padding tokens.
546
+ dropout (`int`, *optional*):
547
+ Attention dropout
548
+ softmax_scale (`float`, *optional*):
549
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
550
+ """
551
+ if not self._flash_attn_uses_top_left_mask:
552
+ causal = self.is_causal
553
+ else:
554
+ # 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__.
555
+ causal = self.is_causal and query_length != 1
556
+
557
+ # Contains at least one padding token in the sequence
558
+ if attention_mask is not None:
559
+ batch_size = query_states.shape[0]
560
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
561
+ query_states, key_states, value_states, attention_mask, query_length
562
+ )
563
+
564
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
565
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
566
+
567
+ attn_output_unpad = flash_attn_varlen_func(
568
+ query_states,
569
+ key_states,
570
+ value_states,
571
+ cu_seqlens_q=cu_seqlens_q,
572
+ cu_seqlens_k=cu_seqlens_k,
573
+ max_seqlen_q=max_seqlen_in_batch_q,
574
+ max_seqlen_k=max_seqlen_in_batch_k,
575
+ dropout_p=dropout,
576
+ softmax_scale=softmax_scale,
577
+ causal=causal,
578
+ )
579
+
580
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
581
+ else:
582
+ attn_output = flash_attn_func(
583
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
584
+ )
585
+
586
+ return attn_output
587
+
588
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._upad_input
589
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
590
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
591
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
592
+
593
+ key_layer = index_first_axis(
594
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
595
+ )
596
+ value_layer = index_first_axis(
597
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
598
+ )
599
+ if query_length == kv_seq_len:
600
+ query_layer = index_first_axis(
601
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
602
+ )
603
+ cu_seqlens_q = cu_seqlens_k
604
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
605
+ indices_q = indices_k
606
+ elif query_length == 1:
607
+ max_seqlen_in_batch_q = 1
608
+ cu_seqlens_q = torch.arange(
609
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
610
+ ) # There is a memcpy here, that is very bad.
611
+ indices_q = cu_seqlens_q[:-1]
612
+ query_layer = query_layer.squeeze(1)
613
+ else:
614
+ # The -q_len: slice assumes left padding.
615
+ attention_mask = attention_mask[:, -query_length:]
616
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
617
+
618
+ return (
619
+ query_layer,
620
+ key_layer,
621
+ value_layer,
622
+ indices_q,
623
+ (cu_seqlens_q, cu_seqlens_k),
624
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
625
+ )
626
+
627
+
628
+ PHI_ATTENTION_CLASSES = {
629
+ "eager": PhiAttention,
630
+ "flash_attention_2": PhiFlashAttention2,
631
+ }
632
+
633
+
634
+ class PhiDecoderLayer(nn.Module):
635
+ def __init__(self, config: PhiConfig, layer_idx: int):
636
+ super().__init__()
637
+ self.self_attn = PHI_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
638
+ self.mlp = PhiMLP(config)
639
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
640
+ self.resid_dropout = nn.Dropout(config.resid_pdrop)
641
+
642
+ def forward(
643
+ self,
644
+ hidden_states: torch.Tensor,
645
+ attention_mask: Optional[torch.Tensor] = None,
646
+ position_ids: Optional[torch.LongTensor] = None,
647
+ output_attentions: Optional[bool] = False,
648
+ use_cache: Optional[bool] = False,
649
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
650
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
651
+ """
652
+ Args:
653
+ hidden_states (`torch.FloatTensor`):
654
+ input to the layer of shape `(batch, seq_len, embed_dim)`
655
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
656
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
657
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
658
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
659
+ `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
660
+ output_attentions (`bool`, *optional*):
661
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
662
+ returned tensors for more detail.
663
+ use_cache (`bool`, *optional*):
664
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
665
+ (see `past_key_values`).
666
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
667
+ """
668
+
669
+ residual = hidden_states
670
+
671
+ hidden_states = self.input_layernorm(hidden_states)
672
+
673
+ # Self Attention
674
+ attn_outputs, self_attn_weights, present_key_value = self.self_attn(
675
+ hidden_states=hidden_states,
676
+ attention_mask=attention_mask,
677
+ position_ids=position_ids,
678
+ past_key_value=past_key_value,
679
+ output_attentions=output_attentions,
680
+ use_cache=use_cache,
681
+ )
682
+ attn_outputs = self.resid_dropout(attn_outputs)
683
+
684
+ feed_forward_hidden_states = self.resid_dropout(self.mlp(hidden_states))
685
+ hidden_states = attn_outputs + feed_forward_hidden_states + residual
686
+ outputs = (hidden_states,)
687
+
688
+ if output_attentions:
689
+ outputs += (self_attn_weights,)
690
+
691
+ if use_cache:
692
+ outputs += (present_key_value,)
693
+
694
+ return outputs
695
+
696
+
697
+ PHI_START_DOCSTRING = r"""
698
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
699
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
700
+ etc.)
701
+
702
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
703
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
704
+ and behavior.
705
+
706
+ Parameters:
707
+ config ([`PhiConfig`]):
708
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
709
+ load the weights associated with the model, only the configuration. Check out the
710
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
711
+ """
712
+
713
+
714
+ @add_start_docstrings(
715
+ "The bare Phi Model outputting raw hidden-states without any specific head on top.",
716
+ PHI_START_DOCSTRING,
717
+ )
718
+ class PhiPreTrainedModel(PreTrainedModel):
719
+ config_class = PhiConfig
720
+ base_model_prefix = "model"
721
+ supports_gradient_checkpointing = True
722
+ _no_split_modules = ["PhiDecoderLayer"]
723
+ _skip_keys_device_placement = "past_key_values"
724
+ _supports_flash_attn_2 = True
725
+ _supports_cache_class = True
726
+
727
+ def _init_weights(self, module):
728
+ std = self.config.initializer_range
729
+ if isinstance(module, nn.Linear):
730
+ module.weight.data.normal_(mean=0.0, std=std)
731
+ if module.bias is not None:
732
+ module.bias.data.zero_()
733
+ elif isinstance(module, nn.Embedding):
734
+ module.weight.data.normal_(mean=0.0, std=std)
735
+ if module.padding_idx is not None:
736
+ module.weight.data[module.padding_idx].zero_()
737
+
738
+
739
+ PHI_INPUTS_DOCSTRING = r"""
740
+ Args:
741
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
742
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
743
+ it.
744
+
745
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
746
+ [`PreTrainedTokenizer.__call__`] for details.
747
+
748
+ [What are input IDs?](../glossary#input-ids)
749
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
750
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
751
+
752
+ - 1 for tokens that are **not masked**,
753
+ - 0 for tokens that are **masked**.
754
+
755
+ [What are attention masks?](../glossary#attention-mask)
756
+
757
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
758
+ [`PreTrainedTokenizer.__call__`] for details.
759
+
760
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
761
+ `past_key_values`).
762
+
763
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
764
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
765
+ information on the default strategy.
766
+
767
+ - 1 indicates the head is **not masked**,
768
+ - 0 indicates the head is **masked**.
769
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
770
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
771
+ config.n_positions - 1]`.
772
+
773
+ [What are position IDs?](../glossary#position-ids)
774
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
775
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
776
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
777
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
778
+
779
+ Two formats are allowed:
780
+ - a [`~cache_utils.Cache`] instance;
781
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
782
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
783
+ cache format.
784
+
785
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
786
+ legacy cache format will be returned.
787
+
788
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
789
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
790
+ of shape `(batch_size, sequence_length)`.
791
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
792
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
793
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
794
+ model's internal embedding lookup matrix.
795
+ use_cache (`bool`, *optional*):
796
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
797
+ `past_key_values`).
798
+ output_attentions (`bool`, *optional*):
799
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
800
+ tensors for more detail.
801
+ output_hidden_states (`bool`, *optional*):
802
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
803
+ more detail.
804
+ return_dict (`bool`, *optional*):
805
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
806
+ """
807
+
808
+
809
+ @add_start_docstrings(
810
+ "The bare Phi Model outputting raw hidden-states without any specific head on top.",
811
+ PHI_START_DOCSTRING,
812
+ )
813
+ class PhiModel(PhiPreTrainedModel):
814
+ """
815
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`PhiDecoderLayer`]
816
+
817
+ Args:
818
+ config: PhiConfig
819
+ """
820
+
821
+ def __init__(self, config: PhiConfig):
822
+ super().__init__(config)
823
+ self.padding_idx = config.pad_token_id
824
+ self.vocab_size = config.vocab_size
825
+
826
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
827
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
828
+ self.layers = nn.ModuleList(
829
+ [PhiDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
830
+ )
831
+ self.final_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
832
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
833
+
834
+ self.gradient_checkpointing = False
835
+ # Initialize weights and apply final processing
836
+ self.post_init()
837
+
838
+ def get_input_embeddings(self):
839
+ return self.embed_tokens
840
+
841
+ def set_input_embeddings(self, value):
842
+ self.embed_tokens = value
843
+
844
+ @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
845
+ def forward(
846
+ self,
847
+ input_ids: torch.LongTensor = None,
848
+ attention_mask: Optional[torch.Tensor] = None,
849
+ position_ids: Optional[torch.LongTensor] = None,
850
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
851
+ inputs_embeds: Optional[torch.FloatTensor] = None,
852
+ use_cache: Optional[bool] = None,
853
+ output_attentions: Optional[bool] = None,
854
+ output_hidden_states: Optional[bool] = None,
855
+ return_dict: Optional[bool] = None,
856
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
857
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
858
+ output_hidden_states = (
859
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
860
+ )
861
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
862
+
863
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
864
+
865
+ # retrieve input_ids and inputs_embeds
866
+ if input_ids is not None and inputs_embeds is not None:
867
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
868
+ elif input_ids is not None:
869
+ batch_size, seq_length = input_ids.shape[:2]
870
+ elif inputs_embeds is not None:
871
+ batch_size, seq_length = inputs_embeds.shape[:2]
872
+ else:
873
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
874
+
875
+ past_key_values_length = 0
876
+
877
+ if self.gradient_checkpointing and self.training:
878
+ if use_cache:
879
+ logger.warning_once(
880
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
881
+ )
882
+ use_cache = False
883
+
884
+ if use_cache:
885
+ use_legacy_cache = not isinstance(past_key_values, Cache)
886
+ if use_legacy_cache:
887
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
888
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
889
+
890
+ if position_ids is None:
891
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
892
+ position_ids = torch.arange(
893
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
894
+ )
895
+ position_ids = position_ids.unsqueeze(0)
896
+
897
+ if inputs_embeds is None:
898
+ inputs_embeds = self.embed_tokens(input_ids)
899
+
900
+ inputs_embeds = self.embed_dropout(inputs_embeds)
901
+
902
+ # Attention mask.
903
+ if self._use_flash_attention_2:
904
+ # 2d mask is passed through the layers
905
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
906
+ else:
907
+ # 4d mask is passed through the layers
908
+ attention_mask = _prepare_4d_causal_attention_mask(
909
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
910
+ )
911
+
912
+ hidden_states = inputs_embeds
913
+
914
+ # decoder layers
915
+ all_hidden_states = () if output_hidden_states else None
916
+ all_self_attns = () if output_attentions else None
917
+ next_decoder_cache = None
918
+
919
+ for decoder_layer in self.layers:
920
+ if output_hidden_states:
921
+ all_hidden_states += (hidden_states,)
922
+
923
+ if self.gradient_checkpointing and self.training:
924
+ layer_outputs = self._gradient_checkpointing_func(
925
+ decoder_layer.__call__,
926
+ hidden_states,
927
+ attention_mask,
928
+ position_ids,
929
+ past_key_values,
930
+ output_attentions,
931
+ )
932
+ else:
933
+ layer_outputs = decoder_layer(
934
+ hidden_states,
935
+ attention_mask=attention_mask,
936
+ position_ids=position_ids,
937
+ past_key_value=past_key_values,
938
+ output_attentions=output_attentions,
939
+ use_cache=use_cache,
940
+ )
941
+
942
+ hidden_states = layer_outputs[0]
943
+
944
+ if use_cache:
945
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
946
+
947
+ if output_attentions:
948
+ all_self_attns += (layer_outputs[1],)
949
+
950
+ hidden_states = self.final_layernorm(hidden_states)
951
+
952
+ # add hidden states from the last decoder layer
953
+ if output_hidden_states:
954
+ all_hidden_states += (hidden_states,)
955
+
956
+ next_cache = None
957
+ if use_cache:
958
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
959
+ if not return_dict:
960
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
961
+ return BaseModelOutputWithPast(
962
+ last_hidden_state=hidden_states,
963
+ past_key_values=next_cache,
964
+ hidden_states=all_hidden_states,
965
+ attentions=all_self_attns,
966
+ )
967
+
968
+
969
+ class PhiForCausalLM(PhiPreTrainedModel):
970
+ _tied_weights_keys = ["lm_head.weight"]
971
+
972
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi,bias=False->bias=True
973
+ def __init__(self, config):
974
+ super().__init__(config)
975
+ self.model = PhiModel(config)
976
+ self.vocab_size = config.vocab_size
977
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
978
+
979
+ # Initialize weights and apply final processing
980
+ self.post_init()
981
+
982
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
983
+ def get_input_embeddings(self):
984
+ return self.model.embed_tokens
985
+
986
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
987
+ def set_input_embeddings(self, value):
988
+ self.model.embed_tokens = value
989
+
990
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
991
+ def get_output_embeddings(self):
992
+ return self.lm_head
993
+
994
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
995
+ def set_output_embeddings(self, new_embeddings):
996
+ self.lm_head = new_embeddings
997
+
998
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
999
+ def set_decoder(self, decoder):
1000
+ self.model = decoder
1001
+
1002
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
1003
+ def get_decoder(self):
1004
+ return self.model
1005
+
1006
+ @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
1007
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1008
+ def forward(
1009
+ self,
1010
+ input_ids: torch.LongTensor = None,
1011
+ attention_mask: Optional[torch.Tensor] = None,
1012
+ position_ids: Optional[torch.LongTensor] = None,
1013
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1014
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1015
+ labels: Optional[torch.LongTensor] = None,
1016
+ use_cache: Optional[bool] = None,
1017
+ output_attentions: Optional[bool] = None,
1018
+ output_hidden_states: Optional[bool] = None,
1019
+ return_dict: Optional[bool] = None,
1020
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1021
+ r"""
1022
+ Args:
1023
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1024
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1025
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1026
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1027
+
1028
+ Returns:
1029
+
1030
+ Example:
1031
+
1032
+ ```python
1033
+ >>> from transformers import AutoTokenizer, PhiForCausalLM
1034
+
1035
+ >>> model = PhiForCausalLM.from_pretrained("microsoft/phi-1")
1036
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-1")
1037
+
1038
+ >>> prompt = "This is an example script ."
1039
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1040
+
1041
+ >>> # Generate
1042
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1043
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1044
+ 'This is an example script .\n\n\n\nfrom typing import List\n\ndef find_most_common_letter(words: List[str'
1045
+ ```"""
1046
+
1047
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1048
+ output_hidden_states = (
1049
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1050
+ )
1051
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1052
+
1053
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1054
+ outputs = self.model(
1055
+ input_ids=input_ids,
1056
+ attention_mask=attention_mask,
1057
+ position_ids=position_ids,
1058
+ past_key_values=past_key_values,
1059
+ inputs_embeds=inputs_embeds,
1060
+ use_cache=use_cache,
1061
+ output_attentions=output_attentions,
1062
+ output_hidden_states=output_hidden_states,
1063
+ return_dict=return_dict,
1064
+ )
1065
+
1066
+ hidden_states = outputs[0]
1067
+ logits = self.lm_head(hidden_states)
1068
+ logits = logits.float()
1069
+
1070
+ loss = None
1071
+ if labels is not None:
1072
+ # Shift so that tokens < n predict n
1073
+ shift_logits = logits[..., :-1, :].contiguous()
1074
+ shift_labels = labels[..., 1:].contiguous()
1075
+ # Flatten the tokens
1076
+ loss_fct = CrossEntropyLoss()
1077
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1078
+ shift_labels = shift_labels.view(-1)
1079
+ # Enable model parallelism
1080
+ shift_labels = shift_labels.to(shift_logits.device)
1081
+ loss = loss_fct(shift_logits, shift_labels)
1082
+
1083
+ if not return_dict:
1084
+ output = (logits,) + outputs[1:]
1085
+ return (loss,) + output if loss is not None else output
1086
+
1087
+ return CausalLMOutputWithPast(
1088
+ loss=loss,
1089
+ logits=logits,
1090
+ past_key_values=outputs.past_key_values,
1091
+ hidden_states=outputs.hidden_states,
1092
+ attentions=outputs.attentions,
1093
+ )
1094
+
1095
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.prepare_inputs_for_generation
1096
+ def prepare_inputs_for_generation(
1097
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1098
+ ):
1099
+ if past_key_values is not None:
1100
+ if isinstance(past_key_values, Cache):
1101
+ cache_length = past_key_values.get_seq_length()
1102
+ past_length = past_key_values.seen_tokens
1103
+ max_cache_length = past_key_values.get_max_length()
1104
+ else:
1105
+ cache_length = past_length = past_key_values[0][0].shape[2]
1106
+ max_cache_length = None
1107
+
1108
+ # Keep only the unprocessed tokens:
1109
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1110
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1111
+ # input)
1112
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1113
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1114
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1115
+ # input_ids based on the past_length.
1116
+ elif past_length < input_ids.shape[1]:
1117
+ input_ids = input_ids[:, past_length:]
1118
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1119
+
1120
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1121
+ if (
1122
+ max_cache_length is not None
1123
+ and attention_mask is not None
1124
+ and cache_length + input_ids.shape[1] > max_cache_length
1125
+ ):
1126
+ attention_mask = attention_mask[:, -max_cache_length:]
1127
+
1128
+ position_ids = kwargs.get("position_ids", None)
1129
+ if attention_mask is not None and position_ids is None:
1130
+ # create position_ids on the fly for batch generation
1131
+ position_ids = attention_mask.long().cumsum(-1) - 1
1132
+ position_ids.masked_fill_(attention_mask == 0, 1)
1133
+ if past_key_values:
1134
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1135
+
1136
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1137
+ if inputs_embeds is not None and past_key_values is None:
1138
+ model_inputs = {"inputs_embeds": inputs_embeds}
1139
+ else:
1140
+ model_inputs = {"input_ids": input_ids}
1141
+
1142
+ model_inputs.update(
1143
+ {
1144
+ "position_ids": position_ids,
1145
+ "past_key_values": past_key_values,
1146
+ "use_cache": kwargs.get("use_cache"),
1147
+ "attention_mask": attention_mask,
1148
+ }
1149
+ )
1150
+ return model_inputs
1151
+
1152
+ @staticmethod
1153
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM._reorder_cache
1154
+ def _reorder_cache(past_key_values, beam_idx):
1155
+ reordered_past = ()
1156
+ for layer_past in past_key_values:
1157
+ reordered_past += (
1158
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1159
+ )
1160
+ return reordered_past
1161
+
1162
+
1163
+ @add_start_docstrings(
1164
+ """
1165
+ The PhiModel with a sequence classification head on top (linear layer).
1166
+
1167
+ [`PhiForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1168
+ (e.g. GPT-2) do.
1169
+
1170
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1171
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1172
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1173
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1174
+ each row of the batch).
1175
+ """,
1176
+ PHI_START_DOCSTRING,
1177
+ )
1178
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with LLAMA->PHI,Llama->Phi with self.transformer->self.model, transformer_outputs->model_outputs
1179
+ class PhiForSequenceClassification(PhiPreTrainedModel):
1180
+ def __init__(self, config):
1181
+ super().__init__(config)
1182
+ self.num_labels = config.num_labels
1183
+ self.model = PhiModel(config)
1184
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1185
+
1186
+ # Initialize weights and apply final processing
1187
+ self.post_init()
1188
+
1189
+ def get_input_embeddings(self):
1190
+ return self.model.embed_tokens
1191
+
1192
+ def set_input_embeddings(self, value):
1193
+ self.model.embed_tokens = value
1194
+
1195
+ @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
1196
+ def forward(
1197
+ self,
1198
+ input_ids: torch.LongTensor = None,
1199
+ attention_mask: Optional[torch.Tensor] = None,
1200
+ position_ids: Optional[torch.LongTensor] = None,
1201
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1202
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1203
+ labels: Optional[torch.LongTensor] = None,
1204
+ use_cache: Optional[bool] = None,
1205
+ output_attentions: Optional[bool] = None,
1206
+ output_hidden_states: Optional[bool] = None,
1207
+ return_dict: Optional[bool] = None,
1208
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1209
+ r"""
1210
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1211
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1212
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1213
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1214
+ """
1215
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1216
+
1217
+ model_outputs = self.model(
1218
+ input_ids,
1219
+ attention_mask=attention_mask,
1220
+ position_ids=position_ids,
1221
+ past_key_values=past_key_values,
1222
+ inputs_embeds=inputs_embeds,
1223
+ use_cache=use_cache,
1224
+ output_attentions=output_attentions,
1225
+ output_hidden_states=output_hidden_states,
1226
+ return_dict=return_dict,
1227
+ )
1228
+ hidden_states = model_outputs[0]
1229
+ logits = self.score(hidden_states)
1230
+
1231
+ if input_ids is not None:
1232
+ batch_size = input_ids.shape[0]
1233
+ else:
1234
+ batch_size = inputs_embeds.shape[0]
1235
+
1236
+ if self.config.pad_token_id is None and batch_size != 1:
1237
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1238
+ if self.config.pad_token_id is None:
1239
+ sequence_lengths = -1
1240
+ else:
1241
+ if input_ids is not None:
1242
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1243
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1244
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1245
+ sequence_lengths = sequence_lengths.to(logits.device)
1246
+ else:
1247
+ sequence_lengths = -1
1248
+
1249
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1250
+
1251
+ loss = None
1252
+ if labels is not None:
1253
+ labels = labels.to(logits.device)
1254
+ if self.config.problem_type is None:
1255
+ if self.num_labels == 1:
1256
+ self.config.problem_type = "regression"
1257
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1258
+ self.config.problem_type = "single_label_classification"
1259
+ else:
1260
+ self.config.problem_type = "multi_label_classification"
1261
+
1262
+ if self.config.problem_type == "regression":
1263
+ loss_fct = MSELoss()
1264
+ if self.num_labels == 1:
1265
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1266
+ else:
1267
+ loss = loss_fct(pooled_logits, labels)
1268
+ elif self.config.problem_type == "single_label_classification":
1269
+ loss_fct = CrossEntropyLoss()
1270
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1271
+ elif self.config.problem_type == "multi_label_classification":
1272
+ loss_fct = BCEWithLogitsLoss()
1273
+ loss = loss_fct(pooled_logits, labels)
1274
+ if not return_dict:
1275
+ output = (pooled_logits,) + model_outputs[1:]
1276
+ return ((loss,) + output) if loss is not None else output
1277
+
1278
+ return SequenceClassifierOutputWithPast(
1279
+ loss=loss,
1280
+ logits=pooled_logits,
1281
+ past_key_values=model_outputs.past_key_values,
1282
+ hidden_states=model_outputs.hidden_states,
1283
+ attentions=model_outputs.attentions,
1284
+ )
1285
+
1286
+
1287
+ @add_start_docstrings(
1288
+ """
1289
+ PhiModel with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1290
+ Named-Entity-Recognition (NER) tasks.
1291
+ """,
1292
+ PHI_START_DOCSTRING,
1293
+ )
1294
+ # Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with MPT->PHI,Mpt->Phi,self.transformer->self.model,transformer_outputs->model_outputs
1295
+ class PhiForTokenClassification(PhiPreTrainedModel):
1296
+ def __init__(self, config: PhiConfig):
1297
+ super().__init__(config)
1298
+ self.num_labels = config.num_labels
1299
+
1300
+ self.model = PhiModel(config)
1301
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1302
+ classifier_dropout = config.classifier_dropout
1303
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1304
+ classifier_dropout = config.hidden_dropout
1305
+ else:
1306
+ classifier_dropout = 0.1
1307
+ self.dropout = nn.Dropout(classifier_dropout)
1308
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1309
+
1310
+ # Initialize weights and apply final processing
1311
+ self.post_init()
1312
+
1313
+ @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
1314
+ @add_code_sample_docstrings(
1315
+ checkpoint=_CHECKPOINT_FOR_DOC,
1316
+ output_type=TokenClassifierOutput,
1317
+ config_class=_CONFIG_FOR_DOC,
1318
+ )
1319
+ def forward(
1320
+ self,
1321
+ input_ids: Optional[torch.LongTensor] = None,
1322
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1323
+ attention_mask: Optional[torch.Tensor] = None,
1324
+ inputs_embeds: Optional[torch.Tensor] = None,
1325
+ labels: Optional[torch.Tensor] = None,
1326
+ use_cache: Optional[bool] = None,
1327
+ output_attentions: Optional[bool] = None,
1328
+ output_hidden_states: Optional[bool] = None,
1329
+ return_dict: Optional[bool] = None,
1330
+ **deprecated_arguments,
1331
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1332
+ r"""
1333
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1334
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1335
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1336
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1337
+ """
1338
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1339
+
1340
+ model_outputs = self.model(
1341
+ input_ids,
1342
+ past_key_values=past_key_values,
1343
+ attention_mask=attention_mask,
1344
+ inputs_embeds=inputs_embeds,
1345
+ use_cache=use_cache,
1346
+ output_attentions=output_attentions,
1347
+ output_hidden_states=output_hidden_states,
1348
+ return_dict=return_dict,
1349
+ )
1350
+
1351
+ hidden_states = model_outputs[0]
1352
+ hidden_states = self.dropout(hidden_states)
1353
+ logits = self.classifier(hidden_states)
1354
+
1355
+ loss = None
1356
+ if labels is not None:
1357
+ # move labels to correct device to enable model parallelism
1358
+ labels = labels.to(logits.device)
1359
+ batch_size, seq_length = labels.shape
1360
+ loss_fct = CrossEntropyLoss()
1361
+ loss = loss_fct(
1362
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
1363
+ )
1364
+
1365
+ if not return_dict:
1366
+ output = (logits,) + model_outputs[2:]
1367
+ return ((loss,) + output) if loss is not None else output
1368
+
1369
+ return TokenClassifierOutput(
1370
+ loss=loss,
1371
+ logits=logits,
1372
+ hidden_states=model_outputs.hidden_states,
1373
+ attentions=model_outputs.attentions,
1374
+ )
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1c79253fafbc1fb423cd4cc03b68b560b5c5b79f99ff7a7b1ca1f3ebf8030648
3
+ size 5813690086
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ }
181
+ },
182
+ "additional_special_tokens": [
183
+ "<|im_start|>",
184
+ "<|im_end|>",
185
+ "<|object_ref_start|>",
186
+ "<|object_ref_end|>",
187
+ "<|box_start|>",
188
+ "<|box_end|>",
189
+ "<|quad_start|>",
190
+ "<|quad_end|>",
191
+ "<|vision_start|>",
192
+ "<|vision_end|>",
193
+ "<|vision_pad|>",
194
+ "<|image_pad|>",
195
+ "<|video_pad|>"
196
+ ],
197
+ "bos_token": null,
198
+ "chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0]['role'] == 'system' %}\n {{- messages[0]['content'] }}\n {%- else %}\n {{- 'You are Phi created by Microsoft. You are a helpful assistant.' }}\n {%- endif %}\n {{- \"\\n\\n# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0]['role'] == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0]['content'] + '<|im_end|>\\n' }}\n {%- else %}\n {{- '<|im_start|>system\\nYou are Phi, created by Microsoft. You are a helpful assistant.<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- for message in messages %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) or (message.role == \"assistant\" and not message.tool_calls) %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {{- '<|im_start|>' + message.role }}\n {%- if message.content %}\n {{- '\\n' + message.content }}\n {%- endif %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '\\n<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {{- tool_call.arguments | tojson }}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}\n",
199
+ "clean_up_tokenization_spaces": false,
200
+ "eos_token": "<|im_end|>",
201
+ "errors": "replace",
202
+ "model_max_length": 131072,
203
+ "pad_token": "<|endoftext|>",
204
+ "split_special_tokens": false,
205
+ "tokenizer_class": "Qwen2Tokenizer",
206
+ "unk_token": null
207
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff