gugarosa commited on
Commit
8a2c68b
1 Parent(s): 530294c

chore(root): Updates files to internal transformers implementation.

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