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