lole25 commited on
Commit
0a157af
1 Parent(s): 8a75558

Upload 2 files

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