kaizen9 commited on
Commit
f08ef96
·
verified ·
1 Parent(s): 28bae8e

Create modeling_phi_rot.py

Browse files
Files changed (1) hide show
  1. modeling_phi_rot.py +1075 -0
modeling_phi_rot.py ADDED
@@ -0,0 +1,1075 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/phi/modular_phi.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_phi.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ from typing import Callable, List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+
12
+ from transformers.activations import ACT2FN
13
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
14
+ from transformers.generation import GenerationMixin
15
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
16
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
17
+ from transformers.modeling_outputs import (
18
+ BaseModelOutputWithPast,
19
+ CausalLMOutputWithPast,
20
+ SequenceClassifierOutputWithPast,
21
+ TokenClassifierOutput,
22
+ )
23
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
24
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
25
+ from transformers.processing_utils import Unpack
26
+ from transformers.utils import (
27
+ LossKwargs,
28
+ add_code_sample_docstrings,
29
+ add_start_docstrings,
30
+ add_start_docstrings_to_model_forward,
31
+ logging,
32
+ replace_return_docstrings,
33
+ )
34
+ from transformers.models.phi.configuration_phi import PhiConfig
35
+ from train_utils.quant_linear import QuantizeLinear
36
+
37
+
38
+ logger = logging.get_logger(__name__)
39
+
40
+ _CHECKPOINT_FOR_DOC = "meta-phi/Phi-2-7b-hf"
41
+ _CONFIG_FOR_DOC = "PhiConfig"
42
+
43
+
44
+ def rotate_half(x):
45
+ """Rotates half the hidden dims of the input."""
46
+ x1 = x[..., : x.shape[-1] // 2]
47
+ x2 = x[..., x.shape[-1] // 2 :]
48
+ return torch.cat((-x2, x1), dim=-1)
49
+
50
+
51
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
52
+ """Applies Rotary Position Embedding to the query and key tensors.
53
+
54
+ Args:
55
+ q (`torch.Tensor`): The query tensor.
56
+ k (`torch.Tensor`): The key tensor.
57
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
58
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
59
+ position_ids (`torch.Tensor`, *optional*):
60
+ Deprecated and unused.
61
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
62
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
63
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
64
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
65
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
66
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
67
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
68
+ Returns:
69
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
70
+ """
71
+ cos = cos.unsqueeze(unsqueeze_dim)
72
+ sin = sin.unsqueeze(unsqueeze_dim)
73
+ q_embed = (q * cos) + (rotate_half(q) * sin)
74
+ k_embed = (k * cos) + (rotate_half(k) * sin)
75
+ return q_embed, k_embed
76
+
77
+
78
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
79
+ """
80
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
81
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
82
+ """
83
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
84
+ if n_rep == 1:
85
+ return hidden_states
86
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
87
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
88
+
89
+
90
+ def eager_attention_forward(
91
+ module: nn.Module,
92
+ query: torch.Tensor,
93
+ key: torch.Tensor,
94
+ value: torch.Tensor,
95
+ attention_mask: Optional[torch.Tensor],
96
+ scaling: float,
97
+ dropout: float = 0.0,
98
+ **kwargs,
99
+ ):
100
+ key_states = repeat_kv(key, module.num_key_value_groups)
101
+ value_states = repeat_kv(value, module.num_key_value_groups)
102
+
103
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
104
+ if attention_mask is not None:
105
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
106
+ attn_weights = attn_weights + causal_mask
107
+
108
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
109
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
110
+ attn_output = torch.matmul(attn_weights, value_states)
111
+ attn_output = attn_output.transpose(1, 2).contiguous()
112
+
113
+ return attn_output, attn_weights
114
+
115
+
116
+ class PhiAttention(nn.Module):
117
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
118
+
119
+ def __init__(self, config: PhiConfig, layer_idx: int):
120
+ super().__init__()
121
+ self.config = config
122
+ self.layer_idx = layer_idx
123
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
124
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
125
+ self.scaling = self.head_dim**-0.5
126
+ self.attention_dropout = config.attention_dropout
127
+ self.is_causal = True
128
+ #self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)
129
+ #self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
130
+ #self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
131
+ ########MODS
132
+ self.q_proj = QuantizeLinear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)
133
+ self.k_proj = QuantizeLinear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
134
+ self.v_proj = QuantizeLinear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
135
+ self.dense = QuantizeLinear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=True)
136
+ self.R2 = None
137
+ #####MODS
138
+ self.rotary_ndims = int(self.head_dim * config.partial_rotary_factor)
139
+ self.qk_layernorm = config.qk_layernorm
140
+ if self.qk_layernorm:
141
+ self.q_layernorm = nn.LayerNorm(
142
+ config.hidden_size // config.num_attention_heads, eps=config.layer_norm_eps, elementwise_affine=True
143
+ )
144
+ self.k_layernorm = nn.LayerNorm(
145
+ config.hidden_size // config.num_attention_heads, eps=config.layer_norm_eps, elementwise_affine=True
146
+ )
147
+
148
+ def forward(
149
+ self,
150
+ hidden_states: torch.Tensor,
151
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
152
+ attention_mask: Optional[torch.Tensor],
153
+ past_key_value: Optional[Cache] = None,
154
+ cache_position: Optional[torch.LongTensor] = None,
155
+ **kwargs,
156
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
157
+ input_shape = hidden_states.shape[:-1]
158
+ hidden_shape = (*input_shape, -1, self.head_dim)
159
+ R1=None,
160
+ query_states = self.q_proj(hidden_states, R1).view(hidden_shape).transpose(1, 2)
161
+ key_states = self.k_proj(hidden_states, R1).view(hidden_shape).transpose(1, 2)
162
+ value_states = self.v_proj(hidden_states, R1, R2=self.R2.weight).view(hidden_shape).transpose(1, 2)
163
+
164
+ if self.qk_layernorm:
165
+ query_states = self.q_layernorm(query_states)
166
+ key_states = self.k_layernorm(key_states)
167
+
168
+ cos, sin = position_embeddings
169
+ # Partial rotary embedding
170
+ query_rot, query_pass = (
171
+ query_states[..., : self.rotary_ndims],
172
+ query_states[..., self.rotary_ndims :],
173
+ )
174
+ key_rot, key_pass = (
175
+ key_states[..., : self.rotary_ndims],
176
+ key_states[..., self.rotary_ndims :],
177
+ )
178
+ # [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
179
+ query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin)
180
+
181
+ # [batch_size, seq_length, num_heads, head_dim]
182
+ query_states = torch.cat((query_rot, query_pass), dim=-1)
183
+ key_states = torch.cat((key_rot, key_pass), dim=-1)
184
+
185
+ if past_key_value is not None:
186
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
187
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
188
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
189
+
190
+ attention_interface: Callable = eager_attention_forward
191
+ if self.config._attn_implementation != "eager":
192
+ if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
193
+ logger.warning_once(
194
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
195
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
196
+ )
197
+ else:
198
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
199
+
200
+ attn_output, attn_weights = attention_interface(
201
+ self,
202
+ query_states,
203
+ key_states,
204
+ value_states,
205
+ attention_mask,
206
+ dropout=0.0 if not self.training else self.attention_dropout,
207
+ scaling=self.scaling,
208
+ **kwargs,
209
+ )
210
+
211
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
212
+ attn_output = self.dense(attn_output, R1, R2=self.R2.weight, transpose=True)
213
+ return attn_output, attn_weights
214
+
215
+
216
+ class PhiMLP(nn.Module):
217
+ def __init__(self, config):
218
+ super().__init__()
219
+ self.config = config
220
+ self.activation_fn = ACT2FN[config.hidden_act]
221
+
222
+ #self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
223
+ #self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
224
+
225
+ self.fc1 = QuantizeLinear(config.hidden_size, config.intermediate_size) #up proj
226
+ self.fc2 = QuantizeLinear(config.intermediate_size, config.hidden_size) #down proj
227
+ '''
228
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
229
+ hidden_states = self.fc1(hidden_states)
230
+ hidden_states = self.activation_fn(hidden_states)
231
+ hidden_states = self.fc2(hidden_states)
232
+ return hidden_states
233
+ '''
234
+
235
+ def forward(self, hidden_states, R1):
236
+ hidden_states = self.fc1(hidden_states, R1)
237
+ hidden_states = self.activation_fn(hidden_states)
238
+ hidden_states = self.fc2(hidden_states, R1, transpose=True)
239
+
240
+
241
+ return hidden_states
242
+
243
+
244
+
245
+ class PhiDecoderLayer(nn.Module):
246
+ def __init__(self, config: PhiConfig, layer_idx: int):
247
+ super().__init__()
248
+ self.self_attn = PhiAttention(config, layer_idx=layer_idx)
249
+ self.mlp = PhiMLP(config)
250
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
251
+ self.resid_dropout = nn.Dropout(config.resid_pdrop)
252
+
253
+ def forward(
254
+ self,
255
+ hidden_states: torch.Tensor,
256
+ attention_mask: Optional[torch.Tensor] = None,
257
+ position_ids: Optional[torch.LongTensor] = None,
258
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
259
+ output_attentions: Optional[bool] = False,
260
+ use_cache: Optional[bool] = False,
261
+ cache_position: Optional[torch.LongTensor] = None,
262
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
263
+ R1=None,
264
+
265
+ **kwargs,
266
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
267
+ residual = hidden_states
268
+
269
+ hidden_states = self.input_layernorm(hidden_states)
270
+
271
+ # Self Attention
272
+ attn_outputs, self_attn_weights = self.self_attn(
273
+ hidden_states=hidden_states,
274
+ attention_mask=attention_mask,
275
+ position_ids=position_ids,
276
+ past_key_value=past_key_value,
277
+ output_attentions=output_attentions,
278
+ use_cache=use_cache,
279
+ cache_position=cache_position,
280
+ position_embeddings=position_embeddings,
281
+ R1=R1,
282
+
283
+ **kwargs,
284
+ )
285
+ attn_outputs = self.resid_dropout(attn_outputs)
286
+
287
+ feed_forward_hidden_states = self.resid_dropout(self.mlp(hidden_states, R1=R1))
288
+ hidden_states = attn_outputs + feed_forward_hidden_states + residual
289
+ outputs = (hidden_states,)
290
+
291
+ if output_attentions:
292
+ outputs += (self_attn_weights,)
293
+
294
+ return outputs
295
+
296
+
297
+ class PhiRotaryEmbedding(nn.Module):
298
+ def __init__(
299
+ self,
300
+ config: PhiConfig,
301
+ device=None,
302
+ ):
303
+ super().__init__()
304
+ self.rope_kwargs = {}
305
+ # BC: "rope_type" was originally "type"
306
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
307
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
308
+ else:
309
+ self.rope_type = "default"
310
+ self.max_seq_len_cached = config.max_position_embeddings
311
+ self.original_max_seq_len = config.max_position_embeddings
312
+
313
+ self.config = config
314
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
315
+
316
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
317
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
318
+ self.original_inv_freq = self.inv_freq
319
+
320
+ def _dynamic_frequency_update(self, position_ids, device):
321
+ """
322
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
323
+ 1 - growing beyond the cached sequence length (allow scaling)
324
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
325
+ """
326
+ seq_len = torch.max(position_ids) + 1
327
+ if seq_len > self.max_seq_len_cached: # growth
328
+ inv_freq, self.attention_scaling = self.rope_init_fn(
329
+ self.config, device, seq_len=seq_len, **self.rope_kwargs
330
+ )
331
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
332
+ self.max_seq_len_cached = seq_len
333
+
334
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
335
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
336
+ self.max_seq_len_cached = self.original_max_seq_len
337
+
338
+ @torch.no_grad()
339
+ def forward(self, x, position_ids):
340
+ if "dynamic" in self.rope_type:
341
+ self._dynamic_frequency_update(position_ids, device=x.device)
342
+
343
+ # Core RoPE block
344
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
345
+ position_ids_expanded = position_ids[:, None, :].float()
346
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
347
+ device_type = x.device.type
348
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
349
+ with torch.autocast(device_type=device_type, enabled=False):
350
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
351
+ emb = torch.cat((freqs, freqs), dim=-1)
352
+ cos = emb.cos()
353
+ sin = emb.sin()
354
+
355
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
356
+ cos = cos * self.attention_scaling
357
+ sin = sin * self.attention_scaling
358
+
359
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
360
+
361
+
362
+ PHI_START_DOCSTRING = r"""
363
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
364
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
365
+ etc.)
366
+
367
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
368
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
369
+ and behavior.
370
+
371
+ Parameters:
372
+ config ([`PhiConfig`]):
373
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
374
+ load the weights associated with the model, only the configuration. Check out the
375
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
376
+ """
377
+
378
+
379
+ @add_start_docstrings(
380
+ "The bare Phi Model outputting raw hidden-states without any specific head on top.",
381
+ PHI_START_DOCSTRING,
382
+ )
383
+ class PhiPreTrainedModel(PreTrainedModel):
384
+ config_class = PhiConfig
385
+ base_model_prefix = "model"
386
+ supports_gradient_checkpointing = True
387
+ _no_split_modules = ["PhiDecoderLayer"]
388
+ _skip_keys_device_placement = ["past_key_values"]
389
+ _supports_flash_attn_2 = True
390
+ _supports_sdpa = True
391
+ _supports_cache_class = True
392
+ _supports_quantized_cache = True
393
+ _supports_static_cache = True
394
+
395
+ def _init_weights(self, module):
396
+ std = self.config.initializer_range
397
+ if isinstance(module, nn.Linear):
398
+ module.weight.data.normal_(mean=0.0, std=std)
399
+ if module.bias is not None:
400
+ module.bias.data.zero_()
401
+ elif isinstance(module, nn.Embedding):
402
+ module.weight.data.normal_(mean=0.0, std=std)
403
+ if module.padding_idx is not None:
404
+ module.weight.data[module.padding_idx].zero_()
405
+
406
+
407
+ PHI_INPUTS_DOCSTRING = r"""
408
+ Args:
409
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
410
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
411
+ it.
412
+
413
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
414
+ [`PreTrainedTokenizer.__call__`] for details.
415
+
416
+ [What are input IDs?](../glossary#input-ids)
417
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
418
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
419
+
420
+ - 1 for tokens that are **not masked**,
421
+ - 0 for tokens that are **masked**.
422
+
423
+ [What are attention masks?](../glossary#attention-mask)
424
+
425
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
426
+ [`PreTrainedTokenizer.__call__`] for details.
427
+
428
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
429
+ `past_key_values`).
430
+
431
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
432
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
433
+ information on the default strategy.
434
+
435
+ - 1 indicates the head is **not masked**,
436
+ - 0 indicates the head is **masked**.
437
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
438
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
439
+ config.n_positions - 1]`.
440
+
441
+ [What are position IDs?](../glossary#position-ids)
442
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
443
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
444
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
445
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
446
+
447
+ Two formats are allowed:
448
+ - a [`~cache_utils.Cache`] instance, see our
449
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
450
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
451
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
452
+ cache format.
453
+
454
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
455
+ legacy cache format will be returned.
456
+
457
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
458
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
459
+ of shape `(batch_size, sequence_length)`.
460
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
461
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
462
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
463
+ model's internal embedding lookup matrix.
464
+ use_cache (`bool`, *optional*):
465
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
466
+ `past_key_values`).
467
+ output_attentions (`bool`, *optional*):
468
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
469
+ tensors for more detail.
470
+ output_hidden_states (`bool`, *optional*):
471
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
472
+ more detail.
473
+ return_dict (`bool`, *optional*):
474
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
475
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
476
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
477
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
478
+ the complete sequence length.
479
+ """
480
+
481
+
482
+ @add_start_docstrings(
483
+ "The bare Phi Model outputting raw hidden-states without any specific head on top.",
484
+ PHI_START_DOCSTRING,
485
+ )
486
+ class PhiModel(PhiPreTrainedModel):
487
+ """
488
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`PhiDecoderLayer`]
489
+
490
+ Args:
491
+ config: PhiConfig
492
+ """
493
+
494
+ def __init__(self, config: PhiConfig):
495
+ super().__init__(config)
496
+ self.padding_idx = config.pad_token_id
497
+ self.vocab_size = config.vocab_size
498
+
499
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
500
+ self.layers = nn.ModuleList(
501
+ [PhiDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
502
+ )
503
+ self.rotary_emb = PhiRotaryEmbedding(config=config)
504
+ self.gradient_checkpointing = False
505
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
506
+ self.final_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
507
+
508
+ # Initialize weights and apply final processing
509
+ self.post_init()
510
+
511
+ def get_input_embeddings(self):
512
+ return self.embed_tokens
513
+
514
+ def set_input_embeddings(self, value):
515
+ self.embed_tokens = value
516
+
517
+ @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
518
+ def forward(
519
+ self,
520
+ input_ids: torch.LongTensor = None,
521
+ attention_mask: Optional[torch.Tensor] = None,
522
+ position_ids: Optional[torch.LongTensor] = None,
523
+ past_key_values: Optional[Cache] = None,
524
+ inputs_embeds: Optional[torch.FloatTensor] = None,
525
+ use_cache: Optional[bool] = None,
526
+ output_attentions: Optional[bool] = None,
527
+ output_hidden_states: Optional[bool] = None,
528
+ return_dict: Optional[bool] = None,
529
+ cache_position: Optional[torch.LongTensor] = None,
530
+ R1=None,
531
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
532
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
533
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
534
+ output_hidden_states = (
535
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
536
+ )
537
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
538
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
539
+
540
+ if (input_ids is None) ^ (inputs_embeds is not None):
541
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
542
+
543
+ if self.gradient_checkpointing and self.training and use_cache:
544
+ logger.warning_once(
545
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
546
+ )
547
+ use_cache = False
548
+
549
+ if inputs_embeds is None:
550
+ inputs_embeds = self.embed_tokens(input_ids)
551
+
552
+ if use_cache and past_key_values is None:
553
+ past_key_values = DynamicCache()
554
+
555
+ if cache_position is None:
556
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
557
+ cache_position = torch.arange(
558
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
559
+ )
560
+
561
+ if position_ids is None:
562
+ position_ids = cache_position.unsqueeze(0)
563
+
564
+ causal_mask = self._update_causal_mask(
565
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
566
+ )
567
+
568
+ inputs_embeds = self.embed_dropout(inputs_embeds) # diff with Llama
569
+ hidden_states = inputs_embeds
570
+
571
+ # create position embeddings to be shared across the decoder layers
572
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
573
+
574
+ # decoder layers
575
+ all_hidden_states = () if output_hidden_states else None
576
+ all_self_attns = () if output_attentions else None
577
+
578
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
579
+ if output_hidden_states:
580
+ all_hidden_states += (hidden_states,)
581
+
582
+ if self.gradient_checkpointing and self.training:
583
+ layer_outputs = self._gradient_checkpointing_func(
584
+ decoder_layer.__call__,
585
+ hidden_states,
586
+ causal_mask,
587
+ position_ids,
588
+ past_key_values,
589
+ output_attentions,
590
+ use_cache,
591
+ cache_position,
592
+ position_embeddings,
593
+ R1,
594
+
595
+ )
596
+ else:
597
+ layer_outputs = decoder_layer(
598
+ hidden_states,
599
+ attention_mask=causal_mask,
600
+ position_ids=position_ids,
601
+ past_key_value=past_key_values,
602
+ output_attentions=output_attentions,
603
+ use_cache=use_cache,
604
+ cache_position=cache_position,
605
+ position_embeddings=position_embeddings,
606
+ R1=R1,
607
+
608
+ **flash_attn_kwargs,
609
+ )
610
+
611
+ hidden_states = layer_outputs[0]
612
+
613
+ if output_attentions:
614
+ all_self_attns += (layer_outputs[1],)
615
+
616
+ hidden_states = self.final_layernorm(hidden_states) # diff with Llama
617
+
618
+ # add hidden states from the last decoder layer
619
+ if output_hidden_states:
620
+ all_hidden_states += (hidden_states,)
621
+
622
+ output = BaseModelOutputWithPast(
623
+ last_hidden_state=hidden_states,
624
+ past_key_values=past_key_values if use_cache else None,
625
+ hidden_states=all_hidden_states,
626
+ attentions=all_self_attns,
627
+ )
628
+ return output if return_dict else output.to_tuple()
629
+
630
+ def _update_causal_mask(
631
+ self,
632
+ attention_mask: torch.Tensor,
633
+ input_tensor: torch.Tensor,
634
+ cache_position: torch.Tensor,
635
+ past_key_values: Cache,
636
+ output_attentions: bool,
637
+ ):
638
+ if self.config._attn_implementation == "flash_attention_2":
639
+ if attention_mask is not None and (attention_mask == 0.0).any():
640
+ return attention_mask
641
+ return None
642
+
643
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
644
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
645
+ # to infer the attention mask.
646
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
647
+ using_static_cache = isinstance(past_key_values, StaticCache)
648
+
649
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
650
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
651
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
652
+ attention_mask,
653
+ inputs_embeds=input_tensor,
654
+ past_key_values_length=past_seen_tokens,
655
+ is_training=self.training,
656
+ ):
657
+ return None
658
+
659
+ dtype, device = input_tensor.dtype, input_tensor.device
660
+ sequence_length = input_tensor.shape[1]
661
+ if using_static_cache:
662
+ target_length = past_key_values.get_max_cache_shape()
663
+ else:
664
+ target_length = (
665
+ attention_mask.shape[-1]
666
+ if isinstance(attention_mask, torch.Tensor)
667
+ else past_seen_tokens + sequence_length + 1
668
+ )
669
+
670
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
671
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
672
+ attention_mask,
673
+ sequence_length=sequence_length,
674
+ target_length=target_length,
675
+ dtype=dtype,
676
+ device=device,
677
+ cache_position=cache_position,
678
+ batch_size=input_tensor.shape[0],
679
+ )
680
+
681
+ if (
682
+ self.config._attn_implementation == "sdpa"
683
+ and attention_mask is not None
684
+ and attention_mask.device.type == "cuda"
685
+ and not output_attentions
686
+ ):
687
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
688
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
689
+ # Details: https://github.com/pytorch/pytorch/issues/110213
690
+ min_dtype = torch.finfo(dtype).min
691
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
692
+
693
+ return causal_mask
694
+
695
+ @staticmethod
696
+ def _prepare_4d_causal_attention_mask_with_cache_position(
697
+ attention_mask: torch.Tensor,
698
+ sequence_length: int,
699
+ target_length: int,
700
+ dtype: torch.dtype,
701
+ device: torch.device,
702
+ cache_position: torch.Tensor,
703
+ batch_size: int,
704
+ **kwargs,
705
+ ):
706
+ """
707
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
708
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
709
+
710
+ Args:
711
+ attention_mask (`torch.Tensor`):
712
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
713
+ `(batch_size, 1, query_length, key_value_length)`.
714
+ sequence_length (`int`):
715
+ The sequence length being processed.
716
+ target_length (`int`):
717
+ The target length: when generating with static cache, the mask should be as long as the static cache,
718
+ to account for the 0 padding, the part of the cache that is not filled yet.
719
+ dtype (`torch.dtype`):
720
+ The dtype to use for the 4D attention mask.
721
+ device (`torch.device`):
722
+ The device to plcae the 4D attention mask on.
723
+ cache_position (`torch.Tensor`):
724
+ Indices depicting the position of the input sequence tokens in the sequence.
725
+ batch_size (`torch.Tensor`):
726
+ Batch size.
727
+ """
728
+ if attention_mask is not None and attention_mask.dim() == 4:
729
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
730
+ causal_mask = attention_mask
731
+ else:
732
+ min_dtype = torch.finfo(dtype).min
733
+ causal_mask = torch.full(
734
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
735
+ )
736
+ if sequence_length != 1:
737
+ causal_mask = torch.triu(causal_mask, diagonal=1)
738
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
739
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
740
+ if attention_mask is not None:
741
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
742
+ mask_length = attention_mask.shape[-1]
743
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
744
+ padding_mask = padding_mask == 0
745
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
746
+ padding_mask, min_dtype
747
+ )
748
+
749
+ return causal_mask
750
+
751
+
752
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
753
+
754
+
755
+ class PhiRotForCausalLM(PhiPreTrainedModel, GenerationMixin):
756
+ _tied_weights_keys = ["lm_head.weight"]
757
+ _tp_plan = {"lm_head": "colwise_rep"}
758
+
759
+ def __init__(self, config):
760
+ super().__init__(config)
761
+ self.model = PhiModel(config)
762
+ self.vocab_size = config.vocab_size
763
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
764
+
765
+ # Initialize weights and apply final processing
766
+ self.post_init()
767
+
768
+ def get_input_embeddings(self):
769
+ return self.model.embed_tokens
770
+
771
+ def set_input_embeddings(self, value):
772
+ self.model.embed_tokens = value
773
+
774
+ def get_output_embeddings(self):
775
+ return self.lm_head
776
+
777
+ def set_output_embeddings(self, new_embeddings):
778
+ self.lm_head = new_embeddings
779
+
780
+ def set_decoder(self, decoder):
781
+ self.model = decoder
782
+
783
+ def get_decoder(self):
784
+ return self.model
785
+
786
+ @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
787
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
788
+ def forward(
789
+ self,
790
+ input_ids: torch.LongTensor = None,
791
+ attention_mask: Optional[torch.Tensor] = None,
792
+ position_ids: Optional[torch.LongTensor] = None,
793
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
794
+ inputs_embeds: Optional[torch.FloatTensor] = None,
795
+ labels: Optional[torch.LongTensor] = None,
796
+ use_cache: Optional[bool] = None,
797
+ output_attentions: Optional[bool] = None,
798
+ output_hidden_states: Optional[bool] = None,
799
+ return_dict: Optional[bool] = None,
800
+ cache_position: Optional[torch.LongTensor] = None,
801
+ num_logits_to_keep: int = 0,
802
+ **kwargs: Unpack[KwargsForCausalLM],
803
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
804
+ r"""
805
+ Args:
806
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
807
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
808
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
809
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
810
+
811
+ num_logits_to_keep (`int`, *optional*):
812
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
813
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
814
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
815
+
816
+ Returns:
817
+
818
+ Example:
819
+
820
+ ```python
821
+ >>> from transformers import AutoTokenizer, PhiForCausalLM
822
+
823
+ >>> model = PhiForCausalLM.from_pretrained("meta-phi/Phi-2-7b-hf")
824
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-phi/Phi-2-7b-hf")
825
+
826
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
827
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
828
+
829
+ >>> # Generate
830
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
831
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
832
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
833
+ ```"""
834
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
835
+ output_hidden_states = (
836
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
837
+ )
838
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
839
+
840
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
841
+ outputs = self.model(
842
+ input_ids=input_ids,
843
+ attention_mask=attention_mask,
844
+ position_ids=position_ids,
845
+ past_key_values=past_key_values,
846
+ inputs_embeds=inputs_embeds,
847
+ use_cache=use_cache,
848
+ output_attentions=output_attentions,
849
+ output_hidden_states=output_hidden_states,
850
+ return_dict=return_dict,
851
+ cache_position=cache_position,
852
+ R1=self.R1.weight,
853
+
854
+ **kwargs,
855
+ )
856
+
857
+ hidden_states = outputs[0]
858
+
859
+ if self.R1 is not None:
860
+ dtype = hidden_states.dtype
861
+ hidden_states = (
862
+ hidden_states.to(torch.float64) @ self.R1.weight.T.to(torch.float64)
863
+ ).to(dtype)
864
+
865
+
866
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
867
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
868
+
869
+ loss = None
870
+ if labels is not None:
871
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
872
+
873
+ if not return_dict:
874
+ output = (logits,) + outputs[1:]
875
+ return (loss,) + output if loss is not None else output
876
+
877
+ return CausalLMOutputWithPast(
878
+ loss=loss,
879
+ logits=logits,
880
+ past_key_values=outputs.past_key_values,
881
+ hidden_states=outputs.hidden_states,
882
+ attentions=outputs.attentions,
883
+ )
884
+
885
+
886
+ @add_start_docstrings(
887
+ """
888
+ The Phi Model transformer with a sequence classification head on top (linear layer).
889
+
890
+ [`PhiForSequenceClassification`] uses the last token in order to do the classification, as other causal models
891
+ (e.g. GPT-2) do.
892
+
893
+ Since it does classification on the last token, it requires to know the position of the last token. If a
894
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
895
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
896
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
897
+ each row of the batch).
898
+ """,
899
+ PHI_START_DOCSTRING,
900
+ )
901
+ class PhiForSequenceClassification(PhiPreTrainedModel):
902
+ def __init__(self, config):
903
+ super().__init__(config)
904
+ self.num_labels = config.num_labels
905
+ self.model = PhiModel(config)
906
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
907
+
908
+ # Initialize weights and apply final processing
909
+ self.post_init()
910
+
911
+ def get_input_embeddings(self):
912
+ return self.model.embed_tokens
913
+
914
+ def set_input_embeddings(self, value):
915
+ self.model.embed_tokens = value
916
+
917
+ @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
918
+ def forward(
919
+ self,
920
+ input_ids: Optional[torch.LongTensor] = None,
921
+ attention_mask: Optional[torch.Tensor] = None,
922
+ position_ids: Optional[torch.LongTensor] = None,
923
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
924
+ inputs_embeds: Optional[torch.FloatTensor] = None,
925
+ labels: Optional[torch.LongTensor] = None,
926
+ use_cache: Optional[bool] = None,
927
+ output_attentions: Optional[bool] = None,
928
+ output_hidden_states: Optional[bool] = None,
929
+ return_dict: Optional[bool] = None,
930
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
931
+ r"""
932
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
933
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
934
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
935
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
936
+ """
937
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
938
+
939
+ transformer_outputs = self.model(
940
+ input_ids,
941
+ attention_mask=attention_mask,
942
+ position_ids=position_ids,
943
+ past_key_values=past_key_values,
944
+ inputs_embeds=inputs_embeds,
945
+ use_cache=use_cache,
946
+ output_attentions=output_attentions,
947
+ output_hidden_states=output_hidden_states,
948
+ return_dict=return_dict,
949
+ )
950
+ hidden_states = transformer_outputs[0]
951
+ logits = self.score(hidden_states)
952
+
953
+ if input_ids is not None:
954
+ batch_size = input_ids.shape[0]
955
+ else:
956
+ batch_size = inputs_embeds.shape[0]
957
+
958
+ if self.config.pad_token_id is None and batch_size != 1:
959
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
960
+ if self.config.pad_token_id is None:
961
+ sequence_lengths = -1
962
+ else:
963
+ if input_ids is not None:
964
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
965
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
966
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
967
+ sequence_lengths = sequence_lengths.to(logits.device)
968
+ else:
969
+ sequence_lengths = -1
970
+
971
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
972
+
973
+ loss = None
974
+ if labels is not None:
975
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
976
+
977
+ if not return_dict:
978
+ output = (pooled_logits,) + transformer_outputs[1:]
979
+ return ((loss,) + output) if loss is not None else output
980
+
981
+ return SequenceClassifierOutputWithPast(
982
+ loss=loss,
983
+ logits=pooled_logits,
984
+ past_key_values=transformer_outputs.past_key_values,
985
+ hidden_states=transformer_outputs.hidden_states,
986
+ attentions=transformer_outputs.attentions,
987
+ )
988
+
989
+
990
+ @add_start_docstrings(
991
+ """
992
+ The Phi Model transformer with a token classification head on top (a linear layer on top of the hidden-states
993
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
994
+ """,
995
+ PHI_START_DOCSTRING,
996
+ )
997
+ class PhiForTokenClassification(PhiPreTrainedModel):
998
+ def __init__(self, config):
999
+ super().__init__(config)
1000
+ self.num_labels = config.num_labels
1001
+ self.model = PhiModel(config)
1002
+ if getattr(config, "classifier_dropout", None) is not None:
1003
+ classifier_dropout = config.classifier_dropout
1004
+ elif getattr(config, "hidden_dropout", None) is not None:
1005
+ classifier_dropout = config.hidden_dropout
1006
+ else:
1007
+ classifier_dropout = 0.1
1008
+ self.dropout = nn.Dropout(classifier_dropout)
1009
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1010
+
1011
+ # Initialize weights and apply final processing
1012
+ self.post_init()
1013
+
1014
+ def get_input_embeddings(self):
1015
+ return self.model.embed_tokens
1016
+
1017
+ def set_input_embeddings(self, value):
1018
+ self.model.embed_tokens = value
1019
+
1020
+ @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
1021
+ @add_code_sample_docstrings(
1022
+ checkpoint=_CHECKPOINT_FOR_DOC,
1023
+ output_type=TokenClassifierOutput,
1024
+ config_class=_CONFIG_FOR_DOC,
1025
+ )
1026
+ def forward(
1027
+ self,
1028
+ input_ids: Optional[torch.LongTensor] = None,
1029
+ attention_mask: Optional[torch.Tensor] = None,
1030
+ position_ids: Optional[torch.LongTensor] = None,
1031
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1032
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1033
+ labels: Optional[torch.LongTensor] = None,
1034
+ use_cache: Optional[bool] = None,
1035
+ output_attentions: Optional[bool] = None,
1036
+ output_hidden_states: Optional[bool] = None,
1037
+ return_dict: Optional[bool] = None,
1038
+ ) -> Union[Tuple, TokenClassifierOutput]:
1039
+ r"""
1040
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1041
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1042
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1043
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1044
+ """
1045
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1046
+
1047
+ outputs = self.model(
1048
+ input_ids,
1049
+ attention_mask=attention_mask,
1050
+ position_ids=position_ids,
1051
+ past_key_values=past_key_values,
1052
+ inputs_embeds=inputs_embeds,
1053
+ use_cache=use_cache,
1054
+ output_attentions=output_attentions,
1055
+ output_hidden_states=output_hidden_states,
1056
+ return_dict=return_dict,
1057
+ )
1058
+ sequence_output = outputs[0]
1059
+ sequence_output = self.dropout(sequence_output)
1060
+ logits = self.score(sequence_output)
1061
+
1062
+ loss = None
1063
+ if labels is not None:
1064
+ loss = self.loss_function(logits, labels, self.config)
1065
+
1066
+ if not return_dict:
1067
+ output = (logits,) + outputs[2:]
1068
+ return ((loss,) + output) if loss is not None else output
1069
+
1070
+ return TokenClassifierOutput(
1071
+ loss=loss,
1072
+ logits=logits,
1073
+ hidden_states=outputs.hidden_states,
1074
+ attentions=outputs.attentions,
1075
+ )