yuchengz commited on
Commit
a175ed9
1 Parent(s): 5633dc1

hpt1.5 edge commit

Browse files
config.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/export/share/models/Phi-3-mini-4k-instruct",
3
+ "architectures": [
4
+ "Phi3ForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_phi3.Phi3Config",
9
+ "AutoModelForCausalLM": "modeling_phi3.Phi3ForCausalLM"
10
+ },
11
+ "bos_token_id": 1,
12
+ "embd_pdrop": 0.0,
13
+ "eos_token_id": 32000,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 3072,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 8192,
18
+ "max_position_embeddings": 4096,
19
+ "model_type": "phi3",
20
+ "num_attention_heads": 32,
21
+ "num_hidden_layers": 32,
22
+ "num_key_value_heads": 32,
23
+ "original_max_position_embeddings": 4096,
24
+ "pad_token_id": 32000,
25
+ "resid_pdrop": 0.0,
26
+ "rms_norm_eps": 1e-05,
27
+ "rope_scaling": null,
28
+ "rope_theta": 10000.0,
29
+ "sliding_window": 2047,
30
+ "tie_word_embeddings": false,
31
+ "torch_dtype": "float16",
32
+ "transformers_version": "4.40.2",
33
+ "use_cache": false,
34
+ "vocab_size": 32064
35
+ }
configuration_phi3.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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-3 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
+ PHI3_PRETRAINED_CONFIG_ARCHIVE_MAP = {
26
+ "microsoft/Phi-3-mini-4k-instruct": "https://huggingface.co/microsoft/Phi-3-mini-4k-instruct/resolve/main/config.json",
27
+ "microsoft/Phi-3-mini-128k-instruct": "https://huggingface.co/microsoft/Phi-3-mini-128k-instruct/resolve/main/config.json",
28
+ }
29
+
30
+
31
+ class Phi3Config(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration of a [`Phi3Model`]. It is used to instantiate a Phi-3
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
36
+ [microsoft/Phi-3-mini-4k-instruct](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct).
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 32064):
43
+ Vocabulary size of the Phi-3 model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`Phi3Model`].
45
+ hidden_size (`int`, *optional*, defaults to 3072):
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 32):
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
+ num_key_value_heads (`int`, *optional*):
54
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
55
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
56
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
57
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
58
+ by meanpooling all the original heads within that group. For more details checkout [this
59
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
60
+ `num_attention_heads`.
61
+ resid_pdrop (`float`, *optional*, defaults to 0.0):
62
+ Dropout probability for mlp outputs.
63
+ embd_pdrop (`int`, *optional*, defaults to 0.0):
64
+ The dropout ratio for the embeddings.
65
+ attention_dropout (`float`, *optional*, defaults to 0.0):
66
+ The dropout ratio after computing the attention scores.
67
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
68
+ The non-linear activation function (function or string) in the decoder.
69
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
70
+ The maximum sequence length that this model might ever be used with.
71
+ original_max_position_embeddings (`int`, *optional*, defaults to 4096):
72
+ The maximum sequence length that this model was trained with. This is used to determine the size of the
73
+ original RoPE embeddings when using long scaling.
74
+ initializer_range (`float`, *optional*, defaults to 0.02):
75
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
76
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
77
+ The epsilon value used for the RMSNorm.
78
+ use_cache (`bool`, *optional*, defaults to `True`):
79
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
80
+ relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
81
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
82
+ Whether to tie weight embeddings
83
+ rope_theta (`float`, *optional*, defaults to 10000.0):
84
+ The base period of the RoPE embeddings.
85
+ rope_scaling (`dict`, *optional*):
86
+ The scaling strategy for the RoPE embeddings. If `None`, no scaling is applied. If a dictionary, it must
87
+ contain the following keys: `type`, `short_factor` and `long_factor`. The `type` must be either `su` or `yarn` and
88
+ the `short_factor` and `long_factor` must be lists of numbers with the same length as the hidden size
89
+ divided by the number of attention heads divided by 2.
90
+ bos_token_id (`int`, *optional*, defaults to 1):
91
+ The id of the "beginning-of-sequence" token.
92
+ eos_token_id (`int`, *optional*, defaults to 32000):
93
+ The id of the "end-of-sequence" token.
94
+ pad_token_id (`int`, *optional*, defaults to 32000):
95
+ The id of the padding token.
96
+ sliding_window (`int`, *optional*):
97
+ Sliding window attention window size. If `None`, no sliding window is applied.
98
+
99
+ Example:
100
+
101
+ ```python
102
+ >>> from transformers import Phi3Model, Phi3Config
103
+
104
+ >>> # Initializing a Phi-3 style configuration
105
+ >>> configuration = Phi3Config.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
106
+
107
+ >>> # Initializing a model from the configuration
108
+ >>> model = Phi3Model(configuration)
109
+
110
+ >>> # Accessing the model configuration
111
+ >>> configuration = model.config
112
+ ```"""
113
+
114
+ model_type = "phi3"
115
+ keys_to_ignore_at_inference = ["past_key_values"]
116
+
117
+ def __init__(
118
+ self,
119
+ vocab_size=32064,
120
+ hidden_size=3072,
121
+ intermediate_size=8192,
122
+ num_hidden_layers=32,
123
+ num_attention_heads=32,
124
+ num_key_value_heads=None,
125
+ resid_pdrop=0.0,
126
+ embd_pdrop=0.0,
127
+ attention_dropout=0.0,
128
+ hidden_act="silu",
129
+ max_position_embeddings=4096,
130
+ original_max_position_embeddings=4096,
131
+ initializer_range=0.02,
132
+ rms_norm_eps=1e-5,
133
+ use_cache=True,
134
+ tie_word_embeddings=False,
135
+ rope_theta=10000.0,
136
+ rope_scaling=None,
137
+ bos_token_id=1,
138
+ eos_token_id=32000,
139
+ pad_token_id=32000,
140
+ sliding_window=None,
141
+ **kwargs,
142
+ ):
143
+ self.vocab_size = vocab_size
144
+ self.hidden_size = hidden_size
145
+ self.intermediate_size = intermediate_size
146
+ self.num_hidden_layers = num_hidden_layers
147
+ self.num_attention_heads = num_attention_heads
148
+
149
+ if num_key_value_heads is None:
150
+ num_key_value_heads = num_attention_heads
151
+
152
+ self.num_key_value_heads = num_key_value_heads
153
+ self.resid_pdrop = resid_pdrop
154
+ self.embd_pdrop = embd_pdrop
155
+ self.attention_dropout = attention_dropout
156
+ self.hidden_act = hidden_act
157
+ self.max_position_embeddings = max_position_embeddings
158
+ self.original_max_position_embeddings = original_max_position_embeddings
159
+ self.initializer_range = initializer_range
160
+ self.rms_norm_eps = rms_norm_eps
161
+ self.use_cache = use_cache
162
+ self.rope_theta = rope_theta
163
+ self.rope_scaling = rope_scaling
164
+ self._rope_scaling_validation()
165
+ self.sliding_window = sliding_window
166
+
167
+ super().__init__(
168
+ bos_token_id=bos_token_id,
169
+ eos_token_id=eos_token_id,
170
+ pad_token_id=pad_token_id,
171
+ tie_word_embeddings=tie_word_embeddings,
172
+ **kwargs,
173
+ )
174
+
175
+ def _rope_scaling_validation(self):
176
+ """
177
+ Validate the `rope_scaling` configuration.
178
+ """
179
+ if self.rope_scaling is None:
180
+ return
181
+
182
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 3:
183
+ raise ValueError(
184
+ "`rope_scaling` must be a dictionary with three fields, `type`, `short_factor` and `long_factor`, "
185
+ f"got {self.rope_scaling}"
186
+ )
187
+ rope_scaling_type = self.rope_scaling.get("type", None)
188
+ rope_scaling_short_factor = self.rope_scaling.get("short_factor", None)
189
+ rope_scaling_long_factor = self.rope_scaling.get("long_factor", None)
190
+ if rope_scaling_type is None or rope_scaling_type not in ["su", "yarn"]:
191
+ raise ValueError(f"`rope_scaling`'s type field must be one of ['su', 'yarn'], got {rope_scaling_type}")
192
+ if not (
193
+ isinstance(rope_scaling_short_factor, list)
194
+ and all(isinstance(x, (int, float)) for x in rope_scaling_short_factor)
195
+ ):
196
+ raise ValueError(
197
+ f"`rope_scaling`'s short_factor field must be a list of numbers, got {rope_scaling_short_factor}"
198
+ )
199
+ if not len(rope_scaling_short_factor) == self.hidden_size // self.num_attention_heads // 2:
200
+ raise ValueError(
201
+ f"`rope_scaling`'s short_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_short_factor)}"
202
+ )
203
+ if not (
204
+ isinstance(rope_scaling_long_factor, list)
205
+ and all(isinstance(x, (int, float)) for x in rope_scaling_long_factor)
206
+ ):
207
+ raise ValueError(
208
+ f"`rope_scaling`'s long_factor field must be a list of numbers, got {rope_scaling_long_factor}"
209
+ )
210
+ if not len(rope_scaling_long_factor) == self.hidden_size // self.num_attention_heads // 2:
211
+ raise ValueError(
212
+ f"`rope_scaling`'s long_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_long_factor)}"
213
+ )
configuration_projector.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) OpenMMLab. All rights reserved.
2
+ from transformers import PretrainedConfig
3
+
4
+
5
+ class ProjectorConfig(PretrainedConfig):
6
+ model_type = 'projector'
7
+ _auto_class = 'AutoConfig'
8
+
9
+ def __init__(
10
+ self,
11
+ visual_hidden_size=4096,
12
+ llm_hidden_size=4096,
13
+ depth=2,
14
+ hidden_act='gelu',
15
+ bias=True,
16
+ **kwargs,
17
+ ):
18
+ self.visual_hidden_size = visual_hidden_size
19
+ self.llm_hidden_size = llm_hidden_size
20
+ self.depth = depth
21
+ self.hidden_act = hidden_act
22
+ self.bias = bias
23
+ super().__init__(**kwargs)
configuration_qformer.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) OpenMMLab. All rights reserved.
2
+ from transformers import PretrainedConfig
3
+
4
+
5
+ class QformerConfig(PretrainedConfig):
6
+ model_type = 'qformer'
7
+ _auto_class = 'AutoConfig'
8
+
9
+ def __init__(
10
+ self,
11
+ num_query_token=32,
12
+ visual_hidden_size=4096,
13
+ llm_hidden_size=768,
14
+ cross_attention_freq=2,
15
+ bert="bert-base-uncased",
16
+ bias=True,
17
+ qformer_pth=None,
18
+ **kwargs,
19
+ ):
20
+ self.num_query_token=num_query_token
21
+ self.visual_hidden_size = visual_hidden_size
22
+ self.llm_hidden_size = llm_hidden_size
23
+ self.bias = bias
24
+ self.bert = bert
25
+ self.cross_attention_freq = cross_attention_freq
26
+ self.qformer_pth = qformer_pth
27
+ super().__init__(**kwargs)
fuse_modules.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ------------------------------------------------------------------------
2
+ # Grounding DINO
3
+ # url: https://github.com/IDEA-Research/GroundingDINO
4
+ # Copyright (c) 2023 IDEA. All Rights Reserved.
5
+ # Licensed under the Apache License, Version 2.0 [see LICENSE for details]
6
+ # ------------------------------------------------------------------------
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ from timm.models.layers import DropPath
12
+
13
+ class BiMultiHeadAttention(nn.Module):
14
+ def __init__(self, v_dim, l_dim, embed_dim, num_heads, dropout=0.1, cfg=None):
15
+ super(BiMultiHeadAttention, self).__init__()
16
+
17
+ self.embed_dim = embed_dim
18
+ self.num_heads = num_heads
19
+ self.head_dim = embed_dim // num_heads
20
+ self.v_dim = v_dim
21
+ self.l_dim = l_dim
22
+
23
+ assert (
24
+ self.head_dim * self.num_heads == self.embed_dim
25
+ ), f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {self.num_heads})."
26
+ self.scale = self.head_dim ** (-0.5)
27
+ self.dropout = dropout
28
+
29
+ self.v_proj = nn.Linear(self.v_dim, self.embed_dim)
30
+ self.l_proj = nn.Linear(self.l_dim, self.embed_dim)
31
+ self.values_l_proj = nn.Linear(self.l_dim, self.embed_dim)
32
+
33
+ self.out_v_proj = nn.Linear(self.embed_dim, self.v_dim)
34
+
35
+ self.stable_softmax_2d = True
36
+ self.clamp_min_for_underflow = True
37
+ self.clamp_max_for_overflow = True
38
+
39
+ self._reset_parameters()
40
+
41
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
42
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
43
+
44
+ def _reset_parameters(self):
45
+ nn.init.xavier_uniform_(self.v_proj.weight)
46
+ self.v_proj.bias.data.fill_(0)
47
+ nn.init.xavier_uniform_(self.l_proj.weight)
48
+ self.l_proj.bias.data.fill_(0)
49
+ nn.init.xavier_uniform_(self.values_l_proj.weight)
50
+ self.values_l_proj.bias.data.fill_(0)
51
+ nn.init.xavier_uniform_(self.out_v_proj.weight)
52
+ self.out_v_proj.bias.data.fill_(0)
53
+
54
+ def forward(self, v, l, attention_mask_v=None, attention_mask_l=None):
55
+ bsz, tgt_len, _ = v.size()
56
+
57
+ query_states = self.v_proj(v) * self.scale
58
+ key_states = self._shape(self.l_proj(l), -1, bsz)
59
+ value_l_states = self._shape(self.values_l_proj(l), -1, bsz)
60
+
61
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
62
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
63
+ key_states = key_states.view(*proj_shape)
64
+ value_l_states = value_l_states.view(*proj_shape)
65
+
66
+ src_len = key_states.size(1)
67
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2)) # bs*nhead, nimg, ntxt
68
+
69
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
70
+ raise ValueError(
71
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is {attn_weights.size()}"
72
+ )
73
+
74
+ if self.stable_softmax_2d:
75
+ attn_weights = attn_weights - attn_weights.max()
76
+
77
+ if self.clamp_min_for_underflow:
78
+ attn_weights = torch.clamp(
79
+ attn_weights, min=-50000
80
+ ) # Do not increase -50000, data type half has quite limited range
81
+ if self.clamp_max_for_overflow:
82
+ attn_weights = torch.clamp(
83
+ attn_weights, max=50000
84
+ ) # Do not increase 50000, data type half has quite limited range
85
+
86
+ attn_weights_v = attn_weights.softmax(dim=-1)
87
+ attn_probs_v = F.dropout(attn_weights_v, p=self.dropout, training=self.training)
88
+ attn_output_v = torch.bmm(attn_probs_v, value_l_states)
89
+ if attn_output_v.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
90
+ raise ValueError(
91
+ f"`attn_output_v` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is {attn_output_v.size()}"
92
+ )
93
+
94
+ attn_output_v = attn_output_v.view(bsz, self.num_heads, tgt_len, self.head_dim)
95
+ attn_output_v = attn_output_v.transpose(1, 2)
96
+ attn_output_v = attn_output_v.reshape(bsz, tgt_len, self.embed_dim)
97
+ attn_output_v = self.out_v_proj(attn_output_v)
98
+
99
+ return attn_output_v
100
+
101
+
102
+ # Bi-Direction MHA (text->image, image->text)
103
+ class BiAttentionBlock(nn.Module):
104
+ def __init__(
105
+ self,
106
+ v_dim,
107
+ l_dim,
108
+ embed_dim,
109
+ num_heads,
110
+ dropout=0.1,
111
+ drop_path=0.0,
112
+ cfg=None,
113
+ ):
114
+ """
115
+ Inputs:
116
+ embed_dim - Dimensionality of input and attention feature vectors
117
+ hidden_dim - Dimensionality of hidden layer in feed-forward network
118
+ (usually 2-4x larger than embed_dim)
119
+ num_heads - Number of heads to use in the Multi-Head Attention block
120
+ dropout - Amount of dropout to apply in the feed-forward network
121
+ """
122
+ super(BiAttentionBlock, self).__init__()
123
+
124
+ # pre layer norm
125
+ self.layer_norm_v = nn.LayerNorm(v_dim)
126
+ self.layer_norm_l = nn.LayerNorm(l_dim)
127
+ self.attn = BiMultiHeadAttention(
128
+ v_dim=v_dim, l_dim=l_dim, embed_dim=embed_dim, num_heads=num_heads, dropout=dropout
129
+ )
130
+
131
+ # add layer scale for training stability
132
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
133
+
134
+ def forward(self, v, l, attention_mask_v=None, attention_mask_l=None):
135
+ v = self.layer_norm_v(v)
136
+ l = self.layer_norm_l(l)
137
+ delta_v = self.attn(
138
+ v, l, attention_mask_v=attention_mask_v, attention_mask_l=attention_mask_l
139
+ )
140
+ delta_v = self.drop_path(delta_v)
141
+
142
+ return delta_v
143
+
144
+
llm/added_tokens.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "<|assistant|>": 32001,
3
+ "<|endoftext|>": 32000,
4
+ "<|end|>": 32007,
5
+ "<|placeholder1|>": 32002,
6
+ "<|placeholder2|>": 32003,
7
+ "<|placeholder3|>": 32004,
8
+ "<|placeholder4|>": 32005,
9
+ "<|placeholder5|>": 32008,
10
+ "<|placeholder6|>": 32009,
11
+ "<|system|>": 32006,
12
+ "<|user|>": 32010
13
+ }
llm/config.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/export/share/models/Phi-3-mini-4k-instruct",
3
+ "architectures": [
4
+ "Phi3ForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_phi3.Phi3Config",
9
+ "AutoModelForCausalLM": "modeling_phi3.Phi3ForCausalLM"
10
+ },
11
+ "bos_token_id": 1,
12
+ "embd_pdrop": 0.0,
13
+ "eos_token_id": 32000,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 3072,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 8192,
18
+ "max_position_embeddings": 4096,
19
+ "model_type": "phi3",
20
+ "num_attention_heads": 32,
21
+ "num_hidden_layers": 32,
22
+ "num_key_value_heads": 32,
23
+ "original_max_position_embeddings": 4096,
24
+ "pad_token_id": 32000,
25
+ "resid_pdrop": 0.0,
26
+ "rms_norm_eps": 1e-05,
27
+ "rope_scaling": null,
28
+ "rope_theta": 10000.0,
29
+ "sliding_window": 2047,
30
+ "tie_word_embeddings": false,
31
+ "torch_dtype": "float16",
32
+ "transformers_version": "4.40.2",
33
+ "use_cache": false,
34
+ "vocab_size": 32064
35
+ }
llm/configuration_phi3.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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-3 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
+ PHI3_PRETRAINED_CONFIG_ARCHIVE_MAP = {
26
+ "microsoft/Phi-3-mini-4k-instruct": "https://huggingface.co/microsoft/Phi-3-mini-4k-instruct/resolve/main/config.json",
27
+ "microsoft/Phi-3-mini-128k-instruct": "https://huggingface.co/microsoft/Phi-3-mini-128k-instruct/resolve/main/config.json",
28
+ }
29
+
30
+
31
+ class Phi3Config(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration of a [`Phi3Model`]. It is used to instantiate a Phi-3
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
36
+ [microsoft/Phi-3-mini-4k-instruct](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct).
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 32064):
43
+ Vocabulary size of the Phi-3 model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`Phi3Model`].
45
+ hidden_size (`int`, *optional*, defaults to 3072):
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 32):
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
+ num_key_value_heads (`int`, *optional*):
54
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
55
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
56
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
57
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
58
+ by meanpooling all the original heads within that group. For more details checkout [this
59
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
60
+ `num_attention_heads`.
61
+ resid_pdrop (`float`, *optional*, defaults to 0.0):
62
+ Dropout probability for mlp outputs.
63
+ embd_pdrop (`int`, *optional*, defaults to 0.0):
64
+ The dropout ratio for the embeddings.
65
+ attention_dropout (`float`, *optional*, defaults to 0.0):
66
+ The dropout ratio after computing the attention scores.
67
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
68
+ The non-linear activation function (function or string) in the decoder.
69
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
70
+ The maximum sequence length that this model might ever be used with.
71
+ original_max_position_embeddings (`int`, *optional*, defaults to 4096):
72
+ The maximum sequence length that this model was trained with. This is used to determine the size of the
73
+ original RoPE embeddings when using long scaling.
74
+ initializer_range (`float`, *optional*, defaults to 0.02):
75
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
76
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
77
+ The epsilon value used for the RMSNorm.
78
+ use_cache (`bool`, *optional*, defaults to `True`):
79
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
80
+ relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
81
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
82
+ Whether to tie weight embeddings
83
+ rope_theta (`float`, *optional*, defaults to 10000.0):
84
+ The base period of the RoPE embeddings.
85
+ rope_scaling (`dict`, *optional*):
86
+ The scaling strategy for the RoPE embeddings. If `None`, no scaling is applied. If a dictionary, it must
87
+ contain the following keys: `type`, `short_factor` and `long_factor`. The `type` must be either `su` or `yarn` and
88
+ the `short_factor` and `long_factor` must be lists of numbers with the same length as the hidden size
89
+ divided by the number of attention heads divided by 2.
90
+ bos_token_id (`int`, *optional*, defaults to 1):
91
+ The id of the "beginning-of-sequence" token.
92
+ eos_token_id (`int`, *optional*, defaults to 32000):
93
+ The id of the "end-of-sequence" token.
94
+ pad_token_id (`int`, *optional*, defaults to 32000):
95
+ The id of the padding token.
96
+ sliding_window (`int`, *optional*):
97
+ Sliding window attention window size. If `None`, no sliding window is applied.
98
+
99
+ Example:
100
+
101
+ ```python
102
+ >>> from transformers import Phi3Model, Phi3Config
103
+
104
+ >>> # Initializing a Phi-3 style configuration
105
+ >>> configuration = Phi3Config.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
106
+
107
+ >>> # Initializing a model from the configuration
108
+ >>> model = Phi3Model(configuration)
109
+
110
+ >>> # Accessing the model configuration
111
+ >>> configuration = model.config
112
+ ```"""
113
+
114
+ model_type = "phi3"
115
+ keys_to_ignore_at_inference = ["past_key_values"]
116
+
117
+ def __init__(
118
+ self,
119
+ vocab_size=32064,
120
+ hidden_size=3072,
121
+ intermediate_size=8192,
122
+ num_hidden_layers=32,
123
+ num_attention_heads=32,
124
+ num_key_value_heads=None,
125
+ resid_pdrop=0.0,
126
+ embd_pdrop=0.0,
127
+ attention_dropout=0.0,
128
+ hidden_act="silu",
129
+ max_position_embeddings=4096,
130
+ original_max_position_embeddings=4096,
131
+ initializer_range=0.02,
132
+ rms_norm_eps=1e-5,
133
+ use_cache=True,
134
+ tie_word_embeddings=False,
135
+ rope_theta=10000.0,
136
+ rope_scaling=None,
137
+ bos_token_id=1,
138
+ eos_token_id=32000,
139
+ pad_token_id=32000,
140
+ sliding_window=None,
141
+ **kwargs,
142
+ ):
143
+ self.vocab_size = vocab_size
144
+ self.hidden_size = hidden_size
145
+ self.intermediate_size = intermediate_size
146
+ self.num_hidden_layers = num_hidden_layers
147
+ self.num_attention_heads = num_attention_heads
148
+
149
+ if num_key_value_heads is None:
150
+ num_key_value_heads = num_attention_heads
151
+
152
+ self.num_key_value_heads = num_key_value_heads
153
+ self.resid_pdrop = resid_pdrop
154
+ self.embd_pdrop = embd_pdrop
155
+ self.attention_dropout = attention_dropout
156
+ self.hidden_act = hidden_act
157
+ self.max_position_embeddings = max_position_embeddings
158
+ self.original_max_position_embeddings = original_max_position_embeddings
159
+ self.initializer_range = initializer_range
160
+ self.rms_norm_eps = rms_norm_eps
161
+ self.use_cache = use_cache
162
+ self.rope_theta = rope_theta
163
+ self.rope_scaling = rope_scaling
164
+ self._rope_scaling_validation()
165
+ self.sliding_window = sliding_window
166
+
167
+ super().__init__(
168
+ bos_token_id=bos_token_id,
169
+ eos_token_id=eos_token_id,
170
+ pad_token_id=pad_token_id,
171
+ tie_word_embeddings=tie_word_embeddings,
172
+ **kwargs,
173
+ )
174
+
175
+ def _rope_scaling_validation(self):
176
+ """
177
+ Validate the `rope_scaling` configuration.
178
+ """
179
+ if self.rope_scaling is None:
180
+ return
181
+
182
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 3:
183
+ raise ValueError(
184
+ "`rope_scaling` must be a dictionary with three fields, `type`, `short_factor` and `long_factor`, "
185
+ f"got {self.rope_scaling}"
186
+ )
187
+ rope_scaling_type = self.rope_scaling.get("type", None)
188
+ rope_scaling_short_factor = self.rope_scaling.get("short_factor", None)
189
+ rope_scaling_long_factor = self.rope_scaling.get("long_factor", None)
190
+ if rope_scaling_type is None or rope_scaling_type not in ["su", "yarn"]:
191
+ raise ValueError(f"`rope_scaling`'s type field must be one of ['su', 'yarn'], got {rope_scaling_type}")
192
+ if not (
193
+ isinstance(rope_scaling_short_factor, list)
194
+ and all(isinstance(x, (int, float)) for x in rope_scaling_short_factor)
195
+ ):
196
+ raise ValueError(
197
+ f"`rope_scaling`'s short_factor field must be a list of numbers, got {rope_scaling_short_factor}"
198
+ )
199
+ if not len(rope_scaling_short_factor) == self.hidden_size // self.num_attention_heads // 2:
200
+ raise ValueError(
201
+ f"`rope_scaling`'s short_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_short_factor)}"
202
+ )
203
+ if not (
204
+ isinstance(rope_scaling_long_factor, list)
205
+ and all(isinstance(x, (int, float)) for x in rope_scaling_long_factor)
206
+ ):
207
+ raise ValueError(
208
+ f"`rope_scaling`'s long_factor field must be a list of numbers, got {rope_scaling_long_factor}"
209
+ )
210
+ if not len(rope_scaling_long_factor) == self.hidden_size // self.num_attention_heads // 2:
211
+ raise ValueError(
212
+ f"`rope_scaling`'s long_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_long_factor)}"
213
+ )
llm/generation_config.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": [
5
+ 32000,
6
+ 32001,
7
+ 32007
8
+ ],
9
+ "pad_token_id": 32000,
10
+ "transformers_version": "4.40.2"
11
+ }
llm/model-00001-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fff267b5337f0afb6d0a194b754646c552c292f6aa50b2dece8b4032c70d538f
3
+ size 1958700208
llm/model-00002-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:abf4177ddec03ba8cb104fe9e89b0773b2903fe77b56f03a2358b1e79a878f55
3
+ size 1937885168
llm/model-00003-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7d13c26a0b5563bfcba68769f4677431a73faaf1417c2725548eb73498d9f860
3
+ size 1981925376
llm/model-00004-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:43d22e35874592ff71c95a22b87ed5865dc683bb431ce1c167bd612617e388a0
3
+ size 1763670872
llm/model.safetensors.index.json ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 7642159104
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00004-of-00004.safetensors",
7
+ "model.embed_tokens.weight": "model-00001-of-00004.safetensors",
8
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00004.safetensors",
9
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
10
+ "model.layers.0.mlp.gate_up_proj.weight": "model-00001-of-00004.safetensors",
11
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
12
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
13
+ "model.layers.0.self_attn.qkv_proj.weight": "model-00001-of-00004.safetensors",
14
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00004.safetensors",
15
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
16
+ "model.layers.1.mlp.gate_up_proj.weight": "model-00001-of-00004.safetensors",
17
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
18
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
19
+ "model.layers.1.self_attn.qkv_proj.weight": "model-00001-of-00004.safetensors",
20
+ "model.layers.10.input_layernorm.weight": "model-00002-of-00004.safetensors",
21
+ "model.layers.10.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
22
+ "model.layers.10.mlp.gate_up_proj.weight": "model-00002-of-00004.safetensors",
23
+ "model.layers.10.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
24
+ "model.layers.10.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
25
+ "model.layers.10.self_attn.qkv_proj.weight": "model-00002-of-00004.safetensors",
26
+ "model.layers.11.input_layernorm.weight": "model-00002-of-00004.safetensors",
27
+ "model.layers.11.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
28
+ "model.layers.11.mlp.gate_up_proj.weight": "model-00002-of-00004.safetensors",
29
+ "model.layers.11.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
30
+ "model.layers.11.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
31
+ "model.layers.11.self_attn.qkv_proj.weight": "model-00002-of-00004.safetensors",
32
+ "model.layers.12.input_layernorm.weight": "model-00002-of-00004.safetensors",
33
+ "model.layers.12.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
34
+ "model.layers.12.mlp.gate_up_proj.weight": "model-00002-of-00004.safetensors",
35
+ "model.layers.12.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
36
+ "model.layers.12.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
37
+ "model.layers.12.self_attn.qkv_proj.weight": "model-00002-of-00004.safetensors",
38
+ "model.layers.13.input_layernorm.weight": "model-00002-of-00004.safetensors",
39
+ "model.layers.13.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
40
+ "model.layers.13.mlp.gate_up_proj.weight": "model-00002-of-00004.safetensors",
41
+ "model.layers.13.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
42
+ "model.layers.13.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
43
+ "model.layers.13.self_attn.qkv_proj.weight": "model-00002-of-00004.safetensors",
44
+ "model.layers.14.input_layernorm.weight": "model-00002-of-00004.safetensors",
45
+ "model.layers.14.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
46
+ "model.layers.14.mlp.gate_up_proj.weight": "model-00002-of-00004.safetensors",
47
+ "model.layers.14.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
48
+ "model.layers.14.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
49
+ "model.layers.14.self_attn.qkv_proj.weight": "model-00002-of-00004.safetensors",
50
+ "model.layers.15.input_layernorm.weight": "model-00002-of-00004.safetensors",
51
+ "model.layers.15.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
52
+ "model.layers.15.mlp.gate_up_proj.weight": "model-00002-of-00004.safetensors",
53
+ "model.layers.15.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
54
+ "model.layers.15.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
55
+ "model.layers.15.self_attn.qkv_proj.weight": "model-00002-of-00004.safetensors",
56
+ "model.layers.16.input_layernorm.weight": "model-00003-of-00004.safetensors",
57
+ "model.layers.16.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
58
+ "model.layers.16.mlp.gate_up_proj.weight": "model-00003-of-00004.safetensors",
59
+ "model.layers.16.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
60
+ "model.layers.16.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
61
+ "model.layers.16.self_attn.qkv_proj.weight": "model-00002-of-00004.safetensors",
62
+ "model.layers.17.input_layernorm.weight": "model-00003-of-00004.safetensors",
63
+ "model.layers.17.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
64
+ "model.layers.17.mlp.gate_up_proj.weight": "model-00003-of-00004.safetensors",
65
+ "model.layers.17.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
66
+ "model.layers.17.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
67
+ "model.layers.17.self_attn.qkv_proj.weight": "model-00003-of-00004.safetensors",
68
+ "model.layers.18.input_layernorm.weight": "model-00003-of-00004.safetensors",
69
+ "model.layers.18.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
70
+ "model.layers.18.mlp.gate_up_proj.weight": "model-00003-of-00004.safetensors",
71
+ "model.layers.18.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
72
+ "model.layers.18.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
73
+ "model.layers.18.self_attn.qkv_proj.weight": "model-00003-of-00004.safetensors",
74
+ "model.layers.19.input_layernorm.weight": "model-00003-of-00004.safetensors",
75
+ "model.layers.19.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
76
+ "model.layers.19.mlp.gate_up_proj.weight": "model-00003-of-00004.safetensors",
77
+ "model.layers.19.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
78
+ "model.layers.19.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
79
+ "model.layers.19.self_attn.qkv_proj.weight": "model-00003-of-00004.safetensors",
80
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00004.safetensors",
81
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
82
+ "model.layers.2.mlp.gate_up_proj.weight": "model-00001-of-00004.safetensors",
83
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
84
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
85
+ "model.layers.2.self_attn.qkv_proj.weight": "model-00001-of-00004.safetensors",
86
+ "model.layers.20.input_layernorm.weight": "model-00003-of-00004.safetensors",
87
+ "model.layers.20.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
88
+ "model.layers.20.mlp.gate_up_proj.weight": "model-00003-of-00004.safetensors",
89
+ "model.layers.20.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
90
+ "model.layers.20.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
91
+ "model.layers.20.self_attn.qkv_proj.weight": "model-00003-of-00004.safetensors",
92
+ "model.layers.21.input_layernorm.weight": "model-00003-of-00004.safetensors",
93
+ "model.layers.21.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
94
+ "model.layers.21.mlp.gate_up_proj.weight": "model-00003-of-00004.safetensors",
95
+ "model.layers.21.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
96
+ "model.layers.21.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
97
+ "model.layers.21.self_attn.qkv_proj.weight": "model-00003-of-00004.safetensors",
98
+ "model.layers.22.input_layernorm.weight": "model-00003-of-00004.safetensors",
99
+ "model.layers.22.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
100
+ "model.layers.22.mlp.gate_up_proj.weight": "model-00003-of-00004.safetensors",
101
+ "model.layers.22.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
102
+ "model.layers.22.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
103
+ "model.layers.22.self_attn.qkv_proj.weight": "model-00003-of-00004.safetensors",
104
+ "model.layers.23.input_layernorm.weight": "model-00003-of-00004.safetensors",
105
+ "model.layers.23.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
106
+ "model.layers.23.mlp.gate_up_proj.weight": "model-00003-of-00004.safetensors",
107
+ "model.layers.23.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
108
+ "model.layers.23.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
109
+ "model.layers.23.self_attn.qkv_proj.weight": "model-00003-of-00004.safetensors",
110
+ "model.layers.24.input_layernorm.weight": "model-00003-of-00004.safetensors",
111
+ "model.layers.24.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
112
+ "model.layers.24.mlp.gate_up_proj.weight": "model-00003-of-00004.safetensors",
113
+ "model.layers.24.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
114
+ "model.layers.24.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
115
+ "model.layers.24.self_attn.qkv_proj.weight": "model-00003-of-00004.safetensors",
116
+ "model.layers.25.input_layernorm.weight": "model-00004-of-00004.safetensors",
117
+ "model.layers.25.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
118
+ "model.layers.25.mlp.gate_up_proj.weight": "model-00004-of-00004.safetensors",
119
+ "model.layers.25.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
120
+ "model.layers.25.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
121
+ "model.layers.25.self_attn.qkv_proj.weight": "model-00004-of-00004.safetensors",
122
+ "model.layers.26.input_layernorm.weight": "model-00004-of-00004.safetensors",
123
+ "model.layers.26.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
124
+ "model.layers.26.mlp.gate_up_proj.weight": "model-00004-of-00004.safetensors",
125
+ "model.layers.26.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
126
+ "model.layers.26.self_attn.o_proj.weight": "model-00004-of-00004.safetensors",
127
+ "model.layers.26.self_attn.qkv_proj.weight": "model-00004-of-00004.safetensors",
128
+ "model.layers.27.input_layernorm.weight": "model-00004-of-00004.safetensors",
129
+ "model.layers.27.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
130
+ "model.layers.27.mlp.gate_up_proj.weight": "model-00004-of-00004.safetensors",
131
+ "model.layers.27.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
132
+ "model.layers.27.self_attn.o_proj.weight": "model-00004-of-00004.safetensors",
133
+ "model.layers.27.self_attn.qkv_proj.weight": "model-00004-of-00004.safetensors",
134
+ "model.layers.28.input_layernorm.weight": "model-00004-of-00004.safetensors",
135
+ "model.layers.28.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
136
+ "model.layers.28.mlp.gate_up_proj.weight": "model-00004-of-00004.safetensors",
137
+ "model.layers.28.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
138
+ "model.layers.28.self_attn.o_proj.weight": "model-00004-of-00004.safetensors",
139
+ "model.layers.28.self_attn.qkv_proj.weight": "model-00004-of-00004.safetensors",
140
+ "model.layers.29.input_layernorm.weight": "model-00004-of-00004.safetensors",
141
+ "model.layers.29.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
142
+ "model.layers.29.mlp.gate_up_proj.weight": "model-00004-of-00004.safetensors",
143
+ "model.layers.29.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
144
+ "model.layers.29.self_attn.o_proj.weight": "model-00004-of-00004.safetensors",
145
+ "model.layers.29.self_attn.qkv_proj.weight": "model-00004-of-00004.safetensors",
146
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00004.safetensors",
147
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
148
+ "model.layers.3.mlp.gate_up_proj.weight": "model-00001-of-00004.safetensors",
149
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
150
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
151
+ "model.layers.3.self_attn.qkv_proj.weight": "model-00001-of-00004.safetensors",
152
+ "model.layers.30.input_layernorm.weight": "model-00004-of-00004.safetensors",
153
+ "model.layers.30.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
154
+ "model.layers.30.mlp.gate_up_proj.weight": "model-00004-of-00004.safetensors",
155
+ "model.layers.30.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
156
+ "model.layers.30.self_attn.o_proj.weight": "model-00004-of-00004.safetensors",
157
+ "model.layers.30.self_attn.qkv_proj.weight": "model-00004-of-00004.safetensors",
158
+ "model.layers.31.input_layernorm.weight": "model-00004-of-00004.safetensors",
159
+ "model.layers.31.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
160
+ "model.layers.31.mlp.gate_up_proj.weight": "model-00004-of-00004.safetensors",
161
+ "model.layers.31.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
162
+ "model.layers.31.self_attn.o_proj.weight": "model-00004-of-00004.safetensors",
163
+ "model.layers.31.self_attn.qkv_proj.weight": "model-00004-of-00004.safetensors",
164
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00004.safetensors",
165
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
166
+ "model.layers.4.mlp.gate_up_proj.weight": "model-00001-of-00004.safetensors",
167
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
168
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
169
+ "model.layers.4.self_attn.qkv_proj.weight": "model-00001-of-00004.safetensors",
170
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00004.safetensors",
171
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
172
+ "model.layers.5.mlp.gate_up_proj.weight": "model-00001-of-00004.safetensors",
173
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
174
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
175
+ "model.layers.5.self_attn.qkv_proj.weight": "model-00001-of-00004.safetensors",
176
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00004.safetensors",
177
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
178
+ "model.layers.6.mlp.gate_up_proj.weight": "model-00001-of-00004.safetensors",
179
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
180
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
181
+ "model.layers.6.self_attn.qkv_proj.weight": "model-00001-of-00004.safetensors",
182
+ "model.layers.7.input_layernorm.weight": "model-00002-of-00004.safetensors",
183
+ "model.layers.7.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
184
+ "model.layers.7.mlp.gate_up_proj.weight": "model-00001-of-00004.safetensors",
185
+ "model.layers.7.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
186
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
187
+ "model.layers.7.self_attn.qkv_proj.weight": "model-00001-of-00004.safetensors",
188
+ "model.layers.8.input_layernorm.weight": "model-00002-of-00004.safetensors",
189
+ "model.layers.8.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
190
+ "model.layers.8.mlp.gate_up_proj.weight": "model-00002-of-00004.safetensors",
191
+ "model.layers.8.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
192
+ "model.layers.8.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
193
+ "model.layers.8.self_attn.qkv_proj.weight": "model-00002-of-00004.safetensors",
194
+ "model.layers.9.input_layernorm.weight": "model-00002-of-00004.safetensors",
195
+ "model.layers.9.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
196
+ "model.layers.9.mlp.gate_up_proj.weight": "model-00002-of-00004.safetensors",
197
+ "model.layers.9.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
198
+ "model.layers.9.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
199
+ "model.layers.9.self_attn.qkv_proj.weight": "model-00002-of-00004.safetensors",
200
+ "model.norm.weight": "model-00004-of-00004.safetensors"
201
+ }
202
+ }
llm/modeling_phi3.py ADDED
@@ -0,0 +1,1606 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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-3 model."""
17
+
18
+ import inspect
19
+ import math
20
+ import warnings
21
+ from typing import List, Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.nn.functional as F
25
+ import torch.utils.checkpoint
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.cache_utils import Cache, DynamicCache
31
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
32
+ from transformers.modeling_outputs import (
33
+ BaseModelOutputWithPast,
34
+ CausalLMOutputWithPast,
35
+ SequenceClassifierOutputWithPast,
36
+ TokenClassifierOutput,
37
+ )
38
+ from transformers.modeling_utils import PreTrainedModel
39
+ from transformers.utils import (
40
+ add_code_sample_docstrings,
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ is_flash_attn_2_available,
44
+ is_flash_attn_greater_or_equal_2_10,
45
+ logging,
46
+ replace_return_docstrings,
47
+ )
48
+ from .configuration_phi3 import Phi3Config
49
+
50
+
51
+ logger = logging.get_logger(__name__)
52
+
53
+ # Transformers scans dependencies in the modeling file, causing issues on conditional loading. The regex only ignores try/catch blocks, but not if statements
54
+ # if is_flash_attn_2_available():
55
+ _flash_supports_window_size = False
56
+ try:
57
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
58
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
59
+
60
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
61
+ except ImportError as error:
62
+ logger.warning(
63
+ f"`flash-attention` package not found, consider installing for better performance: {error}."
64
+ )
65
+ if not _flash_supports_window_size:
66
+ logger.warning(
67
+ "Current `flash-attenton` does not support `window_size`. Either upgrade or use `attn_implementation='eager'`."
68
+ )
69
+
70
+ _CHECKPOINT_FOR_DOC = "microsoft/Phi-3-mini-4k-instruct"
71
+ _CONFIG_FOR_DOC = "Phi3Config"
72
+
73
+ PHI3_PRETRAINED_MODEL_ARCHIVE_LIST = [
74
+ "microsoft/Phi-3-mini-4k-instruct",
75
+ "microsoft/Phi-3-mini-128k-instruct",
76
+ # See all Phi-3 models at https://huggingface.co/models?filter=Phi-3
77
+ ]
78
+
79
+
80
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Phi3
81
+ class Phi3RMSNorm(nn.Module):
82
+ def __init__(self, hidden_size, eps=1e-6):
83
+ """
84
+ Phi3RMSNorm is equivalent to T5LayerNorm
85
+ """
86
+ super().__init__()
87
+ self.weight = nn.Parameter(torch.ones(hidden_size))
88
+ self.variance_epsilon = eps
89
+
90
+ def forward(self, hidden_states):
91
+ input_dtype = hidden_states.dtype
92
+ hidden_states = hidden_states.to(torch.float32)
93
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
94
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
95
+ return self.weight * hidden_states.to(input_dtype)
96
+
97
+
98
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
99
+ def _get_unpad_data(attention_mask):
100
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
101
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
102
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
103
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
104
+ return (
105
+ indices,
106
+ cu_seqlens,
107
+ max_seqlen_in_batch,
108
+ )
109
+
110
+
111
+ # Copied from transformers.models.gemma.modeling_gemma.GemmaRotaryEmbedding with gemma->phi3, Gemma->Phi3
112
+ class Phi3RotaryEmbedding(nn.Module):
113
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
114
+ super().__init__()
115
+
116
+ self.dim = dim
117
+ self.max_position_embeddings = max_position_embeddings
118
+ self.base = base
119
+ self.register_buffer("inv_freq", None, persistent=False)
120
+
121
+ @torch.no_grad()
122
+ def forward(self, x, position_ids, seq_len=None):
123
+ # x: [bs, num_attention_heads, seq_len, head_size]
124
+ if self.inv_freq is None:
125
+ self.inv_freq = 1.0 / (
126
+ self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim)
127
+ )
128
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
129
+ position_ids_expanded = position_ids[:, None, :].float()
130
+ # Force float32 since bfloat16 loses precision on long contexts
131
+ # See https://github.com/huggingface/transformers/pull/29285
132
+ device_type = x.device.type
133
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
134
+ with torch.autocast(device_type=device_type, enabled=False):
135
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
136
+ emb = torch.cat((freqs, freqs), dim=-1)
137
+ cos = emb.cos()
138
+ sin = emb.sin()
139
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
140
+
141
+
142
+ class Phi3SuScaledRotaryEmbedding(Phi3RotaryEmbedding):
143
+ def __init__(self, dim, config, device=None):
144
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
145
+
146
+ self.short_factor = config.rope_scaling["short_factor"]
147
+ self.long_factor = config.rope_scaling["long_factor"]
148
+ self.original_max_position_embeddings = config.original_max_position_embeddings
149
+
150
+ @torch.no_grad()
151
+ def forward(self, x, position_ids, seq_len=None):
152
+ seq_len = torch.max(position_ids) + 1
153
+ if seq_len > self.original_max_position_embeddings:
154
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
155
+ else:
156
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
157
+
158
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
159
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
160
+
161
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
162
+ position_ids_expanded = position_ids[:, None, :].float()
163
+
164
+ # Force float32 since bfloat16 loses precision on long contexts
165
+ # See https://github.com/huggingface/transformers/pull/29285
166
+ device_type = x.device.type
167
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
168
+ with torch.autocast(device_type=device_type, enabled=False):
169
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
170
+ emb = torch.cat((freqs, freqs), dim=-1)
171
+
172
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
173
+ if scale <= 1.0:
174
+ scaling_factor = 1.0
175
+ else:
176
+ scaling_factor = math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
177
+
178
+ cos = emb.cos() * scaling_factor
179
+ sin = emb.sin() * scaling_factor
180
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
181
+
182
+
183
+ class Phi3YarnScaledRotaryEmbedding(Phi3RotaryEmbedding):
184
+ def __init__(self, dim, config, device=None):
185
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
186
+
187
+ self.short_factor = config.rope_scaling["short_factor"]
188
+ self.long_factor = config.rope_scaling["long_factor"]
189
+ self.original_max_position_embeddings = config.original_max_position_embeddings
190
+
191
+ @torch.no_grad()
192
+ def forward(self, x, position_ids, seq_len=None):
193
+ seq_len = torch.max(position_ids) + 1
194
+ if seq_len > self.original_max_position_embeddings:
195
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
196
+ else:
197
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
198
+
199
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
200
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
201
+
202
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
203
+ position_ids_expanded = position_ids[:, None, :].float()
204
+
205
+ # Force float32 since bfloat16 loses precision on long contexts
206
+ # See https://github.com/huggingface/transformers/pull/29285
207
+ device_type = x.device.type
208
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
209
+ with torch.autocast(device_type=device_type, enabled=False):
210
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
211
+ emb = torch.cat((freqs, freqs), dim=-1)
212
+
213
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
214
+ if scale <= 1.0:
215
+ scaling_factor = 1.0
216
+ else:
217
+ scaling_factor = 0.1 * math.log(scale) + 1.0
218
+
219
+ cos = emb.cos() * scaling_factor
220
+ sin = emb.sin() * scaling_factor
221
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
222
+
223
+
224
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
225
+ def rotate_half(x):
226
+ """Rotates half the hidden dims of the input."""
227
+ x1 = x[..., : x.shape[-1] // 2]
228
+ x2 = x[..., x.shape[-1] // 2 :]
229
+ return torch.cat((-x2, x1), dim=-1)
230
+
231
+
232
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
233
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
234
+ """Applies Rotary Position Embedding to the query and key tensors.
235
+
236
+ Args:
237
+ q (`torch.Tensor`): The query tensor.
238
+ k (`torch.Tensor`): The key tensor.
239
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
240
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
241
+ position_ids (`torch.Tensor`, *optional*):
242
+ Deprecated and unused.
243
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
244
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
245
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
246
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
247
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
248
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
249
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
250
+ Returns:
251
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
252
+ """
253
+ cos = cos.unsqueeze(unsqueeze_dim)
254
+ sin = sin.unsqueeze(unsqueeze_dim)
255
+ q_embed = (q * cos) + (rotate_half(q) * sin)
256
+ k_embed = (k * cos) + (rotate_half(k) * sin)
257
+ return q_embed, k_embed
258
+
259
+
260
+ class Phi3MLP(nn.Module):
261
+ def __init__(self, config):
262
+ super().__init__()
263
+
264
+ self.config = config
265
+ self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
266
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
267
+
268
+ self.activation_fn = ACT2FN[config.hidden_act]
269
+
270
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
271
+ up_states = self.gate_up_proj(hidden_states)
272
+
273
+ gate, up_states = up_states.chunk(2, dim=-1)
274
+ up_states = up_states * self.activation_fn(gate)
275
+
276
+ return self.down_proj(up_states)
277
+
278
+
279
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
280
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
281
+ """
282
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
283
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
284
+ """
285
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
286
+ if n_rep == 1:
287
+ return hidden_states
288
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
289
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
290
+
291
+
292
+ class Phi3Attention(nn.Module):
293
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
294
+
295
+ def __init__(self, config: Phi3Config, layer_idx: Optional[int] = None):
296
+ super().__init__()
297
+ self.config = config
298
+ self.layer_idx = layer_idx
299
+ if layer_idx is None:
300
+ logger.warning_once(
301
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
302
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
303
+ "when creating this class."
304
+ )
305
+
306
+ self.attention_dropout = config.attention_dropout
307
+ self.hidden_size = config.hidden_size
308
+ self.num_heads = config.num_attention_heads
309
+ self.head_dim = self.hidden_size // self.num_heads
310
+ self.num_key_value_heads = config.num_key_value_heads
311
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
312
+ self.max_position_embeddings = config.max_position_embeddings
313
+ self.original_max_position_embeddings = config.original_max_position_embeddings
314
+ self.rope_theta = config.rope_theta
315
+ self.rope_scaling = config.rope_scaling
316
+ self.is_causal = True
317
+
318
+ if (self.head_dim * self.num_heads) != self.hidden_size:
319
+ raise ValueError(
320
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
321
+ f" and `num_heads`: {self.num_heads})."
322
+ )
323
+
324
+ op_size = self.num_heads * self.head_dim + 2 * (self.num_key_value_heads * self.head_dim)
325
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
326
+ self.qkv_proj = nn.Linear(self.hidden_size, op_size, bias=False)
327
+ self._init_rope()
328
+
329
+ def _init_rope(self):
330
+ if self.rope_scaling is None:
331
+ self.rotary_emb = Phi3RotaryEmbedding(
332
+ self.head_dim,
333
+ max_position_embeddings=self.max_position_embeddings,
334
+ base=self.rope_theta,
335
+ )
336
+ else:
337
+ scaling_type = self.config.rope_scaling["type"]
338
+ if scaling_type == "su":
339
+ self.rotary_emb = Phi3SuScaledRotaryEmbedding(self.head_dim, self.config)
340
+ elif scaling_type == "yarn":
341
+ self.rotary_emb = Phi3YarnScaledRotaryEmbedding(self.head_dim, self.config)
342
+ else:
343
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
344
+
345
+ def forward(
346
+ self,
347
+ hidden_states: torch.Tensor,
348
+ attention_mask: Optional[torch.Tensor] = None,
349
+ position_ids: Optional[torch.LongTensor] = None,
350
+ past_key_value: Optional[Cache] = None,
351
+ output_attentions: bool = False,
352
+ use_cache: bool = False,
353
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
354
+ logger.warning_once("You are not running the flash-attention implementation, expect numerical differences.")
355
+
356
+ bsz, q_len, _ = hidden_states.size()
357
+
358
+ qkv = self.qkv_proj(hidden_states)
359
+ query_pos = self.num_heads * self.head_dim
360
+ query_states = qkv[..., :query_pos]
361
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
362
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
363
+
364
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
365
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
366
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
367
+
368
+ kv_seq_len = key_states.shape[-2]
369
+ if past_key_value is not None:
370
+ if self.layer_idx is None:
371
+ raise ValueError(
372
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
373
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
374
+ "with a layer index."
375
+ )
376
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
377
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
378
+
379
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
380
+
381
+ if past_key_value is not None:
382
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
383
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
384
+
385
+ # repeat k/v heads if n_kv_heads < n_heads
386
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
387
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
388
+
389
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
390
+
391
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
392
+ raise ValueError(
393
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
394
+ f" {attn_weights.size()}"
395
+ )
396
+
397
+ if attention_mask is not None:
398
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
399
+ raise ValueError(
400
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
401
+ )
402
+ attn_weights = attn_weights + attention_mask
403
+
404
+ # upcast attention to fp32
405
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
406
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
407
+
408
+ attn_output = torch.matmul(attn_weights, value_states)
409
+
410
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
411
+ raise ValueError(
412
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
413
+ f" {attn_output.size()}"
414
+ )
415
+
416
+ attn_output = attn_output.transpose(1, 2).contiguous()
417
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
418
+
419
+ attn_output = self.o_proj(attn_output)
420
+
421
+ if not output_attentions:
422
+ attn_weights = None
423
+
424
+ return attn_output, attn_weights, past_key_value
425
+
426
+
427
+ class Phi3FlashAttention2(Phi3Attention):
428
+ """
429
+ Phi-3 flash attention module. This module inherits from `Phi3Attention` as the weights of the module stays
430
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
431
+ flash attention and deal with padding tokens in case the input contains any of them.
432
+ """
433
+
434
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
435
+ def __init__(self, *args, **kwargs):
436
+ super().__init__(*args, **kwargs)
437
+
438
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
439
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
440
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
441
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
442
+
443
+ def forward(
444
+ self,
445
+ hidden_states: torch.Tensor,
446
+ attention_mask: Optional[torch.LongTensor] = None,
447
+ position_ids: Optional[torch.LongTensor] = None,
448
+ past_key_value: Optional[Cache] = None,
449
+ output_attentions: bool = False,
450
+ use_cache: bool = False,
451
+ **kwargs,
452
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
453
+ # Phi3FlashAttention2 attention does not support output_attentions
454
+
455
+ if not _flash_supports_window_size:
456
+ logger.warning_once(
457
+ "The current flash attention version does not support sliding window attention. Please use `attn_implementation='eager'` or upgrade flash-attn library."
458
+ )
459
+ raise ValueError("The current flash attention version does not support sliding window attention.")
460
+
461
+ output_attentions = False
462
+
463
+ if "padding_mask" in kwargs:
464
+ warnings.warn(
465
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
466
+ )
467
+
468
+ # overwrite attention_mask with padding_mask
469
+ attention_mask = kwargs.pop("padding_mask")
470
+
471
+ bsz, q_len, _ = hidden_states.size()
472
+
473
+ qkv = self.qkv_proj(hidden_states)
474
+ query_pos = self.num_heads * self.head_dim
475
+ query_states = qkv[..., :query_pos]
476
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
477
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
478
+
479
+ # Flash attention requires the input to have the shape
480
+ # batch_size x seq_length x head_dim x hidden_dim
481
+ # therefore we just need to keep the original shape
482
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
483
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
484
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
485
+
486
+ kv_seq_len = key_states.shape[-2]
487
+ if past_key_value is not None:
488
+ if self.layer_idx is None:
489
+ raise ValueError(
490
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
491
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
492
+ "with a layer index."
493
+ )
494
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
495
+
496
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
497
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
498
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=rotary_seq_len)
499
+
500
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
501
+
502
+ use_sliding_windows = (
503
+ _flash_supports_window_size
504
+ and getattr(self.config, "sliding_window", None) is not None
505
+ and kv_seq_len > self.config.sliding_window
506
+ )
507
+
508
+ if past_key_value is not None:
509
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
510
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
511
+ if (
512
+ getattr(self.config, "sliding_window", None) is not None
513
+ and kv_seq_len > self.config.sliding_window
514
+ and cache_has_contents
515
+ ):
516
+ slicing_tokens = 1 - self.config.sliding_window
517
+
518
+ past_key = past_key_value[self.layer_idx][0]
519
+ past_value = past_key_value[self.layer_idx][1]
520
+
521
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
522
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
523
+
524
+ if past_key.shape[-2] != self.config.sliding_window - 1:
525
+ raise ValueError(
526
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
527
+ f" {past_key.shape}"
528
+ )
529
+
530
+ if attention_mask is not None:
531
+ attention_mask = attention_mask[:, slicing_tokens:]
532
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
533
+
534
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
535
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
536
+
537
+ # repeat k/v heads if n_kv_heads < n_heads
538
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
539
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
540
+
541
+ attn_dropout = self.attention_dropout if self.training else 0.0
542
+
543
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
544
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
545
+ # cast them back in the correct dtype just to be sure everything works as expected.
546
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
547
+ # in fp32.
548
+
549
+ if query_states.dtype == torch.float32:
550
+ if torch.is_autocast_enabled():
551
+ target_dtype = torch.get_autocast_gpu_dtype()
552
+ # Handle the case where the model is quantized
553
+ elif hasattr(self.config, "_pre_quantization_dtype"):
554
+ target_dtype = self.config._pre_quantization_dtype
555
+ else:
556
+ target_dtype = self.qkv_proj.weight.dtype
557
+
558
+ logger.warning_once(
559
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
560
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
561
+ f" {target_dtype}."
562
+ )
563
+
564
+ query_states = query_states.to(target_dtype)
565
+ key_states = key_states.to(target_dtype)
566
+ value_states = value_states.to(target_dtype)
567
+
568
+ # Reashape to the expected shape for Flash Attention
569
+ query_states = query_states.transpose(1, 2)
570
+ key_states = key_states.transpose(1, 2)
571
+ value_states = value_states.transpose(1, 2)
572
+
573
+ attn_output = self._flash_attention_forward(
574
+ query_states,
575
+ key_states,
576
+ value_states,
577
+ attention_mask,
578
+ q_len,
579
+ dropout=attn_dropout,
580
+ use_sliding_windows=use_sliding_windows,
581
+ )
582
+
583
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
584
+ attn_output = self.o_proj(attn_output)
585
+
586
+ if not output_attentions:
587
+ attn_weights = None
588
+
589
+ return attn_output, attn_weights, past_key_value
590
+
591
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._flash_attention_forward
592
+ def _flash_attention_forward(
593
+ self,
594
+ query_states,
595
+ key_states,
596
+ value_states,
597
+ attention_mask,
598
+ query_length,
599
+ dropout=0.0,
600
+ softmax_scale=None,
601
+ use_sliding_windows=False,
602
+ ):
603
+ """
604
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
605
+ first unpad the input, then computes the attention scores and pad the final attention scores.
606
+
607
+ Args:
608
+ query_states (`torch.Tensor`):
609
+ Input query states to be passed to Flash Attention API
610
+ key_states (`torch.Tensor`):
611
+ Input key states to be passed to Flash Attention API
612
+ value_states (`torch.Tensor`):
613
+ Input value states to be passed to Flash Attention API
614
+ attention_mask (`torch.Tensor`):
615
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
616
+ position of padding tokens and 1 for the position of non-padding tokens.
617
+ dropout (`float`):
618
+ Attention dropout
619
+ softmax_scale (`float`, *optional*):
620
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
621
+ use_sliding_windows (`bool`, *optional*):
622
+ Whether to activate sliding window attention.
623
+ """
624
+ if not self._flash_attn_uses_top_left_mask:
625
+ causal = self.is_causal
626
+ else:
627
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
628
+ causal = self.is_causal and query_length != 1
629
+
630
+ # Contains at least one padding token in the sequence
631
+ if attention_mask is not None:
632
+ batch_size = query_states.shape[0]
633
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
634
+ query_states, key_states, value_states, attention_mask, query_length
635
+ )
636
+
637
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
638
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
639
+
640
+ if not use_sliding_windows:
641
+ attn_output_unpad = flash_attn_varlen_func(
642
+ query_states,
643
+ key_states,
644
+ value_states,
645
+ cu_seqlens_q=cu_seqlens_q,
646
+ cu_seqlens_k=cu_seqlens_k,
647
+ max_seqlen_q=max_seqlen_in_batch_q,
648
+ max_seqlen_k=max_seqlen_in_batch_k,
649
+ dropout_p=dropout,
650
+ softmax_scale=softmax_scale,
651
+ causal=causal,
652
+ )
653
+ else:
654
+ attn_output_unpad = flash_attn_varlen_func(
655
+ query_states,
656
+ key_states,
657
+ value_states,
658
+ cu_seqlens_q=cu_seqlens_q,
659
+ cu_seqlens_k=cu_seqlens_k,
660
+ max_seqlen_q=max_seqlen_in_batch_q,
661
+ max_seqlen_k=max_seqlen_in_batch_k,
662
+ dropout_p=dropout,
663
+ softmax_scale=softmax_scale,
664
+ causal=causal,
665
+ window_size=(self.config.sliding_window, self.config.sliding_window),
666
+ )
667
+
668
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
669
+ else:
670
+ if not use_sliding_windows:
671
+ attn_output = flash_attn_func(
672
+ query_states,
673
+ key_states,
674
+ value_states,
675
+ dropout,
676
+ softmax_scale=softmax_scale,
677
+ causal=causal,
678
+ )
679
+ else:
680
+ attn_output = flash_attn_func(
681
+ query_states,
682
+ key_states,
683
+ value_states,
684
+ dropout,
685
+ softmax_scale=softmax_scale,
686
+ causal=causal,
687
+ window_size=(self.config.sliding_window, self.config.sliding_window),
688
+ )
689
+
690
+ return attn_output
691
+
692
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
693
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
694
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
695
+
696
+ # On the first iteration we need to properly re-create the padding mask
697
+ # by slicing it on the proper place
698
+ if kv_seq_len != attention_mask.shape[-1]:
699
+ attention_mask_num_tokens = attention_mask.shape[-1]
700
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
701
+
702
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
703
+
704
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
705
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
706
+
707
+ if query_length == kv_seq_len:
708
+ query_layer = index_first_axis(
709
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
710
+ )
711
+ cu_seqlens_q = cu_seqlens_k
712
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
713
+ indices_q = indices_k
714
+ elif query_length == 1:
715
+ max_seqlen_in_batch_q = 1
716
+ cu_seqlens_q = torch.arange(
717
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
718
+ ) # There is a memcpy here, that is very bad.
719
+ indices_q = cu_seqlens_q[:-1]
720
+ query_layer = query_layer.squeeze(1)
721
+ else:
722
+ # The -q_len: slice assumes left padding.
723
+ attention_mask = attention_mask[:, -query_length:]
724
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
725
+
726
+ return (
727
+ query_layer,
728
+ key_layer,
729
+ value_layer,
730
+ indices_q,
731
+ (cu_seqlens_q, cu_seqlens_k),
732
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
733
+ )
734
+
735
+
736
+ # copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Phi3
737
+ # TODO @Arthur no longer copied from LLama after static cache
738
+ class Phi3SdpaAttention(Phi3Attention):
739
+ """
740
+ Phi3 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
741
+ `Phi3Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
742
+ SDPA API.
743
+ """
744
+
745
+ # Adapted from Phi3Attention.forward
746
+ def forward(
747
+ self,
748
+ hidden_states: torch.Tensor,
749
+ attention_mask: Optional[torch.Tensor] = None,
750
+ position_ids: Optional[torch.LongTensor] = None,
751
+ past_key_value: Optional[Cache] = None,
752
+ output_attentions: bool = False,
753
+ use_cache: bool = False,
754
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
755
+ if output_attentions:
756
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
757
+ logger.warning_once(
758
+ "Phi3Model is using Phi3SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
759
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
760
+ )
761
+ return super().forward(
762
+ hidden_states=hidden_states,
763
+ attention_mask=attention_mask,
764
+ position_ids=position_ids,
765
+ past_key_value=past_key_value,
766
+ output_attentions=output_attentions,
767
+ use_cache=use_cache,
768
+ )
769
+
770
+ bsz, q_len, _ = hidden_states.size()
771
+
772
+ qkv = self.qkv_proj(hidden_states)
773
+ query_pos = self.num_heads * self.head_dim
774
+ query_states = qkv[..., :query_pos]
775
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
776
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
777
+
778
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
779
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
780
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
781
+
782
+ kv_seq_len = key_states.shape[-2]
783
+ if past_key_value is not None:
784
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
785
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
786
+
787
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
788
+
789
+ if past_key_value is not None:
790
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
791
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
792
+
793
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
794
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
795
+
796
+ if attention_mask is not None:
797
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
798
+ raise ValueError(
799
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
800
+ )
801
+
802
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
803
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
804
+ if query_states.device.type == "cuda" and attention_mask is not None:
805
+ query_states = query_states.contiguous()
806
+ key_states = key_states.contiguous()
807
+ value_states = value_states.contiguous()
808
+
809
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
810
+ query_states,
811
+ key_states,
812
+ value_states,
813
+ attn_mask=attention_mask,
814
+ dropout_p=self.attention_dropout if self.training else 0.0,
815
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
816
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
817
+ )
818
+
819
+ attn_output = attn_output.transpose(1, 2).contiguous()
820
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
821
+
822
+ attn_output = self.o_proj(attn_output)
823
+
824
+ return attn_output, None, past_key_value
825
+
826
+
827
+ PHI3_ATTENTION_CLASSES = {
828
+ "eager": Phi3Attention,
829
+ "flash_attention_2": Phi3FlashAttention2,
830
+ "sdpa": Phi3SdpaAttention,
831
+ }
832
+
833
+
834
+ class Phi3DecoderLayer(nn.Module):
835
+ def __init__(self, config: Phi3Config, layer_idx: int):
836
+ super().__init__()
837
+
838
+ self.config = config
839
+ self.self_attn = PHI3_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
840
+
841
+ self.mlp = Phi3MLP(config)
842
+ self.input_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
843
+
844
+ self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)
845
+ self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)
846
+ self.post_attention_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
847
+
848
+ def forward(
849
+ self,
850
+ hidden_states: torch.Tensor,
851
+ attention_mask: Optional[torch.Tensor] = None,
852
+ position_ids: Optional[torch.LongTensor] = None,
853
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
854
+ output_attentions: Optional[bool] = False,
855
+ use_cache: Optional[bool] = False,
856
+ **kwargs,
857
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
858
+ if "padding_mask" in kwargs:
859
+ warnings.warn(
860
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
861
+ )
862
+ """
863
+ Args:
864
+ hidden_states (`torch.FloatTensor`):
865
+ input to the layer of shape `(batch, seq_len, embed_dim)`
866
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
867
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
868
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
869
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
870
+ `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
871
+ output_attentions (`bool`, *optional*):
872
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
873
+ returned tensors for more detail.
874
+ use_cache (`bool`, *optional*):
875
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
876
+ (see `past_key_values`).
877
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
878
+ """
879
+
880
+ residual = hidden_states
881
+
882
+ hidden_states = self.input_layernorm(hidden_states)
883
+
884
+ # Self Attention
885
+ attn_outputs, self_attn_weights, present_key_value = self.self_attn(
886
+ hidden_states=hidden_states,
887
+ attention_mask=attention_mask,
888
+ position_ids=position_ids,
889
+ past_key_value=past_key_value,
890
+ output_attentions=output_attentions,
891
+ use_cache=use_cache,
892
+ )
893
+
894
+ hidden_states = residual + self.resid_attn_dropout(attn_outputs)
895
+
896
+ residual = hidden_states
897
+ hidden_states = self.post_attention_layernorm(hidden_states)
898
+ hidden_states = self.mlp(hidden_states)
899
+ hidden_states = residual + self.resid_mlp_dropout(hidden_states)
900
+
901
+ outputs = (hidden_states,)
902
+
903
+ if output_attentions:
904
+ outputs += (self_attn_weights,)
905
+
906
+ if use_cache:
907
+ outputs += (present_key_value,)
908
+
909
+ return outputs
910
+
911
+
912
+ PHI3_START_DOCSTRING = r"""
913
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
914
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
915
+ etc.)
916
+
917
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
918
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
919
+ and behavior.
920
+
921
+ Parameters:
922
+ config ([`Phi3Config`]):
923
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
924
+ load the weights associated with the model, only the configuration. Check out the
925
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
926
+ """
927
+
928
+
929
+ @add_start_docstrings(
930
+ "The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
931
+ PHI3_START_DOCSTRING,
932
+ )
933
+ class Phi3PreTrainedModel(PreTrainedModel):
934
+ config_class = Phi3Config
935
+ base_model_prefix = "model"
936
+ supports_gradient_checkpointing = True
937
+ _no_split_modules = ["Phi3DecoderLayer"]
938
+ _skip_keys_device_placement = "past_key_values"
939
+ _supports_flash_attn_2 = True
940
+ _supports_sdpa = False
941
+ _supports_cache_class = True
942
+
943
+ _version = "0.0.5"
944
+
945
+ def _init_weights(self, module):
946
+ std = self.config.initializer_range
947
+ if isinstance(module, nn.Linear):
948
+ module.weight.data.normal_(mean=0.0, std=std)
949
+ if module.bias is not None:
950
+ module.bias.data.zero_()
951
+ elif isinstance(module, nn.Embedding):
952
+ module.weight.data.normal_(mean=0.0, std=std)
953
+ if module.padding_idx is not None:
954
+ module.weight.data[module.padding_idx].zero_()
955
+
956
+
957
+ PHI3_INPUTS_DOCSTRING = r"""
958
+ Args:
959
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
960
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
961
+ it.
962
+
963
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
964
+ [`PreTrainedTokenizer.__call__`] for details.
965
+
966
+ [What are input IDs?](../glossary#input-ids)
967
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
968
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
969
+
970
+ - 1 for tokens that are **not masked**,
971
+ - 0 for tokens that are **masked**.
972
+
973
+ [What are attention masks?](../glossary#attention-mask)
974
+
975
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
976
+ [`PreTrainedTokenizer.__call__`] for details.
977
+
978
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
979
+ `past_key_values`).
980
+
981
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
982
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
983
+ information on the default strategy.
984
+
985
+ - 1 indicates the head is **not masked**,
986
+ - 0 indicates the head is **masked**.
987
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
988
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
989
+ config.n_positions - 1]`.
990
+
991
+ [What are position IDs?](../glossary#position-ids)
992
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
993
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
994
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
995
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
996
+
997
+ Two formats are allowed:
998
+ - a [`~cache_utils.Cache`] instance;
999
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1000
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1001
+ cache format.
1002
+
1003
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1004
+ legacy cache format will be returned.
1005
+
1006
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1007
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1008
+ of shape `(batch_size, sequence_length)`.
1009
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1010
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1011
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1012
+ model's internal embedding lookup matrix.
1013
+ use_cache (`bool`, *optional*):
1014
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1015
+ `past_key_values`).
1016
+ output_attentions (`bool`, *optional*):
1017
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1018
+ tensors for more detail.
1019
+ output_hidden_states (`bool`, *optional*):
1020
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1021
+ more detail.
1022
+ return_dict (`bool`, *optional*):
1023
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1024
+ """
1025
+
1026
+
1027
+ @add_start_docstrings(
1028
+ "The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
1029
+ PHI3_START_DOCSTRING,
1030
+ )
1031
+ class Phi3Model(Phi3PreTrainedModel):
1032
+ """
1033
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Phi3DecoderLayer`]
1034
+
1035
+ Args:
1036
+ config: Phi3Config
1037
+ """
1038
+
1039
+ def __init__(self, config: Phi3Config):
1040
+ super().__init__(config)
1041
+ self.padding_idx = config.pad_token_id
1042
+ self.vocab_size = config.vocab_size
1043
+
1044
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1045
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
1046
+ self.layers = nn.ModuleList(
1047
+ [Phi3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1048
+ )
1049
+ self._attn_implementation = config._attn_implementation
1050
+ self.norm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1051
+
1052
+ self.gradient_checkpointing = False
1053
+ # Initialize weights and apply final processing
1054
+ self.post_init()
1055
+
1056
+ def get_input_embeddings(self):
1057
+ return self.embed_tokens
1058
+
1059
+ def set_input_embeddings(self, value):
1060
+ self.embed_tokens = value
1061
+
1062
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1063
+ def forward(
1064
+ self,
1065
+ input_ids: torch.LongTensor = None,
1066
+ attention_mask: Optional[torch.Tensor] = None,
1067
+ position_ids: Optional[torch.LongTensor] = None,
1068
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1069
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1070
+ use_cache: Optional[bool] = None,
1071
+ output_attentions: Optional[bool] = None,
1072
+ output_hidden_states: Optional[bool] = None,
1073
+ return_dict: Optional[bool] = None,
1074
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1075
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1076
+ output_hidden_states = (
1077
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1078
+ )
1079
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1080
+
1081
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1082
+
1083
+ # retrieve input_ids and inputs_embeds
1084
+ if input_ids is not None and inputs_embeds is not None:
1085
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1086
+ elif input_ids is not None:
1087
+ batch_size, seq_length = input_ids.shape[:2]
1088
+ elif inputs_embeds is not None:
1089
+ batch_size, seq_length = inputs_embeds.shape[:2]
1090
+ else:
1091
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1092
+
1093
+ past_key_values_length = 0
1094
+
1095
+ if self.gradient_checkpointing and self.training:
1096
+ if use_cache:
1097
+ logger.warning_once(
1098
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1099
+ )
1100
+ use_cache = False
1101
+
1102
+ if use_cache:
1103
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1104
+ if use_legacy_cache:
1105
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1106
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1107
+
1108
+ if position_ids is None:
1109
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1110
+ position_ids = torch.arange(
1111
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1112
+ )
1113
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1114
+ else:
1115
+ position_ids = position_ids.view(-1, seq_length).long()
1116
+
1117
+ if inputs_embeds is None:
1118
+ inputs_embeds = self.embed_tokens(input_ids)
1119
+
1120
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1121
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1122
+ if is_padding_right:
1123
+ raise ValueError(
1124
+ "You are attempting to perform batched generation with padding_side='right'"
1125
+ " this may lead to unexpected behaviour for Flash Attention version of Phi3. Make sure to "
1126
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1127
+ )
1128
+
1129
+ if self._attn_implementation == "flash_attention_2":
1130
+ # 2d mask is passed through the layers
1131
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1132
+ else:
1133
+ # 4d mask is passed through the layers
1134
+ attention_mask = _prepare_4d_causal_attention_mask(
1135
+ attention_mask,
1136
+ (batch_size, seq_length),
1137
+ inputs_embeds,
1138
+ past_key_values_length,
1139
+ sliding_window=self.config.sliding_window,
1140
+ )
1141
+
1142
+ hidden_states = inputs_embeds
1143
+
1144
+ # decoder layers
1145
+ all_hidden_states = () if output_hidden_states else None
1146
+ all_self_attns = () if output_attentions else None
1147
+ next_decoder_cache = None
1148
+
1149
+ for decoder_layer in self.layers:
1150
+ if output_hidden_states:
1151
+ all_hidden_states += (hidden_states,)
1152
+
1153
+ if self.gradient_checkpointing and self.training:
1154
+ layer_outputs = self._gradient_checkpointing_func(
1155
+ decoder_layer.__call__,
1156
+ hidden_states,
1157
+ attention_mask,
1158
+ position_ids,
1159
+ past_key_values,
1160
+ output_attentions,
1161
+ use_cache,
1162
+ )
1163
+ else:
1164
+ layer_outputs = decoder_layer(
1165
+ hidden_states,
1166
+ attention_mask=attention_mask,
1167
+ position_ids=position_ids,
1168
+ past_key_value=past_key_values,
1169
+ output_attentions=output_attentions,
1170
+ use_cache=use_cache,
1171
+ )
1172
+
1173
+ hidden_states = layer_outputs[0]
1174
+
1175
+ if use_cache:
1176
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1177
+
1178
+ if output_attentions:
1179
+ all_self_attns += (layer_outputs[1],)
1180
+
1181
+ hidden_states = self.norm(hidden_states)
1182
+
1183
+ # add hidden states from the last decoder layer
1184
+ if output_hidden_states:
1185
+ all_hidden_states += (hidden_states,)
1186
+
1187
+ next_cache = None
1188
+ if use_cache:
1189
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1190
+ if not return_dict:
1191
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1192
+ return BaseModelOutputWithPast(
1193
+ last_hidden_state=hidden_states,
1194
+ past_key_values=next_cache,
1195
+ hidden_states=all_hidden_states,
1196
+ attentions=all_self_attns,
1197
+ )
1198
+
1199
+
1200
+ class Phi3ForCausalLM(Phi3PreTrainedModel):
1201
+ _tied_weights_keys = ["lm_head.weight"]
1202
+
1203
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi3
1204
+ def __init__(self, config):
1205
+ super().__init__(config)
1206
+ self.model = Phi3Model(config)
1207
+ self.vocab_size = config.vocab_size
1208
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1209
+
1210
+ # Initialize weights and apply final processing
1211
+ self.post_init()
1212
+
1213
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
1214
+ def get_input_embeddings(self):
1215
+ return self.model.embed_tokens
1216
+
1217
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
1218
+ def set_input_embeddings(self, value):
1219
+ self.model.embed_tokens = value
1220
+
1221
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
1222
+ def get_output_embeddings(self):
1223
+ return self.lm_head
1224
+
1225
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
1226
+ def set_output_embeddings(self, new_embeddings):
1227
+ self.lm_head = new_embeddings
1228
+
1229
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
1230
+ def set_decoder(self, decoder):
1231
+ self.model = decoder
1232
+
1233
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
1234
+ def get_decoder(self):
1235
+ return self.model
1236
+
1237
+ # Ignore copy
1238
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1239
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1240
+ def forward(
1241
+ self,
1242
+ input_ids: torch.LongTensor = None,
1243
+ attention_mask: Optional[torch.Tensor] = None,
1244
+ position_ids: Optional[torch.LongTensor] = None,
1245
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1246
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1247
+ labels: Optional[torch.LongTensor] = None,
1248
+ use_cache: Optional[bool] = None,
1249
+ output_attentions: Optional[bool] = None,
1250
+ output_hidden_states: Optional[bool] = None,
1251
+ return_dict: Optional[bool] = None,
1252
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1253
+ r"""
1254
+ Args:
1255
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1256
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1257
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1258
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1259
+
1260
+ Returns:
1261
+
1262
+ Example:
1263
+
1264
+ ```python
1265
+ >>> from transformers import AutoTokenizer, Phi3ForCausalLM
1266
+
1267
+ >>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1268
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1269
+
1270
+ >>> prompt = "This is an example script ."
1271
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1272
+
1273
+ >>> # Generate
1274
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1275
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1276
+ 'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
1277
+ ```"""
1278
+
1279
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1280
+ output_hidden_states = (
1281
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1282
+ )
1283
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1284
+
1285
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1286
+ outputs = self.model(
1287
+ input_ids=input_ids,
1288
+ attention_mask=attention_mask,
1289
+ position_ids=position_ids,
1290
+ past_key_values=past_key_values,
1291
+ inputs_embeds=inputs_embeds,
1292
+ use_cache=use_cache,
1293
+ output_attentions=output_attentions,
1294
+ output_hidden_states=output_hidden_states,
1295
+ return_dict=return_dict,
1296
+ )
1297
+
1298
+ hidden_states = outputs[0]
1299
+ logits = self.lm_head(hidden_states)
1300
+ logits = logits.float()
1301
+
1302
+ loss = None
1303
+ if labels is not None:
1304
+ # Shift so that tokens < n predict n
1305
+ shift_logits = logits[..., :-1, :].contiguous()
1306
+ shift_labels = labels[..., 1:].contiguous()
1307
+ # Flatten the tokens
1308
+ loss_fct = CrossEntropyLoss()
1309
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1310
+ shift_labels = shift_labels.view(-1)
1311
+ # Enable model parallelism
1312
+ shift_labels = shift_labels.to(shift_logits.device)
1313
+ loss = loss_fct(shift_logits, shift_labels)
1314
+
1315
+ if not return_dict:
1316
+ output = (logits,) + outputs[1:]
1317
+ return (loss,) + output if loss is not None else output
1318
+
1319
+ return CausalLMOutputWithPast(
1320
+ loss=loss,
1321
+ logits=logits,
1322
+ past_key_values=outputs.past_key_values,
1323
+ hidden_states=outputs.hidden_states,
1324
+ attentions=outputs.attentions,
1325
+ )
1326
+
1327
+ # Copied from transformers.models.persimmon.modeling_persimmon.PersimmonForCausalLM.prepare_inputs_for_generation
1328
+ def prepare_inputs_for_generation(
1329
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1330
+ ):
1331
+ if past_key_values is not None:
1332
+ if isinstance(past_key_values, Cache):
1333
+ cache_length = past_key_values.get_seq_length()
1334
+ past_length = past_key_values.seen_tokens
1335
+ max_cache_length = past_key_values.get_max_length()
1336
+ else:
1337
+ cache_length = past_length = past_key_values[0][0].shape[2]
1338
+ max_cache_length = None
1339
+
1340
+ # Keep only the unprocessed tokens:
1341
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1342
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1343
+ # input)
1344
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1345
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1346
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1347
+ # input_ids based on the past_length.
1348
+ elif past_length < input_ids.shape[1]:
1349
+ input_ids = input_ids[:, past_length:]
1350
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1351
+
1352
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1353
+ if (
1354
+ max_cache_length is not None
1355
+ and attention_mask is not None
1356
+ and cache_length + input_ids.shape[1] > max_cache_length
1357
+ ):
1358
+ attention_mask = attention_mask[:, -max_cache_length:]
1359
+
1360
+ position_ids = kwargs.get("position_ids", None)
1361
+ if attention_mask is not None and position_ids is None:
1362
+ # create position_ids on the fly for batch generation
1363
+ position_ids = attention_mask.long().cumsum(-1) - 1
1364
+ position_ids.masked_fill_(attention_mask == 0, 1)
1365
+ if past_key_values:
1366
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1367
+
1368
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1369
+ if inputs_embeds is not None and past_key_values is None:
1370
+ model_inputs = {"inputs_embeds": inputs_embeds}
1371
+ else:
1372
+ model_inputs = {"input_ids": input_ids}
1373
+
1374
+ model_inputs.update(
1375
+ {
1376
+ "position_ids": position_ids,
1377
+ "past_key_values": past_key_values,
1378
+ "use_cache": kwargs.get("use_cache"),
1379
+ "attention_mask": attention_mask,
1380
+ }
1381
+ )
1382
+ return model_inputs
1383
+
1384
+ @staticmethod
1385
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM._reorder_cache
1386
+ def _reorder_cache(past_key_values, beam_idx):
1387
+ reordered_past = ()
1388
+ for layer_past in past_key_values:
1389
+ reordered_past += (
1390
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1391
+ )
1392
+ return reordered_past
1393
+
1394
+
1395
+ @add_start_docstrings(
1396
+ """
1397
+ The [`Phi3Model`] with a sequence classification head on top (linear layer).
1398
+
1399
+ [`Phi3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1400
+ (e.g. GPT-2) do.
1401
+
1402
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1403
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1404
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1405
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1406
+ each row of the batch).
1407
+ """,
1408
+ PHI3_START_DOCSTRING,
1409
+ )
1410
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Phi3, LLAMA->PHI3, self.transformer->self.model, transformer_outputs->model_outputs
1411
+ class Phi3ForSequenceClassification(Phi3PreTrainedModel):
1412
+ def __init__(self, config):
1413
+ super().__init__(config)
1414
+ self.num_labels = config.num_labels
1415
+ self.model = Phi3Model(config)
1416
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1417
+
1418
+ # Initialize weights and apply final processing
1419
+ self.post_init()
1420
+
1421
+ def get_input_embeddings(self):
1422
+ return self.model.embed_tokens
1423
+
1424
+ def set_input_embeddings(self, value):
1425
+ self.model.embed_tokens = value
1426
+
1427
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1428
+ def forward(
1429
+ self,
1430
+ input_ids: torch.LongTensor = None,
1431
+ attention_mask: Optional[torch.Tensor] = None,
1432
+ position_ids: Optional[torch.LongTensor] = None,
1433
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1434
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1435
+ labels: Optional[torch.LongTensor] = None,
1436
+ use_cache: Optional[bool] = None,
1437
+ output_attentions: Optional[bool] = None,
1438
+ output_hidden_states: Optional[bool] = None,
1439
+ return_dict: Optional[bool] = None,
1440
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1441
+ r"""
1442
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1443
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1444
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1445
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1446
+ """
1447
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1448
+
1449
+ model_outputs = self.model(
1450
+ input_ids,
1451
+ attention_mask=attention_mask,
1452
+ position_ids=position_ids,
1453
+ past_key_values=past_key_values,
1454
+ inputs_embeds=inputs_embeds,
1455
+ use_cache=use_cache,
1456
+ output_attentions=output_attentions,
1457
+ output_hidden_states=output_hidden_states,
1458
+ return_dict=return_dict,
1459
+ )
1460
+ hidden_states = model_outputs[0]
1461
+ logits = self.score(hidden_states)
1462
+
1463
+ if input_ids is not None:
1464
+ batch_size = input_ids.shape[0]
1465
+ else:
1466
+ batch_size = inputs_embeds.shape[0]
1467
+
1468
+ if self.config.pad_token_id is None and batch_size != 1:
1469
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1470
+ if self.config.pad_token_id is None:
1471
+ sequence_lengths = -1
1472
+ else:
1473
+ if input_ids is not None:
1474
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1475
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1476
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1477
+ sequence_lengths = sequence_lengths.to(logits.device)
1478
+ else:
1479
+ sequence_lengths = -1
1480
+
1481
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1482
+
1483
+ loss = None
1484
+ if labels is not None:
1485
+ labels = labels.to(logits.device)
1486
+ if self.config.problem_type is None:
1487
+ if self.num_labels == 1:
1488
+ self.config.problem_type = "regression"
1489
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1490
+ self.config.problem_type = "single_label_classification"
1491
+ else:
1492
+ self.config.problem_type = "multi_label_classification"
1493
+
1494
+ if self.config.problem_type == "regression":
1495
+ loss_fct = MSELoss()
1496
+ if self.num_labels == 1:
1497
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1498
+ else:
1499
+ loss = loss_fct(pooled_logits, labels)
1500
+ elif self.config.problem_type == "single_label_classification":
1501
+ loss_fct = CrossEntropyLoss()
1502
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1503
+ elif self.config.problem_type == "multi_label_classification":
1504
+ loss_fct = BCEWithLogitsLoss()
1505
+ loss = loss_fct(pooled_logits, labels)
1506
+ if not return_dict:
1507
+ output = (pooled_logits,) + model_outputs[1:]
1508
+ return ((loss,) + output) if loss is not None else output
1509
+
1510
+ return SequenceClassifierOutputWithPast(
1511
+ loss=loss,
1512
+ logits=pooled_logits,
1513
+ past_key_values=model_outputs.past_key_values,
1514
+ hidden_states=model_outputs.hidden_states,
1515
+ attentions=model_outputs.attentions,
1516
+ )
1517
+
1518
+
1519
+ @add_start_docstrings(
1520
+ """
1521
+ [`Phi3Model`] with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1522
+ Named-Entity-Recognition (NER) tasks.
1523
+ """,
1524
+ PHI3_START_DOCSTRING,
1525
+ )
1526
+ # Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with Mpt->Phi3,MPT->PHI3,self.transformer->self.model,transformer_outputs->model_outputs
1527
+ class Phi3ForTokenClassification(Phi3PreTrainedModel):
1528
+ def __init__(self, config: Phi3Config):
1529
+ super().__init__(config)
1530
+ self.num_labels = config.num_labels
1531
+
1532
+ self.model = Phi3Model(config)
1533
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1534
+ classifier_dropout = config.classifier_dropout
1535
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1536
+ classifier_dropout = config.hidden_dropout
1537
+ else:
1538
+ classifier_dropout = 0.1
1539
+ self.dropout = nn.Dropout(classifier_dropout)
1540
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1541
+
1542
+ # Initialize weights and apply final processing
1543
+ self.post_init()
1544
+
1545
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1546
+ @add_code_sample_docstrings(
1547
+ checkpoint=_CHECKPOINT_FOR_DOC,
1548
+ output_type=TokenClassifierOutput,
1549
+ config_class=_CONFIG_FOR_DOC,
1550
+ )
1551
+ def forward(
1552
+ self,
1553
+ input_ids: Optional[torch.LongTensor] = None,
1554
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1555
+ attention_mask: Optional[torch.Tensor] = None,
1556
+ inputs_embeds: Optional[torch.Tensor] = None,
1557
+ labels: Optional[torch.Tensor] = None,
1558
+ use_cache: Optional[bool] = None,
1559
+ output_attentions: Optional[bool] = None,
1560
+ output_hidden_states: Optional[bool] = None,
1561
+ return_dict: Optional[bool] = None,
1562
+ **deprecated_arguments,
1563
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1564
+ r"""
1565
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1566
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1567
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1568
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1569
+ """
1570
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1571
+
1572
+ model_outputs = self.model(
1573
+ input_ids,
1574
+ past_key_values=past_key_values,
1575
+ attention_mask=attention_mask,
1576
+ inputs_embeds=inputs_embeds,
1577
+ use_cache=use_cache,
1578
+ output_attentions=output_attentions,
1579
+ output_hidden_states=output_hidden_states,
1580
+ return_dict=return_dict,
1581
+ )
1582
+
1583
+ hidden_states = model_outputs[0]
1584
+ hidden_states = self.dropout(hidden_states)
1585
+ logits = self.classifier(hidden_states)
1586
+
1587
+ loss = None
1588
+ if labels is not None:
1589
+ # move labels to correct device to enable model parallelism
1590
+ labels = labels.to(logits.device)
1591
+ batch_size, seq_length = labels.shape
1592
+ loss_fct = CrossEntropyLoss()
1593
+ loss = loss_fct(
1594
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
1595
+ )
1596
+
1597
+ if not return_dict:
1598
+ output = (logits,) + model_outputs[2:]
1599
+ return ((loss,) + output) if loss is not None else output
1600
+
1601
+ return TokenClassifierOutput(
1602
+ loss=loss,
1603
+ logits=logits,
1604
+ hidden_states=model_outputs.hidden_states,
1605
+ attentions=model_outputs.attentions,
1606
+ )
llm/special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|endoftext|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<|endoftext|>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "unk_token": {
24
+ "content": "<unk>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ }
30
+ }
llm/tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
3
+ size 499723
llm/tokenizer_config.json ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": true,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<unk>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "</s>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": true,
27
+ "single_word": false,
28
+ "special": false
29
+ },
30
+ "32000": {
31
+ "content": "<|endoftext|>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ },
38
+ "32001": {
39
+ "content": "<|assistant|>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": true,
43
+ "single_word": false,
44
+ "special": true
45
+ },
46
+ "32002": {
47
+ "content": "<|placeholder1|>",
48
+ "lstrip": false,
49
+ "normalized": false,
50
+ "rstrip": true,
51
+ "single_word": false,
52
+ "special": true
53
+ },
54
+ "32003": {
55
+ "content": "<|placeholder2|>",
56
+ "lstrip": false,
57
+ "normalized": false,
58
+ "rstrip": true,
59
+ "single_word": false,
60
+ "special": true
61
+ },
62
+ "32004": {
63
+ "content": "<|placeholder3|>",
64
+ "lstrip": false,
65
+ "normalized": false,
66
+ "rstrip": true,
67
+ "single_word": false,
68
+ "special": true
69
+ },
70
+ "32005": {
71
+ "content": "<|placeholder4|>",
72
+ "lstrip": false,
73
+ "normalized": false,
74
+ "rstrip": true,
75
+ "single_word": false,
76
+ "special": true
77
+ },
78
+ "32006": {
79
+ "content": "<|system|>",
80
+ "lstrip": false,
81
+ "normalized": false,
82
+ "rstrip": true,
83
+ "single_word": false,
84
+ "special": true
85
+ },
86
+ "32007": {
87
+ "content": "<|end|>",
88
+ "lstrip": false,
89
+ "normalized": false,
90
+ "rstrip": true,
91
+ "single_word": false,
92
+ "special": true
93
+ },
94
+ "32008": {
95
+ "content": "<|placeholder5|>",
96
+ "lstrip": false,
97
+ "normalized": false,
98
+ "rstrip": true,
99
+ "single_word": false,
100
+ "special": true
101
+ },
102
+ "32009": {
103
+ "content": "<|placeholder6|>",
104
+ "lstrip": false,
105
+ "normalized": false,
106
+ "rstrip": true,
107
+ "single_word": false,
108
+ "special": true
109
+ },
110
+ "32010": {
111
+ "content": "<|user|>",
112
+ "lstrip": false,
113
+ "normalized": false,
114
+ "rstrip": true,
115
+ "single_word": false,
116
+ "special": true
117
+ }
118
+ },
119
+ "bos_token": "<s>",
120
+ "chat_template": "{{ bos_token }}{% for message in messages %}{% if (message['role'] == 'user') %}{{'<|user|>' + '\n' + message['content'] + '<|end|>' + '\n' + '<|assistant|>' + '\n'}}{% elif (message['role'] == 'assistant') %}{{message['content'] + '<|end|>' + '\n'}}{% endif %}{% endfor %}",
121
+ "clean_up_tokenization_spaces": false,
122
+ "eos_token": "<|endoftext|>",
123
+ "legacy": false,
124
+ "model_max_length": 4096,
125
+ "pad_token": "<|endoftext|>",
126
+ "padding_side": "right",
127
+ "sp_model_kwargs": {},
128
+ "spaces_between_special_tokens": false,
129
+ "tokenizer_class": "LlamaTokenizer",
130
+ "unk_token": "<unk>",
131
+ "use_default_system_prompt": false
132
+ }
modeling_phi3.py ADDED
@@ -0,0 +1,1606 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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-3 model."""
17
+
18
+ import inspect
19
+ import math
20
+ import warnings
21
+ from typing import List, Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.nn.functional as F
25
+ import torch.utils.checkpoint
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.cache_utils import Cache, DynamicCache
31
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
32
+ from transformers.modeling_outputs import (
33
+ BaseModelOutputWithPast,
34
+ CausalLMOutputWithPast,
35
+ SequenceClassifierOutputWithPast,
36
+ TokenClassifierOutput,
37
+ )
38
+ from transformers.modeling_utils import PreTrainedModel
39
+ from transformers.utils import (
40
+ add_code_sample_docstrings,
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ is_flash_attn_2_available,
44
+ is_flash_attn_greater_or_equal_2_10,
45
+ logging,
46
+ replace_return_docstrings,
47
+ )
48
+ from .configuration_phi3 import Phi3Config
49
+
50
+
51
+ logger = logging.get_logger(__name__)
52
+
53
+ # Transformers scans dependencies in the modeling file, causing issues on conditional loading. The regex only ignores try/catch blocks, but not if statements
54
+ # if is_flash_attn_2_available():
55
+ _flash_supports_window_size = False
56
+ try:
57
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
58
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
59
+
60
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
61
+ except ImportError as error:
62
+ logger.warning(
63
+ f"`flash-attention` package not found, consider installing for better performance: {error}."
64
+ )
65
+ if not _flash_supports_window_size:
66
+ logger.warning(
67
+ "Current `flash-attenton` does not support `window_size`. Either upgrade or use `attn_implementation='eager'`."
68
+ )
69
+
70
+ _CHECKPOINT_FOR_DOC = "microsoft/Phi-3-mini-4k-instruct"
71
+ _CONFIG_FOR_DOC = "Phi3Config"
72
+
73
+ PHI3_PRETRAINED_MODEL_ARCHIVE_LIST = [
74
+ "microsoft/Phi-3-mini-4k-instruct",
75
+ "microsoft/Phi-3-mini-128k-instruct",
76
+ # See all Phi-3 models at https://huggingface.co/models?filter=Phi-3
77
+ ]
78
+
79
+
80
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Phi3
81
+ class Phi3RMSNorm(nn.Module):
82
+ def __init__(self, hidden_size, eps=1e-6):
83
+ """
84
+ Phi3RMSNorm is equivalent to T5LayerNorm
85
+ """
86
+ super().__init__()
87
+ self.weight = nn.Parameter(torch.ones(hidden_size))
88
+ self.variance_epsilon = eps
89
+
90
+ def forward(self, hidden_states):
91
+ input_dtype = hidden_states.dtype
92
+ hidden_states = hidden_states.to(torch.float32)
93
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
94
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
95
+ return self.weight * hidden_states.to(input_dtype)
96
+
97
+
98
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
99
+ def _get_unpad_data(attention_mask):
100
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
101
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
102
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
103
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
104
+ return (
105
+ indices,
106
+ cu_seqlens,
107
+ max_seqlen_in_batch,
108
+ )
109
+
110
+
111
+ # Copied from transformers.models.gemma.modeling_gemma.GemmaRotaryEmbedding with gemma->phi3, Gemma->Phi3
112
+ class Phi3RotaryEmbedding(nn.Module):
113
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
114
+ super().__init__()
115
+
116
+ self.dim = dim
117
+ self.max_position_embeddings = max_position_embeddings
118
+ self.base = base
119
+ self.register_buffer("inv_freq", None, persistent=False)
120
+
121
+ @torch.no_grad()
122
+ def forward(self, x, position_ids, seq_len=None):
123
+ # x: [bs, num_attention_heads, seq_len, head_size]
124
+ if self.inv_freq is None:
125
+ self.inv_freq = 1.0 / (
126
+ self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim)
127
+ )
128
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
129
+ position_ids_expanded = position_ids[:, None, :].float()
130
+ # Force float32 since bfloat16 loses precision on long contexts
131
+ # See https://github.com/huggingface/transformers/pull/29285
132
+ device_type = x.device.type
133
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
134
+ with torch.autocast(device_type=device_type, enabled=False):
135
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
136
+ emb = torch.cat((freqs, freqs), dim=-1)
137
+ cos = emb.cos()
138
+ sin = emb.sin()
139
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
140
+
141
+
142
+ class Phi3SuScaledRotaryEmbedding(Phi3RotaryEmbedding):
143
+ def __init__(self, dim, config, device=None):
144
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
145
+
146
+ self.short_factor = config.rope_scaling["short_factor"]
147
+ self.long_factor = config.rope_scaling["long_factor"]
148
+ self.original_max_position_embeddings = config.original_max_position_embeddings
149
+
150
+ @torch.no_grad()
151
+ def forward(self, x, position_ids, seq_len=None):
152
+ seq_len = torch.max(position_ids) + 1
153
+ if seq_len > self.original_max_position_embeddings:
154
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
155
+ else:
156
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
157
+
158
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
159
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
160
+
161
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
162
+ position_ids_expanded = position_ids[:, None, :].float()
163
+
164
+ # Force float32 since bfloat16 loses precision on long contexts
165
+ # See https://github.com/huggingface/transformers/pull/29285
166
+ device_type = x.device.type
167
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
168
+ with torch.autocast(device_type=device_type, enabled=False):
169
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
170
+ emb = torch.cat((freqs, freqs), dim=-1)
171
+
172
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
173
+ if scale <= 1.0:
174
+ scaling_factor = 1.0
175
+ else:
176
+ scaling_factor = math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
177
+
178
+ cos = emb.cos() * scaling_factor
179
+ sin = emb.sin() * scaling_factor
180
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
181
+
182
+
183
+ class Phi3YarnScaledRotaryEmbedding(Phi3RotaryEmbedding):
184
+ def __init__(self, dim, config, device=None):
185
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
186
+
187
+ self.short_factor = config.rope_scaling["short_factor"]
188
+ self.long_factor = config.rope_scaling["long_factor"]
189
+ self.original_max_position_embeddings = config.original_max_position_embeddings
190
+
191
+ @torch.no_grad()
192
+ def forward(self, x, position_ids, seq_len=None):
193
+ seq_len = torch.max(position_ids) + 1
194
+ if seq_len > self.original_max_position_embeddings:
195
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
196
+ else:
197
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
198
+
199
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
200
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
201
+
202
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
203
+ position_ids_expanded = position_ids[:, None, :].float()
204
+
205
+ # Force float32 since bfloat16 loses precision on long contexts
206
+ # See https://github.com/huggingface/transformers/pull/29285
207
+ device_type = x.device.type
208
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
209
+ with torch.autocast(device_type=device_type, enabled=False):
210
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
211
+ emb = torch.cat((freqs, freqs), dim=-1)
212
+
213
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
214
+ if scale <= 1.0:
215
+ scaling_factor = 1.0
216
+ else:
217
+ scaling_factor = 0.1 * math.log(scale) + 1.0
218
+
219
+ cos = emb.cos() * scaling_factor
220
+ sin = emb.sin() * scaling_factor
221
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
222
+
223
+
224
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
225
+ def rotate_half(x):
226
+ """Rotates half the hidden dims of the input."""
227
+ x1 = x[..., : x.shape[-1] // 2]
228
+ x2 = x[..., x.shape[-1] // 2 :]
229
+ return torch.cat((-x2, x1), dim=-1)
230
+
231
+
232
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
233
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
234
+ """Applies Rotary Position Embedding to the query and key tensors.
235
+
236
+ Args:
237
+ q (`torch.Tensor`): The query tensor.
238
+ k (`torch.Tensor`): The key tensor.
239
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
240
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
241
+ position_ids (`torch.Tensor`, *optional*):
242
+ Deprecated and unused.
243
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
244
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
245
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
246
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
247
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
248
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
249
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
250
+ Returns:
251
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
252
+ """
253
+ cos = cos.unsqueeze(unsqueeze_dim)
254
+ sin = sin.unsqueeze(unsqueeze_dim)
255
+ q_embed = (q * cos) + (rotate_half(q) * sin)
256
+ k_embed = (k * cos) + (rotate_half(k) * sin)
257
+ return q_embed, k_embed
258
+
259
+
260
+ class Phi3MLP(nn.Module):
261
+ def __init__(self, config):
262
+ super().__init__()
263
+
264
+ self.config = config
265
+ self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
266
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
267
+
268
+ self.activation_fn = ACT2FN[config.hidden_act]
269
+
270
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
271
+ up_states = self.gate_up_proj(hidden_states)
272
+
273
+ gate, up_states = up_states.chunk(2, dim=-1)
274
+ up_states = up_states * self.activation_fn(gate)
275
+
276
+ return self.down_proj(up_states)
277
+
278
+
279
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
280
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
281
+ """
282
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
283
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
284
+ """
285
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
286
+ if n_rep == 1:
287
+ return hidden_states
288
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
289
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
290
+
291
+
292
+ class Phi3Attention(nn.Module):
293
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
294
+
295
+ def __init__(self, config: Phi3Config, layer_idx: Optional[int] = None):
296
+ super().__init__()
297
+ self.config = config
298
+ self.layer_idx = layer_idx
299
+ if layer_idx is None:
300
+ logger.warning_once(
301
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
302
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
303
+ "when creating this class."
304
+ )
305
+
306
+ self.attention_dropout = config.attention_dropout
307
+ self.hidden_size = config.hidden_size
308
+ self.num_heads = config.num_attention_heads
309
+ self.head_dim = self.hidden_size // self.num_heads
310
+ self.num_key_value_heads = config.num_key_value_heads
311
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
312
+ self.max_position_embeddings = config.max_position_embeddings
313
+ self.original_max_position_embeddings = config.original_max_position_embeddings
314
+ self.rope_theta = config.rope_theta
315
+ self.rope_scaling = config.rope_scaling
316
+ self.is_causal = True
317
+
318
+ if (self.head_dim * self.num_heads) != self.hidden_size:
319
+ raise ValueError(
320
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
321
+ f" and `num_heads`: {self.num_heads})."
322
+ )
323
+
324
+ op_size = self.num_heads * self.head_dim + 2 * (self.num_key_value_heads * self.head_dim)
325
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
326
+ self.qkv_proj = nn.Linear(self.hidden_size, op_size, bias=False)
327
+ self._init_rope()
328
+
329
+ def _init_rope(self):
330
+ if self.rope_scaling is None:
331
+ self.rotary_emb = Phi3RotaryEmbedding(
332
+ self.head_dim,
333
+ max_position_embeddings=self.max_position_embeddings,
334
+ base=self.rope_theta,
335
+ )
336
+ else:
337
+ scaling_type = self.config.rope_scaling["type"]
338
+ if scaling_type == "su":
339
+ self.rotary_emb = Phi3SuScaledRotaryEmbedding(self.head_dim, self.config)
340
+ elif scaling_type == "yarn":
341
+ self.rotary_emb = Phi3YarnScaledRotaryEmbedding(self.head_dim, self.config)
342
+ else:
343
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
344
+
345
+ def forward(
346
+ self,
347
+ hidden_states: torch.Tensor,
348
+ attention_mask: Optional[torch.Tensor] = None,
349
+ position_ids: Optional[torch.LongTensor] = None,
350
+ past_key_value: Optional[Cache] = None,
351
+ output_attentions: bool = False,
352
+ use_cache: bool = False,
353
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
354
+ logger.warning_once("You are not running the flash-attention implementation, expect numerical differences.")
355
+
356
+ bsz, q_len, _ = hidden_states.size()
357
+
358
+ qkv = self.qkv_proj(hidden_states)
359
+ query_pos = self.num_heads * self.head_dim
360
+ query_states = qkv[..., :query_pos]
361
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
362
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
363
+
364
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
365
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
366
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
367
+
368
+ kv_seq_len = key_states.shape[-2]
369
+ if past_key_value is not None:
370
+ if self.layer_idx is None:
371
+ raise ValueError(
372
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
373
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
374
+ "with a layer index."
375
+ )
376
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
377
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
378
+
379
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
380
+
381
+ if past_key_value is not None:
382
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
383
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
384
+
385
+ # repeat k/v heads if n_kv_heads < n_heads
386
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
387
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
388
+
389
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
390
+
391
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
392
+ raise ValueError(
393
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
394
+ f" {attn_weights.size()}"
395
+ )
396
+
397
+ if attention_mask is not None:
398
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
399
+ raise ValueError(
400
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
401
+ )
402
+ attn_weights = attn_weights + attention_mask
403
+
404
+ # upcast attention to fp32
405
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
406
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
407
+
408
+ attn_output = torch.matmul(attn_weights, value_states)
409
+
410
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
411
+ raise ValueError(
412
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
413
+ f" {attn_output.size()}"
414
+ )
415
+
416
+ attn_output = attn_output.transpose(1, 2).contiguous()
417
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
418
+
419
+ attn_output = self.o_proj(attn_output)
420
+
421
+ if not output_attentions:
422
+ attn_weights = None
423
+
424
+ return attn_output, attn_weights, past_key_value
425
+
426
+
427
+ class Phi3FlashAttention2(Phi3Attention):
428
+ """
429
+ Phi-3 flash attention module. This module inherits from `Phi3Attention` as the weights of the module stays
430
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
431
+ flash attention and deal with padding tokens in case the input contains any of them.
432
+ """
433
+
434
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
435
+ def __init__(self, *args, **kwargs):
436
+ super().__init__(*args, **kwargs)
437
+
438
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
439
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
440
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
441
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
442
+
443
+ def forward(
444
+ self,
445
+ hidden_states: torch.Tensor,
446
+ attention_mask: Optional[torch.LongTensor] = None,
447
+ position_ids: Optional[torch.LongTensor] = None,
448
+ past_key_value: Optional[Cache] = None,
449
+ output_attentions: bool = False,
450
+ use_cache: bool = False,
451
+ **kwargs,
452
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
453
+ # Phi3FlashAttention2 attention does not support output_attentions
454
+
455
+ if not _flash_supports_window_size:
456
+ logger.warning_once(
457
+ "The current flash attention version does not support sliding window attention. Please use `attn_implementation='eager'` or upgrade flash-attn library."
458
+ )
459
+ raise ValueError("The current flash attention version does not support sliding window attention.")
460
+
461
+ output_attentions = False
462
+
463
+ if "padding_mask" in kwargs:
464
+ warnings.warn(
465
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
466
+ )
467
+
468
+ # overwrite attention_mask with padding_mask
469
+ attention_mask = kwargs.pop("padding_mask")
470
+
471
+ bsz, q_len, _ = hidden_states.size()
472
+
473
+ qkv = self.qkv_proj(hidden_states)
474
+ query_pos = self.num_heads * self.head_dim
475
+ query_states = qkv[..., :query_pos]
476
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
477
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
478
+
479
+ # Flash attention requires the input to have the shape
480
+ # batch_size x seq_length x head_dim x hidden_dim
481
+ # therefore we just need to keep the original shape
482
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
483
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
484
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
485
+
486
+ kv_seq_len = key_states.shape[-2]
487
+ if past_key_value is not None:
488
+ if self.layer_idx is None:
489
+ raise ValueError(
490
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
491
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
492
+ "with a layer index."
493
+ )
494
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
495
+
496
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
497
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
498
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=rotary_seq_len)
499
+
500
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
501
+
502
+ use_sliding_windows = (
503
+ _flash_supports_window_size
504
+ and getattr(self.config, "sliding_window", None) is not None
505
+ and kv_seq_len > self.config.sliding_window
506
+ )
507
+
508
+ if past_key_value is not None:
509
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
510
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
511
+ if (
512
+ getattr(self.config, "sliding_window", None) is not None
513
+ and kv_seq_len > self.config.sliding_window
514
+ and cache_has_contents
515
+ ):
516
+ slicing_tokens = 1 - self.config.sliding_window
517
+
518
+ past_key = past_key_value[self.layer_idx][0]
519
+ past_value = past_key_value[self.layer_idx][1]
520
+
521
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
522
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
523
+
524
+ if past_key.shape[-2] != self.config.sliding_window - 1:
525
+ raise ValueError(
526
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
527
+ f" {past_key.shape}"
528
+ )
529
+
530
+ if attention_mask is not None:
531
+ attention_mask = attention_mask[:, slicing_tokens:]
532
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
533
+
534
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
535
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
536
+
537
+ # repeat k/v heads if n_kv_heads < n_heads
538
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
539
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
540
+
541
+ attn_dropout = self.attention_dropout if self.training else 0.0
542
+
543
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
544
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
545
+ # cast them back in the correct dtype just to be sure everything works as expected.
546
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
547
+ # in fp32.
548
+
549
+ if query_states.dtype == torch.float32:
550
+ if torch.is_autocast_enabled():
551
+ target_dtype = torch.get_autocast_gpu_dtype()
552
+ # Handle the case where the model is quantized
553
+ elif hasattr(self.config, "_pre_quantization_dtype"):
554
+ target_dtype = self.config._pre_quantization_dtype
555
+ else:
556
+ target_dtype = self.qkv_proj.weight.dtype
557
+
558
+ logger.warning_once(
559
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
560
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
561
+ f" {target_dtype}."
562
+ )
563
+
564
+ query_states = query_states.to(target_dtype)
565
+ key_states = key_states.to(target_dtype)
566
+ value_states = value_states.to(target_dtype)
567
+
568
+ # Reashape to the expected shape for Flash Attention
569
+ query_states = query_states.transpose(1, 2)
570
+ key_states = key_states.transpose(1, 2)
571
+ value_states = value_states.transpose(1, 2)
572
+
573
+ attn_output = self._flash_attention_forward(
574
+ query_states,
575
+ key_states,
576
+ value_states,
577
+ attention_mask,
578
+ q_len,
579
+ dropout=attn_dropout,
580
+ use_sliding_windows=use_sliding_windows,
581
+ )
582
+
583
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
584
+ attn_output = self.o_proj(attn_output)
585
+
586
+ if not output_attentions:
587
+ attn_weights = None
588
+
589
+ return attn_output, attn_weights, past_key_value
590
+
591
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._flash_attention_forward
592
+ def _flash_attention_forward(
593
+ self,
594
+ query_states,
595
+ key_states,
596
+ value_states,
597
+ attention_mask,
598
+ query_length,
599
+ dropout=0.0,
600
+ softmax_scale=None,
601
+ use_sliding_windows=False,
602
+ ):
603
+ """
604
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
605
+ first unpad the input, then computes the attention scores and pad the final attention scores.
606
+
607
+ Args:
608
+ query_states (`torch.Tensor`):
609
+ Input query states to be passed to Flash Attention API
610
+ key_states (`torch.Tensor`):
611
+ Input key states to be passed to Flash Attention API
612
+ value_states (`torch.Tensor`):
613
+ Input value states to be passed to Flash Attention API
614
+ attention_mask (`torch.Tensor`):
615
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
616
+ position of padding tokens and 1 for the position of non-padding tokens.
617
+ dropout (`float`):
618
+ Attention dropout
619
+ softmax_scale (`float`, *optional*):
620
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
621
+ use_sliding_windows (`bool`, *optional*):
622
+ Whether to activate sliding window attention.
623
+ """
624
+ if not self._flash_attn_uses_top_left_mask:
625
+ causal = self.is_causal
626
+ else:
627
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
628
+ causal = self.is_causal and query_length != 1
629
+
630
+ # Contains at least one padding token in the sequence
631
+ if attention_mask is not None:
632
+ batch_size = query_states.shape[0]
633
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
634
+ query_states, key_states, value_states, attention_mask, query_length
635
+ )
636
+
637
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
638
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
639
+
640
+ if not use_sliding_windows:
641
+ attn_output_unpad = flash_attn_varlen_func(
642
+ query_states,
643
+ key_states,
644
+ value_states,
645
+ cu_seqlens_q=cu_seqlens_q,
646
+ cu_seqlens_k=cu_seqlens_k,
647
+ max_seqlen_q=max_seqlen_in_batch_q,
648
+ max_seqlen_k=max_seqlen_in_batch_k,
649
+ dropout_p=dropout,
650
+ softmax_scale=softmax_scale,
651
+ causal=causal,
652
+ )
653
+ else:
654
+ attn_output_unpad = flash_attn_varlen_func(
655
+ query_states,
656
+ key_states,
657
+ value_states,
658
+ cu_seqlens_q=cu_seqlens_q,
659
+ cu_seqlens_k=cu_seqlens_k,
660
+ max_seqlen_q=max_seqlen_in_batch_q,
661
+ max_seqlen_k=max_seqlen_in_batch_k,
662
+ dropout_p=dropout,
663
+ softmax_scale=softmax_scale,
664
+ causal=causal,
665
+ window_size=(self.config.sliding_window, self.config.sliding_window),
666
+ )
667
+
668
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
669
+ else:
670
+ if not use_sliding_windows:
671
+ attn_output = flash_attn_func(
672
+ query_states,
673
+ key_states,
674
+ value_states,
675
+ dropout,
676
+ softmax_scale=softmax_scale,
677
+ causal=causal,
678
+ )
679
+ else:
680
+ attn_output = flash_attn_func(
681
+ query_states,
682
+ key_states,
683
+ value_states,
684
+ dropout,
685
+ softmax_scale=softmax_scale,
686
+ causal=causal,
687
+ window_size=(self.config.sliding_window, self.config.sliding_window),
688
+ )
689
+
690
+ return attn_output
691
+
692
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
693
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
694
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
695
+
696
+ # On the first iteration we need to properly re-create the padding mask
697
+ # by slicing it on the proper place
698
+ if kv_seq_len != attention_mask.shape[-1]:
699
+ attention_mask_num_tokens = attention_mask.shape[-1]
700
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
701
+
702
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
703
+
704
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
705
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
706
+
707
+ if query_length == kv_seq_len:
708
+ query_layer = index_first_axis(
709
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
710
+ )
711
+ cu_seqlens_q = cu_seqlens_k
712
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
713
+ indices_q = indices_k
714
+ elif query_length == 1:
715
+ max_seqlen_in_batch_q = 1
716
+ cu_seqlens_q = torch.arange(
717
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
718
+ ) # There is a memcpy here, that is very bad.
719
+ indices_q = cu_seqlens_q[:-1]
720
+ query_layer = query_layer.squeeze(1)
721
+ else:
722
+ # The -q_len: slice assumes left padding.
723
+ attention_mask = attention_mask[:, -query_length:]
724
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
725
+
726
+ return (
727
+ query_layer,
728
+ key_layer,
729
+ value_layer,
730
+ indices_q,
731
+ (cu_seqlens_q, cu_seqlens_k),
732
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
733
+ )
734
+
735
+
736
+ # copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Phi3
737
+ # TODO @Arthur no longer copied from LLama after static cache
738
+ class Phi3SdpaAttention(Phi3Attention):
739
+ """
740
+ Phi3 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
741
+ `Phi3Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
742
+ SDPA API.
743
+ """
744
+
745
+ # Adapted from Phi3Attention.forward
746
+ def forward(
747
+ self,
748
+ hidden_states: torch.Tensor,
749
+ attention_mask: Optional[torch.Tensor] = None,
750
+ position_ids: Optional[torch.LongTensor] = None,
751
+ past_key_value: Optional[Cache] = None,
752
+ output_attentions: bool = False,
753
+ use_cache: bool = False,
754
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
755
+ if output_attentions:
756
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
757
+ logger.warning_once(
758
+ "Phi3Model is using Phi3SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
759
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
760
+ )
761
+ return super().forward(
762
+ hidden_states=hidden_states,
763
+ attention_mask=attention_mask,
764
+ position_ids=position_ids,
765
+ past_key_value=past_key_value,
766
+ output_attentions=output_attentions,
767
+ use_cache=use_cache,
768
+ )
769
+
770
+ bsz, q_len, _ = hidden_states.size()
771
+
772
+ qkv = self.qkv_proj(hidden_states)
773
+ query_pos = self.num_heads * self.head_dim
774
+ query_states = qkv[..., :query_pos]
775
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
776
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
777
+
778
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
779
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
780
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
781
+
782
+ kv_seq_len = key_states.shape[-2]
783
+ if past_key_value is not None:
784
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
785
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
786
+
787
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
788
+
789
+ if past_key_value is not None:
790
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
791
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
792
+
793
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
794
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
795
+
796
+ if attention_mask is not None:
797
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
798
+ raise ValueError(
799
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
800
+ )
801
+
802
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
803
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
804
+ if query_states.device.type == "cuda" and attention_mask is not None:
805
+ query_states = query_states.contiguous()
806
+ key_states = key_states.contiguous()
807
+ value_states = value_states.contiguous()
808
+
809
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
810
+ query_states,
811
+ key_states,
812
+ value_states,
813
+ attn_mask=attention_mask,
814
+ dropout_p=self.attention_dropout if self.training else 0.0,
815
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
816
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
817
+ )
818
+
819
+ attn_output = attn_output.transpose(1, 2).contiguous()
820
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
821
+
822
+ attn_output = self.o_proj(attn_output)
823
+
824
+ return attn_output, None, past_key_value
825
+
826
+
827
+ PHI3_ATTENTION_CLASSES = {
828
+ "eager": Phi3Attention,
829
+ "flash_attention_2": Phi3FlashAttention2,
830
+ "sdpa": Phi3SdpaAttention,
831
+ }
832
+
833
+
834
+ class Phi3DecoderLayer(nn.Module):
835
+ def __init__(self, config: Phi3Config, layer_idx: int):
836
+ super().__init__()
837
+
838
+ self.config = config
839
+ self.self_attn = PHI3_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
840
+
841
+ self.mlp = Phi3MLP(config)
842
+ self.input_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
843
+
844
+ self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)
845
+ self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)
846
+ self.post_attention_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
847
+
848
+ def forward(
849
+ self,
850
+ hidden_states: torch.Tensor,
851
+ attention_mask: Optional[torch.Tensor] = None,
852
+ position_ids: Optional[torch.LongTensor] = None,
853
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
854
+ output_attentions: Optional[bool] = False,
855
+ use_cache: Optional[bool] = False,
856
+ **kwargs,
857
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
858
+ if "padding_mask" in kwargs:
859
+ warnings.warn(
860
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
861
+ )
862
+ """
863
+ Args:
864
+ hidden_states (`torch.FloatTensor`):
865
+ input to the layer of shape `(batch, seq_len, embed_dim)`
866
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
867
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
868
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
869
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
870
+ `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
871
+ output_attentions (`bool`, *optional*):
872
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
873
+ returned tensors for more detail.
874
+ use_cache (`bool`, *optional*):
875
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
876
+ (see `past_key_values`).
877
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
878
+ """
879
+
880
+ residual = hidden_states
881
+
882
+ hidden_states = self.input_layernorm(hidden_states)
883
+
884
+ # Self Attention
885
+ attn_outputs, self_attn_weights, present_key_value = self.self_attn(
886
+ hidden_states=hidden_states,
887
+ attention_mask=attention_mask,
888
+ position_ids=position_ids,
889
+ past_key_value=past_key_value,
890
+ output_attentions=output_attentions,
891
+ use_cache=use_cache,
892
+ )
893
+
894
+ hidden_states = residual + self.resid_attn_dropout(attn_outputs)
895
+
896
+ residual = hidden_states
897
+ hidden_states = self.post_attention_layernorm(hidden_states)
898
+ hidden_states = self.mlp(hidden_states)
899
+ hidden_states = residual + self.resid_mlp_dropout(hidden_states)
900
+
901
+ outputs = (hidden_states,)
902
+
903
+ if output_attentions:
904
+ outputs += (self_attn_weights,)
905
+
906
+ if use_cache:
907
+ outputs += (present_key_value,)
908
+
909
+ return outputs
910
+
911
+
912
+ PHI3_START_DOCSTRING = r"""
913
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
914
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
915
+ etc.)
916
+
917
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
918
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
919
+ and behavior.
920
+
921
+ Parameters:
922
+ config ([`Phi3Config`]):
923
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
924
+ load the weights associated with the model, only the configuration. Check out the
925
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
926
+ """
927
+
928
+
929
+ @add_start_docstrings(
930
+ "The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
931
+ PHI3_START_DOCSTRING,
932
+ )
933
+ class Phi3PreTrainedModel(PreTrainedModel):
934
+ config_class = Phi3Config
935
+ base_model_prefix = "model"
936
+ supports_gradient_checkpointing = True
937
+ _no_split_modules = ["Phi3DecoderLayer"]
938
+ _skip_keys_device_placement = "past_key_values"
939
+ _supports_flash_attn_2 = True
940
+ _supports_sdpa = False
941
+ _supports_cache_class = True
942
+
943
+ _version = "0.0.5"
944
+
945
+ def _init_weights(self, module):
946
+ std = self.config.initializer_range
947
+ if isinstance(module, nn.Linear):
948
+ module.weight.data.normal_(mean=0.0, std=std)
949
+ if module.bias is not None:
950
+ module.bias.data.zero_()
951
+ elif isinstance(module, nn.Embedding):
952
+ module.weight.data.normal_(mean=0.0, std=std)
953
+ if module.padding_idx is not None:
954
+ module.weight.data[module.padding_idx].zero_()
955
+
956
+
957
+ PHI3_INPUTS_DOCSTRING = r"""
958
+ Args:
959
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
960
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
961
+ it.
962
+
963
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
964
+ [`PreTrainedTokenizer.__call__`] for details.
965
+
966
+ [What are input IDs?](../glossary#input-ids)
967
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
968
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
969
+
970
+ - 1 for tokens that are **not masked**,
971
+ - 0 for tokens that are **masked**.
972
+
973
+ [What are attention masks?](../glossary#attention-mask)
974
+
975
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
976
+ [`PreTrainedTokenizer.__call__`] for details.
977
+
978
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
979
+ `past_key_values`).
980
+
981
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
982
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
983
+ information on the default strategy.
984
+
985
+ - 1 indicates the head is **not masked**,
986
+ - 0 indicates the head is **masked**.
987
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
988
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
989
+ config.n_positions - 1]`.
990
+
991
+ [What are position IDs?](../glossary#position-ids)
992
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
993
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
994
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
995
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
996
+
997
+ Two formats are allowed:
998
+ - a [`~cache_utils.Cache`] instance;
999
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1000
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1001
+ cache format.
1002
+
1003
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1004
+ legacy cache format will be returned.
1005
+
1006
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1007
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1008
+ of shape `(batch_size, sequence_length)`.
1009
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1010
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1011
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1012
+ model's internal embedding lookup matrix.
1013
+ use_cache (`bool`, *optional*):
1014
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1015
+ `past_key_values`).
1016
+ output_attentions (`bool`, *optional*):
1017
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1018
+ tensors for more detail.
1019
+ output_hidden_states (`bool`, *optional*):
1020
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1021
+ more detail.
1022
+ return_dict (`bool`, *optional*):
1023
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1024
+ """
1025
+
1026
+
1027
+ @add_start_docstrings(
1028
+ "The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
1029
+ PHI3_START_DOCSTRING,
1030
+ )
1031
+ class Phi3Model(Phi3PreTrainedModel):
1032
+ """
1033
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Phi3DecoderLayer`]
1034
+
1035
+ Args:
1036
+ config: Phi3Config
1037
+ """
1038
+
1039
+ def __init__(self, config: Phi3Config):
1040
+ super().__init__(config)
1041
+ self.padding_idx = config.pad_token_id
1042
+ self.vocab_size = config.vocab_size
1043
+
1044
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1045
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
1046
+ self.layers = nn.ModuleList(
1047
+ [Phi3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1048
+ )
1049
+ self._attn_implementation = config._attn_implementation
1050
+ self.norm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1051
+
1052
+ self.gradient_checkpointing = False
1053
+ # Initialize weights and apply final processing
1054
+ self.post_init()
1055
+
1056
+ def get_input_embeddings(self):
1057
+ return self.embed_tokens
1058
+
1059
+ def set_input_embeddings(self, value):
1060
+ self.embed_tokens = value
1061
+
1062
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1063
+ def forward(
1064
+ self,
1065
+ input_ids: torch.LongTensor = None,
1066
+ attention_mask: Optional[torch.Tensor] = None,
1067
+ position_ids: Optional[torch.LongTensor] = None,
1068
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1069
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1070
+ use_cache: Optional[bool] = None,
1071
+ output_attentions: Optional[bool] = None,
1072
+ output_hidden_states: Optional[bool] = None,
1073
+ return_dict: Optional[bool] = None,
1074
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1075
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1076
+ output_hidden_states = (
1077
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1078
+ )
1079
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1080
+
1081
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1082
+
1083
+ # retrieve input_ids and inputs_embeds
1084
+ if input_ids is not None and inputs_embeds is not None:
1085
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1086
+ elif input_ids is not None:
1087
+ batch_size, seq_length = input_ids.shape[:2]
1088
+ elif inputs_embeds is not None:
1089
+ batch_size, seq_length = inputs_embeds.shape[:2]
1090
+ else:
1091
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1092
+
1093
+ past_key_values_length = 0
1094
+
1095
+ if self.gradient_checkpointing and self.training:
1096
+ if use_cache:
1097
+ logger.warning_once(
1098
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1099
+ )
1100
+ use_cache = False
1101
+
1102
+ if use_cache:
1103
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1104
+ if use_legacy_cache:
1105
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1106
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1107
+
1108
+ if position_ids is None:
1109
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1110
+ position_ids = torch.arange(
1111
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1112
+ )
1113
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1114
+ else:
1115
+ position_ids = position_ids.view(-1, seq_length).long()
1116
+
1117
+ if inputs_embeds is None:
1118
+ inputs_embeds = self.embed_tokens(input_ids)
1119
+
1120
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1121
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1122
+ if is_padding_right:
1123
+ raise ValueError(
1124
+ "You are attempting to perform batched generation with padding_side='right'"
1125
+ " this may lead to unexpected behaviour for Flash Attention version of Phi3. Make sure to "
1126
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1127
+ )
1128
+
1129
+ if self._attn_implementation == "flash_attention_2":
1130
+ # 2d mask is passed through the layers
1131
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1132
+ else:
1133
+ # 4d mask is passed through the layers
1134
+ attention_mask = _prepare_4d_causal_attention_mask(
1135
+ attention_mask,
1136
+ (batch_size, seq_length),
1137
+ inputs_embeds,
1138
+ past_key_values_length,
1139
+ sliding_window=self.config.sliding_window,
1140
+ )
1141
+
1142
+ hidden_states = inputs_embeds
1143
+
1144
+ # decoder layers
1145
+ all_hidden_states = () if output_hidden_states else None
1146
+ all_self_attns = () if output_attentions else None
1147
+ next_decoder_cache = None
1148
+
1149
+ for decoder_layer in self.layers:
1150
+ if output_hidden_states:
1151
+ all_hidden_states += (hidden_states,)
1152
+
1153
+ if self.gradient_checkpointing and self.training:
1154
+ layer_outputs = self._gradient_checkpointing_func(
1155
+ decoder_layer.__call__,
1156
+ hidden_states,
1157
+ attention_mask,
1158
+ position_ids,
1159
+ past_key_values,
1160
+ output_attentions,
1161
+ use_cache,
1162
+ )
1163
+ else:
1164
+ layer_outputs = decoder_layer(
1165
+ hidden_states,
1166
+ attention_mask=attention_mask,
1167
+ position_ids=position_ids,
1168
+ past_key_value=past_key_values,
1169
+ output_attentions=output_attentions,
1170
+ use_cache=use_cache,
1171
+ )
1172
+
1173
+ hidden_states = layer_outputs[0]
1174
+
1175
+ if use_cache:
1176
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1177
+
1178
+ if output_attentions:
1179
+ all_self_attns += (layer_outputs[1],)
1180
+
1181
+ hidden_states = self.norm(hidden_states)
1182
+
1183
+ # add hidden states from the last decoder layer
1184
+ if output_hidden_states:
1185
+ all_hidden_states += (hidden_states,)
1186
+
1187
+ next_cache = None
1188
+ if use_cache:
1189
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1190
+ if not return_dict:
1191
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1192
+ return BaseModelOutputWithPast(
1193
+ last_hidden_state=hidden_states,
1194
+ past_key_values=next_cache,
1195
+ hidden_states=all_hidden_states,
1196
+ attentions=all_self_attns,
1197
+ )
1198
+
1199
+
1200
+ class Phi3ForCausalLM(Phi3PreTrainedModel):
1201
+ _tied_weights_keys = ["lm_head.weight"]
1202
+
1203
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi3
1204
+ def __init__(self, config):
1205
+ super().__init__(config)
1206
+ self.model = Phi3Model(config)
1207
+ self.vocab_size = config.vocab_size
1208
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1209
+
1210
+ # Initialize weights and apply final processing
1211
+ self.post_init()
1212
+
1213
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
1214
+ def get_input_embeddings(self):
1215
+ return self.model.embed_tokens
1216
+
1217
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
1218
+ def set_input_embeddings(self, value):
1219
+ self.model.embed_tokens = value
1220
+
1221
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
1222
+ def get_output_embeddings(self):
1223
+ return self.lm_head
1224
+
1225
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
1226
+ def set_output_embeddings(self, new_embeddings):
1227
+ self.lm_head = new_embeddings
1228
+
1229
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
1230
+ def set_decoder(self, decoder):
1231
+ self.model = decoder
1232
+
1233
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
1234
+ def get_decoder(self):
1235
+ return self.model
1236
+
1237
+ # Ignore copy
1238
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1239
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1240
+ def forward(
1241
+ self,
1242
+ input_ids: torch.LongTensor = None,
1243
+ attention_mask: Optional[torch.Tensor] = None,
1244
+ position_ids: Optional[torch.LongTensor] = None,
1245
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1246
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1247
+ labels: Optional[torch.LongTensor] = None,
1248
+ use_cache: Optional[bool] = None,
1249
+ output_attentions: Optional[bool] = None,
1250
+ output_hidden_states: Optional[bool] = None,
1251
+ return_dict: Optional[bool] = None,
1252
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1253
+ r"""
1254
+ Args:
1255
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1256
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1257
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1258
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1259
+
1260
+ Returns:
1261
+
1262
+ Example:
1263
+
1264
+ ```python
1265
+ >>> from transformers import AutoTokenizer, Phi3ForCausalLM
1266
+
1267
+ >>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1268
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1269
+
1270
+ >>> prompt = "This is an example script ."
1271
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1272
+
1273
+ >>> # Generate
1274
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1275
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1276
+ 'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
1277
+ ```"""
1278
+
1279
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1280
+ output_hidden_states = (
1281
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1282
+ )
1283
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1284
+
1285
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1286
+ outputs = self.model(
1287
+ input_ids=input_ids,
1288
+ attention_mask=attention_mask,
1289
+ position_ids=position_ids,
1290
+ past_key_values=past_key_values,
1291
+ inputs_embeds=inputs_embeds,
1292
+ use_cache=use_cache,
1293
+ output_attentions=output_attentions,
1294
+ output_hidden_states=output_hidden_states,
1295
+ return_dict=return_dict,
1296
+ )
1297
+
1298
+ hidden_states = outputs[0]
1299
+ logits = self.lm_head(hidden_states)
1300
+ logits = logits.float()
1301
+
1302
+ loss = None
1303
+ if labels is not None:
1304
+ # Shift so that tokens < n predict n
1305
+ shift_logits = logits[..., :-1, :].contiguous()
1306
+ shift_labels = labels[..., 1:].contiguous()
1307
+ # Flatten the tokens
1308
+ loss_fct = CrossEntropyLoss()
1309
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1310
+ shift_labels = shift_labels.view(-1)
1311
+ # Enable model parallelism
1312
+ shift_labels = shift_labels.to(shift_logits.device)
1313
+ loss = loss_fct(shift_logits, shift_labels)
1314
+
1315
+ if not return_dict:
1316
+ output = (logits,) + outputs[1:]
1317
+ return (loss,) + output if loss is not None else output
1318
+
1319
+ return CausalLMOutputWithPast(
1320
+ loss=loss,
1321
+ logits=logits,
1322
+ past_key_values=outputs.past_key_values,
1323
+ hidden_states=outputs.hidden_states,
1324
+ attentions=outputs.attentions,
1325
+ )
1326
+
1327
+ # Copied from transformers.models.persimmon.modeling_persimmon.PersimmonForCausalLM.prepare_inputs_for_generation
1328
+ def prepare_inputs_for_generation(
1329
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1330
+ ):
1331
+ if past_key_values is not None:
1332
+ if isinstance(past_key_values, Cache):
1333
+ cache_length = past_key_values.get_seq_length()
1334
+ past_length = past_key_values.seen_tokens
1335
+ max_cache_length = past_key_values.get_max_length()
1336
+ else:
1337
+ cache_length = past_length = past_key_values[0][0].shape[2]
1338
+ max_cache_length = None
1339
+
1340
+ # Keep only the unprocessed tokens:
1341
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1342
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1343
+ # input)
1344
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1345
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1346
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1347
+ # input_ids based on the past_length.
1348
+ elif past_length < input_ids.shape[1]:
1349
+ input_ids = input_ids[:, past_length:]
1350
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1351
+
1352
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1353
+ if (
1354
+ max_cache_length is not None
1355
+ and attention_mask is not None
1356
+ and cache_length + input_ids.shape[1] > max_cache_length
1357
+ ):
1358
+ attention_mask = attention_mask[:, -max_cache_length:]
1359
+
1360
+ position_ids = kwargs.get("position_ids", None)
1361
+ if attention_mask is not None and position_ids is None:
1362
+ # create position_ids on the fly for batch generation
1363
+ position_ids = attention_mask.long().cumsum(-1) - 1
1364
+ position_ids.masked_fill_(attention_mask == 0, 1)
1365
+ if past_key_values:
1366
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1367
+
1368
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1369
+ if inputs_embeds is not None and past_key_values is None:
1370
+ model_inputs = {"inputs_embeds": inputs_embeds}
1371
+ else:
1372
+ model_inputs = {"input_ids": input_ids}
1373
+
1374
+ model_inputs.update(
1375
+ {
1376
+ "position_ids": position_ids,
1377
+ "past_key_values": past_key_values,
1378
+ "use_cache": kwargs.get("use_cache"),
1379
+ "attention_mask": attention_mask,
1380
+ }
1381
+ )
1382
+ return model_inputs
1383
+
1384
+ @staticmethod
1385
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM._reorder_cache
1386
+ def _reorder_cache(past_key_values, beam_idx):
1387
+ reordered_past = ()
1388
+ for layer_past in past_key_values:
1389
+ reordered_past += (
1390
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1391
+ )
1392
+ return reordered_past
1393
+
1394
+
1395
+ @add_start_docstrings(
1396
+ """
1397
+ The [`Phi3Model`] with a sequence classification head on top (linear layer).
1398
+
1399
+ [`Phi3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1400
+ (e.g. GPT-2) do.
1401
+
1402
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1403
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1404
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1405
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1406
+ each row of the batch).
1407
+ """,
1408
+ PHI3_START_DOCSTRING,
1409
+ )
1410
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Phi3, LLAMA->PHI3, self.transformer->self.model, transformer_outputs->model_outputs
1411
+ class Phi3ForSequenceClassification(Phi3PreTrainedModel):
1412
+ def __init__(self, config):
1413
+ super().__init__(config)
1414
+ self.num_labels = config.num_labels
1415
+ self.model = Phi3Model(config)
1416
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1417
+
1418
+ # Initialize weights and apply final processing
1419
+ self.post_init()
1420
+
1421
+ def get_input_embeddings(self):
1422
+ return self.model.embed_tokens
1423
+
1424
+ def set_input_embeddings(self, value):
1425
+ self.model.embed_tokens = value
1426
+
1427
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1428
+ def forward(
1429
+ self,
1430
+ input_ids: torch.LongTensor = None,
1431
+ attention_mask: Optional[torch.Tensor] = None,
1432
+ position_ids: Optional[torch.LongTensor] = None,
1433
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1434
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1435
+ labels: Optional[torch.LongTensor] = None,
1436
+ use_cache: Optional[bool] = None,
1437
+ output_attentions: Optional[bool] = None,
1438
+ output_hidden_states: Optional[bool] = None,
1439
+ return_dict: Optional[bool] = None,
1440
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1441
+ r"""
1442
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1443
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1444
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1445
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1446
+ """
1447
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1448
+
1449
+ model_outputs = self.model(
1450
+ input_ids,
1451
+ attention_mask=attention_mask,
1452
+ position_ids=position_ids,
1453
+ past_key_values=past_key_values,
1454
+ inputs_embeds=inputs_embeds,
1455
+ use_cache=use_cache,
1456
+ output_attentions=output_attentions,
1457
+ output_hidden_states=output_hidden_states,
1458
+ return_dict=return_dict,
1459
+ )
1460
+ hidden_states = model_outputs[0]
1461
+ logits = self.score(hidden_states)
1462
+
1463
+ if input_ids is not None:
1464
+ batch_size = input_ids.shape[0]
1465
+ else:
1466
+ batch_size = inputs_embeds.shape[0]
1467
+
1468
+ if self.config.pad_token_id is None and batch_size != 1:
1469
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1470
+ if self.config.pad_token_id is None:
1471
+ sequence_lengths = -1
1472
+ else:
1473
+ if input_ids is not None:
1474
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1475
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1476
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1477
+ sequence_lengths = sequence_lengths.to(logits.device)
1478
+ else:
1479
+ sequence_lengths = -1
1480
+
1481
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1482
+
1483
+ loss = None
1484
+ if labels is not None:
1485
+ labels = labels.to(logits.device)
1486
+ if self.config.problem_type is None:
1487
+ if self.num_labels == 1:
1488
+ self.config.problem_type = "regression"
1489
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1490
+ self.config.problem_type = "single_label_classification"
1491
+ else:
1492
+ self.config.problem_type = "multi_label_classification"
1493
+
1494
+ if self.config.problem_type == "regression":
1495
+ loss_fct = MSELoss()
1496
+ if self.num_labels == 1:
1497
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1498
+ else:
1499
+ loss = loss_fct(pooled_logits, labels)
1500
+ elif self.config.problem_type == "single_label_classification":
1501
+ loss_fct = CrossEntropyLoss()
1502
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1503
+ elif self.config.problem_type == "multi_label_classification":
1504
+ loss_fct = BCEWithLogitsLoss()
1505
+ loss = loss_fct(pooled_logits, labels)
1506
+ if not return_dict:
1507
+ output = (pooled_logits,) + model_outputs[1:]
1508
+ return ((loss,) + output) if loss is not None else output
1509
+
1510
+ return SequenceClassifierOutputWithPast(
1511
+ loss=loss,
1512
+ logits=pooled_logits,
1513
+ past_key_values=model_outputs.past_key_values,
1514
+ hidden_states=model_outputs.hidden_states,
1515
+ attentions=model_outputs.attentions,
1516
+ )
1517
+
1518
+
1519
+ @add_start_docstrings(
1520
+ """
1521
+ [`Phi3Model`] with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1522
+ Named-Entity-Recognition (NER) tasks.
1523
+ """,
1524
+ PHI3_START_DOCSTRING,
1525
+ )
1526
+ # Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with Mpt->Phi3,MPT->PHI3,self.transformer->self.model,transformer_outputs->model_outputs
1527
+ class Phi3ForTokenClassification(Phi3PreTrainedModel):
1528
+ def __init__(self, config: Phi3Config):
1529
+ super().__init__(config)
1530
+ self.num_labels = config.num_labels
1531
+
1532
+ self.model = Phi3Model(config)
1533
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1534
+ classifier_dropout = config.classifier_dropout
1535
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1536
+ classifier_dropout = config.hidden_dropout
1537
+ else:
1538
+ classifier_dropout = 0.1
1539
+ self.dropout = nn.Dropout(classifier_dropout)
1540
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1541
+
1542
+ # Initialize weights and apply final processing
1543
+ self.post_init()
1544
+
1545
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1546
+ @add_code_sample_docstrings(
1547
+ checkpoint=_CHECKPOINT_FOR_DOC,
1548
+ output_type=TokenClassifierOutput,
1549
+ config_class=_CONFIG_FOR_DOC,
1550
+ )
1551
+ def forward(
1552
+ self,
1553
+ input_ids: Optional[torch.LongTensor] = None,
1554
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1555
+ attention_mask: Optional[torch.Tensor] = None,
1556
+ inputs_embeds: Optional[torch.Tensor] = None,
1557
+ labels: Optional[torch.Tensor] = None,
1558
+ use_cache: Optional[bool] = None,
1559
+ output_attentions: Optional[bool] = None,
1560
+ output_hidden_states: Optional[bool] = None,
1561
+ return_dict: Optional[bool] = None,
1562
+ **deprecated_arguments,
1563
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1564
+ r"""
1565
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1566
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1567
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1568
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1569
+ """
1570
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1571
+
1572
+ model_outputs = self.model(
1573
+ input_ids,
1574
+ past_key_values=past_key_values,
1575
+ attention_mask=attention_mask,
1576
+ inputs_embeds=inputs_embeds,
1577
+ use_cache=use_cache,
1578
+ output_attentions=output_attentions,
1579
+ output_hidden_states=output_hidden_states,
1580
+ return_dict=return_dict,
1581
+ )
1582
+
1583
+ hidden_states = model_outputs[0]
1584
+ hidden_states = self.dropout(hidden_states)
1585
+ logits = self.classifier(hidden_states)
1586
+
1587
+ loss = None
1588
+ if labels is not None:
1589
+ # move labels to correct device to enable model parallelism
1590
+ labels = labels.to(logits.device)
1591
+ batch_size, seq_length = labels.shape
1592
+ loss_fct = CrossEntropyLoss()
1593
+ loss = loss_fct(
1594
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
1595
+ )
1596
+
1597
+ if not return_dict:
1598
+ output = (logits,) + model_outputs[2:]
1599
+ return ((loss,) + output) if loss is not None else output
1600
+
1601
+ return TokenClassifierOutput(
1602
+ loss=loss,
1603
+ logits=logits,
1604
+ hidden_states=model_outputs.hidden_states,
1605
+ attentions=model_outputs.attentions,
1606
+ )
modeling_projector.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) OpenMMLab. All rights reserved.
2
+ import torch
3
+ import torch.nn as nn
4
+ from transformers import PreTrainedModel
5
+ from transformers.activations import ACT2FN
6
+
7
+ from .configuration_projector import ProjectorConfig
8
+
9
+
10
+ class ProjectorModel(PreTrainedModel):
11
+ _auto_class = 'AutoModel'
12
+ config_class = ProjectorConfig
13
+ base_model_prefix = 'model'
14
+ supports_gradient_checkpointing = True
15
+
16
+ def __init__(self, config: ProjectorConfig) -> None:
17
+ super().__init__(config)
18
+ self.gradient_checkpointing = False
19
+
20
+ modules = [
21
+ nn.Linear(
22
+ config.visual_hidden_size,
23
+ config.llm_hidden_size,
24
+ bias=config.bias)
25
+ ]
26
+ for _ in range(1, config.depth):
27
+ modules.append(ACT2FN[config.hidden_act])
28
+ modules.append(
29
+ nn.Linear(
30
+ config.llm_hidden_size,
31
+ config.llm_hidden_size,
32
+ bias=config.bias))
33
+ self.model = nn.Sequential(*modules)
34
+
35
+ def enable_input_require_grads(self):
36
+
37
+ def make_inputs_require_grad(module, input, output):
38
+ output.requires_grad_(True)
39
+
40
+ self.model.register_forward_hook(make_inputs_require_grad)
41
+
42
+ def _set_gradient_checkpointing(self, module, value=False):
43
+ if isinstance(module, ProjectorModel):
44
+ module.gradient_checkpointing = value
45
+
46
+ def forward(self, x):
47
+ if self.gradient_checkpointing and self.training:
48
+ layer_outputs = torch.utils.checkpoint.checkpoint(self.model, x)
49
+ else:
50
+ layer_outputs = self.model(x)
51
+ return layer_outputs
modeling_qformer_attn.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) OpenMMLab. All rights reserved.
2
+ import torch
3
+ torch.manual_seed(1024)
4
+
5
+ import torch.nn as nn
6
+ from transformers import PreTrainedModel
7
+
8
+ from .configuration_qformer import QformerConfig
9
+ from .qformer_src import BertConfig, BertLMHeadModel
10
+
11
+ from transformers import BertTokenizerFast as BertTokenizer
12
+
13
+ from .configuration_projector import ProjectorConfig
14
+ from .modeling_projector import ProjectorModel
15
+ from .fuse_modules import BiAttentionBlock
16
+ import torch.nn.functional as F
17
+ from transformers.activations import ACT2FN
18
+
19
+
20
+ class LayerNorm(nn.LayerNorm):
21
+ """Subclass torch's LayerNorm to handle fp16."""
22
+
23
+ def forward(self, x: torch.Tensor):
24
+ ret = super().forward(x)
25
+ return ret
26
+ #orig_type = x.dtype
27
+ #ret = super().forward(x.type(torch.float32))
28
+ #return ret.type(orig_type)
29
+
30
+ class QformerAttnModel(PreTrainedModel):
31
+ _auto_class = 'AutoModel'
32
+ config_class = QformerConfig
33
+ base_model_prefix = 'model'
34
+ supports_gradient_checkpointing = False
35
+
36
+ def __init__(self, config) -> None:
37
+ super().__init__(config)
38
+ self.gradient_checkpointing = False
39
+ vision_width = config.visual_hidden_size
40
+ num_query_token = config.num_query_token
41
+ bert = config.bert
42
+ llm_hidden_size = config.llm_hidden_size
43
+ cross_attention_freq = config.cross_attention_freq
44
+ qformer_pth = config.qformer_pth
45
+
46
+ encoder_config = BertConfig.from_pretrained(bert)
47
+ encoder_config.encoder_width = vision_width
48
+ encoder_config.add_cross_attention = True
49
+ encoder_config.cross_attention_freq = cross_attention_freq
50
+ encoder_config.query_length = num_query_token
51
+ encoder_config.num_hidden_layers = 12
52
+ #encoder_config.attention_probs_dropout_prob=0.5
53
+ #encoder_config.hidden_dropout_prob=0.5
54
+ Qformer = BertLMHeadModel.from_pretrained(
55
+ bert, config=encoder_config
56
+ )
57
+ remove_text = False
58
+ if remove_text:
59
+ # remove the Q-former's text component
60
+ Qformer.cls = None
61
+ Qformer.bert.embeddings.word_embeddings = None
62
+ Qformer.bert.embeddings.position_embeddings = None
63
+ for layer in Qformer.bert.encoder.layer:
64
+ layer.output = None
65
+ layer.intermediate = None
66
+
67
+ query_tokens = nn.Parameter(
68
+ torch.zeros(1, num_query_token, encoder_config.hidden_size)
69
+ )
70
+ query_tokens.data.normal_(mean=0.0, std=encoder_config.initializer_range)
71
+
72
+ self.Qformer = Qformer
73
+ self.query_tokens = query_tokens
74
+ self.llm_proj = nn.Linear(encoder_config.hidden_size, llm_hidden_size, bias=config.bias)
75
+ self.ln_vision = LayerNorm(encoder_config.encoder_width)
76
+ self.ln_llava = LayerNorm(encoder_config.encoder_width)
77
+
78
+ tokenizer = BertTokenizer.from_pretrained(bert, truncation_side='right')
79
+ tokenizer.add_special_tokens({"bos_token": "[DEC]"})
80
+ self.Qformer.resize_token_embeddings(len(tokenizer))
81
+
82
+ if qformer_pth is not None:
83
+ pretrained_state_dict = torch.load(qformer_pth, map_location='cpu')['model']
84
+ print(f'Load Qformer from {qformer_pth}')
85
+ self.load_state_dict(pretrained_state_dict, strict=False)
86
+ print('Done.')
87
+
88
+ projector_config = ProjectorConfig(
89
+ visual_hidden_size = config.visual_hidden_size,
90
+ llm_hidden_size = config.llm_hidden_size,
91
+ projector_depth = 2)
92
+ self.connector = ProjectorModel(projector_config)
93
+
94
+ d_model = config.llm_hidden_size
95
+ dim_feedforward = 1024
96
+ nhead = 8
97
+ fusion_dropout = 0.0
98
+ fusion_droppath = 0.1
99
+ self.fuse = BiAttentionBlock(
100
+ v_dim=d_model,
101
+ l_dim=d_model,
102
+ embed_dim=dim_feedforward,
103
+ num_heads=nhead,
104
+ dropout=fusion_dropout,
105
+ drop_path=fusion_droppath,
106
+ )
107
+
108
+ modules = [
109
+ nn.Linear(config.llm_hidden_size, config.llm_hidden_size//4, bias=False),
110
+ ACT2FN['gelu'],
111
+ nn.Linear(config.llm_hidden_size//4, config.llm_hidden_size, bias=False)
112
+ ]
113
+ self.ffn = nn.Sequential(*modules)
114
+
115
+ def enable_input_require_grads(self):
116
+ def make_inputs_require_grad(module, input, output):
117
+ if isinstance(output, tuple):
118
+ output[0].requires_grad_(True)
119
+ output[1].requires_grad_(True)
120
+ else:
121
+ output.requires_grad_(True)
122
+
123
+ self.Qformer.register_forward_hook(make_inputs_require_grad)
124
+ self.llm_proj.register_forward_hook(make_inputs_require_grad)
125
+ self.ln_vision.register_forward_hook(make_inputs_require_grad)
126
+ self.connector.register_forward_hook(make_inputs_require_grad)
127
+ self.ffn.register_forward_hook(make_inputs_require_grad)
128
+ self.fuse.register_forward_hook(make_inputs_require_grad)
129
+
130
+ def _set_gradient_checkpointing(self, module, value=False):
131
+ exit()
132
+ if isinstance(module, ProjectorModel):
133
+ module.gradient_checkpointing = value
134
+
135
+ def forward(self, x_):
136
+ if self.gradient_checkpointing and self.training:
137
+ print('Not supprted gradient checkpointing')
138
+ #
139
+ x = self.ln_vision(x_)
140
+ query_tokens = self.query_tokens.expand(x.shape[0], -1, -1)
141
+ query_output = self.Qformer.bert(
142
+ query_embeds=query_tokens,
143
+ encoder_hidden_states=x,
144
+ return_dict=True,
145
+ )
146
+ q_feat = self.llm_proj(query_output.last_hidden_state)
147
+ mlp_outputs = self.connector(x_)
148
+ mlp_feat = mlp_outputs
149
+
150
+ mlp_feat = mlp_feat + self.fuse(mlp_feat, q_feat)
151
+ out = mlp_feat + self.ffn(mlp_feat)
152
+
153
+ return out
154
+
155
+
156
+
157
+
158
+
159
+
160
+
projector/config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "QformerAttnModel"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_qformer.QformerConfig",
7
+ "AutoModel": "modeling_qformer_attn.QformerAttnModel"
8
+ },
9
+ "bert": "bert-base-uncased",
10
+ "bias": true,
11
+ "cross_attention_freq": 2,
12
+ "llm_hidden_size": 3072,
13
+ "model_type": "qformer",
14
+ "num_query_token": 32,
15
+ "qformer_pth": null,
16
+ "torch_dtype": "float32",
17
+ "transformers_version": "4.40.2",
18
+ "visual_hidden_size": 1152
19
+ }
projector/configuration_projector.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) OpenMMLab. All rights reserved.
2
+ from transformers import PretrainedConfig
3
+
4
+
5
+ class ProjectorConfig(PretrainedConfig):
6
+ model_type = 'projector'
7
+ _auto_class = 'AutoConfig'
8
+
9
+ def __init__(
10
+ self,
11
+ visual_hidden_size=4096,
12
+ llm_hidden_size=4096,
13
+ depth=2,
14
+ hidden_act='gelu',
15
+ bias=True,
16
+ **kwargs,
17
+ ):
18
+ self.visual_hidden_size = visual_hidden_size
19
+ self.llm_hidden_size = llm_hidden_size
20
+ self.depth = depth
21
+ self.hidden_act = hidden_act
22
+ self.bias = bias
23
+ super().__init__(**kwargs)
projector/configuration_qformer.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) OpenMMLab. All rights reserved.
2
+ from transformers import PretrainedConfig
3
+
4
+
5
+ class QformerConfig(PretrainedConfig):
6
+ model_type = 'qformer'
7
+ _auto_class = 'AutoConfig'
8
+
9
+ def __init__(
10
+ self,
11
+ num_query_token=32,
12
+ visual_hidden_size=4096,
13
+ llm_hidden_size=768,
14
+ cross_attention_freq=2,
15
+ bert="bert-base-uncased",
16
+ bias=True,
17
+ qformer_pth=None,
18
+ **kwargs,
19
+ ):
20
+ self.num_query_token=num_query_token
21
+ self.visual_hidden_size = visual_hidden_size
22
+ self.llm_hidden_size = llm_hidden_size
23
+ self.bias = bias
24
+ self.bert = bert
25
+ self.cross_attention_freq = cross_attention_freq
26
+ self.qformer_pth = qformer_pth
27
+ super().__init__(**kwargs)
projector/fuse_modules.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ------------------------------------------------------------------------
2
+ # Grounding DINO
3
+ # url: https://github.com/IDEA-Research/GroundingDINO
4
+ # Copyright (c) 2023 IDEA. All Rights Reserved.
5
+ # Licensed under the Apache License, Version 2.0 [see LICENSE for details]
6
+ # ------------------------------------------------------------------------
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ from timm.models.layers import DropPath
12
+
13
+ class BiMultiHeadAttention(nn.Module):
14
+ def __init__(self, v_dim, l_dim, embed_dim, num_heads, dropout=0.1, cfg=None):
15
+ super(BiMultiHeadAttention, self).__init__()
16
+
17
+ self.embed_dim = embed_dim
18
+ self.num_heads = num_heads
19
+ self.head_dim = embed_dim // num_heads
20
+ self.v_dim = v_dim
21
+ self.l_dim = l_dim
22
+
23
+ assert (
24
+ self.head_dim * self.num_heads == self.embed_dim
25
+ ), f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {self.num_heads})."
26
+ self.scale = self.head_dim ** (-0.5)
27
+ self.dropout = dropout
28
+
29
+ self.v_proj = nn.Linear(self.v_dim, self.embed_dim)
30
+ self.l_proj = nn.Linear(self.l_dim, self.embed_dim)
31
+ self.values_l_proj = nn.Linear(self.l_dim, self.embed_dim)
32
+
33
+ self.out_v_proj = nn.Linear(self.embed_dim, self.v_dim)
34
+
35
+ self.stable_softmax_2d = True
36
+ self.clamp_min_for_underflow = True
37
+ self.clamp_max_for_overflow = True
38
+
39
+ self._reset_parameters()
40
+
41
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
42
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
43
+
44
+ def _reset_parameters(self):
45
+ nn.init.xavier_uniform_(self.v_proj.weight)
46
+ self.v_proj.bias.data.fill_(0)
47
+ nn.init.xavier_uniform_(self.l_proj.weight)
48
+ self.l_proj.bias.data.fill_(0)
49
+ nn.init.xavier_uniform_(self.values_l_proj.weight)
50
+ self.values_l_proj.bias.data.fill_(0)
51
+ nn.init.xavier_uniform_(self.out_v_proj.weight)
52
+ self.out_v_proj.bias.data.fill_(0)
53
+
54
+ def forward(self, v, l, attention_mask_v=None, attention_mask_l=None):
55
+ bsz, tgt_len, _ = v.size()
56
+
57
+ query_states = self.v_proj(v) * self.scale
58
+ key_states = self._shape(self.l_proj(l), -1, bsz)
59
+ value_l_states = self._shape(self.values_l_proj(l), -1, bsz)
60
+
61
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
62
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
63
+ key_states = key_states.view(*proj_shape)
64
+ value_l_states = value_l_states.view(*proj_shape)
65
+
66
+ src_len = key_states.size(1)
67
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2)) # bs*nhead, nimg, ntxt
68
+
69
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
70
+ raise ValueError(
71
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is {attn_weights.size()}"
72
+ )
73
+
74
+ if self.stable_softmax_2d:
75
+ attn_weights = attn_weights - attn_weights.max()
76
+
77
+ if self.clamp_min_for_underflow:
78
+ attn_weights = torch.clamp(
79
+ attn_weights, min=-50000
80
+ ) # Do not increase -50000, data type half has quite limited range
81
+ if self.clamp_max_for_overflow:
82
+ attn_weights = torch.clamp(
83
+ attn_weights, max=50000
84
+ ) # Do not increase 50000, data type half has quite limited range
85
+
86
+ attn_weights_v = attn_weights.softmax(dim=-1)
87
+ attn_probs_v = F.dropout(attn_weights_v, p=self.dropout, training=self.training)
88
+ attn_output_v = torch.bmm(attn_probs_v, value_l_states)
89
+ if attn_output_v.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
90
+ raise ValueError(
91
+ f"`attn_output_v` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is {attn_output_v.size()}"
92
+ )
93
+
94
+ attn_output_v = attn_output_v.view(bsz, self.num_heads, tgt_len, self.head_dim)
95
+ attn_output_v = attn_output_v.transpose(1, 2)
96
+ attn_output_v = attn_output_v.reshape(bsz, tgt_len, self.embed_dim)
97
+ attn_output_v = self.out_v_proj(attn_output_v)
98
+
99
+ return attn_output_v
100
+
101
+
102
+ # Bi-Direction MHA (text->image, image->text)
103
+ class BiAttentionBlock(nn.Module):
104
+ def __init__(
105
+ self,
106
+ v_dim,
107
+ l_dim,
108
+ embed_dim,
109
+ num_heads,
110
+ dropout=0.1,
111
+ drop_path=0.0,
112
+ cfg=None,
113
+ ):
114
+ """
115
+ Inputs:
116
+ embed_dim - Dimensionality of input and attention feature vectors
117
+ hidden_dim - Dimensionality of hidden layer in feed-forward network
118
+ (usually 2-4x larger than embed_dim)
119
+ num_heads - Number of heads to use in the Multi-Head Attention block
120
+ dropout - Amount of dropout to apply in the feed-forward network
121
+ """
122
+ super(BiAttentionBlock, self).__init__()
123
+
124
+ # pre layer norm
125
+ self.layer_norm_v = nn.LayerNorm(v_dim)
126
+ self.layer_norm_l = nn.LayerNorm(l_dim)
127
+ self.attn = BiMultiHeadAttention(
128
+ v_dim=v_dim, l_dim=l_dim, embed_dim=embed_dim, num_heads=num_heads, dropout=dropout
129
+ )
130
+
131
+ # add layer scale for training stability
132
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
133
+
134
+ def forward(self, v, l, attention_mask_v=None, attention_mask_l=None):
135
+ v = self.layer_norm_v(v)
136
+ l = self.layer_norm_l(l)
137
+ delta_v = self.attn(
138
+ v, l, attention_mask_v=attention_mask_v, attention_mask_l=attention_mask_l
139
+ )
140
+ delta_v = self.drop_path(delta_v)
141
+
142
+ return delta_v
143
+
144
+
projector/modeling_projector.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) OpenMMLab. All rights reserved.
2
+ import torch
3
+ import torch.nn as nn
4
+ from transformers import PreTrainedModel
5
+ from transformers.activations import ACT2FN
6
+
7
+ from .configuration_projector import ProjectorConfig
8
+
9
+
10
+ class ProjectorModel(PreTrainedModel):
11
+ _auto_class = 'AutoModel'
12
+ config_class = ProjectorConfig
13
+ base_model_prefix = 'model'
14
+ supports_gradient_checkpointing = True
15
+
16
+ def __init__(self, config: ProjectorConfig) -> None:
17
+ super().__init__(config)
18
+ self.gradient_checkpointing = False
19
+
20
+ modules = [
21
+ nn.Linear(
22
+ config.visual_hidden_size,
23
+ config.llm_hidden_size,
24
+ bias=config.bias)
25
+ ]
26
+ for _ in range(1, config.depth):
27
+ modules.append(ACT2FN[config.hidden_act])
28
+ modules.append(
29
+ nn.Linear(
30
+ config.llm_hidden_size,
31
+ config.llm_hidden_size,
32
+ bias=config.bias))
33
+ self.model = nn.Sequential(*modules)
34
+
35
+ def enable_input_require_grads(self):
36
+
37
+ def make_inputs_require_grad(module, input, output):
38
+ output.requires_grad_(True)
39
+
40
+ self.model.register_forward_hook(make_inputs_require_grad)
41
+
42
+ def _set_gradient_checkpointing(self, module, value=False):
43
+ if isinstance(module, ProjectorModel):
44
+ module.gradient_checkpointing = value
45
+
46
+ def forward(self, x):
47
+ if self.gradient_checkpointing and self.training:
48
+ layer_outputs = torch.utils.checkpoint.checkpoint(self.model, x)
49
+ else:
50
+ layer_outputs = self.model(x)
51
+ return layer_outputs
projector/modeling_qformer_attn.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) OpenMMLab. All rights reserved.
2
+ import torch
3
+ torch.manual_seed(1024)
4
+
5
+ import torch.nn as nn
6
+ from transformers import PreTrainedModel
7
+
8
+ from .configuration_qformer import QformerConfig
9
+ from .qformer_src import BertConfig, BertLMHeadModel
10
+
11
+ from transformers import BertTokenizerFast as BertTokenizer
12
+
13
+ from .configuration_projector import ProjectorConfig
14
+ from .modeling_projector import ProjectorModel
15
+ from .fuse_modules import BiAttentionBlock
16
+ import torch.nn.functional as F
17
+ from transformers.activations import ACT2FN
18
+
19
+
20
+ class LayerNorm(nn.LayerNorm):
21
+ """Subclass torch's LayerNorm to handle fp16."""
22
+
23
+ def forward(self, x: torch.Tensor):
24
+ ret = super().forward(x)
25
+ return ret
26
+ #orig_type = x.dtype
27
+ #ret = super().forward(x.type(torch.float32))
28
+ #return ret.type(orig_type)
29
+
30
+ class QformerAttnModel(PreTrainedModel):
31
+ _auto_class = 'AutoModel'
32
+ config_class = QformerConfig
33
+ base_model_prefix = 'model'
34
+ supports_gradient_checkpointing = False
35
+
36
+ def __init__(self, config) -> None:
37
+ super().__init__(config)
38
+ self.gradient_checkpointing = False
39
+ vision_width = config.visual_hidden_size
40
+ num_query_token = config.num_query_token
41
+ bert = config.bert
42
+ llm_hidden_size = config.llm_hidden_size
43
+ cross_attention_freq = config.cross_attention_freq
44
+ qformer_pth = config.qformer_pth
45
+
46
+ encoder_config = BertConfig.from_pretrained(bert)
47
+ encoder_config.encoder_width = vision_width
48
+ encoder_config.add_cross_attention = True
49
+ encoder_config.cross_attention_freq = cross_attention_freq
50
+ encoder_config.query_length = num_query_token
51
+ encoder_config.num_hidden_layers = 12
52
+ #encoder_config.attention_probs_dropout_prob=0.5
53
+ #encoder_config.hidden_dropout_prob=0.5
54
+ Qformer = BertLMHeadModel.from_pretrained(
55
+ bert, config=encoder_config
56
+ )
57
+ remove_text = False
58
+ if remove_text:
59
+ # remove the Q-former's text component
60
+ Qformer.cls = None
61
+ Qformer.bert.embeddings.word_embeddings = None
62
+ Qformer.bert.embeddings.position_embeddings = None
63
+ for layer in Qformer.bert.encoder.layer:
64
+ layer.output = None
65
+ layer.intermediate = None
66
+
67
+ query_tokens = nn.Parameter(
68
+ torch.zeros(1, num_query_token, encoder_config.hidden_size)
69
+ )
70
+ query_tokens.data.normal_(mean=0.0, std=encoder_config.initializer_range)
71
+
72
+ self.Qformer = Qformer
73
+ self.query_tokens = query_tokens
74
+ self.llm_proj = nn.Linear(encoder_config.hidden_size, llm_hidden_size, bias=config.bias)
75
+ self.ln_vision = LayerNorm(encoder_config.encoder_width)
76
+ self.ln_llava = LayerNorm(encoder_config.encoder_width)
77
+
78
+ tokenizer = BertTokenizer.from_pretrained(bert, truncation_side='right')
79
+ tokenizer.add_special_tokens({"bos_token": "[DEC]"})
80
+ self.Qformer.resize_token_embeddings(len(tokenizer))
81
+
82
+ if qformer_pth is not None:
83
+ pretrained_state_dict = torch.load(qformer_pth, map_location='cpu')['model']
84
+ print(f'Load Qformer from {qformer_pth}')
85
+ self.load_state_dict(pretrained_state_dict, strict=False)
86
+ print('Done.')
87
+
88
+ projector_config = ProjectorConfig(
89
+ visual_hidden_size = config.visual_hidden_size,
90
+ llm_hidden_size = config.llm_hidden_size,
91
+ projector_depth = 2)
92
+ self.connector = ProjectorModel(projector_config)
93
+
94
+ d_model = config.llm_hidden_size
95
+ dim_feedforward = 1024
96
+ nhead = 8
97
+ fusion_dropout = 0.0
98
+ fusion_droppath = 0.1
99
+ self.fuse = BiAttentionBlock(
100
+ v_dim=d_model,
101
+ l_dim=d_model,
102
+ embed_dim=dim_feedforward,
103
+ num_heads=nhead,
104
+ dropout=fusion_dropout,
105
+ drop_path=fusion_droppath,
106
+ )
107
+
108
+ modules = [
109
+ nn.Linear(config.llm_hidden_size, config.llm_hidden_size//4, bias=False),
110
+ ACT2FN['gelu'],
111
+ nn.Linear(config.llm_hidden_size//4, config.llm_hidden_size, bias=False)
112
+ ]
113
+ self.ffn = nn.Sequential(*modules)
114
+
115
+ def enable_input_require_grads(self):
116
+ def make_inputs_require_grad(module, input, output):
117
+ if isinstance(output, tuple):
118
+ output[0].requires_grad_(True)
119
+ output[1].requires_grad_(True)
120
+ else:
121
+ output.requires_grad_(True)
122
+
123
+ self.Qformer.register_forward_hook(make_inputs_require_grad)
124
+ self.llm_proj.register_forward_hook(make_inputs_require_grad)
125
+ self.ln_vision.register_forward_hook(make_inputs_require_grad)
126
+ self.connector.register_forward_hook(make_inputs_require_grad)
127
+ self.ffn.register_forward_hook(make_inputs_require_grad)
128
+ self.fuse.register_forward_hook(make_inputs_require_grad)
129
+
130
+ def _set_gradient_checkpointing(self, module, value=False):
131
+ exit()
132
+ if isinstance(module, ProjectorModel):
133
+ module.gradient_checkpointing = value
134
+
135
+ def forward(self, x_):
136
+ if self.gradient_checkpointing and self.training:
137
+ print('Not supprted gradient checkpointing')
138
+ #
139
+ x = self.ln_vision(x_)
140
+ query_tokens = self.query_tokens.expand(x.shape[0], -1, -1)
141
+ query_output = self.Qformer.bert(
142
+ query_embeds=query_tokens,
143
+ encoder_hidden_states=x,
144
+ return_dict=True,
145
+ )
146
+ q_feat = self.llm_proj(query_output.last_hidden_state)
147
+ mlp_outputs = self.connector(x_)
148
+ mlp_feat = mlp_outputs
149
+
150
+ mlp_feat = mlp_feat + self.fuse(mlp_feat, q_feat)
151
+ out = mlp_feat + self.ffn(mlp_feat)
152
+
153
+ return out
154
+
155
+
156
+
157
+
158
+
159
+
160
+
projector/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bc95e113b47eda4bc4f282a440cda7fd60047b1f386c1d0993bf51aaf45aff0c
3
+ size 866594086
projector/qformer_src.py ADDED
@@ -0,0 +1,1216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ * Copyright (c) 2023, salesforce.com, inc.
3
+ * All rights reserved.
4
+ * SPDX-License-Identifier: BSD-3-Clause
5
+ * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
6
+ * By Junnan Li
7
+ * Based on huggingface code base
8
+ * https://github.com/huggingface/transformers/blob/v4.15.0/src/transformers/models/bert
9
+ """
10
+
11
+ import math
12
+ import os
13
+ import warnings
14
+ from dataclasses import dataclass
15
+ from typing import Optional, Tuple, Dict, Any
16
+
17
+ import torch
18
+ from torch import Tensor, device, dtype, nn
19
+ import torch.utils.checkpoint
20
+ from torch import nn
21
+ from torch.nn import CrossEntropyLoss
22
+ import torch.nn.functional as F
23
+
24
+ from transformers.activations import ACT2FN
25
+ from transformers.file_utils import (
26
+ ModelOutput,
27
+ )
28
+ from transformers.modeling_outputs import (
29
+ BaseModelOutputWithPastAndCrossAttentions,
30
+ BaseModelOutputWithPoolingAndCrossAttentions,
31
+ CausalLMOutputWithCrossAttentions,
32
+ MaskedLMOutput,
33
+ MultipleChoiceModelOutput,
34
+ NextSentencePredictorOutput,
35
+ QuestionAnsweringModelOutput,
36
+ SequenceClassifierOutput,
37
+ TokenClassifierOutput,
38
+ )
39
+ from transformers.modeling_utils import (
40
+ PreTrainedModel,
41
+ apply_chunking_to_forward,
42
+ find_pruneable_heads_and_indices,
43
+ prune_linear_layer,
44
+ )
45
+ from transformers.utils import logging
46
+ from transformers.models.bert.configuration_bert import BertConfig
47
+
48
+ logger = logging.get_logger(__name__)
49
+
50
+
51
+ class BertEmbeddings(nn.Module):
52
+ """Construct the embeddings from word and position embeddings."""
53
+
54
+ def __init__(self, config):
55
+ super().__init__()
56
+ self.word_embeddings = nn.Embedding(
57
+ config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id
58
+ )
59
+ self.position_embeddings = nn.Embedding(
60
+ config.max_position_embeddings, config.hidden_size
61
+ )
62
+
63
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
64
+ # any TensorFlow checkpoint file
65
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
66
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
67
+
68
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
69
+ self.register_buffer(
70
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1))
71
+ )
72
+ self.position_embedding_type = getattr(
73
+ config, "position_embedding_type", "absolute"
74
+ )
75
+
76
+ self.config = config
77
+
78
+ def forward(
79
+ self,
80
+ input_ids=None,
81
+ position_ids=None,
82
+ query_embeds=None,
83
+ past_key_values_length=0,
84
+ ):
85
+ if input_ids is not None:
86
+ seq_length = input_ids.size()[1]
87
+ else:
88
+ seq_length = 0
89
+
90
+ if position_ids is None:
91
+ position_ids = self.position_ids[
92
+ :, past_key_values_length : seq_length + past_key_values_length
93
+ ].clone()
94
+
95
+ if input_ids is not None:
96
+ embeddings = self.word_embeddings(input_ids)
97
+ if self.position_embedding_type == "absolute":
98
+ position_embeddings = self.position_embeddings(position_ids)
99
+ embeddings = embeddings + position_embeddings
100
+
101
+ if query_embeds is not None:
102
+ embeddings = torch.cat((query_embeds, embeddings), dim=1)
103
+ else:
104
+ embeddings = query_embeds
105
+
106
+ embeddings = self.LayerNorm(embeddings)
107
+ embeddings = self.dropout(embeddings)
108
+ return embeddings
109
+
110
+
111
+ class BertSelfAttention(nn.Module):
112
+ def __init__(self, config, is_cross_attention):
113
+ super().__init__()
114
+ self.config = config
115
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(
116
+ config, "embedding_size"
117
+ ):
118
+ raise ValueError(
119
+ "The hidden size (%d) is not a multiple of the number of attention "
120
+ "heads (%d)" % (config.hidden_size, config.num_attention_heads)
121
+ )
122
+
123
+ self.num_attention_heads = config.num_attention_heads
124
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
125
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
126
+
127
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
128
+ if is_cross_attention:
129
+ self.key = nn.Linear(config.encoder_width, self.all_head_size)
130
+ self.value = nn.Linear(config.encoder_width, self.all_head_size)
131
+ else:
132
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
133
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
134
+
135
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
136
+ self.position_embedding_type = getattr(
137
+ config, "position_embedding_type", "absolute"
138
+ )
139
+ if (
140
+ self.position_embedding_type == "relative_key"
141
+ or self.position_embedding_type == "relative_key_query"
142
+ ):
143
+ self.max_position_embeddings = config.max_position_embeddings
144
+ self.distance_embedding = nn.Embedding(
145
+ 2 * config.max_position_embeddings - 1, self.attention_head_size
146
+ )
147
+ self.save_attention = False
148
+
149
+ def save_attn_gradients(self, attn_gradients):
150
+ self.attn_gradients = attn_gradients
151
+
152
+ def get_attn_gradients(self):
153
+ return self.attn_gradients
154
+
155
+ def save_attention_map(self, attention_map):
156
+ self.attention_map = attention_map
157
+
158
+ def get_attention_map(self):
159
+ return self.attention_map
160
+
161
+ def transpose_for_scores(self, x):
162
+ new_x_shape = x.size()[:-1] + (
163
+ self.num_attention_heads,
164
+ self.attention_head_size,
165
+ )
166
+ x = x.view(*new_x_shape)
167
+ return x.permute(0, 2, 1, 3)
168
+
169
+ def forward(
170
+ self,
171
+ hidden_states,
172
+ attention_mask=None,
173
+ head_mask=None,
174
+ encoder_hidden_states=None,
175
+ encoder_attention_mask=None,
176
+ past_key_value=None,
177
+ output_attentions=False,
178
+ ):
179
+
180
+ # If this is instantiated as a cross-attention module, the keys
181
+ # and values come from an encoder; the attention mask needs to be
182
+ # such that the encoder's padding tokens are not attended to.
183
+ is_cross_attention = encoder_hidden_states is not None
184
+
185
+ if is_cross_attention:
186
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
187
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
188
+ attention_mask = encoder_attention_mask
189
+ elif past_key_value is not None:
190
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
191
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
192
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
193
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
194
+ else:
195
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
196
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
197
+
198
+ mixed_query_layer = self.query(hidden_states)
199
+
200
+ query_layer = self.transpose_for_scores(mixed_query_layer)
201
+
202
+ past_key_value = (key_layer, value_layer)
203
+
204
+ # Take the dot product between "query" and "key" to get the raw attention scores.
205
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
206
+
207
+ if (
208
+ self.position_embedding_type == "relative_key"
209
+ or self.position_embedding_type == "relative_key_query"
210
+ ):
211
+ seq_length = hidden_states.size()[1]
212
+ position_ids_l = torch.arange(
213
+ seq_length, dtype=torch.long, device=hidden_states.device
214
+ ).view(-1, 1)
215
+ position_ids_r = torch.arange(
216
+ seq_length, dtype=torch.long, device=hidden_states.device
217
+ ).view(1, -1)
218
+ distance = position_ids_l - position_ids_r
219
+ positional_embedding = self.distance_embedding(
220
+ distance + self.max_position_embeddings - 1
221
+ )
222
+ positional_embedding = positional_embedding.to(
223
+ dtype=query_layer.dtype
224
+ ) # fp16 compatibility
225
+
226
+ if self.position_embedding_type == "relative_key":
227
+ relative_position_scores = torch.einsum(
228
+ "bhld,lrd->bhlr", query_layer, positional_embedding
229
+ )
230
+ attention_scores = attention_scores + relative_position_scores
231
+ elif self.position_embedding_type == "relative_key_query":
232
+ relative_position_scores_query = torch.einsum(
233
+ "bhld,lrd->bhlr", query_layer, positional_embedding
234
+ )
235
+ relative_position_scores_key = torch.einsum(
236
+ "bhrd,lrd->bhlr", key_layer, positional_embedding
237
+ )
238
+ attention_scores = (
239
+ attention_scores
240
+ + relative_position_scores_query
241
+ + relative_position_scores_key
242
+ )
243
+
244
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
245
+ if attention_mask is not None:
246
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
247
+ attention_scores = attention_scores + attention_mask
248
+
249
+ # Normalize the attention scores to probabilities.
250
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
251
+
252
+ if is_cross_attention and self.save_attention:
253
+ self.save_attention_map(attention_probs)
254
+ attention_probs.register_hook(self.save_attn_gradients)
255
+
256
+ # This is actually dropping out entire tokens to attend to, which might
257
+ # seem a bit unusual, but is taken from the original Transformer paper.
258
+ attention_probs_dropped = self.dropout(attention_probs)
259
+
260
+ # Mask heads if we want to
261
+ if head_mask is not None:
262
+ attention_probs_dropped = attention_probs_dropped * head_mask
263
+
264
+ context_layer = torch.matmul(attention_probs_dropped, value_layer)
265
+
266
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
267
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
268
+ context_layer = context_layer.view(*new_context_layer_shape)
269
+
270
+ outputs = (
271
+ (context_layer, attention_probs) if output_attentions else (context_layer,)
272
+ )
273
+
274
+ outputs = outputs + (past_key_value,)
275
+ return outputs
276
+
277
+
278
+ class BertSelfOutput(nn.Module):
279
+ def __init__(self, config):
280
+ super().__init__()
281
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
282
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
283
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
284
+
285
+ def forward(self, hidden_states, input_tensor):
286
+ hidden_states = self.dense(hidden_states)
287
+ hidden_states = self.dropout(hidden_states)
288
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
289
+ return hidden_states
290
+
291
+
292
+ class BertAttention(nn.Module):
293
+ def __init__(self, config, is_cross_attention=False):
294
+ super().__init__()
295
+ self.self = BertSelfAttention(config, is_cross_attention)
296
+ self.output = BertSelfOutput(config)
297
+ self.pruned_heads = set()
298
+
299
+ def prune_heads(self, heads):
300
+ if len(heads) == 0:
301
+ return
302
+ heads, index = find_pruneable_heads_and_indices(
303
+ heads,
304
+ self.self.num_attention_heads,
305
+ self.self.attention_head_size,
306
+ self.pruned_heads,
307
+ )
308
+
309
+ # Prune linear layers
310
+ self.self.query = prune_linear_layer(self.self.query, index)
311
+ self.self.key = prune_linear_layer(self.self.key, index)
312
+ self.self.value = prune_linear_layer(self.self.value, index)
313
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
314
+
315
+ # Update hyper params and store pruned heads
316
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
317
+ self.self.all_head_size = (
318
+ self.self.attention_head_size * self.self.num_attention_heads
319
+ )
320
+ self.pruned_heads = self.pruned_heads.union(heads)
321
+
322
+ def forward(
323
+ self,
324
+ hidden_states,
325
+ attention_mask=None,
326
+ head_mask=None,
327
+ encoder_hidden_states=None,
328
+ encoder_attention_mask=None,
329
+ past_key_value=None,
330
+ output_attentions=False,
331
+ ):
332
+ self_outputs = self.self(
333
+ hidden_states,
334
+ attention_mask,
335
+ head_mask,
336
+ encoder_hidden_states,
337
+ encoder_attention_mask,
338
+ past_key_value,
339
+ output_attentions,
340
+ )
341
+ attention_output = self.output(self_outputs[0], hidden_states)
342
+
343
+ outputs = (attention_output,) + self_outputs[
344
+ 1:
345
+ ] # add attentions if we output them
346
+ return outputs
347
+
348
+
349
+ class BertIntermediate(nn.Module):
350
+ def __init__(self, config):
351
+ super().__init__()
352
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
353
+ if isinstance(config.hidden_act, str):
354
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
355
+ else:
356
+ self.intermediate_act_fn = config.hidden_act
357
+
358
+ def forward(self, hidden_states):
359
+ hidden_states = self.dense(hidden_states)
360
+ hidden_states = self.intermediate_act_fn(hidden_states)
361
+ return hidden_states
362
+
363
+
364
+ class BertOutput(nn.Module):
365
+ def __init__(self, config):
366
+ super().__init__()
367
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
368
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
369
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
370
+
371
+ def forward(self, hidden_states, input_tensor):
372
+ hidden_states = self.dense(hidden_states)
373
+ hidden_states = self.dropout(hidden_states)
374
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
375
+ return hidden_states
376
+
377
+
378
+ class BertLayer(nn.Module):
379
+ def __init__(self, config, layer_num):
380
+ super().__init__()
381
+ self.config = config
382
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
383
+ self.seq_len_dim = 1
384
+ self.attention = BertAttention(config)
385
+ self.layer_num = layer_num
386
+ if (
387
+ self.config.add_cross_attention
388
+ and layer_num % self.config.cross_attention_freq == 0
389
+ ):
390
+ self.crossattention = BertAttention(
391
+ config, is_cross_attention=self.config.add_cross_attention
392
+ )
393
+ self.has_cross_attention = True
394
+ else:
395
+ self.has_cross_attention = False
396
+ self.intermediate = BertIntermediate(config)
397
+ self.output = BertOutput(config)
398
+
399
+ self.intermediate_query = BertIntermediate(config)
400
+ self.output_query = BertOutput(config)
401
+
402
+ def forward(
403
+ self,
404
+ hidden_states,
405
+ attention_mask=None,
406
+ head_mask=None,
407
+ encoder_hidden_states=None,
408
+ encoder_attention_mask=None,
409
+ past_key_value=None,
410
+ output_attentions=False,
411
+ query_length=0,
412
+ ):
413
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
414
+ self_attn_past_key_value = (
415
+ past_key_value[:2] if past_key_value is not None else None
416
+ )
417
+ self_attention_outputs = self.attention(
418
+ hidden_states,
419
+ attention_mask,
420
+ head_mask,
421
+ output_attentions=output_attentions,
422
+ past_key_value=self_attn_past_key_value,
423
+ )
424
+ attention_output = self_attention_outputs[0]
425
+ outputs = self_attention_outputs[1:-1]
426
+
427
+ present_key_value = self_attention_outputs[-1]
428
+
429
+ if query_length > 0:
430
+ query_attention_output = attention_output[:, :query_length, :]
431
+
432
+ if self.has_cross_attention:
433
+ assert (
434
+ encoder_hidden_states is not None
435
+ ), "encoder_hidden_states must be given for cross-attention layers"
436
+ cross_attention_outputs = self.crossattention(
437
+ query_attention_output,
438
+ attention_mask,
439
+ head_mask,
440
+ encoder_hidden_states,
441
+ encoder_attention_mask,
442
+ output_attentions=output_attentions,
443
+ )
444
+ query_attention_output = cross_attention_outputs[0]
445
+ outputs = (
446
+ outputs + cross_attention_outputs[1:-1]
447
+ ) # add cross attentions if we output attention weights
448
+
449
+ layer_output = apply_chunking_to_forward(
450
+ self.feed_forward_chunk_query,
451
+ self.chunk_size_feed_forward,
452
+ self.seq_len_dim,
453
+ query_attention_output,
454
+ )
455
+ if attention_output.shape[1] > query_length:
456
+ layer_output_text = apply_chunking_to_forward(
457
+ self.feed_forward_chunk,
458
+ self.chunk_size_feed_forward,
459
+ self.seq_len_dim,
460
+ attention_output[:, query_length:, :],
461
+ )
462
+ layer_output = torch.cat([layer_output, layer_output_text], dim=1)
463
+ else:
464
+ layer_output = apply_chunking_to_forward(
465
+ self.feed_forward_chunk,
466
+ self.chunk_size_feed_forward,
467
+ self.seq_len_dim,
468
+ attention_output,
469
+ )
470
+ outputs = (layer_output,) + outputs
471
+
472
+ outputs = outputs + (present_key_value,)
473
+
474
+ return outputs
475
+
476
+ def feed_forward_chunk(self, attention_output):
477
+ intermediate_output = self.intermediate(attention_output)
478
+ layer_output = self.output(intermediate_output, attention_output)
479
+ return layer_output
480
+
481
+ def feed_forward_chunk_query(self, attention_output):
482
+ intermediate_output = self.intermediate_query(attention_output)
483
+ layer_output = self.output_query(intermediate_output, attention_output)
484
+ return layer_output
485
+
486
+
487
+ class BertEncoder(nn.Module):
488
+ def __init__(self, config):
489
+ super().__init__()
490
+ self.config = config
491
+ self.layer = nn.ModuleList(
492
+ [BertLayer(config, i) for i in range(config.num_hidden_layers)]
493
+ )
494
+
495
+ def forward(
496
+ self,
497
+ hidden_states,
498
+ attention_mask=None,
499
+ head_mask=None,
500
+ encoder_hidden_states=None,
501
+ encoder_attention_mask=None,
502
+ past_key_values=None,
503
+ use_cache=None,
504
+ output_attentions=False,
505
+ output_hidden_states=False,
506
+ return_dict=True,
507
+ query_length=0,
508
+ ):
509
+ all_hidden_states = () if output_hidden_states else None
510
+ all_self_attentions = () if output_attentions else None
511
+ all_cross_attentions = (
512
+ () if output_attentions and self.config.add_cross_attention else None
513
+ )
514
+
515
+ next_decoder_cache = () if use_cache else None
516
+
517
+ for i in range(self.config.num_hidden_layers):
518
+ layer_module = self.layer[i]
519
+ if output_hidden_states:
520
+ all_hidden_states = all_hidden_states + (hidden_states,)
521
+
522
+ layer_head_mask = head_mask[i] if head_mask is not None else None
523
+ past_key_value = past_key_values[i] if past_key_values is not None else None
524
+
525
+ if getattr(self.config, "gradient_checkpointing", False) and self.training:
526
+
527
+ if use_cache:
528
+ logger.warn(
529
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
530
+ )
531
+ use_cache = False
532
+
533
+ def create_custom_forward(module):
534
+ def custom_forward(*inputs):
535
+ return module(
536
+ *inputs, past_key_value, output_attentions, query_length
537
+ )
538
+
539
+ return custom_forward
540
+
541
+ layer_outputs = torch.utils.checkpoint.checkpoint(
542
+ create_custom_forward(layer_module),
543
+ hidden_states,
544
+ attention_mask,
545
+ layer_head_mask,
546
+ encoder_hidden_states,
547
+ encoder_attention_mask,
548
+ )
549
+ else:
550
+ layer_outputs = layer_module(
551
+ hidden_states,
552
+ attention_mask,
553
+ layer_head_mask,
554
+ encoder_hidden_states,
555
+ encoder_attention_mask,
556
+ past_key_value,
557
+ output_attentions,
558
+ query_length,
559
+ )
560
+
561
+ hidden_states = layer_outputs[0]
562
+ if use_cache:
563
+ next_decoder_cache += (layer_outputs[-1],)
564
+ if output_attentions:
565
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
566
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
567
+
568
+ if output_hidden_states:
569
+ all_hidden_states = all_hidden_states + (hidden_states,)
570
+
571
+ if not return_dict:
572
+ return tuple(
573
+ v
574
+ for v in [
575
+ hidden_states,
576
+ next_decoder_cache,
577
+ all_hidden_states,
578
+ all_self_attentions,
579
+ all_cross_attentions,
580
+ ]
581
+ if v is not None
582
+ )
583
+ return BaseModelOutputWithPastAndCrossAttentions(
584
+ last_hidden_state=hidden_states,
585
+ past_key_values=next_decoder_cache,
586
+ hidden_states=all_hidden_states,
587
+ attentions=all_self_attentions,
588
+ cross_attentions=all_cross_attentions,
589
+ )
590
+
591
+
592
+ class BertPooler(nn.Module):
593
+ def __init__(self, config):
594
+ super().__init__()
595
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
596
+ self.activation = nn.Tanh()
597
+
598
+ def forward(self, hidden_states):
599
+ # We "pool" the model by simply taking the hidden state corresponding
600
+ # to the first token.
601
+ first_token_tensor = hidden_states[:, 0]
602
+ pooled_output = self.dense(first_token_tensor)
603
+ pooled_output = self.activation(pooled_output)
604
+ return pooled_output
605
+
606
+
607
+ class BertPredictionHeadTransform(nn.Module):
608
+ def __init__(self, config):
609
+ super().__init__()
610
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
611
+ if isinstance(config.hidden_act, str):
612
+ self.transform_act_fn = ACT2FN[config.hidden_act]
613
+ else:
614
+ self.transform_act_fn = config.hidden_act
615
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
616
+
617
+ def forward(self, hidden_states):
618
+ hidden_states = self.dense(hidden_states)
619
+ hidden_states = self.transform_act_fn(hidden_states)
620
+ hidden_states = self.LayerNorm(hidden_states)
621
+ return hidden_states
622
+
623
+
624
+ class BertLMPredictionHead(nn.Module):
625
+ def __init__(self, config):
626
+ super().__init__()
627
+ self.transform = BertPredictionHeadTransform(config)
628
+
629
+ # The output weights are the same as the input embeddings, but there is
630
+ # an output-only bias for each token.
631
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
632
+
633
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
634
+
635
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
636
+ self.decoder.bias = self.bias
637
+
638
+ def forward(self, hidden_states):
639
+ hidden_states = self.transform(hidden_states)
640
+ hidden_states = self.decoder(hidden_states)
641
+ return hidden_states
642
+
643
+
644
+ class BertOnlyMLMHead(nn.Module):
645
+ def __init__(self, config):
646
+ super().__init__()
647
+ self.predictions = BertLMPredictionHead(config)
648
+
649
+ def forward(self, sequence_output):
650
+ prediction_scores = self.predictions(sequence_output)
651
+ return prediction_scores
652
+
653
+
654
+ class BertPreTrainedModel(PreTrainedModel):
655
+ """
656
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
657
+ models.
658
+ """
659
+
660
+ config_class = BertConfig
661
+ base_model_prefix = "bert"
662
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
663
+
664
+ def _init_weights(self, module):
665
+ """Initialize the weights"""
666
+ if isinstance(module, (nn.Linear, nn.Embedding)):
667
+ # Slightly different from the TF version which uses truncated_normal for initialization
668
+ # cf https://github.com/pytorch/pytorch/pull/5617
669
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
670
+ elif isinstance(module, nn.LayerNorm):
671
+ module.bias.data.zero_()
672
+ module.weight.data.fill_(1.0)
673
+ if isinstance(module, nn.Linear) and module.bias is not None:
674
+ module.bias.data.zero_()
675
+
676
+
677
+ class BertModel(BertPreTrainedModel):
678
+ """
679
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
680
+ cross-attention is added between the self-attention layers, following the architecture described in `Attention is
681
+ all you need <https://arxiv.org/abs/1706.03762>`__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
682
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
683
+ argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an
684
+ input to the forward pass.
685
+ """
686
+
687
+ def __init__(self, config, add_pooling_layer=False):
688
+ super().__init__(config)
689
+ self.config = config
690
+
691
+ self.embeddings = BertEmbeddings(config)
692
+
693
+ self.encoder = BertEncoder(config)
694
+
695
+ self.pooler = BertPooler(config) if add_pooling_layer else None
696
+
697
+ self.init_weights()
698
+
699
+ def get_input_embeddings(self):
700
+ return self.embeddings.word_embeddings
701
+
702
+ def set_input_embeddings(self, value):
703
+ self.embeddings.word_embeddings = value
704
+
705
+ def _prune_heads(self, heads_to_prune):
706
+ """
707
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
708
+ class PreTrainedModel
709
+ """
710
+ for layer, heads in heads_to_prune.items():
711
+ self.encoder.layer[layer].attention.prune_heads(heads)
712
+
713
+ def get_extended_attention_mask(
714
+ self,
715
+ attention_mask: Tensor,
716
+ input_shape: Tuple[int],
717
+ device: device,
718
+ is_decoder: bool,
719
+ has_query: bool = False,
720
+ ) -> Tensor:
721
+ """
722
+ Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
723
+
724
+ Arguments:
725
+ attention_mask (:obj:`torch.Tensor`):
726
+ Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
727
+ input_shape (:obj:`Tuple[int]`):
728
+ The shape of the input to the model.
729
+ device: (:obj:`torch.device`):
730
+ The device of the input to the model.
731
+
732
+ Returns:
733
+ :obj:`torch.Tensor` The extended attention mask, with a the same dtype as :obj:`attention_mask.dtype`.
734
+ """
735
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
736
+ # ourselves in which case we just need to make it broadcastable to all heads.
737
+ if attention_mask.dim() == 3:
738
+ extended_attention_mask = attention_mask[:, None, :, :]
739
+ elif attention_mask.dim() == 2:
740
+ # Provided a padding mask of dimensions [batch_size, seq_length]
741
+ # - if the model is a decoder, apply a causal mask in addition to the padding mask
742
+ # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length]
743
+ if is_decoder:
744
+ batch_size, seq_length = input_shape
745
+
746
+ seq_ids = torch.arange(seq_length, device=device)
747
+ causal_mask = (
748
+ seq_ids[None, None, :].repeat(batch_size, seq_length, 1)
749
+ <= seq_ids[None, :, None]
750
+ )
751
+
752
+ # add a prefix ones mask to the causal mask
753
+ # causal and attention masks must have same type with pytorch version < 1.3
754
+ causal_mask = causal_mask.to(attention_mask.dtype)
755
+
756
+ if causal_mask.shape[1] < attention_mask.shape[1]:
757
+ prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1]
758
+ if has_query: # UniLM style attention mask
759
+ causal_mask = torch.cat(
760
+ [
761
+ torch.zeros(
762
+ (batch_size, prefix_seq_len, seq_length),
763
+ device=device,
764
+ dtype=causal_mask.dtype,
765
+ ),
766
+ causal_mask,
767
+ ],
768
+ axis=1,
769
+ )
770
+ causal_mask = torch.cat(
771
+ [
772
+ torch.ones(
773
+ (batch_size, causal_mask.shape[1], prefix_seq_len),
774
+ device=device,
775
+ dtype=causal_mask.dtype,
776
+ ),
777
+ causal_mask,
778
+ ],
779
+ axis=-1,
780
+ )
781
+ extended_attention_mask = (
782
+ causal_mask[:, None, :, :] * attention_mask[:, None, None, :]
783
+ )
784
+ else:
785
+ extended_attention_mask = attention_mask[:, None, None, :]
786
+ else:
787
+ raise ValueError(
788
+ "Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format(
789
+ input_shape, attention_mask.shape
790
+ )
791
+ )
792
+
793
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
794
+ # masked positions, this operation will create a tensor which is 0.0 for
795
+ # positions we want to attend and -10000.0 for masked positions.
796
+ # Since we are adding it to the raw scores before the softmax, this is
797
+ # effectively the same as removing these entirely.
798
+ extended_attention_mask = extended_attention_mask.to(
799
+ dtype=self.dtype
800
+ ) # fp16 compatibility
801
+ extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
802
+ return extended_attention_mask
803
+
804
+ def forward(
805
+ self,
806
+ input_ids=None,
807
+ attention_mask=None,
808
+ position_ids=None,
809
+ head_mask=None,
810
+ query_embeds=None,
811
+ encoder_hidden_states=None,
812
+ encoder_attention_mask=None,
813
+ past_key_values=None,
814
+ use_cache=None,
815
+ output_attentions=None,
816
+ output_hidden_states=None,
817
+ return_dict=None,
818
+ is_decoder=False,
819
+ ):
820
+ r"""
821
+ encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
822
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
823
+ the model is configured as a decoder.
824
+ encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
825
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
826
+ the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
827
+ - 1 for tokens that are **not masked**,
828
+ - 0 for tokens that are **masked**.
829
+ past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
830
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
831
+ If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
832
+ (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
833
+ instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
834
+ use_cache (:obj:`bool`, `optional`):
835
+ If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
836
+ decoding (see :obj:`past_key_values`).
837
+ """
838
+ output_attentions = (
839
+ output_attentions
840
+ if output_attentions is not None
841
+ else self.config.output_attentions
842
+ )
843
+ output_hidden_states = (
844
+ output_hidden_states
845
+ if output_hidden_states is not None
846
+ else self.config.output_hidden_states
847
+ )
848
+ return_dict = (
849
+ return_dict if return_dict is not None else self.config.use_return_dict
850
+ )
851
+
852
+ # use_cache = use_cache if use_cache is not None else self.config.use_cache
853
+
854
+ if input_ids is None:
855
+ assert (
856
+ query_embeds is not None
857
+ ), "You have to specify query_embeds when input_ids is None"
858
+
859
+ # past_key_values_length
860
+ past_key_values_length = (
861
+ past_key_values[0][0].shape[2] - self.config.query_length
862
+ if past_key_values is not None
863
+ else 0
864
+ )
865
+
866
+ query_length = query_embeds.shape[1] if query_embeds is not None else 0
867
+
868
+ embedding_output = self.embeddings(
869
+ input_ids=input_ids,
870
+ position_ids=position_ids,
871
+ query_embeds=query_embeds,
872
+ past_key_values_length=past_key_values_length,
873
+ )
874
+
875
+ input_shape = embedding_output.size()[:-1]
876
+ batch_size, seq_length = input_shape
877
+ device = embedding_output.device
878
+
879
+ if attention_mask is None:
880
+ attention_mask = torch.ones(
881
+ ((batch_size, seq_length + past_key_values_length)), device=device
882
+ )
883
+
884
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
885
+ # ourselves in which case we just need to make it broadcastable to all heads.
886
+ if is_decoder:
887
+ extended_attention_mask = self.get_extended_attention_mask(
888
+ attention_mask,
889
+ input_ids.shape,
890
+ device,
891
+ is_decoder,
892
+ has_query=(query_embeds is not None),
893
+ )
894
+ else:
895
+ extended_attention_mask = self.get_extended_attention_mask(
896
+ attention_mask, input_shape, device, is_decoder
897
+ )
898
+
899
+ # If a 2D or 3D attention mask is provided for the cross-attention
900
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
901
+ if encoder_hidden_states is not None:
902
+ if type(encoder_hidden_states) == list:
903
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[
904
+ 0
905
+ ].size()
906
+ else:
907
+ (
908
+ encoder_batch_size,
909
+ encoder_sequence_length,
910
+ _,
911
+ ) = encoder_hidden_states.size()
912
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
913
+
914
+ if type(encoder_attention_mask) == list:
915
+ encoder_extended_attention_mask = [
916
+ self.invert_attention_mask(mask) for mask in encoder_attention_mask
917
+ ]
918
+ elif encoder_attention_mask is None:
919
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
920
+ encoder_extended_attention_mask = self.invert_attention_mask(
921
+ encoder_attention_mask
922
+ )
923
+ else:
924
+ encoder_extended_attention_mask = self.invert_attention_mask(
925
+ encoder_attention_mask
926
+ )
927
+ else:
928
+ encoder_extended_attention_mask = None
929
+
930
+ # Prepare head mask if needed
931
+ # 1.0 in head_mask indicate we keep the head
932
+ # attention_probs has shape bsz x n_heads x N x N
933
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
934
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
935
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
936
+
937
+ encoder_outputs = self.encoder(
938
+ embedding_output,
939
+ attention_mask=extended_attention_mask,
940
+ head_mask=head_mask,
941
+ encoder_hidden_states=encoder_hidden_states,
942
+ encoder_attention_mask=encoder_extended_attention_mask,
943
+ past_key_values=past_key_values,
944
+ use_cache=use_cache,
945
+ output_attentions=output_attentions,
946
+ output_hidden_states=output_hidden_states,
947
+ return_dict=return_dict,
948
+ query_length=query_length,
949
+ )
950
+ sequence_output = encoder_outputs[0]
951
+ pooled_output = (
952
+ self.pooler(sequence_output) if self.pooler is not None else None
953
+ )
954
+
955
+ if not return_dict:
956
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
957
+
958
+ return BaseModelOutputWithPoolingAndCrossAttentions(
959
+ last_hidden_state=sequence_output,
960
+ pooler_output=pooled_output,
961
+ past_key_values=encoder_outputs.past_key_values,
962
+ hidden_states=encoder_outputs.hidden_states,
963
+ attentions=encoder_outputs.attentions,
964
+ cross_attentions=encoder_outputs.cross_attentions,
965
+ )
966
+
967
+
968
+ class BertLMHeadModel(BertPreTrainedModel):
969
+
970
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
971
+ _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
972
+
973
+ def __init__(self, config):
974
+ super().__init__(config)
975
+
976
+ self.bert = BertModel(config, add_pooling_layer=False)
977
+ self.cls = BertOnlyMLMHead(config)
978
+
979
+ self.init_weights()
980
+
981
+ def get_output_embeddings(self):
982
+ return self.cls.predictions.decoder
983
+
984
+ def set_output_embeddings(self, new_embeddings):
985
+ self.cls.predictions.decoder = new_embeddings
986
+
987
+ def forward(
988
+ self,
989
+ input_ids=None,
990
+ attention_mask=None,
991
+ position_ids=None,
992
+ head_mask=None,
993
+ query_embeds=None,
994
+ encoder_hidden_states=None,
995
+ encoder_attention_mask=None,
996
+ labels=None,
997
+ past_key_values=None,
998
+ use_cache=True,
999
+ output_attentions=None,
1000
+ output_hidden_states=None,
1001
+ return_dict=None,
1002
+ return_logits=False,
1003
+ is_decoder=True,
1004
+ reduction="mean",
1005
+ ):
1006
+ r"""
1007
+ encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
1008
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
1009
+ the model is configured as a decoder.
1010
+ encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
1011
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
1012
+ the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
1013
+ - 1 for tokens that are **not masked**,
1014
+ - 0 for tokens that are **masked**.
1015
+ labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
1016
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
1017
+ ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are
1018
+ ignored (masked), the loss is only computed for the tokens with labels n ``[0, ..., config.vocab_size]``
1019
+ past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
1020
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1021
+ If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
1022
+ (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
1023
+ instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
1024
+ use_cache (:obj:`bool`, `optional`):
1025
+ If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
1026
+ decoding (see :obj:`past_key_values`).
1027
+ Returns:
1028
+ Example::
1029
+ >>> from transformers import BertTokenizer, BertLMHeadModel, BertConfig
1030
+ >>> import torch
1031
+ >>> tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
1032
+ >>> config = BertConfig.from_pretrained("bert-base-cased")
1033
+ >>> model = BertLMHeadModel.from_pretrained('bert-base-cased', config=config)
1034
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
1035
+ >>> outputs = model(**inputs)
1036
+ >>> prediction_logits = outputs.logits
1037
+ """
1038
+ return_dict = (
1039
+ return_dict if return_dict is not None else self.config.use_return_dict
1040
+ )
1041
+ if labels is not None:
1042
+ use_cache = False
1043
+ if past_key_values is not None:
1044
+ query_embeds = None
1045
+
1046
+ outputs = self.bert(
1047
+ input_ids,
1048
+ attention_mask=attention_mask,
1049
+ position_ids=position_ids,
1050
+ head_mask=head_mask,
1051
+ query_embeds=query_embeds,
1052
+ encoder_hidden_states=encoder_hidden_states,
1053
+ encoder_attention_mask=encoder_attention_mask,
1054
+ past_key_values=past_key_values,
1055
+ use_cache=use_cache,
1056
+ output_attentions=output_attentions,
1057
+ output_hidden_states=output_hidden_states,
1058
+ return_dict=return_dict,
1059
+ is_decoder=is_decoder,
1060
+ )
1061
+
1062
+ sequence_output = outputs[0]
1063
+ if query_embeds is not None:
1064
+ sequence_output = outputs[0][:, query_embeds.shape[1] :, :]
1065
+
1066
+ prediction_scores = self.cls(sequence_output)
1067
+
1068
+ if return_logits:
1069
+ return prediction_scores[:, :-1, :].contiguous()
1070
+
1071
+ lm_loss = None
1072
+ if labels is not None:
1073
+ # we are doing next-token prediction; shift prediction scores and input ids by one
1074
+ shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
1075
+ labels = labels[:, 1:].contiguous()
1076
+ loss_fct = CrossEntropyLoss(reduction=reduction, label_smoothing=0.1)
1077
+ lm_loss = loss_fct(
1078
+ shifted_prediction_scores.view(-1, self.config.vocab_size),
1079
+ labels.view(-1),
1080
+ )
1081
+ if reduction == "none":
1082
+ lm_loss = lm_loss.view(prediction_scores.size(0), -1).sum(1)
1083
+
1084
+ if not return_dict:
1085
+ output = (prediction_scores,) + outputs[2:]
1086
+ return ((lm_loss,) + output) if lm_loss is not None else output
1087
+
1088
+ return CausalLMOutputWithCrossAttentions(
1089
+ loss=lm_loss,
1090
+ logits=prediction_scores,
1091
+ past_key_values=outputs.past_key_values,
1092
+ hidden_states=outputs.hidden_states,
1093
+ attentions=outputs.attentions,
1094
+ cross_attentions=outputs.cross_attentions,
1095
+ )
1096
+
1097
+ def prepare_inputs_for_generation(
1098
+ self, input_ids, query_embeds, past=None, attention_mask=None, **model_kwargs
1099
+ ):
1100
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
1101
+ if attention_mask is None:
1102
+ attention_mask = input_ids.new_ones(input_ids.shape)
1103
+ query_mask = input_ids.new_ones(query_embeds.shape[:-1])
1104
+ attention_mask = torch.cat([query_mask, attention_mask], dim=-1)
1105
+
1106
+ # cut decoder_input_ids if past is used
1107
+ if past is not None:
1108
+ input_ids = input_ids[:, -1:]
1109
+
1110
+ return {
1111
+ "input_ids": input_ids,
1112
+ "query_embeds": query_embeds,
1113
+ "attention_mask": attention_mask,
1114
+ "past_key_values": past,
1115
+ "encoder_hidden_states": model_kwargs.get("encoder_hidden_states", None),
1116
+ "encoder_attention_mask": model_kwargs.get("encoder_attention_mask", None),
1117
+ "is_decoder": True,
1118
+ }
1119
+
1120
+ def _reorder_cache(self, past, beam_idx):
1121
+ reordered_past = ()
1122
+ for layer_past in past:
1123
+ reordered_past += (
1124
+ tuple(
1125
+ past_state.index_select(0, beam_idx) for past_state in layer_past
1126
+ ),
1127
+ )
1128
+ return reordered_past
1129
+
1130
+
1131
+ class BertForMaskedLM(BertPreTrainedModel):
1132
+
1133
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
1134
+ _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
1135
+
1136
+ def __init__(self, config):
1137
+ super().__init__(config)
1138
+
1139
+ self.bert = BertModel(config, add_pooling_layer=False)
1140
+ self.cls = BertOnlyMLMHead(config)
1141
+
1142
+ self.init_weights()
1143
+
1144
+ def get_output_embeddings(self):
1145
+ return self.cls.predictions.decoder
1146
+
1147
+ def set_output_embeddings(self, new_embeddings):
1148
+ self.cls.predictions.decoder = new_embeddings
1149
+
1150
+ def forward(
1151
+ self,
1152
+ input_ids=None,
1153
+ attention_mask=None,
1154
+ position_ids=None,
1155
+ head_mask=None,
1156
+ query_embeds=None,
1157
+ encoder_hidden_states=None,
1158
+ encoder_attention_mask=None,
1159
+ labels=None,
1160
+ output_attentions=None,
1161
+ output_hidden_states=None,
1162
+ return_dict=None,
1163
+ return_logits=False,
1164
+ is_decoder=False,
1165
+ ):
1166
+ r"""
1167
+ labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
1168
+ Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ...,
1169
+ config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored
1170
+ (masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]``
1171
+ """
1172
+
1173
+ return_dict = (
1174
+ return_dict if return_dict is not None else self.config.use_return_dict
1175
+ )
1176
+
1177
+ outputs = self.bert(
1178
+ input_ids,
1179
+ attention_mask=attention_mask,
1180
+ position_ids=position_ids,
1181
+ head_mask=head_mask,
1182
+ query_embeds=query_embeds,
1183
+ encoder_hidden_states=encoder_hidden_states,
1184
+ encoder_attention_mask=encoder_attention_mask,
1185
+ output_attentions=output_attentions,
1186
+ output_hidden_states=output_hidden_states,
1187
+ return_dict=return_dict,
1188
+ is_decoder=is_decoder,
1189
+ )
1190
+
1191
+ if query_embeds is not None:
1192
+ sequence_output = outputs[0][:, query_embeds.shape[1] :, :]
1193
+ prediction_scores = self.cls(sequence_output)
1194
+
1195
+ if return_logits:
1196
+ return prediction_scores
1197
+
1198
+ masked_lm_loss = None
1199
+ if labels is not None:
1200
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
1201
+ masked_lm_loss = loss_fct(
1202
+ prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)
1203
+ )
1204
+
1205
+ if not return_dict:
1206
+ output = (prediction_scores,) + outputs[2:]
1207
+ return (
1208
+ ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1209
+ )
1210
+
1211
+ return MaskedLMOutput(
1212
+ loss=masked_lm_loss,
1213
+ logits=prediction_scores,
1214
+ hidden_states=outputs.hidden_states,
1215
+ attentions=outputs.attentions,
1216
+ )
qformer_src.py ADDED
@@ -0,0 +1,1216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ * Copyright (c) 2023, salesforce.com, inc.
3
+ * All rights reserved.
4
+ * SPDX-License-Identifier: BSD-3-Clause
5
+ * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
6
+ * By Junnan Li
7
+ * Based on huggingface code base
8
+ * https://github.com/huggingface/transformers/blob/v4.15.0/src/transformers/models/bert
9
+ """
10
+
11
+ import math
12
+ import os
13
+ import warnings
14
+ from dataclasses import dataclass
15
+ from typing import Optional, Tuple, Dict, Any
16
+
17
+ import torch
18
+ from torch import Tensor, device, dtype, nn
19
+ import torch.utils.checkpoint
20
+ from torch import nn
21
+ from torch.nn import CrossEntropyLoss
22
+ import torch.nn.functional as F
23
+
24
+ from transformers.activations import ACT2FN
25
+ from transformers.file_utils import (
26
+ ModelOutput,
27
+ )
28
+ from transformers.modeling_outputs import (
29
+ BaseModelOutputWithPastAndCrossAttentions,
30
+ BaseModelOutputWithPoolingAndCrossAttentions,
31
+ CausalLMOutputWithCrossAttentions,
32
+ MaskedLMOutput,
33
+ MultipleChoiceModelOutput,
34
+ NextSentencePredictorOutput,
35
+ QuestionAnsweringModelOutput,
36
+ SequenceClassifierOutput,
37
+ TokenClassifierOutput,
38
+ )
39
+ from transformers.modeling_utils import (
40
+ PreTrainedModel,
41
+ apply_chunking_to_forward,
42
+ find_pruneable_heads_and_indices,
43
+ prune_linear_layer,
44
+ )
45
+ from transformers.utils import logging
46
+ from transformers.models.bert.configuration_bert import BertConfig
47
+
48
+ logger = logging.get_logger(__name__)
49
+
50
+
51
+ class BertEmbeddings(nn.Module):
52
+ """Construct the embeddings from word and position embeddings."""
53
+
54
+ def __init__(self, config):
55
+ super().__init__()
56
+ self.word_embeddings = nn.Embedding(
57
+ config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id
58
+ )
59
+ self.position_embeddings = nn.Embedding(
60
+ config.max_position_embeddings, config.hidden_size
61
+ )
62
+
63
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
64
+ # any TensorFlow checkpoint file
65
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
66
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
67
+
68
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
69
+ self.register_buffer(
70
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1))
71
+ )
72
+ self.position_embedding_type = getattr(
73
+ config, "position_embedding_type", "absolute"
74
+ )
75
+
76
+ self.config = config
77
+
78
+ def forward(
79
+ self,
80
+ input_ids=None,
81
+ position_ids=None,
82
+ query_embeds=None,
83
+ past_key_values_length=0,
84
+ ):
85
+ if input_ids is not None:
86
+ seq_length = input_ids.size()[1]
87
+ else:
88
+ seq_length = 0
89
+
90
+ if position_ids is None:
91
+ position_ids = self.position_ids[
92
+ :, past_key_values_length : seq_length + past_key_values_length
93
+ ].clone()
94
+
95
+ if input_ids is not None:
96
+ embeddings = self.word_embeddings(input_ids)
97
+ if self.position_embedding_type == "absolute":
98
+ position_embeddings = self.position_embeddings(position_ids)
99
+ embeddings = embeddings + position_embeddings
100
+
101
+ if query_embeds is not None:
102
+ embeddings = torch.cat((query_embeds, embeddings), dim=1)
103
+ else:
104
+ embeddings = query_embeds
105
+
106
+ embeddings = self.LayerNorm(embeddings)
107
+ embeddings = self.dropout(embeddings)
108
+ return embeddings
109
+
110
+
111
+ class BertSelfAttention(nn.Module):
112
+ def __init__(self, config, is_cross_attention):
113
+ super().__init__()
114
+ self.config = config
115
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(
116
+ config, "embedding_size"
117
+ ):
118
+ raise ValueError(
119
+ "The hidden size (%d) is not a multiple of the number of attention "
120
+ "heads (%d)" % (config.hidden_size, config.num_attention_heads)
121
+ )
122
+
123
+ self.num_attention_heads = config.num_attention_heads
124
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
125
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
126
+
127
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
128
+ if is_cross_attention:
129
+ self.key = nn.Linear(config.encoder_width, self.all_head_size)
130
+ self.value = nn.Linear(config.encoder_width, self.all_head_size)
131
+ else:
132
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
133
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
134
+
135
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
136
+ self.position_embedding_type = getattr(
137
+ config, "position_embedding_type", "absolute"
138
+ )
139
+ if (
140
+ self.position_embedding_type == "relative_key"
141
+ or self.position_embedding_type == "relative_key_query"
142
+ ):
143
+ self.max_position_embeddings = config.max_position_embeddings
144
+ self.distance_embedding = nn.Embedding(
145
+ 2 * config.max_position_embeddings - 1, self.attention_head_size
146
+ )
147
+ self.save_attention = False
148
+
149
+ def save_attn_gradients(self, attn_gradients):
150
+ self.attn_gradients = attn_gradients
151
+
152
+ def get_attn_gradients(self):
153
+ return self.attn_gradients
154
+
155
+ def save_attention_map(self, attention_map):
156
+ self.attention_map = attention_map
157
+
158
+ def get_attention_map(self):
159
+ return self.attention_map
160
+
161
+ def transpose_for_scores(self, x):
162
+ new_x_shape = x.size()[:-1] + (
163
+ self.num_attention_heads,
164
+ self.attention_head_size,
165
+ )
166
+ x = x.view(*new_x_shape)
167
+ return x.permute(0, 2, 1, 3)
168
+
169
+ def forward(
170
+ self,
171
+ hidden_states,
172
+ attention_mask=None,
173
+ head_mask=None,
174
+ encoder_hidden_states=None,
175
+ encoder_attention_mask=None,
176
+ past_key_value=None,
177
+ output_attentions=False,
178
+ ):
179
+
180
+ # If this is instantiated as a cross-attention module, the keys
181
+ # and values come from an encoder; the attention mask needs to be
182
+ # such that the encoder's padding tokens are not attended to.
183
+ is_cross_attention = encoder_hidden_states is not None
184
+
185
+ if is_cross_attention:
186
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
187
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
188
+ attention_mask = encoder_attention_mask
189
+ elif past_key_value is not None:
190
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
191
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
192
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
193
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
194
+ else:
195
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
196
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
197
+
198
+ mixed_query_layer = self.query(hidden_states)
199
+
200
+ query_layer = self.transpose_for_scores(mixed_query_layer)
201
+
202
+ past_key_value = (key_layer, value_layer)
203
+
204
+ # Take the dot product between "query" and "key" to get the raw attention scores.
205
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
206
+
207
+ if (
208
+ self.position_embedding_type == "relative_key"
209
+ or self.position_embedding_type == "relative_key_query"
210
+ ):
211
+ seq_length = hidden_states.size()[1]
212
+ position_ids_l = torch.arange(
213
+ seq_length, dtype=torch.long, device=hidden_states.device
214
+ ).view(-1, 1)
215
+ position_ids_r = torch.arange(
216
+ seq_length, dtype=torch.long, device=hidden_states.device
217
+ ).view(1, -1)
218
+ distance = position_ids_l - position_ids_r
219
+ positional_embedding = self.distance_embedding(
220
+ distance + self.max_position_embeddings - 1
221
+ )
222
+ positional_embedding = positional_embedding.to(
223
+ dtype=query_layer.dtype
224
+ ) # fp16 compatibility
225
+
226
+ if self.position_embedding_type == "relative_key":
227
+ relative_position_scores = torch.einsum(
228
+ "bhld,lrd->bhlr", query_layer, positional_embedding
229
+ )
230
+ attention_scores = attention_scores + relative_position_scores
231
+ elif self.position_embedding_type == "relative_key_query":
232
+ relative_position_scores_query = torch.einsum(
233
+ "bhld,lrd->bhlr", query_layer, positional_embedding
234
+ )
235
+ relative_position_scores_key = torch.einsum(
236
+ "bhrd,lrd->bhlr", key_layer, positional_embedding
237
+ )
238
+ attention_scores = (
239
+ attention_scores
240
+ + relative_position_scores_query
241
+ + relative_position_scores_key
242
+ )
243
+
244
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
245
+ if attention_mask is not None:
246
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
247
+ attention_scores = attention_scores + attention_mask
248
+
249
+ # Normalize the attention scores to probabilities.
250
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
251
+
252
+ if is_cross_attention and self.save_attention:
253
+ self.save_attention_map(attention_probs)
254
+ attention_probs.register_hook(self.save_attn_gradients)
255
+
256
+ # This is actually dropping out entire tokens to attend to, which might
257
+ # seem a bit unusual, but is taken from the original Transformer paper.
258
+ attention_probs_dropped = self.dropout(attention_probs)
259
+
260
+ # Mask heads if we want to
261
+ if head_mask is not None:
262
+ attention_probs_dropped = attention_probs_dropped * head_mask
263
+
264
+ context_layer = torch.matmul(attention_probs_dropped, value_layer)
265
+
266
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
267
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
268
+ context_layer = context_layer.view(*new_context_layer_shape)
269
+
270
+ outputs = (
271
+ (context_layer, attention_probs) if output_attentions else (context_layer,)
272
+ )
273
+
274
+ outputs = outputs + (past_key_value,)
275
+ return outputs
276
+
277
+
278
+ class BertSelfOutput(nn.Module):
279
+ def __init__(self, config):
280
+ super().__init__()
281
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
282
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
283
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
284
+
285
+ def forward(self, hidden_states, input_tensor):
286
+ hidden_states = self.dense(hidden_states)
287
+ hidden_states = self.dropout(hidden_states)
288
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
289
+ return hidden_states
290
+
291
+
292
+ class BertAttention(nn.Module):
293
+ def __init__(self, config, is_cross_attention=False):
294
+ super().__init__()
295
+ self.self = BertSelfAttention(config, is_cross_attention)
296
+ self.output = BertSelfOutput(config)
297
+ self.pruned_heads = set()
298
+
299
+ def prune_heads(self, heads):
300
+ if len(heads) == 0:
301
+ return
302
+ heads, index = find_pruneable_heads_and_indices(
303
+ heads,
304
+ self.self.num_attention_heads,
305
+ self.self.attention_head_size,
306
+ self.pruned_heads,
307
+ )
308
+
309
+ # Prune linear layers
310
+ self.self.query = prune_linear_layer(self.self.query, index)
311
+ self.self.key = prune_linear_layer(self.self.key, index)
312
+ self.self.value = prune_linear_layer(self.self.value, index)
313
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
314
+
315
+ # Update hyper params and store pruned heads
316
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
317
+ self.self.all_head_size = (
318
+ self.self.attention_head_size * self.self.num_attention_heads
319
+ )
320
+ self.pruned_heads = self.pruned_heads.union(heads)
321
+
322
+ def forward(
323
+ self,
324
+ hidden_states,
325
+ attention_mask=None,
326
+ head_mask=None,
327
+ encoder_hidden_states=None,
328
+ encoder_attention_mask=None,
329
+ past_key_value=None,
330
+ output_attentions=False,
331
+ ):
332
+ self_outputs = self.self(
333
+ hidden_states,
334
+ attention_mask,
335
+ head_mask,
336
+ encoder_hidden_states,
337
+ encoder_attention_mask,
338
+ past_key_value,
339
+ output_attentions,
340
+ )
341
+ attention_output = self.output(self_outputs[0], hidden_states)
342
+
343
+ outputs = (attention_output,) + self_outputs[
344
+ 1:
345
+ ] # add attentions if we output them
346
+ return outputs
347
+
348
+
349
+ class BertIntermediate(nn.Module):
350
+ def __init__(self, config):
351
+ super().__init__()
352
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
353
+ if isinstance(config.hidden_act, str):
354
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
355
+ else:
356
+ self.intermediate_act_fn = config.hidden_act
357
+
358
+ def forward(self, hidden_states):
359
+ hidden_states = self.dense(hidden_states)
360
+ hidden_states = self.intermediate_act_fn(hidden_states)
361
+ return hidden_states
362
+
363
+
364
+ class BertOutput(nn.Module):
365
+ def __init__(self, config):
366
+ super().__init__()
367
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
368
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
369
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
370
+
371
+ def forward(self, hidden_states, input_tensor):
372
+ hidden_states = self.dense(hidden_states)
373
+ hidden_states = self.dropout(hidden_states)
374
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
375
+ return hidden_states
376
+
377
+
378
+ class BertLayer(nn.Module):
379
+ def __init__(self, config, layer_num):
380
+ super().__init__()
381
+ self.config = config
382
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
383
+ self.seq_len_dim = 1
384
+ self.attention = BertAttention(config)
385
+ self.layer_num = layer_num
386
+ if (
387
+ self.config.add_cross_attention
388
+ and layer_num % self.config.cross_attention_freq == 0
389
+ ):
390
+ self.crossattention = BertAttention(
391
+ config, is_cross_attention=self.config.add_cross_attention
392
+ )
393
+ self.has_cross_attention = True
394
+ else:
395
+ self.has_cross_attention = False
396
+ self.intermediate = BertIntermediate(config)
397
+ self.output = BertOutput(config)
398
+
399
+ self.intermediate_query = BertIntermediate(config)
400
+ self.output_query = BertOutput(config)
401
+
402
+ def forward(
403
+ self,
404
+ hidden_states,
405
+ attention_mask=None,
406
+ head_mask=None,
407
+ encoder_hidden_states=None,
408
+ encoder_attention_mask=None,
409
+ past_key_value=None,
410
+ output_attentions=False,
411
+ query_length=0,
412
+ ):
413
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
414
+ self_attn_past_key_value = (
415
+ past_key_value[:2] if past_key_value is not None else None
416
+ )
417
+ self_attention_outputs = self.attention(
418
+ hidden_states,
419
+ attention_mask,
420
+ head_mask,
421
+ output_attentions=output_attentions,
422
+ past_key_value=self_attn_past_key_value,
423
+ )
424
+ attention_output = self_attention_outputs[0]
425
+ outputs = self_attention_outputs[1:-1]
426
+
427
+ present_key_value = self_attention_outputs[-1]
428
+
429
+ if query_length > 0:
430
+ query_attention_output = attention_output[:, :query_length, :]
431
+
432
+ if self.has_cross_attention:
433
+ assert (
434
+ encoder_hidden_states is not None
435
+ ), "encoder_hidden_states must be given for cross-attention layers"
436
+ cross_attention_outputs = self.crossattention(
437
+ query_attention_output,
438
+ attention_mask,
439
+ head_mask,
440
+ encoder_hidden_states,
441
+ encoder_attention_mask,
442
+ output_attentions=output_attentions,
443
+ )
444
+ query_attention_output = cross_attention_outputs[0]
445
+ outputs = (
446
+ outputs + cross_attention_outputs[1:-1]
447
+ ) # add cross attentions if we output attention weights
448
+
449
+ layer_output = apply_chunking_to_forward(
450
+ self.feed_forward_chunk_query,
451
+ self.chunk_size_feed_forward,
452
+ self.seq_len_dim,
453
+ query_attention_output,
454
+ )
455
+ if attention_output.shape[1] > query_length:
456
+ layer_output_text = apply_chunking_to_forward(
457
+ self.feed_forward_chunk,
458
+ self.chunk_size_feed_forward,
459
+ self.seq_len_dim,
460
+ attention_output[:, query_length:, :],
461
+ )
462
+ layer_output = torch.cat([layer_output, layer_output_text], dim=1)
463
+ else:
464
+ layer_output = apply_chunking_to_forward(
465
+ self.feed_forward_chunk,
466
+ self.chunk_size_feed_forward,
467
+ self.seq_len_dim,
468
+ attention_output,
469
+ )
470
+ outputs = (layer_output,) + outputs
471
+
472
+ outputs = outputs + (present_key_value,)
473
+
474
+ return outputs
475
+
476
+ def feed_forward_chunk(self, attention_output):
477
+ intermediate_output = self.intermediate(attention_output)
478
+ layer_output = self.output(intermediate_output, attention_output)
479
+ return layer_output
480
+
481
+ def feed_forward_chunk_query(self, attention_output):
482
+ intermediate_output = self.intermediate_query(attention_output)
483
+ layer_output = self.output_query(intermediate_output, attention_output)
484
+ return layer_output
485
+
486
+
487
+ class BertEncoder(nn.Module):
488
+ def __init__(self, config):
489
+ super().__init__()
490
+ self.config = config
491
+ self.layer = nn.ModuleList(
492
+ [BertLayer(config, i) for i in range(config.num_hidden_layers)]
493
+ )
494
+
495
+ def forward(
496
+ self,
497
+ hidden_states,
498
+ attention_mask=None,
499
+ head_mask=None,
500
+ encoder_hidden_states=None,
501
+ encoder_attention_mask=None,
502
+ past_key_values=None,
503
+ use_cache=None,
504
+ output_attentions=False,
505
+ output_hidden_states=False,
506
+ return_dict=True,
507
+ query_length=0,
508
+ ):
509
+ all_hidden_states = () if output_hidden_states else None
510
+ all_self_attentions = () if output_attentions else None
511
+ all_cross_attentions = (
512
+ () if output_attentions and self.config.add_cross_attention else None
513
+ )
514
+
515
+ next_decoder_cache = () if use_cache else None
516
+
517
+ for i in range(self.config.num_hidden_layers):
518
+ layer_module = self.layer[i]
519
+ if output_hidden_states:
520
+ all_hidden_states = all_hidden_states + (hidden_states,)
521
+
522
+ layer_head_mask = head_mask[i] if head_mask is not None else None
523
+ past_key_value = past_key_values[i] if past_key_values is not None else None
524
+
525
+ if getattr(self.config, "gradient_checkpointing", False) and self.training:
526
+
527
+ if use_cache:
528
+ logger.warn(
529
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
530
+ )
531
+ use_cache = False
532
+
533
+ def create_custom_forward(module):
534
+ def custom_forward(*inputs):
535
+ return module(
536
+ *inputs, past_key_value, output_attentions, query_length
537
+ )
538
+
539
+ return custom_forward
540
+
541
+ layer_outputs = torch.utils.checkpoint.checkpoint(
542
+ create_custom_forward(layer_module),
543
+ hidden_states,
544
+ attention_mask,
545
+ layer_head_mask,
546
+ encoder_hidden_states,
547
+ encoder_attention_mask,
548
+ )
549
+ else:
550
+ layer_outputs = layer_module(
551
+ hidden_states,
552
+ attention_mask,
553
+ layer_head_mask,
554
+ encoder_hidden_states,
555
+ encoder_attention_mask,
556
+ past_key_value,
557
+ output_attentions,
558
+ query_length,
559
+ )
560
+
561
+ hidden_states = layer_outputs[0]
562
+ if use_cache:
563
+ next_decoder_cache += (layer_outputs[-1],)
564
+ if output_attentions:
565
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
566
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
567
+
568
+ if output_hidden_states:
569
+ all_hidden_states = all_hidden_states + (hidden_states,)
570
+
571
+ if not return_dict:
572
+ return tuple(
573
+ v
574
+ for v in [
575
+ hidden_states,
576
+ next_decoder_cache,
577
+ all_hidden_states,
578
+ all_self_attentions,
579
+ all_cross_attentions,
580
+ ]
581
+ if v is not None
582
+ )
583
+ return BaseModelOutputWithPastAndCrossAttentions(
584
+ last_hidden_state=hidden_states,
585
+ past_key_values=next_decoder_cache,
586
+ hidden_states=all_hidden_states,
587
+ attentions=all_self_attentions,
588
+ cross_attentions=all_cross_attentions,
589
+ )
590
+
591
+
592
+ class BertPooler(nn.Module):
593
+ def __init__(self, config):
594
+ super().__init__()
595
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
596
+ self.activation = nn.Tanh()
597
+
598
+ def forward(self, hidden_states):
599
+ # We "pool" the model by simply taking the hidden state corresponding
600
+ # to the first token.
601
+ first_token_tensor = hidden_states[:, 0]
602
+ pooled_output = self.dense(first_token_tensor)
603
+ pooled_output = self.activation(pooled_output)
604
+ return pooled_output
605
+
606
+
607
+ class BertPredictionHeadTransform(nn.Module):
608
+ def __init__(self, config):
609
+ super().__init__()
610
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
611
+ if isinstance(config.hidden_act, str):
612
+ self.transform_act_fn = ACT2FN[config.hidden_act]
613
+ else:
614
+ self.transform_act_fn = config.hidden_act
615
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
616
+
617
+ def forward(self, hidden_states):
618
+ hidden_states = self.dense(hidden_states)
619
+ hidden_states = self.transform_act_fn(hidden_states)
620
+ hidden_states = self.LayerNorm(hidden_states)
621
+ return hidden_states
622
+
623
+
624
+ class BertLMPredictionHead(nn.Module):
625
+ def __init__(self, config):
626
+ super().__init__()
627
+ self.transform = BertPredictionHeadTransform(config)
628
+
629
+ # The output weights are the same as the input embeddings, but there is
630
+ # an output-only bias for each token.
631
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
632
+
633
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
634
+
635
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
636
+ self.decoder.bias = self.bias
637
+
638
+ def forward(self, hidden_states):
639
+ hidden_states = self.transform(hidden_states)
640
+ hidden_states = self.decoder(hidden_states)
641
+ return hidden_states
642
+
643
+
644
+ class BertOnlyMLMHead(nn.Module):
645
+ def __init__(self, config):
646
+ super().__init__()
647
+ self.predictions = BertLMPredictionHead(config)
648
+
649
+ def forward(self, sequence_output):
650
+ prediction_scores = self.predictions(sequence_output)
651
+ return prediction_scores
652
+
653
+
654
+ class BertPreTrainedModel(PreTrainedModel):
655
+ """
656
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
657
+ models.
658
+ """
659
+
660
+ config_class = BertConfig
661
+ base_model_prefix = "bert"
662
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
663
+
664
+ def _init_weights(self, module):
665
+ """Initialize the weights"""
666
+ if isinstance(module, (nn.Linear, nn.Embedding)):
667
+ # Slightly different from the TF version which uses truncated_normal for initialization
668
+ # cf https://github.com/pytorch/pytorch/pull/5617
669
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
670
+ elif isinstance(module, nn.LayerNorm):
671
+ module.bias.data.zero_()
672
+ module.weight.data.fill_(1.0)
673
+ if isinstance(module, nn.Linear) and module.bias is not None:
674
+ module.bias.data.zero_()
675
+
676
+
677
+ class BertModel(BertPreTrainedModel):
678
+ """
679
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
680
+ cross-attention is added between the self-attention layers, following the architecture described in `Attention is
681
+ all you need <https://arxiv.org/abs/1706.03762>`__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
682
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
683
+ argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an
684
+ input to the forward pass.
685
+ """
686
+
687
+ def __init__(self, config, add_pooling_layer=False):
688
+ super().__init__(config)
689
+ self.config = config
690
+
691
+ self.embeddings = BertEmbeddings(config)
692
+
693
+ self.encoder = BertEncoder(config)
694
+
695
+ self.pooler = BertPooler(config) if add_pooling_layer else None
696
+
697
+ self.init_weights()
698
+
699
+ def get_input_embeddings(self):
700
+ return self.embeddings.word_embeddings
701
+
702
+ def set_input_embeddings(self, value):
703
+ self.embeddings.word_embeddings = value
704
+
705
+ def _prune_heads(self, heads_to_prune):
706
+ """
707
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
708
+ class PreTrainedModel
709
+ """
710
+ for layer, heads in heads_to_prune.items():
711
+ self.encoder.layer[layer].attention.prune_heads(heads)
712
+
713
+ def get_extended_attention_mask(
714
+ self,
715
+ attention_mask: Tensor,
716
+ input_shape: Tuple[int],
717
+ device: device,
718
+ is_decoder: bool,
719
+ has_query: bool = False,
720
+ ) -> Tensor:
721
+ """
722
+ Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
723
+
724
+ Arguments:
725
+ attention_mask (:obj:`torch.Tensor`):
726
+ Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
727
+ input_shape (:obj:`Tuple[int]`):
728
+ The shape of the input to the model.
729
+ device: (:obj:`torch.device`):
730
+ The device of the input to the model.
731
+
732
+ Returns:
733
+ :obj:`torch.Tensor` The extended attention mask, with a the same dtype as :obj:`attention_mask.dtype`.
734
+ """
735
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
736
+ # ourselves in which case we just need to make it broadcastable to all heads.
737
+ if attention_mask.dim() == 3:
738
+ extended_attention_mask = attention_mask[:, None, :, :]
739
+ elif attention_mask.dim() == 2:
740
+ # Provided a padding mask of dimensions [batch_size, seq_length]
741
+ # - if the model is a decoder, apply a causal mask in addition to the padding mask
742
+ # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length]
743
+ if is_decoder:
744
+ batch_size, seq_length = input_shape
745
+
746
+ seq_ids = torch.arange(seq_length, device=device)
747
+ causal_mask = (
748
+ seq_ids[None, None, :].repeat(batch_size, seq_length, 1)
749
+ <= seq_ids[None, :, None]
750
+ )
751
+
752
+ # add a prefix ones mask to the causal mask
753
+ # causal and attention masks must have same type with pytorch version < 1.3
754
+ causal_mask = causal_mask.to(attention_mask.dtype)
755
+
756
+ if causal_mask.shape[1] < attention_mask.shape[1]:
757
+ prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1]
758
+ if has_query: # UniLM style attention mask
759
+ causal_mask = torch.cat(
760
+ [
761
+ torch.zeros(
762
+ (batch_size, prefix_seq_len, seq_length),
763
+ device=device,
764
+ dtype=causal_mask.dtype,
765
+ ),
766
+ causal_mask,
767
+ ],
768
+ axis=1,
769
+ )
770
+ causal_mask = torch.cat(
771
+ [
772
+ torch.ones(
773
+ (batch_size, causal_mask.shape[1], prefix_seq_len),
774
+ device=device,
775
+ dtype=causal_mask.dtype,
776
+ ),
777
+ causal_mask,
778
+ ],
779
+ axis=-1,
780
+ )
781
+ extended_attention_mask = (
782
+ causal_mask[:, None, :, :] * attention_mask[:, None, None, :]
783
+ )
784
+ else:
785
+ extended_attention_mask = attention_mask[:, None, None, :]
786
+ else:
787
+ raise ValueError(
788
+ "Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format(
789
+ input_shape, attention_mask.shape
790
+ )
791
+ )
792
+
793
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
794
+ # masked positions, this operation will create a tensor which is 0.0 for
795
+ # positions we want to attend and -10000.0 for masked positions.
796
+ # Since we are adding it to the raw scores before the softmax, this is
797
+ # effectively the same as removing these entirely.
798
+ extended_attention_mask = extended_attention_mask.to(
799
+ dtype=self.dtype
800
+ ) # fp16 compatibility
801
+ extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
802
+ return extended_attention_mask
803
+
804
+ def forward(
805
+ self,
806
+ input_ids=None,
807
+ attention_mask=None,
808
+ position_ids=None,
809
+ head_mask=None,
810
+ query_embeds=None,
811
+ encoder_hidden_states=None,
812
+ encoder_attention_mask=None,
813
+ past_key_values=None,
814
+ use_cache=None,
815
+ output_attentions=None,
816
+ output_hidden_states=None,
817
+ return_dict=None,
818
+ is_decoder=False,
819
+ ):
820
+ r"""
821
+ encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
822
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
823
+ the model is configured as a decoder.
824
+ encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
825
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
826
+ the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
827
+ - 1 for tokens that are **not masked**,
828
+ - 0 for tokens that are **masked**.
829
+ past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
830
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
831
+ If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
832
+ (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
833
+ instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
834
+ use_cache (:obj:`bool`, `optional`):
835
+ If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
836
+ decoding (see :obj:`past_key_values`).
837
+ """
838
+ output_attentions = (
839
+ output_attentions
840
+ if output_attentions is not None
841
+ else self.config.output_attentions
842
+ )
843
+ output_hidden_states = (
844
+ output_hidden_states
845
+ if output_hidden_states is not None
846
+ else self.config.output_hidden_states
847
+ )
848
+ return_dict = (
849
+ return_dict if return_dict is not None else self.config.use_return_dict
850
+ )
851
+
852
+ # use_cache = use_cache if use_cache is not None else self.config.use_cache
853
+
854
+ if input_ids is None:
855
+ assert (
856
+ query_embeds is not None
857
+ ), "You have to specify query_embeds when input_ids is None"
858
+
859
+ # past_key_values_length
860
+ past_key_values_length = (
861
+ past_key_values[0][0].shape[2] - self.config.query_length
862
+ if past_key_values is not None
863
+ else 0
864
+ )
865
+
866
+ query_length = query_embeds.shape[1] if query_embeds is not None else 0
867
+
868
+ embedding_output = self.embeddings(
869
+ input_ids=input_ids,
870
+ position_ids=position_ids,
871
+ query_embeds=query_embeds,
872
+ past_key_values_length=past_key_values_length,
873
+ )
874
+
875
+ input_shape = embedding_output.size()[:-1]
876
+ batch_size, seq_length = input_shape
877
+ device = embedding_output.device
878
+
879
+ if attention_mask is None:
880
+ attention_mask = torch.ones(
881
+ ((batch_size, seq_length + past_key_values_length)), device=device
882
+ )
883
+
884
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
885
+ # ourselves in which case we just need to make it broadcastable to all heads.
886
+ if is_decoder:
887
+ extended_attention_mask = self.get_extended_attention_mask(
888
+ attention_mask,
889
+ input_ids.shape,
890
+ device,
891
+ is_decoder,
892
+ has_query=(query_embeds is not None),
893
+ )
894
+ else:
895
+ extended_attention_mask = self.get_extended_attention_mask(
896
+ attention_mask, input_shape, device, is_decoder
897
+ )
898
+
899
+ # If a 2D or 3D attention mask is provided for the cross-attention
900
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
901
+ if encoder_hidden_states is not None:
902
+ if type(encoder_hidden_states) == list:
903
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[
904
+ 0
905
+ ].size()
906
+ else:
907
+ (
908
+ encoder_batch_size,
909
+ encoder_sequence_length,
910
+ _,
911
+ ) = encoder_hidden_states.size()
912
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
913
+
914
+ if type(encoder_attention_mask) == list:
915
+ encoder_extended_attention_mask = [
916
+ self.invert_attention_mask(mask) for mask in encoder_attention_mask
917
+ ]
918
+ elif encoder_attention_mask is None:
919
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
920
+ encoder_extended_attention_mask = self.invert_attention_mask(
921
+ encoder_attention_mask
922
+ )
923
+ else:
924
+ encoder_extended_attention_mask = self.invert_attention_mask(
925
+ encoder_attention_mask
926
+ )
927
+ else:
928
+ encoder_extended_attention_mask = None
929
+
930
+ # Prepare head mask if needed
931
+ # 1.0 in head_mask indicate we keep the head
932
+ # attention_probs has shape bsz x n_heads x N x N
933
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
934
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
935
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
936
+
937
+ encoder_outputs = self.encoder(
938
+ embedding_output,
939
+ attention_mask=extended_attention_mask,
940
+ head_mask=head_mask,
941
+ encoder_hidden_states=encoder_hidden_states,
942
+ encoder_attention_mask=encoder_extended_attention_mask,
943
+ past_key_values=past_key_values,
944
+ use_cache=use_cache,
945
+ output_attentions=output_attentions,
946
+ output_hidden_states=output_hidden_states,
947
+ return_dict=return_dict,
948
+ query_length=query_length,
949
+ )
950
+ sequence_output = encoder_outputs[0]
951
+ pooled_output = (
952
+ self.pooler(sequence_output) if self.pooler is not None else None
953
+ )
954
+
955
+ if not return_dict:
956
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
957
+
958
+ return BaseModelOutputWithPoolingAndCrossAttentions(
959
+ last_hidden_state=sequence_output,
960
+ pooler_output=pooled_output,
961
+ past_key_values=encoder_outputs.past_key_values,
962
+ hidden_states=encoder_outputs.hidden_states,
963
+ attentions=encoder_outputs.attentions,
964
+ cross_attentions=encoder_outputs.cross_attentions,
965
+ )
966
+
967
+
968
+ class BertLMHeadModel(BertPreTrainedModel):
969
+
970
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
971
+ _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
972
+
973
+ def __init__(self, config):
974
+ super().__init__(config)
975
+
976
+ self.bert = BertModel(config, add_pooling_layer=False)
977
+ self.cls = BertOnlyMLMHead(config)
978
+
979
+ self.init_weights()
980
+
981
+ def get_output_embeddings(self):
982
+ return self.cls.predictions.decoder
983
+
984
+ def set_output_embeddings(self, new_embeddings):
985
+ self.cls.predictions.decoder = new_embeddings
986
+
987
+ def forward(
988
+ self,
989
+ input_ids=None,
990
+ attention_mask=None,
991
+ position_ids=None,
992
+ head_mask=None,
993
+ query_embeds=None,
994
+ encoder_hidden_states=None,
995
+ encoder_attention_mask=None,
996
+ labels=None,
997
+ past_key_values=None,
998
+ use_cache=True,
999
+ output_attentions=None,
1000
+ output_hidden_states=None,
1001
+ return_dict=None,
1002
+ return_logits=False,
1003
+ is_decoder=True,
1004
+ reduction="mean",
1005
+ ):
1006
+ r"""
1007
+ encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
1008
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
1009
+ the model is configured as a decoder.
1010
+ encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
1011
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
1012
+ the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
1013
+ - 1 for tokens that are **not masked**,
1014
+ - 0 for tokens that are **masked**.
1015
+ labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
1016
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
1017
+ ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are
1018
+ ignored (masked), the loss is only computed for the tokens with labels n ``[0, ..., config.vocab_size]``
1019
+ past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
1020
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1021
+ If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
1022
+ (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
1023
+ instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
1024
+ use_cache (:obj:`bool`, `optional`):
1025
+ If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
1026
+ decoding (see :obj:`past_key_values`).
1027
+ Returns:
1028
+ Example::
1029
+ >>> from transformers import BertTokenizer, BertLMHeadModel, BertConfig
1030
+ >>> import torch
1031
+ >>> tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
1032
+ >>> config = BertConfig.from_pretrained("bert-base-cased")
1033
+ >>> model = BertLMHeadModel.from_pretrained('bert-base-cased', config=config)
1034
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
1035
+ >>> outputs = model(**inputs)
1036
+ >>> prediction_logits = outputs.logits
1037
+ """
1038
+ return_dict = (
1039
+ return_dict if return_dict is not None else self.config.use_return_dict
1040
+ )
1041
+ if labels is not None:
1042
+ use_cache = False
1043
+ if past_key_values is not None:
1044
+ query_embeds = None
1045
+
1046
+ outputs = self.bert(
1047
+ input_ids,
1048
+ attention_mask=attention_mask,
1049
+ position_ids=position_ids,
1050
+ head_mask=head_mask,
1051
+ query_embeds=query_embeds,
1052
+ encoder_hidden_states=encoder_hidden_states,
1053
+ encoder_attention_mask=encoder_attention_mask,
1054
+ past_key_values=past_key_values,
1055
+ use_cache=use_cache,
1056
+ output_attentions=output_attentions,
1057
+ output_hidden_states=output_hidden_states,
1058
+ return_dict=return_dict,
1059
+ is_decoder=is_decoder,
1060
+ )
1061
+
1062
+ sequence_output = outputs[0]
1063
+ if query_embeds is not None:
1064
+ sequence_output = outputs[0][:, query_embeds.shape[1] :, :]
1065
+
1066
+ prediction_scores = self.cls(sequence_output)
1067
+
1068
+ if return_logits:
1069
+ return prediction_scores[:, :-1, :].contiguous()
1070
+
1071
+ lm_loss = None
1072
+ if labels is not None:
1073
+ # we are doing next-token prediction; shift prediction scores and input ids by one
1074
+ shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
1075
+ labels = labels[:, 1:].contiguous()
1076
+ loss_fct = CrossEntropyLoss(reduction=reduction, label_smoothing=0.1)
1077
+ lm_loss = loss_fct(
1078
+ shifted_prediction_scores.view(-1, self.config.vocab_size),
1079
+ labels.view(-1),
1080
+ )
1081
+ if reduction == "none":
1082
+ lm_loss = lm_loss.view(prediction_scores.size(0), -1).sum(1)
1083
+
1084
+ if not return_dict:
1085
+ output = (prediction_scores,) + outputs[2:]
1086
+ return ((lm_loss,) + output) if lm_loss is not None else output
1087
+
1088
+ return CausalLMOutputWithCrossAttentions(
1089
+ loss=lm_loss,
1090
+ logits=prediction_scores,
1091
+ past_key_values=outputs.past_key_values,
1092
+ hidden_states=outputs.hidden_states,
1093
+ attentions=outputs.attentions,
1094
+ cross_attentions=outputs.cross_attentions,
1095
+ )
1096
+
1097
+ def prepare_inputs_for_generation(
1098
+ self, input_ids, query_embeds, past=None, attention_mask=None, **model_kwargs
1099
+ ):
1100
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
1101
+ if attention_mask is None:
1102
+ attention_mask = input_ids.new_ones(input_ids.shape)
1103
+ query_mask = input_ids.new_ones(query_embeds.shape[:-1])
1104
+ attention_mask = torch.cat([query_mask, attention_mask], dim=-1)
1105
+
1106
+ # cut decoder_input_ids if past is used
1107
+ if past is not None:
1108
+ input_ids = input_ids[:, -1:]
1109
+
1110
+ return {
1111
+ "input_ids": input_ids,
1112
+ "query_embeds": query_embeds,
1113
+ "attention_mask": attention_mask,
1114
+ "past_key_values": past,
1115
+ "encoder_hidden_states": model_kwargs.get("encoder_hidden_states", None),
1116
+ "encoder_attention_mask": model_kwargs.get("encoder_attention_mask", None),
1117
+ "is_decoder": True,
1118
+ }
1119
+
1120
+ def _reorder_cache(self, past, beam_idx):
1121
+ reordered_past = ()
1122
+ for layer_past in past:
1123
+ reordered_past += (
1124
+ tuple(
1125
+ past_state.index_select(0, beam_idx) for past_state in layer_past
1126
+ ),
1127
+ )
1128
+ return reordered_past
1129
+
1130
+
1131
+ class BertForMaskedLM(BertPreTrainedModel):
1132
+
1133
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
1134
+ _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
1135
+
1136
+ def __init__(self, config):
1137
+ super().__init__(config)
1138
+
1139
+ self.bert = BertModel(config, add_pooling_layer=False)
1140
+ self.cls = BertOnlyMLMHead(config)
1141
+
1142
+ self.init_weights()
1143
+
1144
+ def get_output_embeddings(self):
1145
+ return self.cls.predictions.decoder
1146
+
1147
+ def set_output_embeddings(self, new_embeddings):
1148
+ self.cls.predictions.decoder = new_embeddings
1149
+
1150
+ def forward(
1151
+ self,
1152
+ input_ids=None,
1153
+ attention_mask=None,
1154
+ position_ids=None,
1155
+ head_mask=None,
1156
+ query_embeds=None,
1157
+ encoder_hidden_states=None,
1158
+ encoder_attention_mask=None,
1159
+ labels=None,
1160
+ output_attentions=None,
1161
+ output_hidden_states=None,
1162
+ return_dict=None,
1163
+ return_logits=False,
1164
+ is_decoder=False,
1165
+ ):
1166
+ r"""
1167
+ labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
1168
+ Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ...,
1169
+ config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored
1170
+ (masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]``
1171
+ """
1172
+
1173
+ return_dict = (
1174
+ return_dict if return_dict is not None else self.config.use_return_dict
1175
+ )
1176
+
1177
+ outputs = self.bert(
1178
+ input_ids,
1179
+ attention_mask=attention_mask,
1180
+ position_ids=position_ids,
1181
+ head_mask=head_mask,
1182
+ query_embeds=query_embeds,
1183
+ encoder_hidden_states=encoder_hidden_states,
1184
+ encoder_attention_mask=encoder_attention_mask,
1185
+ output_attentions=output_attentions,
1186
+ output_hidden_states=output_hidden_states,
1187
+ return_dict=return_dict,
1188
+ is_decoder=is_decoder,
1189
+ )
1190
+
1191
+ if query_embeds is not None:
1192
+ sequence_output = outputs[0][:, query_embeds.shape[1] :, :]
1193
+ prediction_scores = self.cls(sequence_output)
1194
+
1195
+ if return_logits:
1196
+ return prediction_scores
1197
+
1198
+ masked_lm_loss = None
1199
+ if labels is not None:
1200
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
1201
+ masked_lm_loss = loss_fct(
1202
+ prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)
1203
+ )
1204
+
1205
+ if not return_dict:
1206
+ output = (prediction_scores,) + outputs[2:]
1207
+ return (
1208
+ ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1209
+ )
1210
+
1211
+ return MaskedLMOutput(
1212
+ loss=masked_lm_loss,
1213
+ logits=prediction_scores,
1214
+ hidden_states=outputs.hidden_states,
1215
+ attentions=outputs.attentions,
1216
+ )
visual_encoder/config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/export/share/models/siglip-so400m-patch14-384/",
3
+ "architectures": [
4
+ "SiglipVisionModel"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "hidden_act": "gelu_pytorch_tanh",
8
+ "hidden_size": 1152,
9
+ "image_size": 490,
10
+ "intermediate_size": 4304,
11
+ "layer_norm_eps": 1e-06,
12
+ "model_type": "siglip_vision_model",
13
+ "num_attention_heads": 16,
14
+ "num_channels": 3,
15
+ "num_hidden_layers": 27,
16
+ "patch_size": 14,
17
+ "torch_dtype": "float32",
18
+ "transformers_version": "4.40.2"
19
+ }
visual_encoder/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a56ec487bee99f396c9f5b2a6abb30fba6e7b716d966b7477c3915d77036808b
3
+ size 1715242864
visual_encoder/preprocessor_config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_valid_processor_keys": [
3
+ "images",
4
+ "do_resize",
5
+ "size",
6
+ "resample",
7
+ "do_rescale",
8
+ "rescale_factor",
9
+ "do_normalize",
10
+ "image_mean",
11
+ "image_std",
12
+ "return_tensors",
13
+ "data_format",
14
+ "input_data_format"
15
+ ],
16
+ "do_normalize": true,
17
+ "do_rescale": true,
18
+ "do_resize": true,
19
+ "image_mean": [
20
+ 0.5,
21
+ 0.5,
22
+ 0.5
23
+ ],
24
+ "image_processor_type": "SiglipImageProcessor",
25
+ "image_std": [
26
+ 0.5,
27
+ 0.5,
28
+ 0.5
29
+ ],
30
+ "processor_class": "SiglipProcessor",
31
+ "resample": 3,
32
+ "rescale_factor": 0.00392156862745098,
33
+ "size": {
34
+ "height": 490,
35
+ "width": 490
36
+ }
37
+ }