ZetangForward commited on
Commit
1c42829
1 Parent(s): 64c2fba
added_tokens.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "<R>": 250200,
3
+ "<S>": 250201,
4
+ "<X>": 250202
5
+ }
config.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_ffn_bias": false,
3
+ "add_lm_head_bias": true,
4
+ "add_qkv_bias": true,
5
+ "architectures": [
6
+ "OpenBAForConditionalGeneration"
7
+ ],
8
+ "attention_dropout": 0.0,
9
+ "auto_map": {
10
+ "AutoConfig": "configuration_openba.OpenBAConfig",
11
+ "AutoModel": "modeling_openba.OpenBAForConditionalGeneration",
12
+ "AutoModelForCausalLM": "modeling_openba.OpenBAForConditionalGeneration",
13
+ "AutoModelForSeq2SeqLM": "modeling_openba.OpenBAForConditionalGeneration"
14
+ },
15
+ "decoder_max_seq_length": 1040,
16
+ "decoder_start_token_id": 0,
17
+ "eos_token_id": 1,
18
+ "ffn_hidden_size": 6912,
19
+ "hidden_dropout": 0.0,
20
+ "hidden_size": 2560,
21
+ "initializer_factor": 1.0,
22
+ "is_encoder_decoder": true,
23
+ "kv_channels": 128,
24
+ "max_seq_length": 1040,
25
+ "model_type": "openba",
26
+ "num_decoder_layers": 24,
27
+ "num_heads": 20,
28
+ "num_layers": 8,
29
+ "pad_token_id": 0,
30
+ "tie_word_embeddings": false,
31
+ "tokenizer_class": "OpenBATokenizer",
32
+ "transformers_version": "4.32.0",
33
+ "use_cache": true,
34
+ "vocab_size": 250240
35
+ }
configuration_openba.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.utils import logging
2
+ from transformers.configuration_utils import PretrainedConfig
3
+
4
+
5
+ logger = logging.get_logger(__name__)
6
+
7
+
8
+ class OpenBAConfig(PretrainedConfig):
9
+ model_type = "openba"
10
+ keys_to_ignore_at_inference = ["past_key_values"]
11
+ attribute_map = {
12
+ "hidden_size": "hidden_size",
13
+ "num_attention_heads": "num_heads",
14
+ "num_hidden_layers": "num_layers"
15
+ }
16
+
17
+ def __init__(
18
+ self,
19
+ vocab_size=32128,
20
+ hidden_size=512,
21
+ kv_channels=64,
22
+ ffn_hidden_size=2048,
23
+ num_layers=12,
24
+ num_decoder_layers=None,
25
+ hidden_dropout=0.1,
26
+ attention_dropout=0.1,
27
+ num_heads=8,
28
+ is_encoder_decoder=True,
29
+ use_cache=True,
30
+ initializer_factor=1.0,
31
+ pad_token_id=0,
32
+ eos_token_id=1,
33
+ decoder_start_token_id=0,
34
+ add_qkv_bias=False,
35
+ add_ffn_bias=False,
36
+ add_lm_head_bias=False,
37
+ max_seq_length=1024,
38
+ decoder_max_seq_length=256,
39
+ **kwargs,
40
+ ):
41
+ self.vocab_size = vocab_size
42
+ self.hidden_size = hidden_size
43
+ self.kv_channels = kv_channels
44
+ self.ffn_hidden_size = ffn_hidden_size
45
+ self.num_layers = num_layers
46
+ self.num_decoder_layers = (
47
+ num_decoder_layers if num_decoder_layers is not None else self.num_layers
48
+ ) # default = symmetry
49
+ self.hidden_dropout = hidden_dropout
50
+ self.attention_dropout = attention_dropout
51
+ self.initializer_factor = initializer_factor
52
+ self.num_heads = num_heads
53
+ self.add_qkv_bias = add_qkv_bias
54
+ self.add_ffn_bias = add_ffn_bias
55
+ self.add_lm_head_bias = add_lm_head_bias
56
+ self.max_seq_length = max_seq_length
57
+ self.decoder_max_seq_length = decoder_max_seq_length
58
+ self.use_cache = use_cache
59
+
60
+ super().__init__(
61
+ pad_token_id=pad_token_id,
62
+ eos_token_id=eos_token_id,
63
+ decoder_start_token_id=decoder_start_token_id,
64
+ is_encoder_decoder=is_encoder_decoder,
65
+ **kwargs,
66
+ )
modeling_openba.py ADDED
@@ -0,0 +1,707 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Tuple, Union
2
+ import copy
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+
8
+ from transformers import PreTrainedModel
9
+ from transformers.modeling_outputs import (
10
+ BaseModelOutputWithPastAndCrossAttentions,
11
+ Seq2SeqLMOutput,
12
+ BaseModelOutput,
13
+ )
14
+ from transformers.utils import logging, is_torch_fx_proxy
15
+
16
+ from .configuration_openba import OpenBAConfig
17
+
18
+
19
+ logger = logging.get_logger(__name__)
20
+
21
+ # Copied from transformers.models.gptj.modeling_gptj.create_sinusoidal_positions
22
+ def create_sinusoidal_positions(num_pos: int, dim: int) -> torch.Tensor:
23
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2) / dim))
24
+ sinusoid_inp = torch.einsum("i , j -> i j", torch.arange(num_pos, dtype=torch.float), inv_freq).float()
25
+ return torch.cat((torch.sin(sinusoid_inp), torch.cos(sinusoid_inp)), dim=1)
26
+
27
+
28
+ def rotate_half(x) -> torch.Tensor:
29
+ x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
30
+ return torch.cat((-x2, x1), dim=-1)
31
+
32
+
33
+ def apply_rotary_pos_emb(tensor: torch.Tensor, sin: torch.Tensor, cos: torch.Tensor) -> torch.Tensor:
34
+ sin = torch.cat((sin, sin), dim=-1).to(tensor.device)[:, :, None, :]
35
+ cos = torch.cat((cos, cos), dim=-1).to(tensor.device)[:, :, None, :]
36
+ return (tensor * cos) + (rotate_half(tensor) * sin)
37
+
38
+
39
+ class SwiGLUMLP(nn.Module):
40
+ def __init__(self, config):
41
+ super().__init__()
42
+
43
+ multiple_of: int = 256 # make SwiGLU hidden layer size multiple of large power of 2
44
+ hidden_size = config.hidden_size
45
+ # ffn_hidden_size = int(2 * config.ffn_hidden_size / 3)
46
+ # ffn_hidden_size = multiple_of * ((ffn_hidden_size + multiple_of - 1) // multiple_of)
47
+ ffn_hidden_size=config.ffn_hidden_size
48
+ self.ffn_hidden_size = ffn_hidden_size
49
+
50
+ self.fc_in = nn.Linear(hidden_size, 2 * ffn_hidden_size, bias=config.add_ffn_bias)
51
+ self.fc_out = nn.Linear(ffn_hidden_size, hidden_size, bias=config.add_ffn_bias)
52
+
53
+ def swiglu(x):
54
+ x = torch.chunk(x, 2, dim=-1)
55
+ return F.silu(x[0]) * x[1]
56
+ self.act_func = swiglu
57
+
58
+ def forward(self, hidden_states: Optional[torch.FloatTensor]) -> torch.FloatTensor:
59
+ hidden_states = self.fc_in(hidden_states)
60
+ hidden_states = self.act_func(hidden_states)
61
+ hidden_states = self.fc_out(hidden_states)
62
+ return hidden_states
63
+
64
+
65
+ class OpenBAAttention(nn.Module):
66
+ def __init__(self, config, attn_type='self'):
67
+ super().__init__()
68
+ self.attn_type = attn_type
69
+ self.is_decoder = config.is_decoder
70
+ self.hidden_size = config.hidden_size
71
+ self.num_heads = config.num_heads
72
+ self.kv_channels = config.kv_channels
73
+ self.proj_size = self.kv_channels * self.num_heads
74
+ self.dropout = config.attention_dropout
75
+ self.scale_attn = torch.sqrt(torch.tensor(self.kv_channels, dtype=torch.float32))
76
+
77
+ if self.attn_type == 'self':
78
+ self.qkv = nn.Linear(self.hidden_size, 3 * self.proj_size, bias=config.add_qkv_bias)
79
+ else:
80
+ assert self.attn_type == 'cross'
81
+ self.q = nn.Linear(self.hidden_size, self.proj_size, bias=config.add_qkv_bias)
82
+ self.kv = nn.Linear(self.hidden_size, 2 * self.proj_size, bias=config.add_qkv_bias)
83
+
84
+ self.rotary_embedding = create_sinusoidal_positions(
85
+ num_pos=config.max_seq_length,
86
+ dim=self.kv_channels,
87
+ )
88
+
89
+ self.o = nn.Linear(self.proj_size, self.hidden_size, bias=config.add_qkv_bias)
90
+
91
+ def forward(
92
+ self,
93
+ hidden_states: Optional[torch.FloatTensor],
94
+ attention_mask: Optional[torch.FloatTensor] = None,
95
+ key_value_states: Optional[torch.FloatTensor] = None,
96
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
97
+ layer_head_mask: Optional[Tuple[torch.Tensor]] = None,
98
+ position_ids:Optional[torch.LongTensor] = None,
99
+ use_cache: Optional[bool] = False,
100
+ output_attentions: Optional[bool] = False,
101
+ ):
102
+ # input is (batch_size, seq_length, hidden_size)
103
+ batch_size, seq_length = hidden_states.shape[:2]
104
+ if past_key_value is not None:
105
+ if len(past_key_value) != 2:
106
+ raise ValueError(
107
+ f"past_key_value should have 2 past states: keys and values. Got { len(past_key_value)} past states"
108
+ )
109
+
110
+ if self.rotary_embedding.device != position_ids.device:
111
+ self.rotary_embedding = self.rotary_embedding.to(position_ids.device)
112
+
113
+ if self.attn_type == 'self':
114
+ mixed_qkv_states = self.qkv(hidden_states)
115
+ new_tensor_shape = mixed_qkv_states.size()[:-1] + (self.num_heads, 3 * self.kv_channels)
116
+ mixed_qkv_states = mixed_qkv_states.view(*new_tensor_shape)
117
+ query_states, key_states, value_states = torch.chunk(mixed_qkv_states, 3, dim=-1)
118
+ # rotary position embedding
119
+ sincos = self.rotary_embedding[position_ids]
120
+ sin, cos = torch.chunk(sincos, 2, dim=-1)
121
+ query_states = apply_rotary_pos_emb(query_states, sin, cos)
122
+ key_states = apply_rotary_pos_emb(key_states, sin, cos)
123
+ # reshape to (batch_size, num_head, seq_length, kv_channels)
124
+ query_states = query_states.transpose(1, 2)
125
+ key_states = key_states.transpose(1, 2)
126
+ value_states = value_states.transpose(1, 2)
127
+ if past_key_value is not None:
128
+ past_key_states, past_value_states = past_key_value
129
+ key_states = torch.cat([past_key_states, key_states], dim=-2)
130
+ value_states = torch.cat([past_value_states, value_states], dim=-2)
131
+ else:
132
+ assert self.attn_type == 'cross'
133
+ query_states = self.q(hidden_states)
134
+ new_tensor_shape = query_states.size()[:-1] + (self.num_heads, self.kv_channels)
135
+ query_states = query_states.view(*new_tensor_shape)
136
+ # reshape to (batch_size, num_head, seq_length, kv_channels)
137
+ query_states = query_states.transpose(1, 2)
138
+ if past_key_value is None:
139
+ mixed_kv_states = self.kv(key_value_states)
140
+ new_tensor_shape = mixed_kv_states.size()[:-1] + (self.num_heads, 2 * self.kv_channels)
141
+ mixed_kv_states = mixed_kv_states.view(*new_tensor_shape)
142
+ key_states, value_states = torch.chunk(mixed_kv_states, 2, dim=-1)
143
+ # reshape to (batch_size, num_head, seq_length, kv_channels)
144
+ key_states = key_states.transpose(1, 2)
145
+ value_states = value_states.transpose(1, 2)
146
+ else:
147
+ key_states, value_states = past_key_value
148
+
149
+ # compute attention score
150
+ query_states = query_states.to(torch.float32)
151
+ key_states = key_states.to(torch.float32)
152
+ attn_scores = torch.matmul(query_states, key_states.transpose(-1, -2)) / self.scale_attn
153
+ attn_scores = attn_scores.masked_fill_(attention_mask, -10000.0)
154
+ attn_weights = F.softmax(attn_scores, dim=-1).type_as(attn_scores)
155
+ attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
156
+ attn_weights = attn_weights.to(value_states.dtype)
157
+
158
+ # Mask heads if we want to
159
+ if layer_head_mask is not None:
160
+ attn_weights = attn_weights * layer_head_mask
161
+
162
+ attn_output = torch.matmul(attn_weights, value_states)
163
+ attn_output = attn_output.transpose(1, 2).contiguous().view(batch_size, -1, self.proj_size)
164
+ attn_output = self.o(attn_output)
165
+
166
+ present_key_value_state = (key_states, value_states) if (self.is_decoder and use_cache) else None
167
+ outputs = (attn_output, present_key_value_state)
168
+
169
+ if output_attentions:
170
+ outputs += (attn_weights,)
171
+
172
+ return outputs
173
+
174
+
175
+ class OpenBABlock(nn.Module):
176
+ def __init__(self, config) -> None:
177
+ super().__init__()
178
+ self.is_decoder = config.is_decoder
179
+ self.dropout = config.hidden_dropout
180
+ self.input_layernorm = nn.LayerNorm(config.hidden_size)
181
+ self.self_attn = OpenBAAttention(config, attn_type='self')
182
+ self.post_attn_layernorm = nn.LayerNorm(config.hidden_size)
183
+ if self.is_decoder:
184
+ self.inter_attn = OpenBAAttention(config, attn_type='cross')
185
+ self.post_inter_attn_layernorm = nn.LayerNorm(config.hidden_size)
186
+ self.mlp = SwiGLUMLP(config)
187
+
188
+ def forward(
189
+ self,
190
+ hidden_states=None,
191
+ attention_mask=None,
192
+ position_ids=None,
193
+ encoder_hidden_states=None,
194
+ encoder_attention_mask=None,
195
+ layer_head_mask=None,
196
+ cross_attn_layer_head_mask=None,
197
+ past_key_value=None,
198
+ use_cache=False,
199
+ output_attentions=False,
200
+ ):
201
+ if past_key_value is not None:
202
+ if not self.is_decoder:
203
+ raise ValueError("`past_key_values` is passed to the encoder. Please make sure this is intended.")
204
+ expected_num_past_key_values = 2 if encoder_hidden_states is None else 4
205
+
206
+ if len(past_key_value) != expected_num_past_key_values:
207
+ raise ValueError(
208
+ f"There should be {expected_num_past_key_values} past states. "
209
+ f"{'2 (past / key) for cross attention. ' if expected_num_past_key_values == 4 else ''}"
210
+ f"Got {len(past_key_value)} past key / value states"
211
+ )
212
+
213
+ self_attn_past_key_value = past_key_value[:2]
214
+ cross_attn_past_key_value = past_key_value[2:]
215
+ else:
216
+ self_attn_past_key_value, cross_attn_past_key_value = None, None
217
+
218
+ # Layer norm at the beginning of the transformer layer.
219
+ layernorm_output = self.input_layernorm(hidden_states)
220
+ # Self attention.
221
+ attn_outputs = self.self_attn(
222
+ layernorm_output,
223
+ attention_mask=attention_mask,
224
+ position_ids=position_ids,
225
+ layer_head_mask=layer_head_mask,
226
+ past_key_value=self_attn_past_key_value,
227
+ use_cache=use_cache,
228
+ output_attentions=output_attentions,
229
+ )
230
+ attn_output, present_key_value_state = attn_outputs[:2]
231
+ attn_weights = attn_outputs[2:]
232
+ residual = hidden_states
233
+ # Layer norm post the self attention.
234
+ attn_output = nn.functional.dropout(attn_output, p=self.dropout, training=self.training)
235
+ layernorm_input = residual + attn_output
236
+ layernorm_output = self.post_attn_layernorm(layernorm_input)
237
+
238
+ if self.is_decoder:
239
+ assert encoder_hidden_states is not None
240
+ attn_outputs = self.inter_attn(
241
+ layernorm_output,
242
+ attention_mask=encoder_attention_mask,
243
+ key_value_states=encoder_hidden_states,
244
+ position_ids=position_ids,
245
+ layer_head_mask=cross_attn_layer_head_mask,
246
+ past_key_value=cross_attn_past_key_value,
247
+ use_cache=use_cache,
248
+ output_attentions=output_attentions,
249
+ )
250
+ attn_output = attn_outputs[0]
251
+ attn_output = nn.functional.dropout(attn_output, p=self.dropout, training=self.training)
252
+ # residual connection
253
+ residual = layernorm_input
254
+ layernorm_input = residual + attn_output
255
+ layernorm_output = self.post_inter_attn_layernorm(layernorm_input)
256
+ # Combine self attn and cross attn key value states
257
+ if present_key_value_state is not None:
258
+ present_key_value_state += attn_outputs[1]
259
+ attn_weights += attn_outputs[2:]
260
+
261
+ # MLP.
262
+ mlp_output = self.mlp(layernorm_output)
263
+ mlp_output = nn.functional.dropout(mlp_output, p=self.dropout, training=self.training)
264
+ # Second residual connection.
265
+ residual = layernorm_input
266
+ output = residual + mlp_output
267
+ outputs = (output,)
268
+
269
+ if use_cache:
270
+ outputs += (present_key_value_state,) + attn_weights
271
+ else:
272
+ outputs += attn_weights
273
+ return outputs
274
+
275
+
276
+ class OpenBAPreTrainedModel(PreTrainedModel):
277
+ config_class = OpenBAConfig
278
+ base_model_prefix = "transformer"
279
+ _no_split_modules = ["OpenBABlock"]
280
+
281
+ def _set_gradient_checkpointing(self, module, value=False):
282
+ if isinstance(module, (OpenBAAttention, OpenBAStack)):
283
+ module.gradient_checkpointing = value
284
+
285
+ def _init_weights(self, module):
286
+ """Initialize the weights"""
287
+ factor = self.config.initializer_factor
288
+ if isinstance(module, nn.LayerNorm):
289
+ module.weight.data.fill_(1.0)
290
+ module.bias.data.zero_()
291
+ elif isinstance(module, OpenBAForConditionalGeneration):
292
+ module.shared_embedding.weight.data.normal_(mean=0.0, std=factor * 1.0)
293
+ if hasattr(module, "lm_head") and not self.config.tie_word_embeddings:
294
+ module.lm_head.weight.data.normal_(mean=0.0, std=factor * 1.0)
295
+ elif isinstance(module, SwiGLUMLP):
296
+ module.fc_in.weight.data.normal_(mean=0.0, std=factor * ((self.config.hidden_size) ** -0.5))
297
+ if hasattr(module.fc_in, "bias") and module.fc_in.bias is not None:
298
+ module.fc_in.bias.data.zero_()
299
+ module.fc_out.weight.data.normal_(mean=0.0, std=factor * ((module.ffn_hidden_size) ** -0.5))
300
+ if hasattr(module.fc_out, "bias") and module.fc_out.bias is not None:
301
+ module.fc_out.bias.data.zero_()
302
+ elif isinstance(module, OpenBAAttention):
303
+ hidden_size = self.config.hidden_size
304
+ kv_channels = self.config.kv_channels
305
+ n_heads = self.config.num_heads
306
+ if module.attn_type == 'self':
307
+ module.qkv.weight.data[:n_heads * kv_channels].normal_(mean=0.0, std=factor * ((hidden_size * kv_channels) ** -0.5))
308
+ module.qkv.weight.data[n_heads * kv_channels:].normal_(mean=0.0, std=factor * (hidden_size ** -0.5))
309
+ else:
310
+ module.q.weight.data.normal_(mean=0.0, std=factor * ((hidden_size * kv_channels) ** -0.5))
311
+ module.kv.weight.data.normal_(mean=0.0, std=factor * (hidden_size ** -0.5))
312
+ module.o.weight.data.normal_(mean=0.0, std=factor * ((n_heads * kv_channels) ** -0.5))
313
+
314
+ def _shift_right(self, input_ids):
315
+ decoder_start_token_id = self.config.decoder_start_token_id
316
+ pad_token_id = self.config.pad_token_id
317
+
318
+ if decoder_start_token_id is None:
319
+ raise ValueError(
320
+ "self.model.config.decoder_start_token_id has to be defined. In T5 it is usually set to the pad_token_id."
321
+ "See T5 docs for more information."
322
+ )
323
+
324
+ # shift inputs to the right
325
+ if is_torch_fx_proxy(input_ids):
326
+ # Item assignment is not supported natively for proxies.
327
+ shifted_input_ids = torch.full(input_ids.shape[:-1] + (1,), decoder_start_token_id)
328
+ shifted_input_ids = torch.cat([shifted_input_ids, input_ids[..., :-1]], dim=-1)
329
+ else:
330
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
331
+ shifted_input_ids[..., 1:] = input_ids[..., :-1].clone()
332
+ shifted_input_ids[..., 0] = decoder_start_token_id
333
+
334
+ if pad_token_id is None:
335
+ raise ValueError("self.model.config.pad_token_id has to be defined.")
336
+ # replace possible -100 values in labels by `pad_token_id`
337
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
338
+
339
+ return shifted_input_ids
340
+
341
+ class OpenBAStack(OpenBAPreTrainedModel):
342
+ def __init__(self, config, embed_tokens):
343
+ super().__init__(config)
344
+ self.embed_tokens = embed_tokens
345
+ self.is_decoder = config.is_decoder
346
+ self.block = nn.ModuleList(
347
+ [OpenBABlock(config) for _ in range(config.num_layers)]
348
+ )
349
+ self.final_layernorm = nn.LayerNorm(config.hidden_size)
350
+
351
+ def forward(
352
+ self,
353
+ input_ids=None,
354
+ attention_mask=None,
355
+ encoder_hidden_states=None,
356
+ encoder_attention_mask=None,
357
+ inputs_embeds=None,
358
+ head_mask=None,
359
+ cross_attn_head_mask=None,
360
+ past_key_values=None,
361
+ use_cache=None,
362
+ output_attentions=None,
363
+ output_hidden_states=None,
364
+ return_dict=None,
365
+ ):
366
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
367
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
368
+ output_hidden_states = (
369
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
370
+ )
371
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
372
+
373
+ # get batch size and seq_length
374
+ if input_ids is not None and inputs_embeds is not None:
375
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
376
+ elif input_ids is not None:
377
+ input_shape = input_ids.size()
378
+ input_ids = input_ids.view(-1, input_shape[-1])
379
+ elif inputs_embeds is not None:
380
+ input_shape = inputs_embeds.size()[:-1]
381
+ else:
382
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
383
+
384
+ batch_size, seq_length = input_shape
385
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
386
+
387
+ # required mask seq length can be calculated via length of past
388
+ if past_key_values is None:
389
+ past_length = 0
390
+ past_key_values = [None] * len(self.block)
391
+ else:
392
+ past_length = past_key_values[0][0].size(-2)
393
+ cur_length = past_length + seq_length
394
+
395
+ # position ids
396
+ position_ids = torch.arange(past_length, cur_length, dtype=torch.long, device=device)
397
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
398
+
399
+ # Attention mask
400
+ if attention_mask is None:
401
+ attention_mask = torch.ones(batch_size, seq_length, device=device)
402
+ # get extended self-attention mask
403
+ if self.is_decoder:
404
+ if len(attention_mask.shape) == 2:
405
+ seq_ids = torch.arange(seq_length, device=device)
406
+ causal_mask = seq_ids[None, None, :].repeat(batch_size, seq_length, 1) <= seq_ids[None, :, None]
407
+ causal_mask = causal_mask.to(attention_mask.dtype)
408
+ extended_attention_mask = causal_mask[:, None, :, :] * attention_mask[:, None, None, :]
409
+ elif len(attention_mask.shape) == 3:
410
+ extended_attention_mask = attention_mask[:, None, :, :]
411
+ else:
412
+ raise ValueError
413
+ else:
414
+ extended_attention_mask = attention_mask[:, None, None, :]
415
+ extended_attention_mask = extended_attention_mask < 0.5
416
+ # get extended self-attention mask
417
+ # here we replace encoder_decoder_attention_mask with encoder_attention_mask
418
+ if self.is_decoder and encoder_hidden_states is not None:
419
+ if encoder_attention_mask is None:
420
+ encoder_seq_length = encoder_hidden_states.shape[1]
421
+ encoder_attention_mask = torch.ones(
422
+ batch_size, encoder_seq_length, device=device, dtype=torch.long
423
+ )
424
+ extended_encoder_attention_mask = encoder_attention_mask[:, None, None, :]
425
+ extended_encoder_attention_mask = extended_encoder_attention_mask < 0.5
426
+ else:
427
+ extended_encoder_attention_mask = None
428
+
429
+
430
+ # input embeddings
431
+ if inputs_embeds is None:
432
+ inputs_embeds = self.embed_tokens(input_ids)
433
+
434
+ # Prepare head mask if needed
435
+ head_mask = self.get_head_mask(head_mask, self.config.num_layers)
436
+ cross_attn_head_mask = self.get_head_mask(cross_attn_head_mask, self.config.num_layers)
437
+ present_key_value_states = () if use_cache else None
438
+ all_hidden_states = () if output_hidden_states else None
439
+ all_attentions = () if output_attentions else None
440
+ all_cross_attentions = () if (output_attentions and self.is_decoder) else None
441
+ hidden_states = inputs_embeds
442
+
443
+ for i, (layer_module, past_key_value) in enumerate(zip(self.block, past_key_values)):
444
+ layer_head_mask = head_mask[i]
445
+ cross_attn_layer_head_mask = cross_attn_head_mask[i]
446
+ if output_hidden_states:
447
+ all_hidden_states += (hidden_states,)
448
+ layer_outputs = layer_module(
449
+ hidden_states,
450
+ attention_mask=extended_attention_mask,
451
+ position_ids=position_ids,
452
+ encoder_hidden_states=encoder_hidden_states,
453
+ encoder_attention_mask=extended_encoder_attention_mask,
454
+ layer_head_mask=layer_head_mask,
455
+ cross_attn_layer_head_mask=cross_attn_layer_head_mask,
456
+ past_key_value=past_key_value,
457
+ use_cache=use_cache,
458
+ output_attentions=output_attentions,
459
+ )
460
+ # layer_outputs is a tuple with:
461
+ # hidden-states, key-value-states, (self-attention weights), (cross-attention weights)
462
+ if use_cache is False:
463
+ layer_outputs = layer_outputs[:1] + (None,) + layer_outputs[1:]
464
+
465
+ hidden_states, present_key_value_state = layer_outputs[:2]
466
+ if use_cache:
467
+ present_key_value_states += (present_key_value_state,)
468
+
469
+ if output_attentions:
470
+ all_attentions = all_attentions + (layer_outputs[2],)
471
+ if self.is_decoder:
472
+ all_cross_attentions = all_cross_attentions + (layer_outputs[3],)
473
+
474
+ hidden_states = self.final_layernorm(hidden_states)
475
+
476
+ if output_hidden_states:
477
+ all_hidden_states += (hidden_states,)
478
+
479
+ if not return_dict:
480
+ return tuple(
481
+ v
482
+ for v in [
483
+ hidden_states,
484
+ present_key_value_states,
485
+ all_hidden_states,
486
+ all_attentions,
487
+ all_cross_attentions,
488
+ ]
489
+ if v is not None
490
+ )
491
+ return BaseModelOutputWithPastAndCrossAttentions(
492
+ last_hidden_state=hidden_states,
493
+ past_key_values=present_key_value_states,
494
+ hidden_states=all_hidden_states,
495
+ attentions=all_attentions,
496
+ cross_attentions=all_cross_attentions,
497
+ )
498
+
499
+
500
+ class OpenBAForConditionalGeneration(OpenBAPreTrainedModel):
501
+ _keys_to_ignore_on_load_missing = [
502
+ r"encoder.embed_tokens.weight",
503
+ r"decoder.embed_tokens.weight",
504
+ ]
505
+ def __init__(self, config):
506
+ super().__init__(config)
507
+ self.shared_embedding = nn.Embedding(config.vocab_size, config.hidden_size)
508
+ self.hidden_size = config.hidden_size
509
+
510
+ encoder_config = copy.deepcopy(config)
511
+ encoder_config.is_decoder = False
512
+ encoder_config.use_cache = False
513
+ encoder_config.is_encoder_decoder = False
514
+ self.encoder = OpenBAStack(encoder_config, self.shared_embedding)
515
+
516
+ decoder_config = copy.deepcopy(config)
517
+ decoder_config.is_decoder = True
518
+ decoder_config.is_encoder_decoder = False
519
+ decoder_config.num_layers = config.num_decoder_layers
520
+ decoder_config.max_seq_length = config.decoder_max_seq_length
521
+ self.decoder = OpenBAStack(decoder_config, self.shared_embedding)
522
+
523
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=config.add_lm_head_bias)
524
+
525
+ # Initialize weights and apply final processing
526
+ self.post_init()
527
+
528
+ # Model parallel
529
+ self.model_parallel = False
530
+ self.device_map = None
531
+
532
+ def get_input_embeddings(self):
533
+ return self.shared_embedding
534
+
535
+ def set_input_embeddings(self, new_embeddings):
536
+ self.shared_embedding = new_embeddings
537
+ self.encoder.set_input_embeddings(new_embeddings)
538
+ self.decoder.set_input_embeddings(new_embeddings)
539
+
540
+ def set_output_embeddings(self, new_embeddings):
541
+ self.lm_head = new_embeddings
542
+
543
+ def get_output_embeddings(self):
544
+ return self.lm_head
545
+
546
+ def get_encoder(self):
547
+ return self.encoder
548
+
549
+ def get_decoder(self):
550
+ return self.decoder
551
+
552
+ def forward(
553
+ self,
554
+ input_ids: Optional[torch.LongTensor] = None,
555
+ attention_mask: Optional[torch.FloatTensor] = None,
556
+ decoder_input_ids: Optional[torch.LongTensor] = None,
557
+ decoder_attention_mask: Optional[torch.BoolTensor] = None,
558
+ head_mask: Optional[torch.FloatTensor] = None,
559
+ decoder_head_mask: Optional[torch.FloatTensor] = None,
560
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
561
+ encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
562
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
563
+ inputs_embeds: Optional[torch.Tensor] = None,
564
+ decoder_inputs_embeds: Optional[torch.Tensor] = None,
565
+ labels: Optional[torch.LongTensor] = None,
566
+ use_cache: Optional[bool] = None,
567
+ output_attentions: Optional[bool] = None,
568
+ output_hidden_states: Optional[bool] = None,
569
+ return_dict: Optional[bool] = None,
570
+ ) -> Union[Tuple[torch.FloatTensor], Seq2SeqLMOutput]:
571
+
572
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
573
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
574
+
575
+ # Encode if needed (training, first prediction pass)
576
+ if encoder_outputs is None:
577
+ encoder_outputs = self.encoder(
578
+ input_ids=input_ids,
579
+ attention_mask=attention_mask,
580
+ inputs_embeds=inputs_embeds,
581
+ head_mask=head_mask,
582
+ output_attentions=output_attentions,
583
+ output_hidden_states=output_hidden_states,
584
+ return_dict=return_dict,
585
+ )
586
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
587
+ encoder_outputs = BaseModelOutput(
588
+ last_hidden_state=encoder_outputs[0],
589
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
590
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,\
591
+ )
592
+
593
+ hidden_states = encoder_outputs[0]
594
+
595
+ if labels is not None and decoder_input_ids is None and decoder_inputs_embeds is None:
596
+ # get decoder inputs from shifting lm labels to the right
597
+ decoder_input_ids = self._shift_right(labels)
598
+
599
+ # Decode
600
+ decoder_outputs = self.decoder(
601
+ input_ids=decoder_input_ids,
602
+ attention_mask=decoder_attention_mask,
603
+ inputs_embeds=decoder_inputs_embeds,
604
+ past_key_values=past_key_values,
605
+ encoder_hidden_states=hidden_states,
606
+ encoder_attention_mask=attention_mask,
607
+ head_mask=decoder_head_mask,
608
+ cross_attn_head_mask=cross_attn_head_mask,
609
+ use_cache=use_cache,
610
+ output_attentions=output_attentions,
611
+ output_hidden_states=output_hidden_states,
612
+ return_dict=return_dict,
613
+ )
614
+
615
+ sequence_output = decoder_outputs[0]
616
+ # share embedding and softmax embedding
617
+ if self.config.tie_word_embeddings:
618
+ # Rescale output before projecting on vocab
619
+ sequence_output = sequence_output * (self.hidden_size ** -0.5)
620
+
621
+ lm_logits = self.lm_head(sequence_output).to(torch.float32)
622
+
623
+ loss = None
624
+ if labels is not None:
625
+ loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
626
+ # move labels to correct device to enable PP
627
+ labels = labels.to(lm_logits.device)
628
+ loss = loss_fct(lm_logits.view(-1, lm_logits.size(-1)), labels.view(-1))
629
+ loss = loss.to(hidden_states.dtype)
630
+
631
+ if not return_dict:
632
+ output = (lm_logits,) + decoder_outputs[1:] + encoder_outputs
633
+ return ((loss,) + output) if loss is not None else output
634
+
635
+ return Seq2SeqLMOutput(
636
+ loss=loss,
637
+ logits=lm_logits,
638
+ past_key_values=decoder_outputs.past_key_values,
639
+ decoder_hidden_states=decoder_outputs.hidden_states,
640
+ decoder_attentions=decoder_outputs.attentions,
641
+ cross_attentions=decoder_outputs.cross_attentions,
642
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
643
+ encoder_hidden_states=encoder_outputs.hidden_states,
644
+ encoder_attentions=encoder_outputs.attentions,
645
+ )
646
+
647
+ def prepare_inputs_for_generation(
648
+ self,
649
+ input_ids,
650
+ past_key_values=None,
651
+ attention_mask=None,
652
+ head_mask=None,
653
+ decoder_head_mask=None,
654
+ decoder_attention_mask=None,
655
+ cross_attn_head_mask=None,
656
+ use_cache=None,
657
+ encoder_outputs=None,
658
+ **kwargs,
659
+ ):
660
+ # cut decoder_input_ids if past is used
661
+ if past_key_values is not None:
662
+ input_ids = input_ids[:, -1:]
663
+
664
+ return {
665
+ "decoder_input_ids": input_ids,
666
+ "past_key_values": past_key_values,
667
+ "encoder_outputs": encoder_outputs,
668
+ "attention_mask": attention_mask,
669
+ "head_mask": head_mask,
670
+ "decoder_head_mask": decoder_head_mask,
671
+ "decoder_attention_mask": decoder_attention_mask,
672
+ "cross_attn_head_mask": cross_attn_head_mask,
673
+ "use_cache": use_cache,
674
+ }
675
+
676
+ def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
677
+ return self._shift_right(labels)
678
+
679
+ def _reorder_cache(self, past_key_values, beam_idx):
680
+ # if decoder past is not included in output
681
+ # speedy decoding is disabled and no need to reorder
682
+ if past_key_values is None:
683
+ logger.warning("You might want to consider setting `use_cache=True` to speed up decoding")
684
+ return past_key_values
685
+
686
+ reordered_decoder_past = ()
687
+ for layer_past_states in past_key_values:
688
+ # get the correct batch idx from layer past batch dim
689
+ # batch dim of `past` is at 2nd position
690
+ reordered_layer_past_states = ()
691
+ for layer_past_state in layer_past_states:
692
+ # need to set correct `past` for each of the four key / value states
693
+ reordered_layer_past_states = reordered_layer_past_states + (
694
+ layer_past_state.index_select(0, beam_idx.to(layer_past_state.device)),
695
+ )
696
+
697
+ if reordered_layer_past_states[0].shape != layer_past_states[0].shape:
698
+ raise ValueError(
699
+ f"reordered_layer_past_states[0] shape {reordered_layer_past_states[0].shape} and layer_past_states[0] shape {layer_past_states[0].shape} mismatched"
700
+ )
701
+ if len(reordered_layer_past_states) != len(layer_past_states):
702
+ raise ValueError(
703
+ f"length of reordered_layer_past_states {len(reordered_layer_past_states)} and length of layer_past_states {len(layer_past_states)} mismatched"
704
+ )
705
+
706
+ reordered_decoder_past = reordered_decoder_past + (reordered_layer_past_states,)
707
+ return reordered_decoder_past
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:738865e96f4567a71f238e3ced6120d7fa8b44c8461966f64a1ce66ee232d526
3
+ size 7617363989
special_tokens_map.json ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<extra_id_0>",
4
+ "<extra_id_1>",
5
+ "<extra_id_2>",
6
+ "<extra_id_3>",
7
+ "<extra_id_4>",
8
+ "<extra_id_5>",
9
+ "<extra_id_6>",
10
+ "<extra_id_7>",
11
+ "<extra_id_8>",
12
+ "<extra_id_9>",
13
+ "<extra_id_10>",
14
+ "<extra_id_11>",
15
+ "<extra_id_12>",
16
+ "<extra_id_13>",
17
+ "<extra_id_14>",
18
+ "<extra_id_15>",
19
+ "<extra_id_16>",
20
+ "<extra_id_17>",
21
+ "<extra_id_18>",
22
+ "<extra_id_19>",
23
+ "<extra_id_20>",
24
+ "<extra_id_21>",
25
+ "<extra_id_22>",
26
+ "<extra_id_23>",
27
+ "<extra_id_24>",
28
+ "<extra_id_25>",
29
+ "<extra_id_26>",
30
+ "<extra_id_27>",
31
+ "<extra_id_28>",
32
+ "<extra_id_29>",
33
+ "<extra_id_30>",
34
+ "<extra_id_31>",
35
+ "<extra_id_32>",
36
+ "<extra_id_33>",
37
+ "<extra_id_34>",
38
+ "<extra_id_35>",
39
+ "<extra_id_36>",
40
+ "<extra_id_37>",
41
+ "<extra_id_38>",
42
+ "<extra_id_39>",
43
+ "<extra_id_40>",
44
+ "<extra_id_41>",
45
+ "<extra_id_42>",
46
+ "<extra_id_43>",
47
+ "<extra_id_44>",
48
+ "<extra_id_45>",
49
+ "<extra_id_46>",
50
+ "<extra_id_47>",
51
+ "<extra_id_48>",
52
+ "<extra_id_49>",
53
+ "<extra_id_50>",
54
+ "<extra_id_51>",
55
+ "<extra_id_52>",
56
+ "<extra_id_53>",
57
+ "<extra_id_54>",
58
+ "<extra_id_55>",
59
+ "<extra_id_56>",
60
+ "<extra_id_57>",
61
+ "<extra_id_58>",
62
+ "<extra_id_59>",
63
+ "<extra_id_60>",
64
+ "<extra_id_61>",
65
+ "<extra_id_62>",
66
+ "<extra_id_63>",
67
+ "<extra_id_64>",
68
+ "<extra_id_65>",
69
+ "<extra_id_66>",
70
+ "<extra_id_67>",
71
+ "<extra_id_68>",
72
+ "<extra_id_69>",
73
+ "<extra_id_70>",
74
+ "<extra_id_71>",
75
+ "<extra_id_72>",
76
+ "<extra_id_73>",
77
+ "<extra_id_74>",
78
+ "<extra_id_75>",
79
+ "<extra_id_76>",
80
+ "<extra_id_77>",
81
+ "<extra_id_78>",
82
+ "<extra_id_79>",
83
+ "<extra_id_80>",
84
+ "<extra_id_81>",
85
+ "<extra_id_82>",
86
+ "<extra_id_83>",
87
+ "<extra_id_84>",
88
+ "<extra_id_85>",
89
+ "<extra_id_86>",
90
+ "<extra_id_87>",
91
+ "<extra_id_88>",
92
+ "<extra_id_89>",
93
+ "<extra_id_90>",
94
+ "<extra_id_91>",
95
+ "<extra_id_92>",
96
+ "<extra_id_93>",
97
+ "<extra_id_94>",
98
+ "<extra_id_95>",
99
+ "<extra_id_96>",
100
+ "<extra_id_97>",
101
+ "<extra_id_98>",
102
+ "<extra_id_99>"
103
+ ],
104
+ "eos_token": "</s>",
105
+ "pad_token": "<pad>",
106
+ "unk_token": "<unk>"
107
+ }
spiece.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ef78f86560d809067d12bac6c09f19a462cb3af3f54d2b8acbba26e1433125d6
3
+ size 4309802
tokenization_openba.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+
3
+
4
+ import os
5
+ import re
6
+ import warnings
7
+ from shutil import copyfile
8
+ from typing import Any, Dict, List, Optional, Tuple
9
+
10
+ import sentencepiece as spm
11
+
12
+ from transformers.tokenization_utils import PreTrainedTokenizer
13
+ from transformers.utils import logging
14
+
15
+
16
+ logger = logging.get_logger(__name__)
17
+
18
+ VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
19
+
20
+
21
+ class OpenBATokenizer(PreTrainedTokenizer):
22
+
23
+ vocab_files_names = VOCAB_FILES_NAMES
24
+ model_input_names = ["input_ids", "attention_mask"]
25
+
26
+ def __init__(
27
+ self,
28
+ vocab_file,
29
+ eos_token="</s>",
30
+ unk_token="<unk>",
31
+ pad_token="<pad>",
32
+ extra_ids=100,
33
+ additional_special_tokens=None,
34
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
35
+ **kwargs,
36
+ ) -> None:
37
+ # Add extra_ids to the special token list
38
+ if extra_ids > 0 and additional_special_tokens is None:
39
+ additional_special_tokens = [f"<extra_id_{i}>" for i in range(extra_ids)]
40
+ elif extra_ids > 0 and additional_special_tokens is not None:
41
+ # Check that we have the right number of extra_id special tokens
42
+ extra_tokens = len(set(filter(lambda x: bool("extra_id" in str(x)), additional_special_tokens)))
43
+ if extra_tokens != extra_ids:
44
+ raise ValueError(
45
+ f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are"
46
+ " provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids"
47
+ " tokens"
48
+ )
49
+
50
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
51
+
52
+ super().__init__(
53
+ eos_token=eos_token,
54
+ unk_token=unk_token,
55
+ pad_token=pad_token,
56
+ extra_ids=extra_ids,
57
+ additional_special_tokens=additional_special_tokens,
58
+ sp_model_kwargs=self.sp_model_kwargs,
59
+ **kwargs,
60
+ )
61
+
62
+ self.vocab_file = vocab_file
63
+ self._extra_ids = extra_ids
64
+
65
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
66
+ self.sp_model.Load(vocab_file)
67
+
68
+ @staticmethod
69
+ def _eventually_correct_t5_max_length(pretrained_model_name_or_path, max_model_length, init_max_model_length):
70
+ if pretrained_model_name_or_path in OpenBATokenizer.max_model_input_sizes:
71
+ deprecated_max_model_length = OpenBATokenizer.max_model_input_sizes[pretrained_model_name_or_path]
72
+ if init_max_model_length is not None and init_max_model_length != max_model_length:
73
+ return init_max_model_length
74
+ elif init_max_model_length is None:
75
+ warnings.warn(
76
+ "This tokenizer was incorrectly instantiated with a model max length of"
77
+ f" {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this"
78
+ " behavior is kept to avoid breaking backwards compatibility when padding/encoding with"
79
+ " `truncation is True`.\n- Be aware that you SHOULD NOT rely on"
80
+ f" {pretrained_model_name_or_path} automatically truncating your input to"
81
+ f" {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences"
82
+ f" longer than {deprecated_max_model_length} you can either instantiate this tokenizer with"
83
+ " `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please"
84
+ " instantiate this tokenizer with `model_max_length` set to your preferred value.",
85
+ FutureWarning,
86
+ )
87
+
88
+ return max_model_length
89
+
90
+ @property
91
+ def vocab_size(self):
92
+ return self.sp_model.get_piece_size() + self._extra_ids
93
+
94
+ def get_vocab(self):
95
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
96
+ vocab.update(self.added_tokens_encoder)
97
+ return vocab
98
+
99
+ def get_special_tokens_mask(
100
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
101
+ ) -> List[int]:
102
+ """
103
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
104
+ special tokens using the tokenizer `prepare_for_model` method.
105
+
106
+ Args:
107
+ token_ids_0 (`List[int]`):
108
+ List of IDs.
109
+ token_ids_1 (`List[int]`, *optional*):
110
+ Optional second list of IDs for sequence pairs.
111
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
112
+ Whether or not the token list is already formatted with special tokens for the model.
113
+
114
+ Returns:
115
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
116
+ """
117
+ if already_has_special_tokens:
118
+ return super().get_special_tokens_mask(
119
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
120
+ )
121
+
122
+ # normal case: some special tokens
123
+ if token_ids_1 is None:
124
+ return ([0] * len(token_ids_0)) + [1]
125
+ return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
126
+
127
+ def get_sentinel_tokens(self):
128
+ return list(
129
+ set(filter(lambda x: bool(re.search(r"<extra_id_\d+>", x)) is not None, self.additional_special_tokens))
130
+ )
131
+
132
+ def get_sentinel_token_ids(self):
133
+ return [self._convert_token_to_id(token) for token in self.get_sentinel_tokens()]
134
+
135
+ def _add_eos_if_not_present(self, token_ids: List[int]) -> List[int]:
136
+ """Do not add eos again if user already added it."""
137
+ if len(token_ids) > 0 and token_ids[-1] == self.eos_token_id:
138
+ warnings.warn(
139
+ f"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated"
140
+ " eos tokens being added."
141
+ )
142
+ return token_ids
143
+ else:
144
+ return token_ids + [self.eos_token_id]
145
+
146
+ def create_token_type_ids_from_sequences(
147
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
148
+ ) -> List[int]:
149
+ """
150
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. T5 does not make
151
+ use of token type ids, therefore a list of zeros is returned.
152
+
153
+ Args:
154
+ token_ids_0 (`List[int]`):
155
+ List of IDs.
156
+ token_ids_1 (`List[int]`, *optional*):
157
+ Optional second list of IDs for sequence pairs.
158
+
159
+ Returns:
160
+ `List[int]`: List of zeros.
161
+ """
162
+ eos = [self.eos_token_id]
163
+
164
+ if token_ids_1 is None:
165
+ return len(token_ids_0 + eos) * [0]
166
+ return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
167
+
168
+ def build_inputs_with_special_tokens(
169
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
170
+ ) -> List[int]:
171
+ """
172
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
173
+ adding special tokens. A sequence has the following format:
174
+
175
+ - single sequence: `X </s>`
176
+ - pair of sequences: `A </s> B </s>`
177
+
178
+ Args:
179
+ token_ids_0 (`List[int]`):
180
+ List of IDs to which the special tokens will be added.
181
+ token_ids_1 (`List[int]`, *optional*):
182
+ Optional second list of IDs for sequence pairs.
183
+
184
+ Returns:
185
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
186
+ """
187
+ token_ids_0 = self._add_eos_if_not_present(token_ids_0)
188
+ if token_ids_1 is None:
189
+ return token_ids_0
190
+ else:
191
+ token_ids_1 = self._add_eos_if_not_present(token_ids_1)
192
+ return token_ids_0 + token_ids_1
193
+
194
+ def __getstate__(self):
195
+ state = self.__dict__.copy()
196
+ state["sp_model"] = None
197
+ return state
198
+
199
+ def __setstate__(self, d):
200
+ self.__dict__ = d
201
+
202
+ # for backward compatibility
203
+ if not hasattr(self, "sp_model_kwargs"):
204
+ self.sp_model_kwargs = {}
205
+
206
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
207
+ self.sp_model.Load(self.vocab_file)
208
+
209
+ def _tokenize(self, text: str) -> List[str]:
210
+ """Take as input a string and return a list of strings (tokens) for words/sub-words"""
211
+ return self.sp_model.encode(text, out_type=str)
212
+
213
+ def _convert_token_to_id(self, token):
214
+ """Converts a token (str) in an id using the vocab."""
215
+ if token.startswith("<extra_id_"):
216
+ match = re.match(r"<extra_id_(\d+)>", token)
217
+ num = int(match.group(1))
218
+ return self.vocab_size - num - 1
219
+ return self.sp_model.piece_to_id(token)
220
+
221
+ def _convert_id_to_token(self, index):
222
+ """Converts an index (integer) in a token (str) using the vocab."""
223
+ if index < self.sp_model.get_piece_size():
224
+ token = self.sp_model.IdToPiece(index)
225
+ else:
226
+ token = f"<extra_id_{self.vocab_size - 1 - index}>"
227
+ return token
228
+
229
+ def convert_tokens_to_string(self, tokens):
230
+ """Converts a sequence of tokens (string) in a single string."""
231
+ current_sub_tokens = []
232
+ out_string = ""
233
+ prev_is_special = False
234
+ for token in tokens:
235
+ # make sure that special tokens are not decoded using sentencepiece model
236
+ if token in self.all_special_tokens:
237
+ if not prev_is_special:
238
+ out_string += " "
239
+ out_string += self.sp_model.decode(current_sub_tokens) + token
240
+ prev_is_special = True
241
+ current_sub_tokens = []
242
+ else:
243
+ current_sub_tokens.append(token)
244
+ prev_is_special = False
245
+ out_string += self.sp_model.decode(current_sub_tokens)
246
+ return out_string.strip()
247
+
248
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
249
+ if not os.path.isdir(save_directory):
250
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
251
+ return
252
+ out_vocab_file = os.path.join(
253
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
254
+ )
255
+
256
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
257
+ copyfile(self.vocab_file, out_vocab_file)
258
+ elif not os.path.isfile(self.vocab_file):
259
+ with open(out_vocab_file, "wb") as fi:
260
+ content_spiece_model = self.sp_model.serialized_model_proto()
261
+ fi.write(content_spiece_model)
262
+
263
+ return (out_vocab_file,)
tokenizer_config.json ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<extra_id_0>",
4
+ "<extra_id_1>",
5
+ "<extra_id_2>",
6
+ "<extra_id_3>",
7
+ "<extra_id_4>",
8
+ "<extra_id_5>",
9
+ "<extra_id_6>",
10
+ "<extra_id_7>",
11
+ "<extra_id_8>",
12
+ "<extra_id_9>",
13
+ "<extra_id_10>",
14
+ "<extra_id_11>",
15
+ "<extra_id_12>",
16
+ "<extra_id_13>",
17
+ "<extra_id_14>",
18
+ "<extra_id_15>",
19
+ "<extra_id_16>",
20
+ "<extra_id_17>",
21
+ "<extra_id_18>",
22
+ "<extra_id_19>",
23
+ "<extra_id_20>",
24
+ "<extra_id_21>",
25
+ "<extra_id_22>",
26
+ "<extra_id_23>",
27
+ "<extra_id_24>",
28
+ "<extra_id_25>",
29
+ "<extra_id_26>",
30
+ "<extra_id_27>",
31
+ "<extra_id_28>",
32
+ "<extra_id_29>",
33
+ "<extra_id_30>",
34
+ "<extra_id_31>",
35
+ "<extra_id_32>",
36
+ "<extra_id_33>",
37
+ "<extra_id_34>",
38
+ "<extra_id_35>",
39
+ "<extra_id_36>",
40
+ "<extra_id_37>",
41
+ "<extra_id_38>",
42
+ "<extra_id_39>",
43
+ "<extra_id_40>",
44
+ "<extra_id_41>",
45
+ "<extra_id_42>",
46
+ "<extra_id_43>",
47
+ "<extra_id_44>",
48
+ "<extra_id_45>",
49
+ "<extra_id_46>",
50
+ "<extra_id_47>",
51
+ "<extra_id_48>",
52
+ "<extra_id_49>",
53
+ "<extra_id_50>",
54
+ "<extra_id_51>",
55
+ "<extra_id_52>",
56
+ "<extra_id_53>",
57
+ "<extra_id_54>",
58
+ "<extra_id_55>",
59
+ "<extra_id_56>",
60
+ "<extra_id_57>",
61
+ "<extra_id_58>",
62
+ "<extra_id_59>",
63
+ "<extra_id_60>",
64
+ "<extra_id_61>",
65
+ "<extra_id_62>",
66
+ "<extra_id_63>",
67
+ "<extra_id_64>",
68
+ "<extra_id_65>",
69
+ "<extra_id_66>",
70
+ "<extra_id_67>",
71
+ "<extra_id_68>",
72
+ "<extra_id_69>",
73
+ "<extra_id_70>",
74
+ "<extra_id_71>",
75
+ "<extra_id_72>",
76
+ "<extra_id_73>",
77
+ "<extra_id_74>",
78
+ "<extra_id_75>",
79
+ "<extra_id_76>",
80
+ "<extra_id_77>",
81
+ "<extra_id_78>",
82
+ "<extra_id_79>",
83
+ "<extra_id_80>",
84
+ "<extra_id_81>",
85
+ "<extra_id_82>",
86
+ "<extra_id_83>",
87
+ "<extra_id_84>",
88
+ "<extra_id_85>",
89
+ "<extra_id_86>",
90
+ "<extra_id_87>",
91
+ "<extra_id_88>",
92
+ "<extra_id_89>",
93
+ "<extra_id_90>",
94
+ "<extra_id_91>",
95
+ "<extra_id_92>",
96
+ "<extra_id_93>",
97
+ "<extra_id_94>",
98
+ "<extra_id_95>",
99
+ "<extra_id_96>",
100
+ "<extra_id_97>",
101
+ "<extra_id_98>",
102
+ "<extra_id_99>"
103
+ ],
104
+ "auto_map": {
105
+ "AutoTokenizer": [
106
+ "tokenization_openba.OpenBATokenizer",
107
+ null
108
+ ]
109
+ },
110
+ "clean_up_tokenization_spaces": true,
111
+ "eos_token": "</s>",
112
+ "extra_ids": 100,
113
+ "model_max_length": 1000000000000000019884624838656,
114
+ "pad_token": "<pad>",
115
+ "sp_model_kwargs": {},
116
+ "tokenizer_class": "OpenBATokenizer",
117
+ "tokenizer_file": null,
118
+ "unk_token": "<unk>"
119
+ }
120
+