Guanzheng commited on
Commit
21060a9
1 Parent(s): 8d7db66

Upload 3 files

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