Philipp Singer commited on
Commit
106cbc4
1 Parent(s): f53532f
config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "alibi": false,
3
+ "apply_residual_connection_post_layernorm": false,
4
+ "architectures": [
5
+ "RWForCausalLM"
6
+ ],
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_RW.RWConfig",
10
+ "AutoModel": "modelling_RW.RWModel",
11
+ "AutoModelForSequenceClassification": "modelling_RW.RWForSequenceClassification",
12
+ "AutoModelForTokenClassification": "modelling_RW.RWForTokenClassification",
13
+ "AutoModelForQuestionAnswering": "modelling_RW.RWForQuestionAnswering",
14
+ "AutoModelForCausalLM": "modelling_RW.RWForCausalLM"
15
+ },
16
+ "bias": false,
17
+ "bos_token_id": 11,
18
+ "eos_token_id": 11,
19
+ "hidden_dropout": 0.0,
20
+ "hidden_size": 4544,
21
+ "initializer_range": 0.02,
22
+ "layer_norm_epsilon": 1e-05,
23
+ "model_type": "RefinedWebModel",
24
+ "multi_query": true,
25
+ "n_head": 71,
26
+ "n_layer": 32,
27
+ "parallel_attn": true,
28
+ "torch_dtype": "bfloat16",
29
+ "transformers_version": "4.27.4",
30
+ "use_cache": true,
31
+ "vocab_size": 65024
32
+ }
configuration_RW.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 the Big Science Workshop and 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
+ """ Bloom configuration"""
16
+ from transformers.configuration_utils import PretrainedConfig
17
+ from transformers.utils import logging
18
+
19
+
20
+ logger = logging.get_logger(__name__)
21
+
22
+
23
+ class RWConfig(PretrainedConfig):
24
+ model_type = "RefinedWebModel"
25
+ keys_to_ignore_at_inference = ["past_key_values"]
26
+ attribute_map = {
27
+ "num_hidden_layers": "n_layer",
28
+ "num_attention_heads": "n_head",
29
+ }
30
+
31
+ def __init__(
32
+ self,
33
+ vocab_size=250880,
34
+ hidden_size=64,
35
+ n_layer=2,
36
+ n_head=8,
37
+ layer_norm_epsilon=1e-5,
38
+ initializer_range=0.02,
39
+ use_cache=True,
40
+ bos_token_id=1,
41
+ eos_token_id=2,
42
+ apply_residual_connection_post_layernorm=False,
43
+ hidden_dropout=0.0,
44
+ attention_dropout=0.0,
45
+ multi_query=False,
46
+ alibi=False,
47
+ bias=False,
48
+ parallel_attn=False,
49
+ **kwargs,
50
+ ):
51
+ self.vocab_size = vocab_size
52
+ # Backward compatibility with n_embed kwarg
53
+ n_embed = kwargs.pop("n_embed", None)
54
+ self.hidden_size = hidden_size if n_embed is None else n_embed
55
+ self.n_layer = n_layer
56
+ self.n_head = n_head
57
+ self.layer_norm_epsilon = layer_norm_epsilon
58
+ self.initializer_range = initializer_range
59
+ self.use_cache = use_cache
60
+ self.apply_residual_connection_post_layernorm = apply_residual_connection_post_layernorm
61
+ self.hidden_dropout = hidden_dropout
62
+ self.attention_dropout = attention_dropout
63
+
64
+ self.bos_token_id = bos_token_id
65
+ self.eos_token_id = eos_token_id
66
+ self.multi_query = multi_query
67
+ self.alibi = alibi
68
+ self.bias = bias
69
+ self.parallel_attn = parallel_attn
70
+
71
+ super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
72
+
73
+ @property
74
+ def head_dim(self):
75
+ return self.hidden_size // self.n_head
76
+
77
+ @property
78
+ def rotary(self):
79
+ return not self.alibi
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 11,
4
+ "eos_token_id": 11,
5
+ "transformers_version": "4.29.2"
6
+ }
modelling_RW.py ADDED
@@ -0,0 +1,1096 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # port of models described in RW
2
+ # We use the bloom model as a starting point for these model.
3
+ # Please refer to the bloom models for usage instructions.
4
+
5
+ import math
6
+ import warnings
7
+ from typing import Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.utils.checkpoint
11
+ from torch import nn
12
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, LayerNorm, MSELoss
13
+ from torch.nn import functional as F
14
+
15
+ from transformers.modeling_outputs import (
16
+ BaseModelOutputWithPastAndCrossAttentions,
17
+ CausalLMOutputWithCrossAttentions,
18
+ QuestionAnsweringModelOutput,
19
+ SequenceClassifierOutputWithPast,
20
+ TokenClassifierOutput,
21
+ )
22
+ from transformers.modeling_utils import PreTrainedModel
23
+ from transformers.utils import logging
24
+ from .configuration_RW import RWConfig
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ # NOTE(Hesslow): Unfortunately we did not fuse matmul and bias during training, this means that there's one additional quantization to bfloat16 between the operations.
29
+ # In order not to degrade the quality of our HF-port, we keep these characteristics in the final model.
30
+ class Linear(nn.Linear):
31
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
32
+ ret = input @ self.weight.T
33
+ if self.bias is None:
34
+ return ret
35
+ else:
36
+ return ret + self.bias
37
+
38
+
39
+ from einops import rearrange
40
+
41
+ # rotary pos emb helpers (torch.jit.script does not seem to support staticmethod...)
42
+ def rotate_half(x):
43
+ x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
44
+ return torch.cat((-x2, x1), dim=x1.ndim - 1) # dim=-1 triggers a bug in torch < 1.8.0
45
+
46
+
47
+ class RotaryEmbedding(torch.nn.Module):
48
+ """Implementation of RotaryEmbedding from GPT-NeoX.
49
+ This implementation is design to operate on queries and keys that are compatible with
50
+ [batch_size, n_heads_per_partition, seq_len, head_dim] (e.g. MinGPTAttention format).
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ head_dim: int,
56
+ base=10000,
57
+ ):
58
+ super().__init__()
59
+ inv_freq = 1.0 / (base ** (torch.arange(0, head_dim, 2).float() / head_dim))
60
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
61
+ self.head_dim = head_dim
62
+ self.seq_len_cached = None
63
+ self.batch_size_cached = None
64
+ self.cos_cached: torch.Tensor | None = None
65
+ self.sin_cached: torch.Tensor | None = None
66
+
67
+ def cos_sin(
68
+ self,
69
+ seq_len: int,
70
+ device="cuda",
71
+ dtype=torch.bfloat16,
72
+ ) -> torch.Tensor:
73
+ if seq_len != self.seq_len_cached:
74
+ self.seq_len_cached = seq_len
75
+ t = torch.arange(seq_len, device=device).type_as(self.inv_freq)
76
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
77
+ emb = torch.cat((freqs, freqs), dim=-1).to(device)
78
+
79
+ if dtype in [torch.float16, torch.bfloat16]:
80
+ emb = emb.float()
81
+
82
+ self.cos_cached = emb.cos()[None, :, :]
83
+ self.sin_cached = emb.sin()[None, :, :]
84
+
85
+ self.cos_cached = self.cos_cached.type(dtype)
86
+ self.sin_cached = self.sin_cached.type(dtype)
87
+
88
+ return self.cos_cached, self.sin_cached
89
+
90
+ def forward(self, q, k):
91
+ batch, seq_len, head_dim = q.shape
92
+ cos, sin = self.cos_sin(seq_len, q.device, q.dtype)
93
+ return (q * cos) + (rotate_half(q) * sin), (k * cos) + (rotate_half(k) * sin)
94
+
95
+
96
+ def _make_causal_mask(
97
+ input_ids_shape: torch.Size, device: torch.device, past_key_values_length: int
98
+ ) -> torch.BoolTensor:
99
+ batch_size, target_length = input_ids_shape
100
+ mask = torch.empty((target_length, target_length + past_key_values_length), dtype=torch.bool, device=device)
101
+ # ONNX doesn't support `torch.Tensor.triu` properly, thus we use this workaround
102
+ seq_ids = torch.arange(target_length, device=device)
103
+ mask[:, past_key_values_length:] = seq_ids[:, None] < seq_ids[None, :]
104
+
105
+ if past_key_values_length > 0:
106
+ mask[:, :past_key_values_length] = False
107
+
108
+ expanded_mask = mask[None, None, :, :].expand(batch_size, 1, target_length, target_length + past_key_values_length)
109
+ return expanded_mask
110
+
111
+
112
+ def _expand_mask(mask: torch.Tensor, tgt_length: int) -> torch.BoolTensor:
113
+ batch_size, src_length = mask.shape
114
+ tgt_length = tgt_length if tgt_length is not None else src_length
115
+
116
+ expanded_mask = ~(mask[:, None, None, :].to(torch.bool))
117
+ return expanded_mask.expand(batch_size, 1, tgt_length, src_length)
118
+
119
+
120
+ def build_alibi_tensor(attention_mask: torch.Tensor, num_heads: int, dtype: torch.dtype) -> torch.Tensor:
121
+ batch_size, seq_length = attention_mask.shape
122
+ closest_power_of_2 = 2 ** math.floor(math.log2(num_heads))
123
+ base = torch.tensor(
124
+ 2 ** (-(2 ** -(math.log2(closest_power_of_2) - 3))), device=attention_mask.device, dtype=torch.float32
125
+ )
126
+ powers = torch.arange(1, 1 + closest_power_of_2, device=attention_mask.device, dtype=torch.int32)
127
+ slopes = torch.pow(base, powers)
128
+
129
+ if closest_power_of_2 != num_heads:
130
+ extra_base = torch.tensor(
131
+ 2 ** (-(2 ** -(math.log2(2 * closest_power_of_2) - 3))), device=attention_mask.device, dtype=torch.float32
132
+ )
133
+ num_remaining_heads = min(closest_power_of_2, num_heads - closest_power_of_2)
134
+ extra_powers = torch.arange(1, 1 + 2 * num_remaining_heads, 2, device=attention_mask.device, dtype=torch.int32)
135
+ slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0)
136
+
137
+ # Note: alibi will added to the attention bias that will be applied to the query, key product of attention
138
+ # => therefore alibi will have to be of shape (batch_size, num_heads, query_length, key_length)
139
+ # => here we set (batch_size=1, num_heads=num_heads, query_length=1, key_length=max_length)
140
+ # => the query_length dimension will then be broadcasted correctly
141
+ # This is more or less identical to T5's relative position bias:
142
+ # https://github.com/huggingface/transformers/blob/f681437203baa7671de3174b0fa583c349d9d5e1/src/transformers/models/t5/modeling_t5.py#L527
143
+ arange_tensor = ((attention_mask.cumsum(dim=-1) - 1) * attention_mask)[:, None, :]
144
+ alibi = slopes[..., None].bfloat16() * arange_tensor
145
+ return alibi.reshape(batch_size * num_heads, 1, seq_length).to(dtype)
146
+
147
+
148
+ def dropout_add(x: torch.Tensor, residual: torch.Tensor, prob: float, training: bool) -> torch.Tensor:
149
+ out = F.dropout(x, p=prob, training=training)
150
+ out = residual + out
151
+ return out
152
+
153
+
154
+ class Attention(nn.Module):
155
+ def __init__(self, config: RWConfig):
156
+ super().__init__()
157
+
158
+ self.hidden_size = config.hidden_size
159
+ self.num_heads = config.n_head
160
+ self.head_dim = self.hidden_size // self.num_heads
161
+ self.split_size = self.hidden_size
162
+ self.hidden_dropout = config.hidden_dropout
163
+
164
+ if self.head_dim * self.num_heads != self.hidden_size:
165
+ raise ValueError(
166
+ f"`hidden_size` must be divisible by num_heads (got `hidden_size`: {self.hidden_size} and `num_heads`:"
167
+ f" {self.num_heads})."
168
+ )
169
+
170
+ self.maybe_rotary = RotaryEmbedding(config.head_dim) if config.rotary else lambda q, k: (q, k)
171
+
172
+ # Layer-wise attention scaling
173
+ self.inv_norm_factor = 1.0 / math.sqrt(self.head_dim)
174
+ self.beta = self.inv_norm_factor
175
+
176
+ self.query_key_value = Linear(
177
+ self.hidden_size,
178
+ 3 * self.hidden_size if not config.multi_query else (self.hidden_size + 2 * self.head_dim),
179
+ bias=config.bias,
180
+ )
181
+ self.multi_query = config.multi_query
182
+ self.dense = Linear(self.hidden_size, self.hidden_size, bias=config.bias)
183
+ self.attention_dropout = nn.Dropout(config.attention_dropout)
184
+ self.num_kv = config.n_head if not self.multi_query else 1
185
+
186
+ def _split_heads(self, fused_qkv: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
187
+ """
188
+ Split the last dimension into (num_heads, head_dim) without making any copies, results share same memory
189
+ storage as `fused_qkv`
190
+ Args:
191
+ fused_qkv (`torch.tensor`, *required*): [batch_size, seq_length, num_heads * 3 * head_dim]
192
+ Returns:
193
+ query: [batch_size, seq_length, num_heads, head_dim] key: [batch_size, seq_length, num_heads, head_dim]
194
+ value: [batch_size, seq_length, num_heads, head_dim]
195
+ """
196
+ if not self.multi_query:
197
+ batch_size, seq_length, three_times_hidden_size = fused_qkv.shape
198
+ fused_qkv = fused_qkv.view(batch_size, seq_length, self.num_heads, 3, self.head_dim)
199
+ return fused_qkv[..., 0, :], fused_qkv[..., 1, :], fused_qkv[..., 2, :]
200
+ else:
201
+ batch_size, seq_length, three_times_hidden_size = fused_qkv.shape
202
+ fused_qkv = fused_qkv.view(batch_size, seq_length, self.num_heads + 2, self.head_dim)
203
+ return fused_qkv[..., :-2, :], fused_qkv[..., [-2], :], fused_qkv[..., [-1], :]
204
+
205
+ def _merge_heads(self, x: torch.Tensor) -> torch.Tensor:
206
+ """
207
+ Merge heads together over the last dimenstion
208
+ Args:
209
+ x: (`torch.tensor`, *required*): [batch_size * num_heads, seq_length, head_dim]
210
+ Returns:
211
+ torch.tensor: [batch_size, seq_length, num_heads * head_dim]
212
+ """
213
+ # What we want to achieve is:
214
+ # batch_size * num_heads, seq_length, head_dim -> batch_size, seq_length, num_heads * head_dim
215
+ batch_size_and_num_heads, seq_length, _ = x.shape
216
+ batch_size = batch_size_and_num_heads // self.num_heads
217
+
218
+ # First view to decompose the batch size
219
+ # batch_size * num_heads, seq_length, head_dim -> batch_size, num_heads, seq_length, head_dim
220
+ x = x.view(batch_size, self.num_heads, seq_length, self.head_dim)
221
+
222
+ # batch_size, num_heads, seq_length, head_dim -> batch_size, seq_length, num_heads, head_dim
223
+ x = x.permute(0, 2, 1, 3)
224
+
225
+ # batch_size, seq_length, num_heads, head_dim -> batch_size, seq_length, num_heads * head_dim
226
+ return x.reshape(batch_size, seq_length, self.num_heads * self.head_dim)
227
+
228
+ def forward(
229
+ self,
230
+ hidden_states: torch.Tensor,
231
+ alibi: torch.Tensor,
232
+ attention_mask: torch.Tensor,
233
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
234
+ head_mask: Optional[torch.Tensor] = None,
235
+ use_cache: bool = False,
236
+ output_attentions: bool = False,
237
+ ):
238
+ fused_qkv = self.query_key_value(hidden_states) # [batch_size, seq_length, 3 x hidden_size]
239
+
240
+ # 3 x [batch_size, seq_length, num_heads, head_dim]
241
+ (query_layer, key_layer, value_layer) = self._split_heads(fused_qkv)
242
+
243
+ batch_size, q_length, _, _ = query_layer.shape
244
+
245
+ query_layer = query_layer.transpose(1, 2).reshape(batch_size * self.num_heads, q_length, self.head_dim)
246
+ key_layer = key_layer.transpose(1, 2).reshape(
247
+ batch_size * self.num_kv,
248
+ q_length,
249
+ self.head_dim,
250
+ )
251
+ value_layer = value_layer.transpose(1, 2).reshape(batch_size * self.num_kv, q_length, self.head_dim)
252
+
253
+ query_layer, key_layer = self.maybe_rotary(query_layer, key_layer)
254
+
255
+ if layer_past is not None:
256
+ past_key, past_value = layer_past
257
+ # concatenate along seq_length dimension:
258
+ # - key: [batch_size * self.num_heads, head_dim, kv_length]
259
+ # - value: [batch_size * self.num_heads, kv_length, head_dim]
260
+ key_layer = torch.cat((past_key, key_layer), dim=1)
261
+ value_layer = torch.cat((past_value, value_layer), dim=1)
262
+
263
+ _, kv_length, _ = key_layer.shape
264
+
265
+ if use_cache is True:
266
+ present = (key_layer, value_layer)
267
+ else:
268
+ present = None
269
+
270
+ if alibi is None:
271
+ query_layer_ = query_layer.reshape(batch_size, self.num_heads, -1, self.head_dim)
272
+ key_layer_ = key_layer.reshape(batch_size, self.num_kv, -1, self.head_dim)
273
+ value_layer_ = value_layer.reshape(batch_size, self.num_kv, -1, self.head_dim)
274
+
275
+ attention_mask_float = (attention_mask * 1.0).masked_fill(attention_mask, torch.finfo(torch.float16).min).to(query_layer_.dtype)
276
+ attn_output = F.scaled_dot_product_attention(
277
+ query_layer_, key_layer_, value_layer_, attention_mask_float, 0.0, is_causal=False
278
+ )
279
+
280
+ x = attn_output.view(batch_size, self.num_heads, q_length, self.head_dim)
281
+ x = x.permute(0, 2, 1, 3)
282
+ attn_output = x.reshape(batch_size, q_length, self.num_heads * self.head_dim)
283
+
284
+ output_tensor = self.dense(attn_output)
285
+
286
+ outputs = (output_tensor, present)
287
+ assert not output_attentions # not supported.
288
+ return outputs
289
+ else:
290
+ attention_mask_float = (attention_mask * 1.0).masked_fill(attention_mask, -1e9).to(torch.bfloat16)
291
+ matmul_result = query_layer @ key_layer.transpose(-1, -2)
292
+
293
+ # change view to [batch_size, num_heads, q_length, kv_length]
294
+ attention_scores = matmul_result.view(batch_size, self.num_heads, q_length, kv_length)
295
+
296
+ # cast attention scores to fp32, compute scaled softmax and cast back to initial dtype - [batch_size, num_heads, q_length, kv_length]
297
+ input_dtype = attention_scores.dtype
298
+ # `float16` has a minimum value of -65504.0, whereas `bfloat16` and `float32` have a minimum value of `-3.4e+38`
299
+ if input_dtype == torch.float16 or input_dtype == torch.bfloat16:
300
+ attention_scores = attention_scores.to(torch.float32)
301
+ # attn_weights = torch.masked_fill(attention_scores, attention_mask, torch.finfo(attention_scores.dtype).min)
302
+ attention_probs = F.softmax(
303
+ (attention_scores + alibi.view(batch_size, self.num_heads, 1, -1)) * self.inv_norm_factor + attention_mask_float,
304
+ dim=-1,
305
+ dtype=hidden_states.dtype,
306
+ )
307
+ # [batch_size, num_heads, q_length, kv_length]
308
+ attention_probs = self.attention_dropout(attention_probs)
309
+
310
+ if head_mask is not None:
311
+ attention_probs = attention_probs * head_mask
312
+
313
+ # change view [batch_size x num_heads, q_length, kv_length]
314
+ attention_probs_reshaped = attention_probs.view(batch_size * self.num_heads, q_length, kv_length)
315
+
316
+ # matmul: [batch_size * num_heads, q_length, head_dim]
317
+ context_layer = attention_probs_reshaped @ value_layer
318
+
319
+ # change view [batch_size, num_heads, q_length, head_dim]
320
+ context_layer = self._merge_heads(context_layer)
321
+
322
+ output_tensor = self.dense(context_layer)
323
+
324
+ outputs = (output_tensor, present)
325
+ if output_attentions:
326
+ outputs += (attention_probs,)
327
+
328
+ return outputs
329
+
330
+
331
+ class MLP(nn.Module):
332
+ def __init__(self, config: RWConfig):
333
+ super().__init__()
334
+ hidden_size = config.hidden_size
335
+
336
+ self.dense_h_to_4h = Linear(hidden_size, 4 * hidden_size, bias=config.bias)
337
+ self.act = nn.GELU()
338
+ self.dense_4h_to_h = Linear(4 * hidden_size, hidden_size, bias=config.bias)
339
+ self.hidden_dropout = config.hidden_dropout
340
+
341
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
342
+ x = self.act(self.dense_h_to_4h(x))
343
+ x = self.dense_4h_to_h(x)
344
+ return x
345
+
346
+
347
+ class DecoderLayer(nn.Module):
348
+ def __init__(self, config: RWConfig):
349
+ super().__init__()
350
+ hidden_size = config.hidden_size
351
+
352
+ self.input_layernorm = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
353
+ self.num_heads = config.n_head
354
+ self.self_attention = Attention(config)
355
+
356
+ if not config.parallel_attn:
357
+ # unused if parallel attn
358
+ self.post_attention_layernorm = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
359
+
360
+ self.mlp = MLP(config)
361
+
362
+ self.apply_residual_connection_post_layernorm = config.apply_residual_connection_post_layernorm
363
+ self.hidden_dropout = config.hidden_dropout
364
+
365
+ self.config = config
366
+
367
+ def forward(
368
+ self,
369
+ hidden_states: torch.Tensor,
370
+ alibi: torch.Tensor,
371
+ attention_mask: torch.Tensor,
372
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
373
+ head_mask: Optional[torch.Tensor] = None,
374
+ use_cache: bool = False,
375
+ output_attentions: bool = False,
376
+ ):
377
+
378
+ layernorm_output = self.input_layernorm(hidden_states)
379
+ residual = hidden_states
380
+
381
+ # Self attention.
382
+ attn_outputs = self.self_attention(
383
+ layernorm_output,
384
+ layer_past=layer_past,
385
+ attention_mask=attention_mask,
386
+ alibi=alibi,
387
+ head_mask=head_mask,
388
+ use_cache=use_cache,
389
+ output_attentions=output_attentions,
390
+ )
391
+
392
+ attention_output = attn_outputs[0]
393
+
394
+ if not self.config.parallel_attn:
395
+ residual = dropout_add(attention_output, residual, self.config.attention_dropout, training=self.training)
396
+ layernorm_output = self.post_attention_layernorm(residual)
397
+
398
+ outputs = attn_outputs[1:]
399
+
400
+ # MLP.
401
+ mlp_output = self.mlp(layernorm_output)
402
+
403
+ if self.config.parallel_attn:
404
+ mlp_output += attention_output
405
+
406
+ output = dropout_add(mlp_output, residual, self.config.hidden_dropout, training=self.training)
407
+
408
+ if use_cache:
409
+ outputs = (output,) + outputs
410
+ else:
411
+ outputs = (output,) + outputs[1:]
412
+
413
+ return outputs # hidden_states, present, attentions
414
+
415
+
416
+ class RWPreTrainedModel(PreTrainedModel):
417
+ _keys_to_ignore_on_load_missing = [r"h.*.self_attention.scale_mask_softmax.causal_mask", r"lm_head.weight"]
418
+ """
419
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
420
+ models.
421
+ """
422
+
423
+ config_class = RWConfig
424
+ base_model_prefix = "transformer"
425
+ supports_gradient_checkpointing = True
426
+ _no_split_modules = ["DecoderLayer"]
427
+
428
+ def __init__(self, *inputs, **kwargs):
429
+ super().__init__(*inputs, **kwargs)
430
+
431
+ def _init_weights(self, module: nn.Module):
432
+ """Initialize the weights."""
433
+ if isinstance(module, nn.Linear) or isinstance(module, Linear):
434
+ # Slightly different from the TF version which uses truncated_normal for initialization
435
+ # cf https://github.com/pytorch/pytorch/pull/5617
436
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
437
+ if module.bias is not None:
438
+ module.bias.data.zero_()
439
+ elif isinstance(module, nn.Embedding):
440
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
441
+ if module.padding_idx is not None:
442
+ module.weight.data[module.padding_idx].zero_()
443
+ elif isinstance(module, LayerNorm):
444
+ module.bias.data.zero_()
445
+ module.weight.data.fill_(1.0)
446
+
447
+ def _set_gradient_checkpointing(self, module: nn.Module, value: bool = False):
448
+ if isinstance(module, RWModel):
449
+ module.gradient_checkpointing = value
450
+
451
+ @staticmethod
452
+ def _convert_to_standard_cache(
453
+ past_key_value: Tuple[Tuple[torch.Tensor, torch.Tensor]], batch_size: int
454
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor]]:
455
+ """
456
+ Standardizes the format of the cache so as to match most implementations, i.e. to tuple(tuple([batch_size,
457
+ num_heads, ...]))
458
+ """
459
+ batch_size_times_num_heads, head_dim, seq_length = past_key_value[0][0].shape
460
+ num_heads = batch_size_times_num_heads // batch_size
461
+ # key: [batch_size * num_heads, head_dim, seq_length] -> [batch_size, num_heads, head_dim, seq_length]
462
+ # value: [batch_size * num_heads, seq_length, head_dim] -> [batch_size, num_heads, seq_length, head_dim]
463
+ return tuple(
464
+ (
465
+ layer_past[0].view(batch_size, num_heads, head_dim, seq_length),
466
+ layer_past[1].view(batch_size, num_heads, seq_length, head_dim),
467
+ )
468
+ for layer_past in past_key_value
469
+ )
470
+
471
+ @staticmethod
472
+ def _convert_to_rw_cache(
473
+ past_key_value: Tuple[Tuple[torch.Tensor, torch.Tensor]]
474
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor]]:
475
+ batch_size, num_heads, head_dim, seq_length = past_key_value[0][0].shape
476
+ batch_size_times_num_heads = batch_size * num_heads
477
+ # key: [batch_size, num_heads, head_dim, seq_length] -> [batch_size * num_heads, head_dim, seq_length]
478
+ # value: [batch_size, num_heads, seq_length, head_dim] -> [batch_size * num_heads, seq_length, head_dim]
479
+ return tuple(
480
+ (
481
+ layer_past[0].view(batch_size_times_num_heads, head_dim, seq_length),
482
+ layer_past[1].view(batch_size_times_num_heads, seq_length, head_dim),
483
+ )
484
+ for layer_past in past_key_value
485
+ )
486
+
487
+
488
+ class RWModel(RWPreTrainedModel):
489
+ def __init__(self, config: RWConfig):
490
+ super().__init__(config)
491
+
492
+ self.embed_dim = config.hidden_size
493
+ self.num_heads = config.n_head
494
+ self.alibi = config.alibi
495
+
496
+ # Embedding + LN Embedding
497
+ self.word_embeddings = nn.Embedding(config.vocab_size, self.embed_dim)
498
+
499
+ # Transformer blocks
500
+ self.h = nn.ModuleList([DecoderLayer(config) for _ in range(config.num_hidden_layers)])
501
+
502
+ # Final Layer Norm
503
+ self.ln_f = LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
504
+
505
+ self.gradient_checkpointing = False
506
+
507
+ # Initialize weights and apply final processing
508
+ self.post_init()
509
+
510
+ def get_input_embeddings(self):
511
+ return self.word_embeddings
512
+
513
+ def _prepare_attn_mask(
514
+ self, attention_mask: torch.Tensor, input_shape: Tuple[int, int], past_key_values_length: int
515
+ ) -> torch.BoolTensor:
516
+ # create causal mask
517
+ # [batch_size, seq_length] -> [batch_size, 1, tgt_length, src_length]
518
+ combined_attention_mask = None
519
+ device = attention_mask.device
520
+ _, src_length = input_shape
521
+
522
+ if src_length > 1:
523
+ combined_attention_mask = _make_causal_mask(
524
+ input_shape, device=device, past_key_values_length=past_key_values_length
525
+ )
526
+
527
+ # [batch_size, seq_length] -> [batch_size, 1, tgt_length, src_length]
528
+ expanded_attn_mask = _expand_mask(attention_mask, tgt_length=src_length)
529
+ combined_attention_mask = (
530
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask | combined_attention_mask
531
+ )
532
+
533
+ return combined_attention_mask
534
+
535
+ def set_input_embeddings(self, new_embeddings: torch.Tensor):
536
+ self.word_embeddings = new_embeddings
537
+
538
+ def forward(
539
+ self,
540
+ input_ids: Optional[torch.LongTensor] = None,
541
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
542
+ attention_mask: Optional[torch.Tensor] = None,
543
+ head_mask: Optional[torch.LongTensor] = None,
544
+ inputs_embeds: Optional[torch.LongTensor] = None,
545
+ use_cache: Optional[bool] = None,
546
+ output_attentions: Optional[bool] = None,
547
+ output_hidden_states: Optional[bool] = None,
548
+ return_dict: Optional[bool] = None,
549
+ **deprecated_arguments,
550
+ ) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPastAndCrossAttentions]:
551
+ if deprecated_arguments.pop("position_ids", False) is not False:
552
+ # `position_ids` could have been `torch.Tensor` or `None` so defaulting pop to `False` allows to detect if users were passing explicitly `None`
553
+ warnings.warn(
554
+ "`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. You can safely ignore"
555
+ " passing `position_ids`.",
556
+ FutureWarning,
557
+ )
558
+ if len(deprecated_arguments) > 0:
559
+ raise ValueError(f"Got unexpected arguments: {deprecated_arguments}")
560
+
561
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
562
+ output_hidden_states = (
563
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
564
+ )
565
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
566
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
567
+
568
+ if input_ids is not None and inputs_embeds is not None:
569
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
570
+ elif input_ids is not None:
571
+ batch_size, seq_length = input_ids.shape
572
+ elif inputs_embeds is not None:
573
+ batch_size, seq_length, _ = inputs_embeds.shape
574
+ else:
575
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
576
+
577
+ if past_key_values is None:
578
+ past_key_values = tuple([None] * len(self.h))
579
+
580
+ # Prepare head mask if needed
581
+ # 1.0 in head_mask indicate we keep the head
582
+ # attention_probs has shape batch_size x num_heads x N x N
583
+ # head_mask has shape n_layer x batch x num_heads x N x N
584
+ head_mask = self.get_head_mask(head_mask, self.config.n_layer)
585
+
586
+ if inputs_embeds is None:
587
+ inputs_embeds = self.word_embeddings(input_ids)
588
+
589
+ hidden_states = inputs_embeds
590
+
591
+ presents = () if use_cache else None
592
+ all_self_attentions = () if output_attentions else None
593
+ all_hidden_states = () if output_hidden_states else None
594
+
595
+ # Compute alibi tensor: check build_alibi_tensor documentation
596
+ seq_length_with_past = seq_length
597
+ past_key_values_length = 0
598
+ if past_key_values[0] is not None:
599
+ past_key_values_length = past_key_values[0][0].shape[2]
600
+ seq_length_with_past = seq_length_with_past + past_key_values_length
601
+ if attention_mask is None:
602
+ attention_mask = torch.ones((batch_size, seq_length_with_past), device=hidden_states.device)
603
+ else:
604
+ attention_mask = attention_mask.to(hidden_states.device)
605
+
606
+ if self.alibi:
607
+ alibi = build_alibi_tensor(attention_mask, self.num_heads, dtype=hidden_states.dtype)
608
+ else:
609
+ alibi = None
610
+
611
+ causal_mask = self._prepare_attn_mask(
612
+ attention_mask,
613
+ input_shape=(batch_size, seq_length),
614
+ past_key_values_length=past_key_values_length,
615
+ )
616
+
617
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
618
+
619
+ if output_hidden_states:
620
+ all_hidden_states = all_hidden_states + (hidden_states,)
621
+
622
+ if self.gradient_checkpointing and self.training:
623
+
624
+ if use_cache:
625
+ logger.warning(
626
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
627
+ )
628
+ use_cache = False
629
+
630
+ def create_custom_forward(module):
631
+ def custom_forward(*inputs):
632
+ # None for past_key_value
633
+ return module(*inputs, use_cache=use_cache, output_attentions=output_attentions)
634
+
635
+ return custom_forward
636
+
637
+ outputs = torch.utils.checkpoint.checkpoint(
638
+ create_custom_forward(block),
639
+ hidden_states,
640
+ alibi,
641
+ causal_mask,
642
+ head_mask[i],
643
+ )
644
+ else:
645
+ outputs = block(
646
+ hidden_states,
647
+ layer_past=layer_past,
648
+ attention_mask=causal_mask,
649
+ head_mask=head_mask[i],
650
+ use_cache=use_cache,
651
+ output_attentions=output_attentions,
652
+ alibi=alibi,
653
+ )
654
+
655
+ hidden_states = outputs[0]
656
+ if use_cache is True:
657
+ presents = presents + (outputs[1],)
658
+
659
+ if output_attentions:
660
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
661
+
662
+ # Add last hidden state
663
+ hidden_states = self.ln_f(hidden_states)
664
+
665
+ if output_hidden_states:
666
+ all_hidden_states = all_hidden_states + (hidden_states,)
667
+
668
+ if not return_dict:
669
+ return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
670
+
671
+ return BaseModelOutputWithPastAndCrossAttentions(
672
+ last_hidden_state=hidden_states,
673
+ past_key_values=presents,
674
+ hidden_states=all_hidden_states,
675
+ attentions=all_self_attentions,
676
+ )
677
+
678
+
679
+ class RWForCausalLM(RWPreTrainedModel):
680
+ _keys_to_ignore_on_load_missing = [r"h.*.self_attention.scale_mask_softmax.causal_mask", r"lm_head.weight"]
681
+
682
+ def __init__(self, config: RWConfig):
683
+ super().__init__(config)
684
+ self.transformer = RWModel(config)
685
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
686
+
687
+ # Initialize weights and apply final processing
688
+ self.post_init()
689
+
690
+ def get_output_embeddings(self):
691
+ return self.lm_head
692
+
693
+ def set_output_embeddings(self, new_embeddings: torch.Tensor):
694
+ self.lm_head = new_embeddings
695
+
696
+ def prepare_inputs_for_generation(
697
+ self,
698
+ input_ids: torch.LongTensor,
699
+ past: Optional[torch.Tensor] = None,
700
+ attention_mask: Optional[torch.Tensor] = None,
701
+ **kwargs,
702
+ ) -> dict:
703
+ # only last token for input_ids if past is not None
704
+ if past:
705
+ input_ids = input_ids[:, -1].unsqueeze(-1)
706
+
707
+ # the cache may be in the stardard format (e.g. in contrastive search), convert to our's format if needed
708
+ if past[0][0].shape[0] == input_ids.shape[0]:
709
+ past = self._convert_to_rw_cache(past)
710
+
711
+ return {
712
+ "input_ids": input_ids,
713
+ "past_key_values": past,
714
+ "use_cache": kwargs.get("use_cache"),
715
+ "attention_mask": attention_mask,
716
+ }
717
+
718
+ def forward(
719
+ self,
720
+ input_ids: Optional[torch.LongTensor] = None,
721
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
722
+ attention_mask: Optional[torch.Tensor] = None,
723
+ head_mask: Optional[torch.Tensor] = None,
724
+ inputs_embeds: Optional[torch.Tensor] = None,
725
+ labels: Optional[torch.Tensor] = None,
726
+ use_cache: Optional[bool] = None,
727
+ output_attentions: Optional[bool] = None,
728
+ output_hidden_states: Optional[bool] = None,
729
+ return_dict: Optional[bool] = None,
730
+ **deprecated_arguments,
731
+ ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
732
+ r"""
733
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
734
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
735
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
736
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
737
+ """
738
+ if deprecated_arguments.pop("position_ids", False) is not False:
739
+ # `position_ids` could have been `torch.Tensor` or `None` so defaulting pop to `False` allows to detect if users were passing explicitly `None`
740
+ warnings.warn(
741
+ "`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. You can safely ignore"
742
+ " passing `position_ids`.",
743
+ FutureWarning,
744
+ )
745
+ if len(deprecated_arguments) > 0:
746
+ raise ValueError(f"Got unexpected arguments: {deprecated_arguments}")
747
+
748
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
749
+
750
+ transformer_outputs = self.transformer(
751
+ input_ids,
752
+ past_key_values=past_key_values,
753
+ attention_mask=attention_mask,
754
+ head_mask=head_mask,
755
+ inputs_embeds=inputs_embeds,
756
+ use_cache=use_cache,
757
+ output_attentions=output_attentions,
758
+ output_hidden_states=output_hidden_states,
759
+ return_dict=return_dict,
760
+ )
761
+ hidden_states = transformer_outputs[0]
762
+
763
+ lm_logits = self.lm_head(hidden_states)
764
+
765
+ loss = None
766
+ if labels is not None:
767
+ # Shift so that tokens < n predict n
768
+ shift_logits = lm_logits[..., :-1, :].contiguous()
769
+ shift_labels = labels[..., 1:].contiguous()
770
+ batch_size, seq_length, vocab_size = shift_logits.shape
771
+ # Flatten the tokens
772
+ loss_fct = CrossEntropyLoss()
773
+ loss = loss_fct(
774
+ shift_logits.view(batch_size * seq_length, vocab_size), shift_labels.view(batch_size * seq_length)
775
+ )
776
+
777
+ if not return_dict:
778
+ output = (lm_logits,) + transformer_outputs[1:]
779
+ return ((loss,) + output) if loss is not None else output
780
+
781
+ return CausalLMOutputWithCrossAttentions(
782
+ loss=loss,
783
+ logits=lm_logits,
784
+ past_key_values=transformer_outputs.past_key_values,
785
+ hidden_states=transformer_outputs.hidden_states,
786
+ attentions=transformer_outputs.attentions,
787
+ )
788
+
789
+ def _reorder_cache(
790
+ self, past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
791
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
792
+ """
793
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
794
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
795
+ beam_idx at every generation step.
796
+ Output shares the same memory storage as `past`.
797
+ """
798
+ standardized_past = self._convert_to_standard_cache(past, batch_size=len(beam_idx))
799
+
800
+ # Get a copy of `beam_idx` on all the devices where we need those indices.
801
+ device_to_beam_idx = {
802
+ past_state.device: beam_idx.to(past_state.device) for layer_past in past for past_state in layer_past
803
+ }
804
+ reordered_past = tuple(
805
+ (
806
+ layer_past[0].index_select(0, device_to_beam_idx[layer_past[0].device]),
807
+ layer_past[1].index_select(0, device_to_beam_idx[layer_past[0].device]),
808
+ )
809
+ for layer_past in standardized_past
810
+ )
811
+ return self._convert_to_rw_cache(reordered_past)
812
+
813
+
814
+ class RWForSequenceClassification(RWPreTrainedModel):
815
+ _keys_to_ignore_on_load_missing = [r"h.*.self_attention.scale_mask_softmax.causal_mask", r"lm_head.weight"]
816
+
817
+ def __init__(self, config: RWConfig):
818
+ super().__init__(config)
819
+ self.num_labels = config.num_labels
820
+ self.transformer = RWModel(config)
821
+ self.score = nn.Linear(config.hidden_size, config.num_labels, bias=False)
822
+
823
+ # Initialize weights and apply final processing
824
+ self.post_init()
825
+
826
+ def forward(
827
+ self,
828
+ input_ids: Optional[torch.LongTensor] = None,
829
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
830
+ attention_mask: Optional[torch.Tensor] = None,
831
+ head_mask: Optional[torch.Tensor] = None,
832
+ inputs_embeds: Optional[torch.Tensor] = None,
833
+ labels: Optional[torch.Tensor] = None,
834
+ use_cache: Optional[bool] = None,
835
+ output_attentions: Optional[bool] = None,
836
+ output_hidden_states: Optional[bool] = None,
837
+ return_dict: Optional[bool] = None,
838
+ **deprecated_arguments,
839
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutputWithPast]:
840
+ r"""
841
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
842
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
843
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
844
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
845
+ """
846
+ if deprecated_arguments.pop("position_ids", False) is not False:
847
+ # `position_ids` could have been `torch.Tensor` or `None` so defaulting pop to `False` allows to detect if users were passing explicitly `None`
848
+ warnings.warn(
849
+ "`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. You can safely ignore"
850
+ " passing `position_ids`.",
851
+ FutureWarning,
852
+ )
853
+ if len(deprecated_arguments) > 0:
854
+ raise ValueError(f"Got unexpected arguments: {deprecated_arguments}")
855
+
856
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
857
+
858
+ transformer_outputs = self.transformer(
859
+ input_ids,
860
+ past_key_values=past_key_values,
861
+ attention_mask=attention_mask,
862
+ head_mask=head_mask,
863
+ inputs_embeds=inputs_embeds,
864
+ use_cache=use_cache,
865
+ output_attentions=output_attentions,
866
+ output_hidden_states=output_hidden_states,
867
+ return_dict=return_dict,
868
+ )
869
+
870
+ hidden_states = transformer_outputs[0]
871
+ logits = self.score(hidden_states)
872
+
873
+ if input_ids is not None:
874
+ batch_size = input_ids.shape[0]
875
+ else:
876
+ batch_size = inputs_embeds.shape[0]
877
+
878
+ if self.config.pad_token_id is None and batch_size != 1:
879
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
880
+ if self.config.pad_token_id is None:
881
+ sequence_lengths = -1
882
+ else:
883
+ if input_ids is not None:
884
+ sequence_lengths = torch.ne(input_ids, self.config.pad_token_id).sum(dim=-1) - 1
885
+ else:
886
+ sequence_lengths = -1
887
+ logger.warning(
888
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
889
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
890
+ )
891
+
892
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
893
+
894
+ loss = None
895
+ if labels is not None:
896
+ if self.config.problem_type is None:
897
+ if self.num_labels == 1:
898
+ self.config.problem_type = "regression"
899
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
900
+ self.config.problem_type = "single_label_classification"
901
+ else:
902
+ self.config.problem_type = "multi_label_classification"
903
+
904
+ if self.config.problem_type == "regression":
905
+ loss_fct = MSELoss()
906
+ if self.num_labels == 1:
907
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
908
+ else:
909
+ loss = loss_fct(pooled_logits, labels)
910
+ elif self.config.problem_type == "single_label_classification":
911
+ loss_fct = CrossEntropyLoss()
912
+ loss = loss_fct(pooled_logits, labels)
913
+ elif self.config.problem_type == "multi_label_classification":
914
+ loss_fct = BCEWithLogitsLoss()
915
+ loss = loss_fct(pooled_logits, labels)
916
+ if not return_dict:
917
+ output = (pooled_logits,) + transformer_outputs[1:]
918
+ return ((loss,) + output) if loss is not None else output
919
+
920
+ return SequenceClassifierOutputWithPast(
921
+ loss=loss,
922
+ logits=pooled_logits,
923
+ past_key_values=transformer_outputs.past_key_values,
924
+ hidden_states=transformer_outputs.hidden_states,
925
+ attentions=transformer_outputs.attentions,
926
+ )
927
+
928
+
929
+ class RWForTokenClassification(RWPreTrainedModel):
930
+ _keys_to_ignore_on_load_missing = [r"h.*.self_attention.scale_mask_softmax.causal_mask", r"lm_head.weight"]
931
+
932
+ def __init__(self, config: RWConfig):
933
+ super().__init__(config)
934
+ self.num_labels = config.num_labels
935
+
936
+ self.transformer = RWModel(config)
937
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
938
+ classifier_dropout = config.classifier_dropout
939
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
940
+ classifier_dropout = config.hidden_dropout
941
+ else:
942
+ classifier_dropout = 0.1
943
+ self.dropout = nn.Dropout(classifier_dropout)
944
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
945
+
946
+ # Initialize weights and apply final processing
947
+ self.post_init()
948
+
949
+ def forward(
950
+ self,
951
+ input_ids: Optional[torch.LongTensor] = None,
952
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
953
+ attention_mask: Optional[torch.Tensor] = None,
954
+ head_mask: Optional[torch.Tensor] = None,
955
+ inputs_embeds: Optional[torch.Tensor] = None,
956
+ labels: Optional[torch.Tensor] = None,
957
+ use_cache: Optional[bool] = None,
958
+ output_attentions: Optional[bool] = None,
959
+ output_hidden_states: Optional[bool] = None,
960
+ return_dict: Optional[bool] = None,
961
+ **deprecated_arguments,
962
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
963
+ r"""
964
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
965
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
966
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
967
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
968
+ """
969
+ if deprecated_arguments.pop("position_ids", False) is not False:
970
+ # `position_ids` could have been `torch.Tensor` or `None` so defaulting pop to `False` allows to detect if users were passing explicitly `None`
971
+ warnings.warn(
972
+ "`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. You can safely ignore"
973
+ " passing `position_ids`.",
974
+ FutureWarning,
975
+ )
976
+ if len(deprecated_arguments) > 0:
977
+ raise ValueError(f"Got unexpected arguments: {deprecated_arguments}")
978
+
979
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
980
+
981
+ transformer_outputs = self.transformer(
982
+ input_ids,
983
+ past_key_values=past_key_values,
984
+ attention_mask=attention_mask,
985
+ head_mask=head_mask,
986
+ inputs_embeds=inputs_embeds,
987
+ use_cache=use_cache,
988
+ output_attentions=output_attentions,
989
+ output_hidden_states=output_hidden_states,
990
+ return_dict=return_dict,
991
+ )
992
+
993
+ hidden_states = transformer_outputs[0]
994
+ hidden_states = self.dropout(hidden_states)
995
+ logits = self.classifier(hidden_states)
996
+
997
+ loss = None
998
+ if labels is not None:
999
+ batch_size, seq_length = labels.shape
1000
+ loss_fct = CrossEntropyLoss()
1001
+ loss = loss_fct(logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length))
1002
+
1003
+ if not return_dict:
1004
+ output = (logits,) + transformer_outputs[2:]
1005
+ return ((loss,) + output) if loss is not None else output
1006
+
1007
+ return TokenClassifierOutput(
1008
+ loss=loss,
1009
+ logits=logits,
1010
+ hidden_states=transformer_outputs.hidden_states,
1011
+ attentions=transformer_outputs.attentions,
1012
+ )
1013
+
1014
+
1015
+ class RWForQuestionAnswering(RWPreTrainedModel):
1016
+ _keys_to_ignore_on_load_missing = [r"h.*.self_attention.scale_mask_softmax.causal_mask", r"lm_head.weight"]
1017
+
1018
+ def __init__(self, config):
1019
+ super().__init__(config)
1020
+ self.transformer = RWModel(config)
1021
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1022
+
1023
+ # Initialize weights and apply final processing
1024
+ self.post_init()
1025
+
1026
+ def forward(
1027
+ self,
1028
+ input_ids: Optional[torch.LongTensor] = None,
1029
+ attention_mask: Optional[torch.FloatTensor] = None,
1030
+ position_ids: Optional[torch.LongTensor] = None,
1031
+ head_mask: Optional[torch.FloatTensor] = None,
1032
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1033
+ start_positions: Optional[torch.LongTensor] = None,
1034
+ end_positions: Optional[torch.LongTensor] = None,
1035
+ output_attentions: Optional[bool] = None,
1036
+ output_hidden_states: Optional[bool] = None,
1037
+ return_dict: Optional[bool] = None,
1038
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1039
+ r"""
1040
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1041
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1042
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1043
+ are not taken into account for computing the loss.
1044
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1045
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1046
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1047
+ are not taken into account for computing the loss.
1048
+ """
1049
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1050
+
1051
+ outputs = self.transformer(
1052
+ input_ids,
1053
+ attention_mask=attention_mask,
1054
+ position_ids=position_ids,
1055
+ head_mask=head_mask,
1056
+ inputs_embeds=inputs_embeds,
1057
+ output_attentions=output_attentions,
1058
+ output_hidden_states=output_hidden_states,
1059
+ return_dict=return_dict,
1060
+ )
1061
+
1062
+ sequence_output = outputs[0]
1063
+
1064
+ logits = self.qa_outputs(sequence_output)
1065
+ start_logits, end_logits = logits.split(1, dim=-1)
1066
+ start_logits = start_logits.squeeze(-1).contiguous()
1067
+ end_logits = end_logits.squeeze(-1).contiguous()
1068
+
1069
+ total_loss = None
1070
+ if start_positions is not None and end_positions is not None:
1071
+ # If we are on multi-GPU, split add a dimension
1072
+ if len(start_positions.size()) > 1:
1073
+ start_positions = start_positions.squeeze(-1)
1074
+ if len(end_positions.size()) > 1:
1075
+ end_positions = end_positions.squeeze(-1)
1076
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1077
+ ignored_index = start_logits.size(1)
1078
+ start_positions = start_positions.clamp(0, ignored_index)
1079
+ end_positions = end_positions.clamp(0, ignored_index)
1080
+
1081
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1082
+ start_loss = loss_fct(start_logits, start_positions)
1083
+ end_loss = loss_fct(end_logits, end_positions)
1084
+ total_loss = (start_loss + end_loss) / 2
1085
+
1086
+ if not return_dict:
1087
+ output = (start_logits, end_logits) + outputs[2:]
1088
+ return ((total_loss,) + output) if total_loss is not None else output
1089
+
1090
+ return QuestionAnsweringModelOutput(
1091
+ loss=total_loss,
1092
+ start_logits=start_logits,
1093
+ end_logits=end_logits,
1094
+ hidden_states=outputs.hidden_states,
1095
+ attentions=outputs.attentions,
1096
+ )
pytorch_model-00001-of-00002.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1c4b989693576ce79edf5f8f1a2d199d66c1448d35a126e52ba09cb67ca5da39
3
+ size 9951028193
pytorch_model-00002-of-00002.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:11822397cd22f88cc56344b019cac4f04e4970e3775b7d5fc9263bc9fca8bdb1
3
+ size 4483421659
pytorch_model.bin.index.json ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 14434379520
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "pytorch_model-00002-of-00002.bin",
7
+ "transformer.h.0.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
8
+ "transformer.h.0.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
9
+ "transformer.h.0.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00002.bin",
10
+ "transformer.h.0.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00002.bin",
11
+ "transformer.h.0.self_attention.dense.weight": "pytorch_model-00001-of-00002.bin",
12
+ "transformer.h.0.self_attention.query_key_value.weight": "pytorch_model-00001-of-00002.bin",
13
+ "transformer.h.1.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
14
+ "transformer.h.1.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
15
+ "transformer.h.1.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00002.bin",
16
+ "transformer.h.1.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00002.bin",
17
+ "transformer.h.1.self_attention.dense.weight": "pytorch_model-00001-of-00002.bin",
18
+ "transformer.h.1.self_attention.query_key_value.weight": "pytorch_model-00001-of-00002.bin",
19
+ "transformer.h.10.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
20
+ "transformer.h.10.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
21
+ "transformer.h.10.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00002.bin",
22
+ "transformer.h.10.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00002.bin",
23
+ "transformer.h.10.self_attention.dense.weight": "pytorch_model-00001-of-00002.bin",
24
+ "transformer.h.10.self_attention.query_key_value.weight": "pytorch_model-00001-of-00002.bin",
25
+ "transformer.h.11.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
26
+ "transformer.h.11.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
27
+ "transformer.h.11.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00002.bin",
28
+ "transformer.h.11.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00002.bin",
29
+ "transformer.h.11.self_attention.dense.weight": "pytorch_model-00001-of-00002.bin",
30
+ "transformer.h.11.self_attention.query_key_value.weight": "pytorch_model-00001-of-00002.bin",
31
+ "transformer.h.12.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
32
+ "transformer.h.12.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
33
+ "transformer.h.12.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00002.bin",
34
+ "transformer.h.12.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00002.bin",
35
+ "transformer.h.12.self_attention.dense.weight": "pytorch_model-00001-of-00002.bin",
36
+ "transformer.h.12.self_attention.query_key_value.weight": "pytorch_model-00001-of-00002.bin",
37
+ "transformer.h.13.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
38
+ "transformer.h.13.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
39
+ "transformer.h.13.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00002.bin",
40
+ "transformer.h.13.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00002.bin",
41
+ "transformer.h.13.self_attention.dense.weight": "pytorch_model-00001-of-00002.bin",
42
+ "transformer.h.13.self_attention.query_key_value.weight": "pytorch_model-00001-of-00002.bin",
43
+ "transformer.h.14.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
44
+ "transformer.h.14.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
45
+ "transformer.h.14.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00002.bin",
46
+ "transformer.h.14.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00002.bin",
47
+ "transformer.h.14.self_attention.dense.weight": "pytorch_model-00001-of-00002.bin",
48
+ "transformer.h.14.self_attention.query_key_value.weight": "pytorch_model-00001-of-00002.bin",
49
+ "transformer.h.15.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
50
+ "transformer.h.15.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
51
+ "transformer.h.15.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00002.bin",
52
+ "transformer.h.15.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00002.bin",
53
+ "transformer.h.15.self_attention.dense.weight": "pytorch_model-00001-of-00002.bin",
54
+ "transformer.h.15.self_attention.query_key_value.weight": "pytorch_model-00001-of-00002.bin",
55
+ "transformer.h.16.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
56
+ "transformer.h.16.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
57
+ "transformer.h.16.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00002.bin",
58
+ "transformer.h.16.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00002.bin",
59
+ "transformer.h.16.self_attention.dense.weight": "pytorch_model-00001-of-00002.bin",
60
+ "transformer.h.16.self_attention.query_key_value.weight": "pytorch_model-00001-of-00002.bin",
61
+ "transformer.h.17.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
62
+ "transformer.h.17.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
63
+ "transformer.h.17.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00002.bin",
64
+ "transformer.h.17.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00002.bin",
65
+ "transformer.h.17.self_attention.dense.weight": "pytorch_model-00001-of-00002.bin",
66
+ "transformer.h.17.self_attention.query_key_value.weight": "pytorch_model-00001-of-00002.bin",
67
+ "transformer.h.18.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
68
+ "transformer.h.18.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
69
+ "transformer.h.18.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00002.bin",
70
+ "transformer.h.18.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00002.bin",
71
+ "transformer.h.18.self_attention.dense.weight": "pytorch_model-00001-of-00002.bin",
72
+ "transformer.h.18.self_attention.query_key_value.weight": "pytorch_model-00001-of-00002.bin",
73
+ "transformer.h.19.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
74
+ "transformer.h.19.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
75
+ "transformer.h.19.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00002.bin",
76
+ "transformer.h.19.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00002.bin",
77
+ "transformer.h.19.self_attention.dense.weight": "pytorch_model-00001-of-00002.bin",
78
+ "transformer.h.19.self_attention.query_key_value.weight": "pytorch_model-00001-of-00002.bin",
79
+ "transformer.h.2.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
80
+ "transformer.h.2.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
81
+ "transformer.h.2.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00002.bin",
82
+ "transformer.h.2.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00002.bin",
83
+ "transformer.h.2.self_attention.dense.weight": "pytorch_model-00001-of-00002.bin",
84
+ "transformer.h.2.self_attention.query_key_value.weight": "pytorch_model-00001-of-00002.bin",
85
+ "transformer.h.20.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
86
+ "transformer.h.20.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
87
+ "transformer.h.20.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00002.bin",
88
+ "transformer.h.20.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00002.bin",
89
+ "transformer.h.20.self_attention.dense.weight": "pytorch_model-00001-of-00002.bin",
90
+ "transformer.h.20.self_attention.query_key_value.weight": "pytorch_model-00001-of-00002.bin",
91
+ "transformer.h.21.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
92
+ "transformer.h.21.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
93
+ "transformer.h.21.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00002.bin",
94
+ "transformer.h.21.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00002.bin",
95
+ "transformer.h.21.self_attention.dense.weight": "pytorch_model-00001-of-00002.bin",
96
+ "transformer.h.21.self_attention.query_key_value.weight": "pytorch_model-00001-of-00002.bin",
97
+ "transformer.h.22.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
98
+ "transformer.h.22.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
99
+ "transformer.h.22.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00002.bin",
100
+ "transformer.h.22.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00002.bin",
101
+ "transformer.h.22.self_attention.dense.weight": "pytorch_model-00001-of-00002.bin",
102
+ "transformer.h.22.self_attention.query_key_value.weight": "pytorch_model-00001-of-00002.bin",
103
+ "transformer.h.23.input_layernorm.bias": "pytorch_model-00002-of-00002.bin",
104
+ "transformer.h.23.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
105
+ "transformer.h.23.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00002.bin",
106
+ "transformer.h.23.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00002.bin",
107
+ "transformer.h.23.self_attention.dense.weight": "pytorch_model-00002-of-00002.bin",
108
+ "transformer.h.23.self_attention.query_key_value.weight": "pytorch_model-00002-of-00002.bin",
109
+ "transformer.h.24.input_layernorm.bias": "pytorch_model-00002-of-00002.bin",
110
+ "transformer.h.24.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
111
+ "transformer.h.24.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00002.bin",
112
+ "transformer.h.24.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00002.bin",
113
+ "transformer.h.24.self_attention.dense.weight": "pytorch_model-00002-of-00002.bin",
114
+ "transformer.h.24.self_attention.query_key_value.weight": "pytorch_model-00002-of-00002.bin",
115
+ "transformer.h.25.input_layernorm.bias": "pytorch_model-00002-of-00002.bin",
116
+ "transformer.h.25.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
117
+ "transformer.h.25.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00002.bin",
118
+ "transformer.h.25.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00002.bin",
119
+ "transformer.h.25.self_attention.dense.weight": "pytorch_model-00002-of-00002.bin",
120
+ "transformer.h.25.self_attention.query_key_value.weight": "pytorch_model-00002-of-00002.bin",
121
+ "transformer.h.26.input_layernorm.bias": "pytorch_model-00002-of-00002.bin",
122
+ "transformer.h.26.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
123
+ "transformer.h.26.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00002.bin",
124
+ "transformer.h.26.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00002.bin",
125
+ "transformer.h.26.self_attention.dense.weight": "pytorch_model-00002-of-00002.bin",
126
+ "transformer.h.26.self_attention.query_key_value.weight": "pytorch_model-00002-of-00002.bin",
127
+ "transformer.h.27.input_layernorm.bias": "pytorch_model-00002-of-00002.bin",
128
+ "transformer.h.27.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
129
+ "transformer.h.27.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00002.bin",
130
+ "transformer.h.27.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00002.bin",
131
+ "transformer.h.27.self_attention.dense.weight": "pytorch_model-00002-of-00002.bin",
132
+ "transformer.h.27.self_attention.query_key_value.weight": "pytorch_model-00002-of-00002.bin",
133
+ "transformer.h.28.input_layernorm.bias": "pytorch_model-00002-of-00002.bin",
134
+ "transformer.h.28.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
135
+ "transformer.h.28.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00002.bin",
136
+ "transformer.h.28.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00002.bin",
137
+ "transformer.h.28.self_attention.dense.weight": "pytorch_model-00002-of-00002.bin",
138
+ "transformer.h.28.self_attention.query_key_value.weight": "pytorch_model-00002-of-00002.bin",
139
+ "transformer.h.29.input_layernorm.bias": "pytorch_model-00002-of-00002.bin",
140
+ "transformer.h.29.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
141
+ "transformer.h.29.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00002.bin",
142
+ "transformer.h.29.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00002.bin",
143
+ "transformer.h.29.self_attention.dense.weight": "pytorch_model-00002-of-00002.bin",
144
+ "transformer.h.29.self_attention.query_key_value.weight": "pytorch_model-00002-of-00002.bin",
145
+ "transformer.h.3.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
146
+ "transformer.h.3.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
147
+ "transformer.h.3.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00002.bin",
148
+ "transformer.h.3.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00002.bin",
149
+ "transformer.h.3.self_attention.dense.weight": "pytorch_model-00001-of-00002.bin",
150
+ "transformer.h.3.self_attention.query_key_value.weight": "pytorch_model-00001-of-00002.bin",
151
+ "transformer.h.30.input_layernorm.bias": "pytorch_model-00002-of-00002.bin",
152
+ "transformer.h.30.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
153
+ "transformer.h.30.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00002.bin",
154
+ "transformer.h.30.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00002.bin",
155
+ "transformer.h.30.self_attention.dense.weight": "pytorch_model-00002-of-00002.bin",
156
+ "transformer.h.30.self_attention.query_key_value.weight": "pytorch_model-00002-of-00002.bin",
157
+ "transformer.h.31.input_layernorm.bias": "pytorch_model-00002-of-00002.bin",
158
+ "transformer.h.31.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
159
+ "transformer.h.31.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00002.bin",
160
+ "transformer.h.31.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00002.bin",
161
+ "transformer.h.31.self_attention.dense.weight": "pytorch_model-00002-of-00002.bin",
162
+ "transformer.h.31.self_attention.query_key_value.weight": "pytorch_model-00002-of-00002.bin",
163
+ "transformer.h.4.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
164
+ "transformer.h.4.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
165
+ "transformer.h.4.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00002.bin",
166
+ "transformer.h.4.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00002.bin",
167
+ "transformer.h.4.self_attention.dense.weight": "pytorch_model-00001-of-00002.bin",
168
+ "transformer.h.4.self_attention.query_key_value.weight": "pytorch_model-00001-of-00002.bin",
169
+ "transformer.h.5.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
170
+ "transformer.h.5.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
171
+ "transformer.h.5.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00002.bin",
172
+ "transformer.h.5.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00002.bin",
173
+ "transformer.h.5.self_attention.dense.weight": "pytorch_model-00001-of-00002.bin",
174
+ "transformer.h.5.self_attention.query_key_value.weight": "pytorch_model-00001-of-00002.bin",
175
+ "transformer.h.6.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
176
+ "transformer.h.6.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
177
+ "transformer.h.6.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00002.bin",
178
+ "transformer.h.6.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00002.bin",
179
+ "transformer.h.6.self_attention.dense.weight": "pytorch_model-00001-of-00002.bin",
180
+ "transformer.h.6.self_attention.query_key_value.weight": "pytorch_model-00001-of-00002.bin",
181
+ "transformer.h.7.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
182
+ "transformer.h.7.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
183
+ "transformer.h.7.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00002.bin",
184
+ "transformer.h.7.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00002.bin",
185
+ "transformer.h.7.self_attention.dense.weight": "pytorch_model-00001-of-00002.bin",
186
+ "transformer.h.7.self_attention.query_key_value.weight": "pytorch_model-00001-of-00002.bin",
187
+ "transformer.h.8.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
188
+ "transformer.h.8.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
189
+ "transformer.h.8.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00002.bin",
190
+ "transformer.h.8.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00002.bin",
191
+ "transformer.h.8.self_attention.dense.weight": "pytorch_model-00001-of-00002.bin",
192
+ "transformer.h.8.self_attention.query_key_value.weight": "pytorch_model-00001-of-00002.bin",
193
+ "transformer.h.9.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
194
+ "transformer.h.9.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
195
+ "transformer.h.9.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00002.bin",
196
+ "transformer.h.9.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00002.bin",
197
+ "transformer.h.9.self_attention.dense.weight": "pytorch_model-00001-of-00002.bin",
198
+ "transformer.h.9.self_attention.query_key_value.weight": "pytorch_model-00001-of-00002.bin",
199
+ "transformer.ln_f.bias": "pytorch_model-00002-of-00002.bin",
200
+ "transformer.ln_f.weight": "pytorch_model-00002-of-00002.bin",
201
+ "transformer.word_embeddings.weight": "pytorch_model-00001-of-00002.bin"
202
+ }
203
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ ">>TITLE<<",
4
+ ">>ABSTRACT<<",
5
+ ">>INTRODUCTION<<",
6
+ ">>SUMMARY<<",
7
+ ">>COMMENT<<",
8
+ ">>ANSWER<<",
9
+ ">>QUESTION<<",
10
+ ">>DOMAIN<<",
11
+ ">>PREFIX<<",
12
+ ">>SUFFIX<<",
13
+ ">>MIDDLE<<"
14
+ ],
15
+ "eos_token": "<|endoftext|>"
16
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "eos_token": "<|endoftext|>",
4
+ "model_max_length": 2048,
5
+ "name_or_path": "tiiuae/falcon_tokenizer",
6
+ "special_tokens_map_file": null,
7
+ "tokenizer_class": "PreTrainedTokenizerFast"
8
+ }