Ayushk44 commited on
Commit
5ab18d1
1 Parent(s): 2cdb461

Upload 2 files

Browse files
configuration_lordcoder_v0.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LoRDCoder configuration class, based on GPT configuration class.
2
+
3
+ License: Apache-2.0
4
+ """
5
+ from transformers.configuration_utils import PretrainedConfig
6
+
7
+ class LoRDCoderConfig(PretrainedConfig):
8
+ """
9
+ This is the configuration class to store the configuration of a [`LoRDCoderModel`]. It is used to instantiate a
10
+ LoRDCoder model according to the specified arguments, defining the model architecture.
11
+
12
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
13
+ documentation from [`PretrainedConfig`] for more information.
14
+
15
+
16
+ Args:
17
+ vocab_size (`int`, *optional*, defaults to 50257):
18
+ Vocabulary size of the GPT-2 model. Defines the number of different tokens that can be represented by the
19
+ `inputs_ids` passed when calling [`LoRDCoderModel`].
20
+ n_positions (`int`, *optional*, defaults to 1024):
21
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
22
+ just in case (e.g., 512 or 1024 or 2048).
23
+ n_embd (`int`, *optional*, defaults to 768):
24
+ Dimensionality of the embeddings and hidden states.
25
+ n_layer (`int`, *optional*, defaults to 12):
26
+ Number of hidden layers in the Transformer encoder.
27
+ n_head (`int`, *optional*, defaults to 12):
28
+ Number of attention heads for each attention layer in the Transformer encoder.
29
+ n_inner (`int`, *optional*, defaults to None):
30
+ Dimensionality of the inner feed-forward layers. `None` will set it to 4 times n_embd
31
+ activation_function (`str`, *optional*, defaults to `"gelu_pytorch_tanh"`):
32
+ Activation function, to be selected in the list `["relu", "silu", "gelu", "tanh", "gelu_new",
33
+ "gelu_pytorch_tanh"]`.
34
+ resid_pdrop (`float`, *optional*, defaults to 0.1):
35
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
36
+ embd_pdrop (`float`, *optional*, defaults to 0.1):
37
+ The dropout ratio for the embeddings.
38
+ attn_pdrop (`float`, *optional*, defaults to 0.1):
39
+ The dropout ratio for the attention.
40
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):
41
+ The epsilon to use in the layer normalization layers.
42
+ initializer_range (`float`, *optional*, defaults to 0.02):
43
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
44
+ scale_attn_weights (`bool`, *optional*, defaults to `True`):
45
+ Scale attention weights by dividing by sqrt(hidden_size)..
46
+ use_cache (`bool`, *optional*, defaults to `True`):
47
+ Whether or not the model should return the last key/values attentions (not used by all models).
48
+ attention_softmax_in_fp32 (`bool`, *optional*, defaults to `True`):
49
+ Whether to call the fused softmax in float32.
50
+ scale_attention_softmax_in_fp32 (`bool`, *optional*, defaults to `True`):
51
+ Whether to scale the attention softmax in float32.
52
+ attention_type (`bool`, *optional*, defaults to `True`):
53
+ Whether to use Multi-Query Attion (`True`) or Multi-Head Attention (`False`).
54
+ Example:
55
+
56
+ ```python
57
+ >>> from transformers import LoRDCoderConfig, LoRDCoderModel
58
+
59
+ >>> # Initializing a LoRDCoder configuration
60
+ >>> configuration = LoRDCoderConfig()
61
+
62
+ >>> # Initializing a model (with random weights) from the configuration
63
+ >>> model = LoRDCoderModel(configuration)
64
+
65
+ >>> # Accessing the model configuration
66
+ >>> configuration = model.config
67
+ ```"""
68
+
69
+ model_type = "lordcoder"
70
+ keys_to_ignore_at_inference = ["past_key_values"]
71
+ attribute_map = {
72
+ "hidden_size": "n_embd",
73
+ "max_position_embeddings": "n_positions",
74
+ "num_attention_heads": "n_head",
75
+ "num_hidden_layers": "n_layer",
76
+ }
77
+
78
+ def __init__(
79
+ self,
80
+ vocab_size=50257,
81
+ n_positions=1024,
82
+ n_embd=768,
83
+ n_layer=12,
84
+ n_head=12,
85
+ n_inner=None,
86
+ activation_function="gelu_pytorch_tanh",
87
+ resid_pdrop=0.1,
88
+ embd_pdrop=0.1,
89
+ attn_pdrop=0.1,
90
+ layer_norm_epsilon=1e-5,
91
+ initializer_range=0.02,
92
+ scale_attn_weights=True,
93
+ use_cache=True,
94
+ bos_token_id=50256,
95
+ eos_token_id=50256,
96
+ attention_softmax_in_fp32=True,
97
+ scale_attention_softmax_in_fp32=True,
98
+ multi_query=True,
99
+ gate_dim=4096,
100
+ **kwargs,
101
+ ):
102
+ self.vocab_size = vocab_size
103
+ self.n_positions = n_positions
104
+ self.n_embd = n_embd
105
+ self.n_layer = n_layer
106
+ self.n_head = n_head
107
+ self.n_inner = n_inner
108
+ self.activation_function = activation_function
109
+ self.resid_pdrop = resid_pdrop
110
+ self.embd_pdrop = embd_pdrop
111
+ self.attn_pdrop = attn_pdrop
112
+ self.layer_norm_epsilon = layer_norm_epsilon
113
+ self.initializer_range = initializer_range
114
+ self.scale_attn_weights = scale_attn_weights
115
+ self.use_cache = use_cache
116
+ self.attention_softmax_in_fp32 = attention_softmax_in_fp32
117
+ self.scale_attention_softmax_in_fp32 = scale_attention_softmax_in_fp32
118
+ self.multi_query = multi_query
119
+ self.gate_dim = gate_dim
120
+
121
+ self.bos_token_id = bos_token_id
122
+ self.eos_token_id = eos_token_id
123
+
124
+ super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
modeling_lordcoder_v0.py ADDED
@@ -0,0 +1,770 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LoRDCoder model class, based on GPT model.
2
+
3
+ License: Apache-2.0
4
+ """
5
+ import math
6
+ from typing import List, Optional, Tuple, Union
7
+
8
+ import torch
9
+ import torch.utils.checkpoint
10
+ from torch import nn
11
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
12
+
13
+ from transformers.activations import ACT2FN
14
+ from transformers.modeling_outputs import (
15
+ BaseModelOutputWithPastAndCrossAttentions,
16
+ CausalLMOutputWithCrossAttentions,
17
+ SequenceClassifierOutputWithPast,
18
+ TokenClassifierOutput,
19
+ )
20
+ from transformers.modeling_utils import PreTrainedModel
21
+ from .configuration_lordcoder_v0 import LoRDCoderConfig
22
+
23
+
24
+ # Fused kernels
25
+ # Use separate functions for each case because conditionals prevent kernel fusion.
26
+ @torch.jit.script
27
+ def upcast_masked_softmax(
28
+ x: torch.Tensor, mask: torch.Tensor, mask_value: torch.Tensor, scale: float, softmax_dtype: torch.dtype
29
+ ):
30
+ input_dtype = x.dtype
31
+ x = x.to(softmax_dtype) * scale
32
+ x = torch.where(mask, x, mask_value)
33
+ x = torch.nn.functional.softmax(x, dim=-1).to(input_dtype)
34
+ return x
35
+
36
+
37
+ @torch.jit.script
38
+ def upcast_softmax(x: torch.Tensor, scale: float, softmax_dtype: torch.dtype):
39
+ input_dtype = x.dtype
40
+ x = x.to(softmax_dtype) * scale
41
+ x = torch.nn.functional.softmax(x, dim=-1).to(input_dtype)
42
+ return x
43
+
44
+
45
+ @torch.jit.script
46
+ def masked_softmax(x: torch.Tensor, mask: torch.Tensor, mask_value: torch.Tensor):
47
+ x = torch.where(mask, x, mask_value)
48
+ x = torch.nn.functional.softmax(x, dim=-1)
49
+ return x
50
+
51
+
52
+ class LoRDCoderAttention(nn.Module):
53
+ def __init__(self, config, is_cross_attention=False, layer_idx=None):
54
+ super().__init__()
55
+ self.mask_value = None
56
+
57
+ self.multi_query = config.multi_query
58
+ self.embed_dim = config.hidden_size
59
+ self.num_heads = config.num_attention_heads
60
+ self.head_dim = self.embed_dim // self.num_heads
61
+ self.kv_heads = 1 if self.multi_query else self.num_heads
62
+ self.kv_dim = self.kv_heads * self.head_dim
63
+ self.split_size = self.embed_dim
64
+ if self.head_dim * self.num_heads != self.embed_dim:
65
+ raise ValueError(
66
+ f"`embed_dim` must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
67
+ f" {self.num_heads})."
68
+ )
69
+
70
+ self.scale_attn_weights = config.scale_attn_weights
71
+ self.is_cross_attention = is_cross_attention
72
+
73
+ self.layer_idx = layer_idx
74
+ self.attention_softmax_in_fp32 = config.attention_softmax_in_fp32
75
+ self.scale_attention_softmax_in_fp32 = (
76
+ config.scale_attention_softmax_in_fp32 and config.attention_softmax_in_fp32
77
+ )
78
+
79
+ if self.is_cross_attention:
80
+ raise NotImplementedError("Cross Attention not supported.")
81
+ if self.multi_query:
82
+ raise NotImplementedError("Multi-Query Attention not supported for cross_attention")
83
+
84
+ self.c_attn = nn.Linear(self.embed_dim, 2 * self.embed_dim)
85
+ self.q_attn = nn.Linear(self.embed_dim, self.embed_dim)
86
+ else:
87
+ self.c_attn = nn.Linear(self.embed_dim, self.embed_dim + 2 * self.kv_dim)
88
+
89
+ self.c_proj = nn.Linear(self.embed_dim, self.embed_dim)
90
+
91
+ self.attn_dropout = nn.Dropout(config.attn_pdrop)
92
+ self.resid_dropout = nn.Dropout(config.resid_pdrop)
93
+
94
+ def _get_mask_value(self, device, dtype):
95
+ # torch.where expects a tensor. We use a cache to avoid recreating it every time.
96
+ if self.mask_value is None or self.mask_value.dtype != dtype or self.mask_value.device != device:
97
+ self.mask_value = torch.full([], torch.finfo(dtype).min, dtype=dtype, device=device)
98
+ return self.mask_value
99
+
100
+ def _attn(self, query, key, value, attention_mask=None, head_mask=None):
101
+ dtype = query.dtype
102
+ softmax_dtype = torch.float32 if self.attention_softmax_in_fp32 else dtype
103
+ upcast = dtype != softmax_dtype
104
+
105
+ unscale = self.layer_idx + 1 if self.scale_attention_softmax_in_fp32 and upcast else 1
106
+ scale_factor = unscale**-1
107
+ if self.scale_attn_weights:
108
+ scale_factor /= self.head_dim**0.5
109
+
110
+ # MQA models: (batch_size, query_length, num_heads * head_dim)
111
+ # MHA models: (batch_size, num_heads, query_length, head_dim)
112
+ query_shape = query.shape
113
+ batch_size = query_shape[0]
114
+ key_length = key.size(-1)
115
+ if self.multi_query:
116
+ # (batch_size, query_length, num_heads, head_dim) x (batch_size, head_dim, key_length)
117
+ # -> (batch_size, query_length, num_heads, key_length)
118
+ query_length = query_shape[1]
119
+ attn_shape = (batch_size, query_length, self.num_heads, key_length)
120
+ attn_view = (batch_size, query_length * self.num_heads, key_length)
121
+ # No copy needed for MQA 2, or when layer_past is provided.
122
+ query = query.reshape(batch_size, query_length * self.num_heads, self.head_dim)
123
+ else:
124
+ # (batch_size, num_heads, query_length, head_dim) x (batch_size, num_heads, head_dim, key_length)
125
+ # -> (batch_size, num_heads, query_length, key_length)
126
+ query_length = query_shape[2]
127
+ attn_shape = (batch_size, self.num_heads, query_length, key_length)
128
+ attn_view = (batch_size * self.num_heads, query_length, key_length)
129
+ # Always copies
130
+ query = query.reshape(batch_size * self.num_heads, query_length, self.head_dim)
131
+ # No copy when layer_past is provided.
132
+ key = key.reshape(batch_size * self.num_heads, self.head_dim, key_length)
133
+
134
+ attn_weights = torch.empty(attn_view, device=query.device, dtype=query.dtype)
135
+ if query.device.type == "cpu":
136
+ # This is needed because of a bug in pytorch https://github.com/pytorch/pytorch/issues/80588.
137
+ # The bug was fixed in https://github.com/pytorch/pytorch/pull/96086,
138
+ # but the fix has not been released as of pytorch version 2.0.0.
139
+ attn_weights = torch.zeros_like(attn_weights)
140
+ beta = 1
141
+ else:
142
+ beta = 0
143
+ attn_weights = torch.baddbmm(attn_weights, query, key, beta=beta, alpha=scale_factor).view(attn_shape)
144
+
145
+ if upcast:
146
+ # Use a fused kernel to prevent a large overhead from casting and scaling.
147
+ # Sub-optimal when the key length is not a multiple of 8.
148
+ if attention_mask is None:
149
+ attn_weights = upcast_softmax(attn_weights, unscale, softmax_dtype)
150
+ else:
151
+ mask_value = self._get_mask_value(attn_weights.device, softmax_dtype)
152
+ # print(attn_weights.device, attention_mask.device, mask_value.device, unscale.device, softmax_dtype)
153
+ attn_weights = upcast_masked_softmax(attn_weights, attention_mask, mask_value, unscale, softmax_dtype)
154
+ else:
155
+ if attention_mask is not None:
156
+ mask_value = self._get_mask_value(attn_weights.device, softmax_dtype)
157
+
158
+ # The fused kernel is very slow when the key length is not a multiple of 8, so we skip fusion.
159
+ attn_weights = torch.where(attention_mask, attn_weights, mask_value)
160
+
161
+ attn_weights = torch.nn.functional.softmax(attn_weights, dim=-1)
162
+
163
+ attn_weights = self.attn_dropout(attn_weights)
164
+
165
+ # Mask heads if we want to
166
+ if head_mask is not None:
167
+ if self.multi_query:
168
+ head_mask = head_mask.transpose(1, 2)
169
+ attn_weights = attn_weights * head_mask
170
+
171
+ if self.multi_query:
172
+ attn_output = torch.bmm(attn_weights.view(attn_view), value).view(query_shape)
173
+ else:
174
+ attn_output = torch.matmul(attn_weights, value)
175
+
176
+ return attn_output, attn_weights
177
+
178
+ def forward(
179
+ self,
180
+ hidden_states: torch.Tensor,
181
+ layer_past: Optional[torch.Tensor] = None,
182
+ attention_mask: Optional[torch.Tensor] = None,
183
+ head_mask: Optional[torch.Tensor] = None,
184
+ encoder_hidden_states: Optional[torch.Tensor] = None,
185
+ encoder_attention_mask: Optional[torch.Tensor] = None,
186
+ use_cache: Optional[bool] = False,
187
+ output_attentions: Optional[bool] = False,
188
+ ) -> Union[
189
+ Tuple[torch.Tensor, Optional[torch.Tensor]],
190
+ Tuple[torch.Tensor, Optional[torch.Tensor], Tuple[torch.Tensor, ...]],
191
+ ]:
192
+ if encoder_hidden_states is not None:
193
+ if not hasattr(self, "q_attn") or not self.is_cross_attention:
194
+ raise ValueError(
195
+ "If class is used as cross attention, the weights `q_attn` have to be defined. "
196
+ "Please make sure to instantiate class with `LoRDCoderAttention(..., is_cross_attention=True)`."
197
+ )
198
+
199
+ query = self.q_attn(hidden_states)
200
+ key_value = self.c_attn(encoder_hidden_states)
201
+ attention_mask = encoder_attention_mask
202
+ elif self.multi_query:
203
+ query, key_value = self.c_attn(hidden_states).split((self.embed_dim, 2 * self.kv_dim), dim=2)
204
+ else:
205
+ # Note: We split as (self.num_heads, 3, self.head_dim) instead of (3, self.num_heads, self.head_dim),
206
+ # i.e., the memory layout is not the same as GPT2.
207
+ # This makes the concatenation with past_key_value more efficient.
208
+ query, key_value = (
209
+ self.c_attn(hidden_states)
210
+ .view(*hidden_states.shape[:2], self.num_heads, 3 * self.head_dim)
211
+ .transpose(1, 2)
212
+ .split((self.head_dim, 2 * self.head_dim), dim=3)
213
+ )
214
+
215
+ if layer_past is not None:
216
+ key_value = torch.cat((layer_past, key_value), dim=-2)
217
+ present = key_value if use_cache else None
218
+
219
+ key, value = key_value.split((self.head_dim, self.head_dim), dim=-1)
220
+
221
+ attn_output, attn_weights = self._attn(query, key.transpose(-1, -2), value, attention_mask, head_mask)
222
+
223
+ if not self.multi_query:
224
+ attn_output = attn_output.transpose(1, 2).reshape(hidden_states.shape)
225
+ attn_output = self.c_proj(attn_output)
226
+ attn_output = self.resid_dropout(attn_output)
227
+
228
+ outputs = (attn_output, present)
229
+ if output_attentions:
230
+ if self.multi_query:
231
+ # Transpose to return weights in the usual format (batch_size, num_heads, query_length, key_length)
232
+ attn_weights = attn_weights.transpose(1, 2)
233
+ outputs += (attn_weights,)
234
+
235
+ return outputs # a, present, (attentions)
236
+
237
+
238
+ class LoRDCoderMLP(nn.Module):
239
+ def __init__(self, intermediate_size, config):
240
+ super().__init__()
241
+ embed_dim = config.hidden_size
242
+ self.gate_dim = config.gate_dim
243
+
244
+ self.c_fc = torch.nn.Linear(in_features=embed_dim, out_features=intermediate_size, bias=True)
245
+ self.c_gate = torch.nn.Linear(in_features=intermediate_size, out_features=self.gate_dim, bias=True)
246
+ self.c_proj = torch.nn.Linear(in_features=self.gate_dim, out_features=embed_dim, bias=True)
247
+
248
+ self.act = ACT2FN[config.activation_function]
249
+ self.dropout = nn.Dropout(config.resid_pdrop)
250
+
251
+ def forward(self, hidden_states: Optional[Tuple[torch.FloatTensor]]) -> torch.FloatTensor:
252
+ hidden_states = self.c_fc(hidden_states)
253
+ hidden_states = self.c_gate(self.act(hidden_states))
254
+ hidden_states = self.c_proj(hidden_states)
255
+ hidden_states = self.dropout(hidden_states)
256
+ return hidden_states
257
+
258
+
259
+ class LoRDCoderBlock(nn.Module):
260
+ def __init__(self, config, layer_idx=None):
261
+ super().__init__()
262
+ hidden_size = config.hidden_size
263
+ self.inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
264
+
265
+ self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
266
+ self.attn = LoRDCoderAttention(config, layer_idx=layer_idx)
267
+ self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
268
+
269
+ if config.add_cross_attention:
270
+ if config.multi_query:
271
+ raise NotImplementedError("Cross-attention not implemented for MQA")
272
+ self.crossattention = LoRDCoderAttention(config, is_cross_attention=True, layer_idx=layer_idx)
273
+ self.ln_cross_attn = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
274
+
275
+ self.mlp = LoRDCoderMLP(self.inner_dim, config)
276
+
277
+ def forward(
278
+ self,
279
+ hidden_states: Optional[Tuple[torch.Tensor]],
280
+ layer_past: Optional[torch.Tensor] = None,
281
+ attention_mask: Optional[torch.Tensor] = None,
282
+ head_mask: Optional[torch.Tensor] = None,
283
+ encoder_hidden_states: Optional[torch.Tensor] = None,
284
+ encoder_attention_mask: Optional[torch.Tensor] = None,
285
+ use_cache: Optional[bool] = False,
286
+ output_attentions: Optional[bool] = False,
287
+ ) -> Union[
288
+ Tuple[torch.Tensor], Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor, torch.Tensor, torch.Tensor]
289
+ ]:
290
+ residual = hidden_states
291
+ hidden_states = self.ln_1(hidden_states)
292
+ attn_outputs = self.attn(
293
+ hidden_states,
294
+ layer_past=layer_past,
295
+ attention_mask=attention_mask,
296
+ head_mask=head_mask,
297
+ use_cache=use_cache,
298
+ output_attentions=output_attentions,
299
+ )
300
+ attn_output = attn_outputs[0] # output_attn: a, present, (attentions)
301
+ outputs = attn_outputs[1:]
302
+ # residual connection
303
+ hidden_states = attn_output + residual
304
+
305
+ if encoder_hidden_states is not None:
306
+ # add one self-attention block for cross-attention
307
+ if not hasattr(self, "crossattention"):
308
+ raise ValueError(
309
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with "
310
+ "cross-attention layers by setting `config.add_cross_attention=True`"
311
+ )
312
+ residual = hidden_states
313
+ hidden_states = self.ln_cross_attn(hidden_states)
314
+ cross_attn_outputs = self.crossattention(
315
+ hidden_states,
316
+ attention_mask=attention_mask,
317
+ head_mask=head_mask,
318
+ encoder_hidden_states=encoder_hidden_states,
319
+ encoder_attention_mask=encoder_attention_mask,
320
+ output_attentions=output_attentions,
321
+ )
322
+ attn_output = cross_attn_outputs[0]
323
+ # residual connection
324
+ hidden_states = residual + attn_output
325
+ outputs = outputs + cross_attn_outputs[2:] # add cross attentions if we output attention weights
326
+
327
+ residual = hidden_states
328
+ hidden_states = self.ln_2(hidden_states)
329
+ feed_forward_hidden_states = self.mlp(hidden_states)
330
+ # residual connection
331
+ hidden_states = residual + feed_forward_hidden_states
332
+
333
+ if use_cache:
334
+ outputs = (hidden_states,) + outputs
335
+ else:
336
+ outputs = (hidden_states,) + outputs[1:]
337
+
338
+ return outputs # hidden_states, present, (attentions, cross_attentions)
339
+
340
+
341
+ class LoRDCoderPreTrainedModel(PreTrainedModel):
342
+ """
343
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
344
+ models.
345
+ """
346
+
347
+ config_class = LoRDCoderConfig
348
+ base_model_prefix = "transformer"
349
+ supports_gradient_checkpointing = True
350
+ _no_split_modules = ["LoRDCoderBlock"]
351
+ _skip_keys_device_placement = "past_key_values"
352
+
353
+ def __init__(self, *inputs, **kwargs):
354
+ super().__init__(*inputs, **kwargs)
355
+
356
+ def _init_weights(self, module):
357
+ """Initialize the weights."""
358
+ if isinstance(module, LoRDCoderMLP):
359
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
360
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
361
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
362
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
363
+ #
364
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
365
+ module.c_proj.weight.data.normal_(
366
+ mean=0.0, std=(self.config.initializer_range / math.sqrt(2 * self.config.n_layer))
367
+ )
368
+ module.c_proj._is_hf_initialized = True
369
+ elif isinstance(module, LoRDCoderAttention):
370
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
371
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
372
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
373
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
374
+ #
375
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
376
+ module.c_proj.weight.data.normal_(
377
+ mean=0.0, std=(self.config.initializer_range / math.sqrt(2 * self.config.n_layer))
378
+ )
379
+ module.c_proj.weight.data.normal_(
380
+ mean=0.0, std=(self.config.initializer_range / math.sqrt(2 * self.config.n_layer))
381
+ )
382
+ module.c_proj._is_hf_initialized = True
383
+ elif isinstance(module, nn.Linear):
384
+ # Slightly different from the TF version which uses truncated_normal for initialization
385
+ # cf https://github.com/pytorch/pytorch/pull/5617
386
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
387
+ if module.bias is not None:
388
+ module.bias.data.zero_()
389
+ elif isinstance(module, nn.Embedding):
390
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
391
+ if module.padding_idx is not None:
392
+ module.weight.data[module.padding_idx].zero_()
393
+ elif isinstance(module, nn.LayerNorm):
394
+ module.bias.data.zero_()
395
+ module.weight.data.fill_(1.0)
396
+
397
+ def _set_gradient_checkpointing(self, module, value=False):
398
+ if isinstance(module, LoRDCoderModel):
399
+ module.gradient_checkpointing = value
400
+
401
+
402
+ class LoRDCoderModel(LoRDCoderPreTrainedModel):
403
+ def __init__(self, config):
404
+ super().__init__(config)
405
+
406
+ self.multi_query = config.multi_query
407
+ self.embed_dim = config.hidden_size
408
+
409
+ self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
410
+ self.wpe = nn.Embedding(config.max_position_embeddings, self.embed_dim)
411
+
412
+ self.drop = nn.Dropout(config.embd_pdrop)
413
+ self.h = nn.ModuleList([LoRDCoderBlock(config, layer_idx=i) for i in range(config.num_hidden_layers)])
414
+ self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
415
+
416
+ max_positions = config.max_position_embeddings
417
+ self.register_buffer(
418
+ "bias", torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)), persistent=False
419
+ )
420
+
421
+ self.gradient_checkpointing = False
422
+
423
+ # Initialize weights and apply final processing
424
+ self.post_init()
425
+
426
+ def get_input_embeddings(self):
427
+ return self.wte
428
+
429
+ def set_input_embeddings(self, new_embeddings):
430
+ self.wte = new_embeddings
431
+
432
+ def warn_if_padding_and_no_attention_mask(self, input_ids, attention_mask):
433
+ """
434
+ Shows a one-time warning if the input_ids appear to contain padding and no attention mask was given.
435
+ """
436
+
437
+ if (attention_mask is not None) or (self.config.pad_token_id is None):
438
+ return
439
+
440
+ # Check only the first and last input IDs to reduce overhead.
441
+ if self.config.pad_token_id in input_ids[:, [-1, 0]]:
442
+ warn_string = (
443
+ "We strongly recommend passing in an `attention_mask` since your input_ids may be padded. See "
444
+ "https://huggingface.co/docs/transformers/troubleshooting"
445
+ "#incorrect-output-when-padding-tokens-arent-masked."
446
+ )
447
+
448
+ # If the pad token is equal to either BOS, EOS, or SEP, we do not know whether the user should use an
449
+ # attention_mask or not. In this case, we should still show a warning because this is a rare case.
450
+ if (
451
+ (self.config.bos_token_id is not None and self.config.bos_token_id == self.config.pad_token_id)
452
+ or (self.config.eos_token_id is not None and self.config.eos_token_id == self.config.pad_token_id)
453
+ or (self.config.sep_token_id is not None and self.config.sep_token_id == self.config.pad_token_id)
454
+ ):
455
+ warn_string += (
456
+ f"\nYou may ignore this warning if your `pad_token_id` ({self.config.pad_token_id}) is identical "
457
+ f"to the `bos_token_id` ({self.config.bos_token_id}), `eos_token_id` ({self.config.eos_token_id}), "
458
+ f"or the `sep_token_id` ({self.config.sep_token_id}), and your input is not padded."
459
+ )
460
+
461
+ print("Warning:", warn_string)
462
+
463
+ def forward(
464
+ self,
465
+ input_ids: Optional[torch.Tensor] = None,
466
+ past_key_values: Optional[List[torch.Tensor]] = None,
467
+ attention_mask: Optional[torch.Tensor] = None,
468
+ token_type_ids: Optional[torch.Tensor] = None,
469
+ position_ids: Optional[torch.Tensor] = None,
470
+ head_mask: Optional[torch.Tensor] = None,
471
+ inputs_embeds: Optional[torch.Tensor] = None,
472
+ encoder_hidden_states: Optional[torch.Tensor] = None,
473
+ encoder_attention_mask: Optional[torch.Tensor] = None,
474
+ use_cache: Optional[bool] = None,
475
+ output_attentions: Optional[bool] = None,
476
+ output_hidden_states: Optional[bool] = None,
477
+ return_dict: Optional[bool] = None,
478
+ ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
479
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
480
+ output_hidden_states = (
481
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
482
+ )
483
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
484
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
485
+
486
+ if input_ids is not None and inputs_embeds is not None:
487
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
488
+ elif input_ids is not None:
489
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
490
+ input_shape = input_ids.size()
491
+ input_ids = input_ids.view(-1, input_shape[-1])
492
+ batch_size = input_ids.shape[0]
493
+ elif inputs_embeds is not None:
494
+ input_shape = inputs_embeds.size()[:-1]
495
+ batch_size = inputs_embeds.shape[0]
496
+ else:
497
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
498
+
499
+ if batch_size <= 0:
500
+ raise ValueError("batch_size has to be defined and > 0")
501
+
502
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
503
+
504
+ if token_type_ids is not None:
505
+ token_type_ids = token_type_ids.view(-1, input_shape[-1])
506
+ if position_ids is not None:
507
+ position_ids = position_ids.view(-1, input_shape[-1])
508
+
509
+ if past_key_values is None:
510
+ past_length = 0
511
+ past_key_values = tuple([None] * len(self.h))
512
+ else:
513
+ past_length = past_key_values[0].size(-2)
514
+
515
+ if attention_mask is not None and len(attention_mask.shape) == 2 and position_ids is None:
516
+ # create position_ids on the fly for batch generation
517
+ position_ids = attention_mask.long().cumsum(-1) - 1
518
+ position_ids.masked_fill_(attention_mask == 0, 1)
519
+ if past_length > 0:
520
+ position_ids = position_ids[:, past_length : input_shape[-1] + past_length :]
521
+ elif position_ids is None:
522
+ position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
523
+ position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
524
+
525
+ # Self-attention mask.
526
+ query_length = input_shape[-1]
527
+ key_length = past_length + query_length
528
+ self_attention_mask = self.bias[None, key_length - query_length : key_length, :key_length]
529
+
530
+ if attention_mask is not None:
531
+ self_attention_mask = self_attention_mask * attention_mask.view(batch_size, 1, -1).to(
532
+ dtype=torch.bool, device=self_attention_mask.device
533
+ )
534
+
535
+ # MQA models: (batch_size, query_length, n_heads, key_length)
536
+ # MHA models: (batch_size, n_heads, query_length, key_length)
537
+ attention_mask = self_attention_mask.unsqueeze(2 if self.multi_query else 1)
538
+
539
+ # If a 2D or 3D attention mask is provided for the cross-attention
540
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
541
+ if (
542
+ self.config.add_cross_attention
543
+ and encoder_hidden_states is not None
544
+ and encoder_attention_mask is not None
545
+ ):
546
+ if encoder_attention_mask.dim() == 2:
547
+ encoder_attention_mask.unsqueeze(1)
548
+ assert encoder_attention_mask.dim() == 3
549
+ encoder_attention_mask = encoder_attention_mask.bool().unsqueeze(2 if self.multi_query else 1)
550
+ else:
551
+ encoder_attention_mask = None
552
+
553
+ # Prepare head mask if needed
554
+ # 1.0 in head_mask indicate we keep the head
555
+ # attention_probs has shape bsz x n_heads x N x N
556
+ # head_mask has shape n_layer x batch x n_heads x N x N
557
+ head_mask = self.get_head_mask(head_mask, self.config.n_layer)
558
+
559
+ if inputs_embeds is None:
560
+ inputs_embeds = self.wte(input_ids)
561
+ position_embeds = self.wpe(position_ids)
562
+ hidden_states = inputs_embeds + position_embeds
563
+
564
+ if token_type_ids is not None:
565
+ token_type_embeds = self.wte(token_type_ids)
566
+ hidden_states = hidden_states + token_type_embeds
567
+
568
+ hidden_states = self.drop(hidden_states)
569
+
570
+ output_shape = input_shape + (hidden_states.size(-1),)
571
+
572
+ presents = [] if use_cache else None
573
+ all_self_attentions = () if output_attentions else None
574
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
575
+ all_hidden_states = () if output_hidden_states else None
576
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
577
+ if output_hidden_states:
578
+ all_hidden_states = all_hidden_states + (hidden_states,)
579
+
580
+ if self.gradient_checkpointing and self.training:
581
+
582
+ def create_custom_forward(module):
583
+ def custom_forward(*inputs):
584
+ # None for past_key_value
585
+ return module(*inputs, use_cache, output_attentions)
586
+
587
+ return custom_forward
588
+
589
+ outputs = torch.utils.checkpoint.checkpoint(
590
+ create_custom_forward(block),
591
+ hidden_states,
592
+ None,
593
+ attention_mask,
594
+ head_mask[i],
595
+ encoder_hidden_states,
596
+ encoder_attention_mask,
597
+ )
598
+ else:
599
+ outputs = block(
600
+ hidden_states,
601
+ layer_past=layer_past,
602
+ attention_mask=attention_mask,
603
+ head_mask=head_mask[i],
604
+ encoder_hidden_states=encoder_hidden_states,
605
+ encoder_attention_mask=encoder_attention_mask,
606
+ use_cache=use_cache,
607
+ output_attentions=output_attentions,
608
+ )
609
+
610
+ hidden_states = outputs[0]
611
+ if use_cache:
612
+ presents.append(outputs[1])
613
+
614
+ if output_attentions:
615
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
616
+ if self.config.add_cross_attention:
617
+ all_cross_attentions = all_cross_attentions + (outputs[3 if use_cache else 2],)
618
+
619
+ hidden_states = self.ln_f(hidden_states)
620
+
621
+ hidden_states = hidden_states.view(output_shape)
622
+ # Add last hidden state
623
+ if output_hidden_states:
624
+ all_hidden_states = all_hidden_states + (hidden_states,)
625
+
626
+ if not return_dict:
627
+ return tuple(
628
+ v
629
+ for v in [hidden_states, presents, all_hidden_states, all_self_attentions, all_cross_attentions]
630
+ if v is not None
631
+ )
632
+
633
+ return BaseModelOutputWithPastAndCrossAttentions(
634
+ last_hidden_state=hidden_states,
635
+ past_key_values=presents,
636
+ hidden_states=all_hidden_states,
637
+ attentions=all_self_attentions,
638
+ cross_attentions=all_cross_attentions,
639
+ )
640
+
641
+
642
+ class LoRDCoderForCausalLM(LoRDCoderPreTrainedModel):
643
+
644
+ def __init__(self, config):
645
+ super().__init__(config)
646
+ self.transformer = LoRDCoderModel(config)
647
+ self.lm_head = lambda x: torch.matmul(x, self.transformer.wte.weight.T)
648
+
649
+ # Initialize weights and apply final processing
650
+ self.post_init()
651
+
652
+ def get_output_embeddings(self):
653
+ return self.lm_head
654
+
655
+ def set_output_embeddings(self, new_embeddings):
656
+ raise NotImplementedError("Cannot resize the embeddings of LoRDCoderForCausalLM.")
657
+
658
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
659
+ token_type_ids = kwargs.get("token_type_ids", None)
660
+ # only last token for inputs_ids if past is defined in kwargs
661
+ if past_key_values:
662
+ input_ids = input_ids[:, -1].unsqueeze(-1)
663
+ if token_type_ids is not None:
664
+ token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
665
+
666
+ attention_mask = kwargs.get("attention_mask", None)
667
+ position_ids = kwargs.get("position_ids", None)
668
+
669
+ if attention_mask is not None and position_ids is None:
670
+ # create position_ids on the fly for batch generation
671
+ position_ids = attention_mask.long().cumsum(-1) - 1
672
+ position_ids.masked_fill_(attention_mask == 0, 1)
673
+ if past_key_values:
674
+ position_ids = position_ids[:, -1].unsqueeze(-1)
675
+ else:
676
+ position_ids = None
677
+
678
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
679
+ if inputs_embeds is not None and past_key_values is None:
680
+ model_inputs = {"inputs_embeds": inputs_embeds}
681
+ else:
682
+ model_inputs = {"input_ids": input_ids}
683
+
684
+ model_inputs.update(
685
+ {
686
+ "past_key_values": past_key_values,
687
+ "use_cache": kwargs.get("use_cache"),
688
+ "position_ids": position_ids,
689
+ "attention_mask": attention_mask,
690
+ "token_type_ids": token_type_ids,
691
+ }
692
+ )
693
+ return model_inputs
694
+
695
+ def forward(
696
+ self,
697
+ input_ids: Optional[torch.Tensor] = None,
698
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
699
+ attention_mask: Optional[torch.Tensor] = None,
700
+ token_type_ids: Optional[torch.Tensor] = None,
701
+ position_ids: Optional[torch.Tensor] = None,
702
+ head_mask: Optional[torch.Tensor] = None,
703
+ inputs_embeds: Optional[torch.Tensor] = None,
704
+ encoder_hidden_states: Optional[torch.Tensor] = None,
705
+ encoder_attention_mask: Optional[torch.Tensor] = None,
706
+ labels: Optional[torch.Tensor] = None,
707
+ use_cache: Optional[bool] = None,
708
+ output_attentions: Optional[bool] = None,
709
+ output_hidden_states: Optional[bool] = None,
710
+ return_dict: Optional[bool] = None,
711
+ ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
712
+ r"""
713
+ labels (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
714
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
715
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
716
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
717
+ """
718
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
719
+
720
+ transformer_outputs = self.transformer(
721
+ input_ids,
722
+ past_key_values=past_key_values,
723
+ attention_mask=attention_mask,
724
+ token_type_ids=token_type_ids,
725
+ position_ids=position_ids,
726
+ head_mask=head_mask,
727
+ inputs_embeds=inputs_embeds,
728
+ encoder_hidden_states=encoder_hidden_states,
729
+ encoder_attention_mask=encoder_attention_mask,
730
+ use_cache=use_cache,
731
+ output_attentions=output_attentions,
732
+ output_hidden_states=output_hidden_states,
733
+ return_dict=return_dict,
734
+ )
735
+ hidden_states = transformer_outputs[0]
736
+
737
+ lm_logits = self.lm_head(hidden_states)
738
+
739
+ loss = None
740
+ if labels is not None:
741
+ # Shift so that tokens < n predict n
742
+ shift_logits = lm_logits[..., :-1, :].contiguous()
743
+ shift_labels = labels[..., 1:].contiguous().to(shift_logits.device)
744
+ # Flatten the tokens
745
+ loss_fct = CrossEntropyLoss()
746
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
747
+
748
+ if not return_dict:
749
+ output = (lm_logits,) + transformer_outputs[1:]
750
+ return ((loss,) + output) if loss is not None else output
751
+
752
+ return CausalLMOutputWithCrossAttentions(
753
+ loss=loss,
754
+ logits=lm_logits,
755
+ past_key_values=transformer_outputs.past_key_values,
756
+ hidden_states=transformer_outputs.hidden_states,
757
+ attentions=transformer_outputs.attentions,
758
+ cross_attentions=transformer_outputs.cross_attentions,
759
+ )
760
+
761
+ @staticmethod
762
+ def _reorder_cache(
763
+ past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
764
+ ) -> Tuple[Tuple[torch.Tensor]]:
765
+ """
766
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
767
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
768
+ beam_idx at every generation step.
769
+ """
770
+ return tuple(layer_past.index_select(0, beam_idx.to(layer_past.device)) for layer_past in past_key_values)