vince62s commited on
Commit
0d3b225
1 Parent(s): 32c49d3

Upload 6 files

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