PCLNLP commited on
Commit
4ab70f0
·
verified ·
1 Parent(s): 44ca3bf

Upload folder using huggingface_hub

Browse files
config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation_function": "swgelu",
3
+ "architectures": [
4
+ "MindLMHeadModel"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_Mind.MindConfig",
8
+ "AutoModelForCausalLM": "modeling_mind.MindLMHeadModel"
9
+ },
10
+ "attn_pdrop": 0.1,
11
+ "bos_token_id": 1,
12
+ "embd_pdrop": 0.1,
13
+ "eos_token_id": 2,
14
+ "initializer_range": 0.02,
15
+ "layer_norm_epsilon": 1e-05,
16
+ "n_embd": 4096,
17
+ "n_head": 32,
18
+ "n_inner": 10880,
19
+ "n_layer": 32,
20
+ "n_positions": 4096,
21
+ "reorder_and_upcast_attn": false,
22
+ "resid_pdrop": 0.1,
23
+ "scale_attn_by_inverse_layer_idx": false,
24
+ "scale_attn_weights": true,
25
+ "summary_activation": null,
26
+ "summary_first_dropout": 0.1,
27
+ "summary_proj_to_labels": true,
28
+ "summary_type": "cls_index",
29
+ "summary_use_proj": true,
30
+ "tokenizer_class": "BaichuanTokenizer",
31
+ "transformers_version": "4.30.2",
32
+ "use_cache": true,
33
+ "vocab_size": 125952
34
+ }
configuration_Mind.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ OpenAI GPT-2 configuration"""
17
+ from collections import OrderedDict
18
+ from typing import Any, List, Mapping, Optional
19
+
20
+ from transformers import PreTrainedTokenizer, TensorType, is_torch_available
21
+ from transformers.configuration_utils import PretrainedConfig
22
+ from transformers.onnx import OnnxConfigWithPast, PatchingSpec
23
+ from transformers.utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ Mind_PRETRAINED_CONFIG_ARCHIVE_MAP = {
29
+ "Mind": "https://huggingface.co/Mind/resolve/main/config.json",
30
+ "Mind-medium": "https://huggingface.co/Mind-medium/resolve/main/config.json",
31
+ "Mind-large": "https://huggingface.co/Mind-large/resolve/main/config.json",
32
+ "Mind-xl": "https://huggingface.co/Mind-xl/resolve/main/config.json",
33
+ "distilMind": "https://huggingface.co/distilMind/resolve/main/config.json",
34
+ }
35
+
36
+
37
+ class MindConfig(PretrainedConfig):
38
+ """
39
+ This is the configuration class to store the configuration of a [`MindModel`] or a [`TFMindModel`]. It is used to
40
+ instantiate a GPT-2 model according to the specified arguments, defining the model architecture. Instantiating a
41
+ configuration with the defaults will yield a similar configuration to that of the GPT-2
42
+ [Mind](https://huggingface.co/Mind) architecture.
43
+
44
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
45
+ documentation from [`PretrainedConfig`] for more information.
46
+
47
+
48
+ Args:
49
+ vocab_size (`int`, *optional*, defaults to 50257):
50
+ Vocabulary size of the GPT-2 model. Defines the number of different tokens that can be represented by the
51
+ `inputs_ids` passed when calling [`MindModel`] or [`TFMindModel`].
52
+ n_positions (`int`, *optional*, defaults to 1024):
53
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
54
+ just in case (e.g., 512 or 1024 or 2048).
55
+ n_embd (`int`, *optional*, defaults to 768):
56
+ Dimensionality of the embeddings and hidden states.
57
+ n_layer (`int`, *optional*, defaults to 12):
58
+ Number of hidden layers in the Transformer encoder.
59
+ n_head (`int`, *optional*, defaults to 12):
60
+ Number of attention heads for each attention layer in the Transformer encoder.
61
+ n_inner (`int`, *optional*, defaults to None):
62
+ Dimensionality of the inner feed-forward layers. `None` will set it to 4 times n_embd
63
+ activation_function (`str`, *optional*, defaults to `"gelu"`):
64
+ Activation function, to be selected in the list `["relu", "silu", "gelu", "tanh", "gelu_new"]`.
65
+ resid_pdrop (`float`, *optional*, defaults to 0.1):
66
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
67
+ embd_pdrop (`float`, *optional*, defaults to 0.1):
68
+ The dropout ratio for the embeddings.
69
+ attn_pdrop (`float`, *optional*, defaults to 0.1):
70
+ The dropout ratio for the attention.
71
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):
72
+ The epsilon to use in the layer normalization layers.
73
+ initializer_range (`float`, *optional*, defaults to 0.02):
74
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
75
+ summary_type (`string`, *optional*, defaults to `"cls_index"`):
76
+ Argument used when doing sequence summary, used in the models [`MindDoubleHeadsModel`] and
77
+ [`TFMindDoubleHeadsModel`].
78
+
79
+ Has to be one of the following options:
80
+
81
+ - `"last"`: Take the last token hidden state (like XLNet).
82
+ - `"first"`: Take the first token hidden state (like BERT).
83
+ - `"mean"`: Take the mean of all tokens hidden states.
84
+ - `"cls_index"`: Supply a Tensor of classification token position (like GPT/GPT-2).
85
+ - `"attn"`: Not implemented now, use multi-head attention.
86
+ summary_use_proj (`bool`, *optional*, defaults to `True`):
87
+ Argument used when doing sequence summary, used in the models [`MindDoubleHeadsModel`] and
88
+ [`TFMindDoubleHeadsModel`].
89
+
90
+ Whether or not to add a projection after the vector extraction.
91
+ summary_activation (`str`, *optional*):
92
+ Argument used when doing sequence summary. Used in for the multiple choice head in
93
+ [`MindDoubleHeadsModel`].
94
+
95
+ Pass `"tanh"` for a tanh activation to the output, any other value will result in no activation.
96
+ summary_proj_to_labels (`bool`, *optional*, defaults to `True`):
97
+ Argument used when doing sequence summary, used in the models [`MindDoubleHeadsModel`] and
98
+ [`TFMindDoubleHeadsModel`].
99
+
100
+ Whether the projection outputs should have `config.num_labels` or `config.hidden_size` classes.
101
+ summary_first_dropout (`float`, *optional*, defaults to 0.1):
102
+ Argument used when doing sequence summary, used in the models [`MindDoubleHeadsModel`] and
103
+ [`TFMindDoubleHeadsModel`].
104
+
105
+ The dropout ratio to be used after the projection and activation.
106
+ scale_attn_weights (`bool`, *optional*, defaults to `True`):
107
+ Scale attention weights by dividing by sqrt(hidden_size)..
108
+ use_cache (`bool`, *optional*, defaults to `True`):
109
+ Whether or not the model should return the last key/values attentions (not used by all models).
110
+ scale_attn_by_inverse_layer_idx (`bool`, *optional*, defaults to `False`):
111
+ Whether to additionally scale attention weights by `1 / layer_idx + 1`.
112
+ reorder_and_upcast_attn (`bool`, *optional*, defaults to `False`):
113
+ Whether to scale keys (K) prior to computing attention (dot-product) and upcast attention
114
+ dot-product/softmax to float() when training with mixed precision.
115
+
116
+ Example:
117
+
118
+ ```python
119
+ >>> from transformers import MindConfig, MindModel
120
+
121
+ >>> # Initializing a Mind configuration
122
+ >>> configuration = MindConfig()
123
+
124
+ >>> # Initializing a model (with random weights) from the configuration
125
+ >>> model = MindModel(configuration)
126
+
127
+ >>> # Accessing the model configuration
128
+ >>> configuration = model.config
129
+ ```"""
130
+
131
+ # model_type = "Mind"
132
+ keys_to_ignore_at_inference = ["past_key_values"]
133
+ attribute_map = {
134
+ "hidden_size": "n_embd",
135
+ "max_position_embeddings": "n_positions",
136
+ "num_attention_heads": "n_head",
137
+ "num_hidden_layers": "n_layer",
138
+ }
139
+
140
+ def __init__(
141
+ self,
142
+ vocab_size=50257,
143
+ n_positions=1024,
144
+ n_embd=768,
145
+ n_layer=12,
146
+ n_head=12,
147
+ n_inner=None,
148
+ activation_function="gelu_new",
149
+ resid_pdrop=0.1,
150
+ embd_pdrop=0.1,
151
+ attn_pdrop=0.1,
152
+ layer_norm_epsilon=1e-5,
153
+ initializer_range=0.02,
154
+ summary_type="cls_index",
155
+ summary_use_proj=True,
156
+ summary_activation=None,
157
+ summary_proj_to_labels=True,
158
+ summary_first_dropout=0.1,
159
+ scale_attn_weights=True,
160
+ use_cache=True,
161
+ bos_token_id=50256,
162
+ eos_token_id=50256,
163
+ scale_attn_by_inverse_layer_idx=False,
164
+ reorder_and_upcast_attn=False,
165
+ **kwargs,
166
+ ):
167
+ self.vocab_size = vocab_size
168
+ self.n_positions = n_positions
169
+ self.n_embd = n_embd
170
+ self.n_layer = n_layer
171
+ self.n_head = n_head
172
+ self.n_inner = n_inner
173
+ self.activation_function = activation_function
174
+ self.resid_pdrop = resid_pdrop
175
+ self.embd_pdrop = embd_pdrop
176
+ self.attn_pdrop = attn_pdrop
177
+ self.layer_norm_epsilon = layer_norm_epsilon
178
+ self.initializer_range = initializer_range
179
+ self.summary_type = summary_type
180
+ self.summary_use_proj = summary_use_proj
181
+ self.summary_activation = summary_activation
182
+ self.summary_first_dropout = summary_first_dropout
183
+ self.summary_proj_to_labels = summary_proj_to_labels
184
+ self.scale_attn_weights = scale_attn_weights
185
+ self.use_cache = use_cache
186
+ self.scale_attn_by_inverse_layer_idx = scale_attn_by_inverse_layer_idx
187
+ self.reorder_and_upcast_attn = reorder_and_upcast_attn
188
+
189
+ self.bos_token_id = bos_token_id
190
+ self.eos_token_id = eos_token_id
191
+
192
+ super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
193
+
194
+
195
+ class MindOnnxConfig(OnnxConfigWithPast):
196
+ def __init__(
197
+ self,
198
+ config: PretrainedConfig,
199
+ task: str = "default",
200
+ patching_specs: List[PatchingSpec] = None,
201
+ use_past: bool = False,
202
+ ):
203
+ super().__init__(config, task=task, patching_specs=patching_specs, use_past=use_past)
204
+ if not getattr(self._config, "pad_token_id", None):
205
+ # TODO: how to do that better?
206
+ self._config.pad_token_id = 0
207
+
208
+ @property
209
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
210
+ common_inputs = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}})
211
+ if self.use_past:
212
+ self.fill_with_past_key_values_(common_inputs, direction="inputs")
213
+ common_inputs["attention_mask"] = {0: "batch", 1: "past_sequence + sequence"}
214
+ else:
215
+ common_inputs["attention_mask"] = {0: "batch", 1: "sequence"}
216
+
217
+ return common_inputs
218
+
219
+ @property
220
+ def num_layers(self) -> int:
221
+ return self._config.n_layer
222
+
223
+ @property
224
+ def num_attention_heads(self) -> int:
225
+ return self._config.n_head
226
+
227
+ def generate_dummy_inputs(
228
+ self,
229
+ tokenizer: PreTrainedTokenizer,
230
+ batch_size: int = -1,
231
+ seq_length: int = -1,
232
+ is_pair: bool = False,
233
+ framework: Optional[TensorType] = None,
234
+ ) -> Mapping[str, Any]:
235
+ common_inputs = super(OnnxConfigWithPast, self).generate_dummy_inputs(
236
+ tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
237
+ )
238
+
239
+ # We need to order the input in the way they appears in the forward()
240
+ ordered_inputs = OrderedDict({"input_ids": common_inputs["input_ids"]})
241
+
242
+ # Need to add the past_keys
243
+ if self.use_past:
244
+ if not is_torch_available():
245
+ raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
246
+ else:
247
+ import torch
248
+
249
+ batch, seqlen = common_inputs["input_ids"].shape
250
+ # Not using the same length for past_key_values
251
+ past_key_values_length = seqlen + 2
252
+ past_shape = (
253
+ batch,
254
+ self.num_attention_heads,
255
+ past_key_values_length,
256
+ self._config.hidden_size // self.num_attention_heads,
257
+ )
258
+ ordered_inputs["past_key_values"] = [
259
+ (torch.zeros(past_shape), torch.zeros(past_shape)) for _ in range(self.num_layers)
260
+ ]
261
+
262
+ ordered_inputs["attention_mask"] = common_inputs["attention_mask"]
263
+ if self.use_past:
264
+ mask_dtype = ordered_inputs["attention_mask"].dtype
265
+ ordered_inputs["attention_mask"] = torch.cat(
266
+ [ordered_inputs["attention_mask"], torch.ones(batch, past_key_values_length, dtype=mask_dtype)], dim=1
267
+ )
268
+
269
+ return ordered_inputs
270
+
271
+ @property
272
+ def default_onnx_opset(self) -> int:
273
+ return 13
convert_ms_to_hf.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: UTF-8 -*-
2
+
3
+ from collections import OrderedDict
4
+
5
+ import mindspore as ms
6
+ import numpy as np
7
+ import torch
8
+
9
+ ckpt_path = "new-fp16-pcmind_new7B_1080Btks.ckpt"
10
+ torch_path = "./pytorch_model.bin"
11
+
12
+ loaded = {}
13
+ param_dict = ms.load_checkpoint(ckpt_path)
14
+ for (key, value) in param_dict.items():
15
+ loaded[key] = torch.from_numpy(ms.Tensor(value.data, ms.float16).asnumpy())
16
+
17
+ args = {'bf16': False,
18
+ 'fp16': True,
19
+ 'num_layers': 32,
20
+ 'encoder_num_layers': 32,
21
+ 'seq_length': 2048,
22
+ 'encoder_seq_length': 2048,
23
+ 'max_position_embeddings': 2048,
24
+ 'hidden_size': 4096,
25
+ 'ffn_hidden_size': 16384,
26
+ 'make_vocab_size_divisible_by': 16,
27
+ 'micro_batch_size': 1,
28
+ 'num_attention_heads': 32,
29
+ 'use_rotary_position_embeddings': True,
30
+ 'ms_fast_gelu': True,
31
+ 'add_position_embedding': False,
32
+ 'padded_vocab_size': 136832}
33
+
34
+ new_sd = OrderedDict()
35
+ for layer_i in range(args['num_layers']):
36
+ new_sd[f'transformer.h.{layer_i}.ln_1.weight'] = loaded[f"backbone.blocks.{layer_i}.layernorm1.gamma"]
37
+ new_sd[f'transformer.h.{layer_i}.ln_1.bias'] = loaded[f"backbone.blocks.{layer_i}.layernorm1.beta"]
38
+ new_sd[f'transformer.h.{layer_i}.ln_2.weight'] = loaded[f"backbone.blocks.{layer_i}.layernorm2.gamma"]
39
+ new_sd[f'transformer.h.{layer_i}.ln_2.bias'] = loaded[f"backbone.blocks.{layer_i}.layernorm2.beta"]
40
+
41
+ q_w = loaded[f"backbone.blocks.{layer_i}.attention.dense1.weight"].T
42
+ k_w = loaded[f"backbone.blocks.{layer_i}.attention.dense2.weight"].T
43
+ v_w = loaded[f"backbone.blocks.{layer_i}.attention.dense3.weight"].T
44
+ # todo check
45
+ new_sd[f'transformer.h.{layer_i}.attn.c_attn.weight'] = torch.cat((q_w, k_w, v_w), dim=-1)
46
+
47
+ q_b = loaded[f"backbone.blocks.{layer_i}.attention.dense1.bias"]
48
+ k_b = loaded[f"backbone.blocks.{layer_i}.attention.dense2.bias"]
49
+ v_b = loaded[f"backbone.blocks.{layer_i}.attention.dense3.bias"]
50
+ # todo check
51
+ new_sd[f'transformer.h.{layer_i}.attn.c_attn.bias'] = torch.cat((q_b, k_b, v_b), dim=-1)
52
+
53
+ # todo check
54
+ new_sd[f'transformer.h.{layer_i}.attn.c_proj.weight'] = loaded[f"backbone.blocks.{layer_i}.attention.projection.weight"]
55
+ new_sd[f'transformer.h.{layer_i}.attn.c_proj.bias'] = loaded[f"backbone.blocks.{layer_i}.attention.projection.bias"]
56
+
57
+
58
+ new_sd[f'transformer.h.{layer_i}.mlp.c_fc.weight'] = loaded[f"backbone.blocks.{layer_i}.output.mapping.weight"]
59
+ new_sd[f'transformer.h.{layer_i}.mlp.c_fc.bias'] = loaded[f"backbone.blocks.{layer_i}.output.mapping.bias"]
60
+
61
+
62
+ new_sd[f'transformer.h.{layer_i}.mlp.c_proj.weight'] = loaded[f"backbone.blocks.{layer_i}.output.projection.weight"]
63
+ new_sd[f'transformer.h.{layer_i}.mlp.c_proj.bias'] = loaded[f"backbone.blocks.{layer_i}.output.projection.bias"]
64
+
65
+ new_sd[f'transformer.ln_f.weight'] = loaded["backbone.layernorm.gamma"]
66
+ new_sd[f'transformer.ln_f.bias'] = loaded["backbone.layernorm.beta"]
67
+
68
+ new_sd[f'transformer.wte.weight'] = loaded["backbone.embedding.word_embedding.embedding_table"]
69
+ new_sd[f'lm_head.weight'] = loaded["backbone.embedding.word_embedding.embedding_table"]
70
+
71
+
72
+ torch.save(new_sd, torch_path)
modeling_mind.py ADDED
@@ -0,0 +1,1774 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import math
18
+ import os
19
+ import warnings
20
+ from dataclasses import dataclass
21
+ from typing import Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.utils.checkpoint
25
+ from torch import nn, Tensor
26
+ from torch.cuda.amp import autocast
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.modeling_outputs import (
31
+ BaseModelOutputWithPastAndCrossAttentions,
32
+ CausalLMOutputWithCrossAttentions,
33
+ QuestionAnsweringModelOutput,
34
+ SequenceClassifierOutputWithPast,
35
+ TokenClassifierOutput,
36
+ )
37
+ from transformers.modeling_utils import PreTrainedModel, SequenceSummary
38
+ from transformers.pytorch_utils import Conv1D, find_pruneable_heads_and_indices, prune_conv1d_layer
39
+ from transformers.utils import (
40
+ ModelOutput,
41
+ add_code_sample_docstrings,
42
+ add_start_docstrings,
43
+ add_start_docstrings_to_model_forward,
44
+ logging,
45
+ replace_return_docstrings,
46
+ )
47
+ from transformers.utils.model_parallel_utils import assert_device_map, get_device_map
48
+ from .configuration_Mind import MindConfig
49
+
50
+
51
+ logger = logging.get_logger(__name__)
52
+
53
+ _CHECKPOINT_FOR_DOC = "Mind"
54
+ _CONFIG_FOR_DOC = "MindConfig"
55
+
56
+ Mind_PRETRAINED_MODEL_ARCHIVE_LIST = [
57
+ "Mind",
58
+ ]
59
+
60
+
61
+
62
+ class LlamaRotaryEmbedding(torch.nn.Module):
63
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
64
+ super().__init__()
65
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
66
+ self.register_buffer("inv_freq", inv_freq)
67
+
68
+ # Build here to make `torch.jit.trace` work.
69
+ self.max_seq_len_cached = max_position_embeddings
70
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
71
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
72
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
73
+ emb = torch.cat((freqs, freqs), dim=-1)
74
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
75
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
76
+
77
+ def forward(self, x, seq_len=None):
78
+ # x: [bs, num_attention_heads, seq_len, head_size]
79
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
80
+ if seq_len > self.max_seq_len_cached:
81
+ self.max_seq_len_cached = seq_len
82
+ t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
83
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
84
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
85
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
86
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
87
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
88
+ return (
89
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
90
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
91
+ )
92
+
93
+ def rotate_half(x):
94
+ """Rotates half the hidden dims of the input."""
95
+ x1 = x[..., : x.shape[-1] // 2]
96
+ x2 = x[..., x.shape[-1] // 2 :]
97
+ return torch.cat((-x2, x1), dim=-1).view(*x.shape)
98
+
99
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
100
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
101
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
102
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
103
+ cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
104
+ sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
105
+ q_embed = (q * cos) + (rotate_half(q) * sin)
106
+ k_embed = (k * cos) + (rotate_half(k) * sin)
107
+ return q_embed, k_embed
108
+
109
+ def load_tf_weights_in_Mind(model, config, Mind_checkpoint_path):
110
+ """Load tf checkpoints in a pytorch model"""
111
+ try:
112
+ import re
113
+
114
+ import tensorflow as tf
115
+ except ImportError:
116
+ logger.error(
117
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
118
+ "https://www.tensorflow.org/install/ for installation instructions."
119
+ )
120
+ raise
121
+ tf_path = os.path.abspath(Mind_checkpoint_path)
122
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
123
+ # Load weights from TF model
124
+ init_vars = tf.train.list_variables(tf_path)
125
+ names = []
126
+ arrays = []
127
+ for name, shape in init_vars:
128
+ logger.info(f"Loading TF weight {name} with shape {shape}")
129
+ array = tf.train.load_variable(tf_path, name)
130
+ names.append(name)
131
+ arrays.append(array.squeeze())
132
+
133
+ for name, array in zip(names, arrays):
134
+ name = name[6:] # skip "model/"
135
+ name = name.split("/")
136
+ pointer = model
137
+ for m_name in name:
138
+ if re.fullmatch(r"[A-Za-z]+\d+", m_name):
139
+ scope_names = re.split(r"(\d+)", m_name)
140
+ else:
141
+ scope_names = [m_name]
142
+ if scope_names[0] == "w" or scope_names[0] == "g":
143
+ pointer = getattr(pointer, "weight")
144
+ elif scope_names[0] == "b":
145
+ pointer = getattr(pointer, "bias")
146
+ elif scope_names[0] == "wpe" or scope_names[0] == "wte":
147
+ pointer = getattr(pointer, scope_names[0])
148
+ pointer = getattr(pointer, "weight")
149
+ else:
150
+ pointer = getattr(pointer, scope_names[0])
151
+ if len(scope_names) >= 2:
152
+ num = int(scope_names[1])
153
+ pointer = pointer[num]
154
+ try:
155
+ assert (
156
+ pointer.shape == array.shape
157
+ ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
158
+ except AssertionError as e:
159
+ e.args += (pointer.shape, array.shape)
160
+ raise
161
+ logger.info(f"Initialize PyTorch weight {name}")
162
+ pointer.data = torch.from_numpy(array)
163
+ return model
164
+
165
+
166
+ class MindAttention(nn.Module):
167
+ def __init__(self, config, is_cross_attention=False, layer_idx=None):
168
+ super().__init__()
169
+
170
+ max_positions = config.max_position_embeddings
171
+ self.register_buffer(
172
+ "bias",
173
+ torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)).view(
174
+ 1, 1, max_positions, max_positions
175
+ ),
176
+ persistent=False,
177
+ )
178
+ self.register_buffer("masked_bias", torch.tensor(-1e4), persistent=False)
179
+
180
+ self.embed_dim = config.hidden_size
181
+ self.num_heads = config.num_attention_heads
182
+ self.head_dim = self.embed_dim // self.num_heads
183
+ self.split_size = self.embed_dim
184
+ if self.head_dim * self.num_heads != self.embed_dim:
185
+ raise ValueError(
186
+ f"`embed_dim` must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
187
+ f" {self.num_heads})."
188
+ )
189
+
190
+ self.scale_attn_weights = config.scale_attn_weights
191
+ self.is_cross_attention = is_cross_attention
192
+
193
+ # Layer-wise attention scaling, reordering, and upcasting
194
+ self.scale_attn_by_inverse_layer_idx = config.scale_attn_by_inverse_layer_idx
195
+ self.layer_idx = layer_idx
196
+ self.reorder_and_upcast_attn = config.reorder_and_upcast_attn
197
+
198
+ if self.is_cross_attention:
199
+ self.c_attn = Conv1D(2 * self.embed_dim, self.embed_dim)
200
+ self.q_attn = Conv1D(self.embed_dim, self.embed_dim)
201
+ else:
202
+ self.c_attn = Conv1D(3 * self.embed_dim, self.embed_dim)
203
+ self.c_proj = Conv1D(self.embed_dim, self.embed_dim)
204
+
205
+ self.attn_dropout = nn.Dropout(config.attn_pdrop)
206
+ self.resid_dropout = nn.Dropout(config.resid_pdrop)
207
+
208
+ self.pruned_heads = set()
209
+
210
+
211
+ self.rotary_emb = LlamaRotaryEmbedding(self.head_dim, max_position_embeddings=config.max_position_embeddings)
212
+
213
+ def prune_heads(self, heads):
214
+ if len(heads) == 0:
215
+ return
216
+ heads, index = find_pruneable_heads_and_indices(heads, self.num_heads, self.head_dim, self.pruned_heads)
217
+ index_attn = torch.cat([index, index + self.split_size, index + (2 * self.split_size)])
218
+
219
+ # Prune conv1d layers
220
+ self.c_attn = prune_conv1d_layer(self.c_attn, index_attn, dim=1)
221
+ self.c_proj = prune_conv1d_layer(self.c_proj, index, dim=0)
222
+
223
+ # Update hyper params
224
+ self.split_size = (self.split_size // self.num_heads) * (self.num_heads - len(heads))
225
+ self.num_heads = self.num_heads - len(heads)
226
+ self.pruned_heads = self.pruned_heads.union(heads)
227
+
228
+ def _attn(self, query, key, value, attention_mask=None, head_mask=None):
229
+ attn_weights = torch.matmul(query, key.transpose(-1, -2))
230
+
231
+ if self.scale_attn_weights:
232
+ attn_weights = attn_weights / torch.full(
233
+ [], value.size(-1) ** 0.5, dtype=attn_weights.dtype, device=attn_weights.device
234
+ )
235
+
236
+ # Layer-wise attention scaling
237
+ if self.scale_attn_by_inverse_layer_idx:
238
+ attn_weights = attn_weights / float(self.layer_idx + 1)
239
+
240
+ if not self.is_cross_attention:
241
+ # if only "normal" attention layer implements causal mask
242
+ query_length, key_length = query.size(-2), key.size(-2)
243
+ causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length]
244
+ mask_value = torch.finfo(attn_weights.dtype).min
245
+ # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
246
+ # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
247
+ mask_value = torch.full([], mask_value, dtype=attn_weights.dtype).to(attn_weights.device)
248
+ attn_weights = torch.where(causal_mask, attn_weights.to(attn_weights.dtype), mask_value)
249
+
250
+ if attention_mask is not None:
251
+ # Apply the attention mask
252
+ attn_weights = attn_weights + attention_mask
253
+
254
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
255
+
256
+ # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op otherwise
257
+ attn_weights = attn_weights.type(value.dtype)
258
+ attn_weights = self.attn_dropout(attn_weights)
259
+
260
+ # Mask heads if we want to
261
+ if head_mask is not None:
262
+ attn_weights = attn_weights * head_mask
263
+
264
+ attn_output = torch.matmul(attn_weights, value)
265
+
266
+ return attn_output, attn_weights
267
+
268
+ def _upcast_and_reordered_attn(self, query, key, value, attention_mask=None, head_mask=None):
269
+ # Use `torch.baddbmm` (a bit more efficient w/ alpha param for scaling -- from Megatron-LM)
270
+ bsz, num_heads, q_seq_len, dk = query.size()
271
+ _, _, k_seq_len, _ = key.size()
272
+
273
+ # Preallocate attn_weights for `baddbmm`
274
+ attn_weights = torch.empty(bsz * num_heads, q_seq_len, k_seq_len, dtype=torch.float32, device=query.device)
275
+
276
+ # Compute Scale Factor
277
+ scale_factor = 1.0
278
+ if self.scale_attn_weights:
279
+ scale_factor /= float(value.size(-1)) ** 0.5
280
+
281
+ if self.scale_attn_by_inverse_layer_idx:
282
+ scale_factor /= float(self.layer_idx + 1)
283
+
284
+ # Upcast (turn off autocast) and reorder (Scale K by 1 / root(dk))
285
+ with autocast(enabled=False):
286
+ q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(-1, dk, k_seq_len)
287
+ attn_weights = torch.baddbmm(attn_weights, q.float(), k.float(), beta=0, alpha=scale_factor)
288
+ attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len)
289
+
290
+ if not self.is_cross_attention:
291
+ # if only "normal" attention layer implements causal mask
292
+ query_length, key_length = query.size(-2), key.size(-2)
293
+ causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length]
294
+ mask_value = torch.finfo(attn_weights.dtype).min
295
+ # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
296
+ # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
297
+ mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype).to(attn_weights.device)
298
+ attn_weights = torch.where(causal_mask, attn_weights, mask_value)
299
+
300
+ if attention_mask is not None:
301
+ # Apply the attention mask
302
+ attn_weights = attn_weights + attention_mask
303
+
304
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
305
+
306
+ # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op if otherwise
307
+ if attn_weights.dtype != torch.float32:
308
+ raise RuntimeError("Error with upcasting, attn_weights does not have dtype torch.float32")
309
+ attn_weights = attn_weights.type(value.dtype)
310
+ attn_weights = self.attn_dropout(attn_weights)
311
+
312
+ # Mask heads if we want to
313
+ if head_mask is not None:
314
+ attn_weights = attn_weights * head_mask
315
+
316
+ attn_output = torch.matmul(attn_weights, value)
317
+
318
+ return attn_output, attn_weights
319
+
320
+ def _split_heads(self, tensor, num_heads, attn_head_size):
321
+ """
322
+ Splits hidden_size dim into attn_head_size and num_heads
323
+ """
324
+ new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
325
+ tensor = tensor.view(new_shape)
326
+ return tensor.permute(0, 2, 1, 3) # (batch, head, seq_length, head_features)
327
+
328
+ def _merge_heads(self, tensor, num_heads, attn_head_size):
329
+ """
330
+ Merges attn_head_size dim and num_attn_heads dim into hidden_size
331
+ """
332
+ tensor = tensor.permute(0, 2, 1, 3).contiguous()
333
+ new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,)
334
+ return tensor.view(new_shape)
335
+
336
+ def forward(
337
+ self,
338
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
339
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
340
+ attention_mask: Optional[torch.FloatTensor] = None,
341
+ head_mask: Optional[torch.FloatTensor] = None,
342
+ encoder_hidden_states: Optional[torch.Tensor] = None,
343
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
344
+ use_cache: Optional[bool] = False,
345
+ output_attentions: Optional[bool] = False,
346
+ position_ids: Optional[torch.LongTensor] = None,
347
+ ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]], ...]:
348
+ if encoder_hidden_states is not None:
349
+ if not hasattr(self, "q_attn"):
350
+ raise ValueError(
351
+ "If class is used as cross attention, the weights `q_attn` have to be defined. "
352
+ "Please make sure to instantiate class with `MindAttention(..., is_cross_attention=True)`."
353
+ )
354
+
355
+ query = self.q_attn(hidden_states)
356
+ key, value = self.c_attn(encoder_hidden_states).split(self.split_size, dim=2)
357
+ attention_mask = encoder_attention_mask
358
+ else:
359
+ query, key, value = self.c_attn(hidden_states).split(self.split_size, dim=2)
360
+
361
+ query = self._split_heads(query, self.num_heads, self.head_dim)
362
+ key = self._split_heads(key, self.num_heads, self.head_dim)
363
+ value = self._split_heads(value, self.num_heads, self.head_dim)
364
+
365
+ kv_seq_len = key.shape[-2]
366
+ if layer_past is not None:
367
+ kv_seq_len += layer_past[0].shape[-2]
368
+
369
+ cos, sin = self.rotary_emb(value, seq_len=kv_seq_len)
370
+ query, key = apply_rotary_pos_emb(query, key, cos, sin, position_ids)
371
+
372
+ if layer_past is not None:
373
+ past_key, past_value = layer_past
374
+ key = torch.cat((past_key, key), dim=-2)
375
+ value = torch.cat((past_value, value), dim=-2)
376
+
377
+ if use_cache is True:
378
+ present = (key, value)
379
+ else:
380
+ present = None
381
+
382
+ if self.reorder_and_upcast_attn:
383
+ attn_output, attn_weights = self._upcast_and_reordered_attn(query, key, value, attention_mask, head_mask)
384
+ else:
385
+ attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask)
386
+
387
+ attn_output = self._merge_heads(attn_output, self.num_heads, self.head_dim)
388
+ attn_output = self.c_proj(attn_output)
389
+ attn_output = self.resid_dropout(attn_output)
390
+
391
+ outputs = (attn_output, present)
392
+ if output_attentions:
393
+ outputs += (attn_weights,)
394
+
395
+ return outputs # a, present, (attentions)
396
+
397
+ @torch.jit.script
398
+ def SwGluActivation(x):
399
+ x = torch.chunk(x, 2, dim=-1)
400
+ return torch.nn.functional.silu(x[0]) * x[1]
401
+
402
+
403
+ class MsFastGELUActivation(nn.Module):
404
+ """
405
+ Applies GELU approximation from MindSpore
406
+ """
407
+
408
+ def forward(self, x: Tensor) -> Tensor:
409
+ return x / (1 + torch.exp(-1.702 * torch.abs(x))) * torch.exp(0.851 * (x - torch.abs(x)))
410
+
411
+
412
+ class MindMLP(nn.Module):
413
+ def __init__(self, intermediate_size, config):
414
+ super().__init__()
415
+ embed_dim = config.hidden_size
416
+ self.c_fc = Conv1D(intermediate_size*2, embed_dim)
417
+ self.c_proj = Conv1D(embed_dim, intermediate_size)
418
+ self.act = SwGluActivation
419
+ self.dropout = nn.Dropout(config.resid_pdrop)
420
+
421
+ def forward(self, hidden_states: Optional[Tuple[torch.FloatTensor]]) -> torch.FloatTensor:
422
+ hidden_states = self.c_fc(hidden_states)
423
+ hidden_states = self.act(hidden_states)
424
+ hidden_states = self.c_proj(hidden_states)
425
+ hidden_states = self.dropout(hidden_states)
426
+ return hidden_states
427
+
428
+
429
+ class MindBlock(nn.Module):
430
+ def __init__(self, config, layer_idx=None):
431
+ super().__init__()
432
+ hidden_size = config.hidden_size
433
+ inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
434
+
435
+ self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
436
+ self.attn = MindAttention(config, layer_idx=layer_idx)
437
+ self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
438
+
439
+ if config.add_cross_attention:
440
+ self.crossattention = MindAttention(config, is_cross_attention=True, layer_idx=layer_idx)
441
+ self.ln_cross_attn = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
442
+
443
+ self.mlp = MindMLP(inner_dim, config)
444
+
445
+ def forward(
446
+ self,
447
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
448
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
449
+ attention_mask: Optional[torch.FloatTensor] = None,
450
+ head_mask: Optional[torch.FloatTensor] = None,
451
+ encoder_hidden_states: Optional[torch.Tensor] = None,
452
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
453
+ use_cache: Optional[bool] = False,
454
+ output_attentions: Optional[bool] = False,
455
+ position_ids: Optional[torch.LongTensor] = None,
456
+ ) -> Union[Tuple[torch.Tensor], Optional[Tuple[torch.Tensor, Tuple[torch.FloatTensor, ...]]]]:
457
+ residual = hidden_states
458
+ hidden_states = self.ln_1(hidden_states)
459
+ attn_outputs = self.attn(
460
+ hidden_states,
461
+ layer_past=layer_past,
462
+ attention_mask=attention_mask,
463
+ head_mask=head_mask,
464
+ use_cache=use_cache,
465
+ output_attentions=output_attentions,
466
+ position_ids=position_ids,
467
+ )
468
+ attn_output = attn_outputs[0] # output_attn: a, present, (attentions)
469
+ outputs = attn_outputs[1:]
470
+ # residual connection
471
+ hidden_states = attn_output + residual
472
+
473
+ if encoder_hidden_states is not None:
474
+ # add one self-attention block for cross-attention
475
+ if not hasattr(self, "crossattention"):
476
+ raise ValueError(
477
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with "
478
+ "cross-attention layers by setting `config.add_cross_attention=True`"
479
+ )
480
+ residual = hidden_states
481
+ hidden_states = self.ln_cross_attn(hidden_states)
482
+ cross_attn_outputs = self.crossattention(
483
+ hidden_states,
484
+ attention_mask=attention_mask,
485
+ head_mask=head_mask,
486
+ encoder_hidden_states=encoder_hidden_states,
487
+ encoder_attention_mask=encoder_attention_mask,
488
+ output_attentions=output_attentions,
489
+ )
490
+ attn_output = cross_attn_outputs[0]
491
+ # residual connection
492
+ hidden_states = residual + attn_output
493
+ outputs = outputs + cross_attn_outputs[2:] # add cross attentions if we output attention weights
494
+
495
+ residual = hidden_states
496
+ hidden_states = self.ln_2(hidden_states)
497
+ feed_forward_hidden_states = self.mlp(hidden_states)
498
+ # residual connection
499
+ hidden_states = residual + feed_forward_hidden_states
500
+
501
+ if use_cache:
502
+ outputs = (hidden_states,) + outputs
503
+ else:
504
+ outputs = (hidden_states,) + outputs[1:]
505
+
506
+ return outputs # hidden_states, present, (attentions, cross_attentions)
507
+
508
+
509
+ class MindPreTrainedModel(PreTrainedModel):
510
+ """
511
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
512
+ models.
513
+ """
514
+
515
+ config_class = MindConfig
516
+ load_tf_weights = load_tf_weights_in_Mind
517
+ base_model_prefix = "transformer"
518
+ is_parallelizable = True
519
+ supports_gradient_checkpointing = True
520
+ _no_split_modules = ["MindBlock"]
521
+ _skip_keys_device_placement = "past_key_values"
522
+
523
+ def __init__(self, *inputs, **kwargs):
524
+ super().__init__(*inputs, **kwargs)
525
+
526
+ def _init_weights(self, module):
527
+ """Initialize the weights."""
528
+ if isinstance(module, (nn.Linear, Conv1D)):
529
+ # Slightly different from the TF version which uses truncated_normal for initialization
530
+ # cf https://github.com/pytorch/pytorch/pull/5617
531
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
532
+ if module.bias is not None:
533
+ module.bias.data.zero_()
534
+ elif isinstance(module, nn.Embedding):
535
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
536
+ if module.padding_idx is not None:
537
+ module.weight.data[module.padding_idx].zero_()
538
+ elif isinstance(module, nn.LayerNorm):
539
+ module.bias.data.zero_()
540
+ module.weight.data.fill_(1.0)
541
+
542
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
543
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
544
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
545
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
546
+ #
547
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
548
+ for name, p in module.named_parameters():
549
+ if name == "c_proj.weight":
550
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
551
+ p.data.normal_(mean=0.0, std=(self.config.initializer_range / math.sqrt(2 * self.config.n_layer)))
552
+
553
+ def _set_gradient_checkpointing(self, module, value=False):
554
+ if isinstance(module, MindModel):
555
+ module.gradient_checkpointing = value
556
+
557
+
558
+ @dataclass
559
+ class MindDoubleHeadsModelOutput(ModelOutput):
560
+ """
561
+ Base class for outputs of models predicting if two sentences are consecutive or not.
562
+
563
+ Args:
564
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
565
+ Language modeling loss.
566
+ mc_loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `mc_labels` is provided):
567
+ Multiple choice classification loss.
568
+ logits (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, config.vocab_size)`):
569
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
570
+ mc_logits (`torch.FloatTensor` of shape `(batch_size, num_choices)`):
571
+ Prediction scores of the multiple choice classification head (scores for each choice before SoftMax).
572
+ past_key_values (`Tuple[Tuple[torch.Tensor]]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
573
+ Tuple of length `config.n_layers`, containing tuples of tensors of shape `(batch_size, num_heads,
574
+ sequence_length, embed_size_per_head)`).
575
+
576
+ Contains pre-computed hidden-states (key and values in the attention blocks) that can be used (see
577
+ `past_key_values` input) to speed up sequential decoding.
578
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
579
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
580
+ shape `(batch_size, sequence_length, hidden_size)`.
581
+
582
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
583
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
584
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
585
+ sequence_length)`.
586
+
587
+ MindAttentions weights after the attention softmax, used to compute the weighted average in the
588
+ self-attention heads.
589
+ """
590
+
591
+ loss: Optional[torch.FloatTensor] = None
592
+ mc_loss: Optional[torch.FloatTensor] = None
593
+ logits: torch.FloatTensor = None
594
+ mc_logits: torch.FloatTensor = None
595
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
596
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
597
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
598
+
599
+
600
+ Mind_START_DOCSTRING = r"""
601
+
602
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
603
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
604
+ etc.)
605
+
606
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
607
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
608
+ and behavior.
609
+
610
+ Parameters:
611
+ config ([`MindConfig`]): Model configuration class with all the parameters of the model.
612
+ Initializing with a config file does not load the weights associated with the model, only the
613
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
614
+ """
615
+
616
+ Mind_INPUTS_DOCSTRING = r"""
617
+ Args:
618
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
619
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
620
+ `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
621
+ sequence tokens in the vocabulary.
622
+
623
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
624
+ `input_ids`.
625
+
626
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
627
+ [`PreTrainedTokenizer.__call__`] for details.
628
+
629
+ [What are input IDs?](../glossary#input-ids)
630
+ past_key_values (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`):
631
+ Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
632
+ `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
633
+ their past given to this model should not be passed as `input_ids` as they have already been computed.
634
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
635
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
636
+
637
+ - 1 for tokens that are **not masked**,
638
+ - 0 for tokens that are **masked**.
639
+
640
+ If `past_key_values` is used, `attention_mask` needs to contain the masking strategy that was used for
641
+ `past_key_values`. In other words, the `attention_mask` always has to have the length:
642
+ `len(past_key_values) + len(input_ids)`
643
+
644
+ [What are attention masks?](../glossary#attention-mask)
645
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`, *optional*):
646
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
647
+ 1]`:
648
+
649
+ - 0 corresponds to a *sentence A* token,
650
+ - 1 corresponds to a *sentence B* token.
651
+
652
+ [What are token type IDs?](../glossary#token-type-ids)
653
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
654
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
655
+ config.max_position_embeddings - 1]`.
656
+
657
+ [What are position IDs?](../glossary#position-ids)
658
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
659
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
660
+
661
+ - 1 indicates the head is **not masked**,
662
+ - 0 indicates the head is **masked**.
663
+
664
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
665
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
666
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
667
+ model's internal embedding lookup matrix.
668
+
669
+ If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
670
+ `past_key_values`).
671
+ use_cache (`bool`, *optional*):
672
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
673
+ `past_key_values`).
674
+ output_attentions (`bool`, *optional*):
675
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
676
+ tensors for more detail.
677
+ output_hidden_states (`bool`, *optional*):
678
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
679
+ more detail.
680
+ return_dict (`bool`, *optional*):
681
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
682
+ """
683
+ PARALLELIZE_DOCSTRING = r"""
684
+ This is an experimental feature and is a subject to change at a moment's notice.
685
+
686
+ Uses a device map to distribute attention modules of the model across several devices. If no device map is given,
687
+ it will evenly distribute blocks across all devices.
688
+
689
+ Args:
690
+ device_map (`Dict[int, list]`, optional, defaults to None):
691
+ A dictionary that maps attention modules to devices. Note that the embedding module and LMHead are always
692
+ automatically mapped to the first device (for esoteric reasons). That means that the first device should
693
+ have fewer attention modules mapped to it than other devices. For reference, the Mind models have the
694
+ following number of attention modules:
695
+
696
+ - Mind: 12
697
+ - Mind-medium: 24
698
+ - Mind-large: 36
699
+ - Mind-xl: 48
700
+
701
+ Example:
702
+
703
+ ```python
704
+ # Here is an example of a device map on a machine with 4 GPUs using Mind-xl, which has a total of 48 attention modules:
705
+ model = MindLMHeadModel.from_pretrained("Mind-xl")
706
+ device_map = {
707
+ 0: [0, 1, 2, 3, 4, 5, 6, 7, 8],
708
+ 1: [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
709
+ 2: [22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34],
710
+ 3: [35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47],
711
+ }
712
+ model.parallelize(device_map)
713
+ ```
714
+ """
715
+ DEPARALLELIZE_DOCSTRING = r"""
716
+ Moves the model to cpu from a model parallel state.
717
+
718
+ Example:
719
+
720
+ ```python
721
+ # On a 4 GPU machine with Mind-large:
722
+ model = MindLMHeadModel.from_pretrained("Mind-large")
723
+ device_map = {
724
+ 0: [0, 1, 2, 3, 4, 5, 6, 7],
725
+ 1: [8, 9, 10, 11, 12, 13, 14, 15],
726
+ 2: [16, 17, 18, 19, 20, 21, 22, 23],
727
+ 3: [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35],
728
+ }
729
+ model.parallelize(device_map) # Splits the model across several devices
730
+ model.deparallelize() # Put the model back on cpu and cleans memory by calling torch.cuda.empty_cache()
731
+ ```
732
+ """
733
+
734
+
735
+ @add_start_docstrings(
736
+ "The bare Mind Model transformer outputting raw hidden-states without any specific head on top.",
737
+ Mind_START_DOCSTRING,
738
+ )
739
+ class MindModel(MindPreTrainedModel):
740
+ # _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"]
741
+ # _keys_to_ignore_on_load_missing = [r"attn.masked_bias", r"h\.\d+\.attn\.masked_bias", r"h\.\d+\.attn\.bias"]
742
+
743
+ def __init__(self, config):
744
+ super().__init__(config)
745
+
746
+ self.embed_dim = config.hidden_size
747
+
748
+ self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
749
+ # self.wpe = nn.Embedding(config.max_position_embeddings, self.embed_dim)
750
+
751
+ self.drop = nn.Dropout(config.embd_pdrop)
752
+ self.h = nn.ModuleList([MindBlock(config, layer_idx=i) for i in range(config.num_hidden_layers)])
753
+ self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
754
+
755
+ # Model parallel
756
+ self.model_parallel = False
757
+ self.device_map = None
758
+ self.gradient_checkpointing = False
759
+
760
+ # Initialize weights and apply final processing
761
+ self.post_init()
762
+
763
+ @add_start_docstrings(PARALLELIZE_DOCSTRING)
764
+ def parallelize(self, device_map=None):
765
+ # Check validity of device_map
766
+ warnings.warn(
767
+ "`MindModel.parallelize` is deprecated and will be removed in v5 of Transformers, you should load your"
768
+ " model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your own"
769
+ " `device_map` but it needs to be a dictionary module_name to device, so for instance {'h.0': 0, 'h.1': 1,"
770
+ " ...}",
771
+ FutureWarning,
772
+ )
773
+ self.device_map = (
774
+ get_device_map(len(self.h), range(torch.cuda.device_count())) if device_map is None else device_map
775
+ )
776
+ assert_device_map(self.device_map, len(self.h))
777
+ self.model_parallel = True
778
+ self.first_device = "cpu" if "cpu" in self.device_map.keys() else "cuda:" + str(min(self.device_map.keys()))
779
+ self.last_device = "cuda:" + str(max(self.device_map.keys()))
780
+ self.wte = self.wte.to(self.first_device)
781
+ # self.wpe = self.wpe.to(self.first_device)
782
+ # Load onto devices
783
+ for k, v in self.device_map.items():
784
+ for block in v:
785
+ cuda_device = "cuda:" + str(k)
786
+ self.h[block] = self.h[block].to(cuda_device)
787
+ # ln_f to last
788
+ self.ln_f = self.ln_f.to(self.last_device)
789
+
790
+ @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
791
+ def deparallelize(self):
792
+ warnings.warn(
793
+ "Like `parallelize`, `deparallelize` is deprecated and will be removed in v5 of Transformers.",
794
+ FutureWarning,
795
+ )
796
+ self.model_parallel = False
797
+ self.device_map = None
798
+ self.first_device = "cpu"
799
+ self.last_device = "cpu"
800
+ self.wte = self.wte.to("cpu")
801
+ # self.wpe = self.wpe.to("cpu")
802
+ for index in range(len(self.h)):
803
+ self.h[index] = self.h[index].to("cpu")
804
+ self.ln_f = self.ln_f.to("cpu")
805
+ torch.cuda.empty_cache()
806
+
807
+ def get_input_embeddings(self):
808
+ return self.wte
809
+
810
+ def set_input_embeddings(self, new_embeddings):
811
+ self.wte = new_embeddings
812
+
813
+ def _prune_heads(self, heads_to_prune):
814
+ """
815
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
816
+ """
817
+ for layer, heads in heads_to_prune.items():
818
+ self.h[layer].attn.prune_heads(heads)
819
+
820
+ @add_start_docstrings_to_model_forward(Mind_INPUTS_DOCSTRING)
821
+ @add_code_sample_docstrings(
822
+ checkpoint=_CHECKPOINT_FOR_DOC,
823
+ output_type=BaseModelOutputWithPastAndCrossAttentions,
824
+ config_class=_CONFIG_FOR_DOC,
825
+ )
826
+ def forward(
827
+ self,
828
+ input_ids: Optional[torch.LongTensor] = None,
829
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
830
+ attention_mask: Optional[torch.FloatTensor] = None,
831
+ token_type_ids: Optional[torch.LongTensor] = None,
832
+ position_ids: Optional[torch.LongTensor] = None,
833
+ head_mask: Optional[torch.FloatTensor] = None,
834
+ inputs_embeds: Optional[torch.FloatTensor] = None,
835
+ encoder_hidden_states: Optional[torch.Tensor] = None,
836
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
837
+ use_cache: Optional[bool] = None,
838
+ output_attentions: Optional[bool] = None,
839
+ output_hidden_states: Optional[bool] = None,
840
+ return_dict: Optional[bool] = None,
841
+ ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
842
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
843
+ output_hidden_states = (
844
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
845
+ )
846
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
847
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
848
+
849
+ if input_ids is not None and inputs_embeds is not None:
850
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
851
+ elif input_ids is not None:
852
+ input_shape = input_ids.size()
853
+ input_ids = input_ids.view(-1, input_shape[-1])
854
+ batch_size = input_ids.shape[0]
855
+ elif inputs_embeds is not None:
856
+ input_shape = inputs_embeds.size()[:-1]
857
+ batch_size = inputs_embeds.shape[0]
858
+ else:
859
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
860
+
861
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
862
+
863
+ if token_type_ids is not None:
864
+ token_type_ids = token_type_ids.view(-1, input_shape[-1])
865
+ if position_ids is not None:
866
+ position_ids = position_ids.view(-1, input_shape[-1])
867
+
868
+ if past_key_values is None:
869
+ past_length = 0
870
+ past_key_values = tuple([None] * len(self.h))
871
+ else:
872
+ past_length = past_key_values[0][0].size(-2)
873
+ if position_ids is None:
874
+ position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
875
+ position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
876
+
877
+ # MindAttention mask.
878
+ if attention_mask is not None:
879
+ if batch_size <= 0:
880
+ raise ValueError("batch_size has to be defined and > 0")
881
+ attention_mask = attention_mask.view(batch_size, -1)
882
+ # We create a 3D attention mask from a 2D tensor mask.
883
+ # Sizes are [batch_size, 1, 1, to_seq_length]
884
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
885
+ # this attention mask is more simple than the triangular masking of causal attention
886
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
887
+ attention_mask = attention_mask[:, None, None, :]
888
+
889
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
890
+ # masked positions, this operation will create a tensor which is 0.0 for
891
+ # positions we want to attend and the dtype's smallest value for masked positions.
892
+ # Since we are adding it to the raw scores before the softmax, this is
893
+ # effectively the same as removing these entirely.
894
+ attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
895
+ attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
896
+
897
+ # If a 2D or 3D attention mask is provided for the cross-attention
898
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
899
+ if self.config.add_cross_attention and encoder_hidden_states is not None:
900
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
901
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
902
+ if encoder_attention_mask is None:
903
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
904
+ encoder_attention_mask = self.invert_attention_mask(encoder_attention_mask)
905
+ else:
906
+ encoder_attention_mask = None
907
+
908
+ # Prepare head mask if needed
909
+ # 1.0 in head_mask indicate we keep the head
910
+ # attention_probs has shape bsz x n_heads x N x N
911
+ # head_mask has shape n_layer x batch x n_heads x N x N
912
+ head_mask = self.get_head_mask(head_mask, self.config.n_layer)
913
+
914
+ if inputs_embeds is None:
915
+ inputs_embeds = self.wte(input_ids)
916
+ # position_embeds = self.wpe(position_ids)
917
+ # hidden_states = inputs_embeds + position_embeds
918
+ hidden_states = inputs_embeds
919
+
920
+ if token_type_ids is not None:
921
+ token_type_embeds = self.wte(token_type_ids)
922
+ hidden_states = hidden_states + token_type_embeds
923
+
924
+ hidden_states = self.drop(hidden_states)
925
+
926
+ output_shape = input_shape + (hidden_states.size(-1),)
927
+
928
+ if self.gradient_checkpointing and self.training:
929
+ if use_cache:
930
+ logger.warning_once(
931
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
932
+ )
933
+ use_cache = False
934
+
935
+ presents = () if use_cache else None
936
+ all_self_attentions = () if output_attentions else None
937
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
938
+ all_hidden_states = () if output_hidden_states else None
939
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
940
+ # Model parallel
941
+ if self.model_parallel:
942
+ torch.cuda.set_device(hidden_states.device)
943
+ # Ensure layer_past is on same device as hidden_states (might not be correct)
944
+ if layer_past is not None:
945
+ layer_past = tuple(past_state.to(hidden_states.device) for past_state in layer_past)
946
+ # Ensure that attention_mask is always on the same device as hidden_states
947
+ if attention_mask is not None:
948
+ attention_mask = attention_mask.to(hidden_states.device)
949
+ if isinstance(head_mask, torch.Tensor):
950
+ head_mask = head_mask.to(hidden_states.device)
951
+ if output_hidden_states:
952
+ all_hidden_states = all_hidden_states + (hidden_states,)
953
+
954
+ if self.gradient_checkpointing and self.training:
955
+
956
+ def create_custom_forward(module):
957
+ def custom_forward(*inputs):
958
+ # None for past_key_value
959
+ return module(*inputs, use_cache, output_attentions)
960
+
961
+ return custom_forward
962
+
963
+ outputs = torch.utils.checkpoint.checkpoint(
964
+ create_custom_forward(block),
965
+ hidden_states,
966
+ None,
967
+ attention_mask,
968
+ head_mask[i],
969
+ encoder_hidden_states,
970
+ encoder_attention_mask,
971
+ position_ids=position_ids,
972
+ )
973
+ else:
974
+ outputs = block(
975
+ hidden_states,
976
+ layer_past=layer_past,
977
+ attention_mask=attention_mask,
978
+ head_mask=head_mask[i],
979
+ encoder_hidden_states=encoder_hidden_states,
980
+ encoder_attention_mask=encoder_attention_mask,
981
+ use_cache=use_cache,
982
+ output_attentions=output_attentions,
983
+ position_ids=position_ids,
984
+ )
985
+
986
+ hidden_states = outputs[0]
987
+ if use_cache is True:
988
+ presents = presents + (outputs[1],)
989
+
990
+ if output_attentions:
991
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
992
+ if self.config.add_cross_attention:
993
+ all_cross_attentions = all_cross_attentions + (outputs[3 if use_cache else 2],)
994
+
995
+ # Model Parallel: If it's the last layer for that device, put things on the next device
996
+ if self.model_parallel:
997
+ for k, v in self.device_map.items():
998
+ if i == v[-1] and "cuda:" + str(k) != self.last_device:
999
+ hidden_states = hidden_states.to("cuda:" + str(k + 1))
1000
+
1001
+ hidden_states = self.ln_f(hidden_states)
1002
+
1003
+ hidden_states = hidden_states.view(output_shape)
1004
+ # Add last hidden state
1005
+ if output_hidden_states:
1006
+ all_hidden_states = all_hidden_states + (hidden_states,)
1007
+
1008
+ if not return_dict:
1009
+ return tuple(
1010
+ v
1011
+ for v in [hidden_states, presents, all_hidden_states, all_self_attentions, all_cross_attentions]
1012
+ if v is not None
1013
+ )
1014
+
1015
+ return BaseModelOutputWithPastAndCrossAttentions(
1016
+ last_hidden_state=hidden_states,
1017
+ past_key_values=presents,
1018
+ hidden_states=all_hidden_states,
1019
+ attentions=all_self_attentions,
1020
+ cross_attentions=all_cross_attentions,
1021
+ )
1022
+
1023
+
1024
+ @add_start_docstrings(
1025
+ """
1026
+ The PCLMind Model transformer with a language modeling head on top (linear layer with weights tied to the input
1027
+ embeddings).
1028
+ """,
1029
+ Mind_START_DOCSTRING,
1030
+ )
1031
+ class MindLMHeadModel(MindPreTrainedModel):
1032
+ _keys_to_ignore_on_load_missing = [r"attn.rotary_emb.inv_freq"]
1033
+ # _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.masked_bias", r"h\.\d+\.attn\.bias"]
1034
+
1035
+ def __init__(self, config):
1036
+ super().__init__(config)
1037
+ self.transformer = MindModel(config)
1038
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
1039
+
1040
+ # Model parallel
1041
+ self.model_parallel = False
1042
+ self.device_map = None
1043
+
1044
+ # Initialize weights and apply final processing
1045
+ self.post_init()
1046
+
1047
+ @add_start_docstrings(PARALLELIZE_DOCSTRING)
1048
+ def parallelize(self, device_map=None):
1049
+ warnings.warn(
1050
+ "`MindLMHeadModel.parallelize` is deprecated and will be removed in v5 of Transformers, you should load"
1051
+ " your model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your own"
1052
+ " `device_map` but it needs to be a dictionary module_name to device, so for instance {'transformer.h.0':"
1053
+ " 0, 'transformer.h.1': 1, ...}",
1054
+ FutureWarning,
1055
+ )
1056
+ self.device_map = (
1057
+ get_device_map(len(self.transformer.h), range(torch.cuda.device_count()))
1058
+ if device_map is None
1059
+ else device_map
1060
+ )
1061
+ assert_device_map(self.device_map, len(self.transformer.h))
1062
+ self.transformer.parallelize(self.device_map)
1063
+ self.lm_head = self.lm_head.to(self.transformer.first_device)
1064
+ self.model_parallel = True
1065
+
1066
+ @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
1067
+ def deparallelize(self):
1068
+ warnings.warn(
1069
+ "Like `parallelize`, `deparallelize` is deprecated and will be removed in v5 of Transformers.",
1070
+ FutureWarning,
1071
+ )
1072
+ self.transformer.deparallelize()
1073
+ self.transformer = self.transformer.to("cpu")
1074
+ self.lm_head = self.lm_head.to("cpu")
1075
+ self.model_parallel = False
1076
+ torch.cuda.empty_cache()
1077
+
1078
+ def get_output_embeddings(self):
1079
+ return self.lm_head
1080
+
1081
+ def set_output_embeddings(self, new_embeddings):
1082
+ self.lm_head = new_embeddings
1083
+
1084
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
1085
+ token_type_ids = kwargs.get("token_type_ids", None)
1086
+ # only last token for inputs_ids if past is defined in kwargs
1087
+ if past_key_values:
1088
+ input_ids = input_ids[:, -1].unsqueeze(-1)
1089
+ if token_type_ids is not None:
1090
+ token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
1091
+
1092
+ attention_mask = kwargs.get("attention_mask", None)
1093
+ position_ids = kwargs.get("position_ids", None)
1094
+
1095
+ if attention_mask is not None and position_ids is None:
1096
+ # create position_ids on the fly for batch generation
1097
+ position_ids = attention_mask.long().cumsum(-1) - 1
1098
+ position_ids.masked_fill_(attention_mask == 0, 1)
1099
+ if past_key_values:
1100
+ position_ids = position_ids[:, -1].unsqueeze(-1)
1101
+ else:
1102
+ position_ids = None
1103
+
1104
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1105
+ if inputs_embeds is not None and past_key_values is None:
1106
+ model_inputs = {"inputs_embeds": inputs_embeds}
1107
+ else:
1108
+ model_inputs = {"input_ids": input_ids}
1109
+
1110
+ model_inputs.update(
1111
+ {
1112
+ "past_key_values": past_key_values,
1113
+ "use_cache": kwargs.get("use_cache"),
1114
+ "position_ids": position_ids,
1115
+ "attention_mask": attention_mask,
1116
+ "token_type_ids": token_type_ids,
1117
+ }
1118
+ )
1119
+ return model_inputs
1120
+
1121
+ @add_start_docstrings_to_model_forward(Mind_INPUTS_DOCSTRING)
1122
+ @add_code_sample_docstrings(
1123
+ checkpoint=_CHECKPOINT_FOR_DOC,
1124
+ output_type=CausalLMOutputWithCrossAttentions,
1125
+ config_class=_CONFIG_FOR_DOC,
1126
+ )
1127
+ def forward(
1128
+ self,
1129
+ input_ids: Optional[torch.LongTensor] = None,
1130
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1131
+ attention_mask: Optional[torch.FloatTensor] = None,
1132
+ token_type_ids: Optional[torch.LongTensor] = None,
1133
+ position_ids: Optional[torch.LongTensor] = None,
1134
+ head_mask: Optional[torch.FloatTensor] = None,
1135
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1136
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1137
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
1138
+ labels: Optional[torch.LongTensor] = None,
1139
+ use_cache: Optional[bool] = None,
1140
+ output_attentions: Optional[bool] = None,
1141
+ output_hidden_states: Optional[bool] = None,
1142
+ return_dict: Optional[bool] = None,
1143
+ ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
1144
+ r"""
1145
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1146
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1147
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
1148
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
1149
+ """
1150
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1151
+
1152
+ transformer_outputs = self.transformer(
1153
+ input_ids,
1154
+ past_key_values=past_key_values,
1155
+ attention_mask=attention_mask,
1156
+ token_type_ids=token_type_ids,
1157
+ position_ids=position_ids,
1158
+ head_mask=head_mask,
1159
+ inputs_embeds=inputs_embeds,
1160
+ encoder_hidden_states=encoder_hidden_states,
1161
+ encoder_attention_mask=encoder_attention_mask,
1162
+ use_cache=use_cache,
1163
+ output_attentions=output_attentions,
1164
+ output_hidden_states=output_hidden_states,
1165
+ return_dict=return_dict,
1166
+ )
1167
+ hidden_states = transformer_outputs[0]
1168
+
1169
+ # Set device for model parallelism
1170
+ if self.model_parallel:
1171
+ torch.cuda.set_device(self.transformer.first_device)
1172
+ hidden_states = hidden_states.to(self.lm_head.weight.device)
1173
+
1174
+ lm_logits = self.lm_head(hidden_states)
1175
+
1176
+ loss = None
1177
+ if labels is not None:
1178
+ # move labels to correct device to enable model parallelism
1179
+ labels = labels.to(lm_logits.device)
1180
+ # Shift so that tokens < n predict n
1181
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1182
+ shift_labels = labels[..., 1:].contiguous()
1183
+ # Flatten the tokens
1184
+ loss_fct = CrossEntropyLoss()
1185
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1186
+
1187
+ if not return_dict:
1188
+ output = (lm_logits,) + transformer_outputs[1:]
1189
+ return ((loss,) + output) if loss is not None else output
1190
+
1191
+ return CausalLMOutputWithCrossAttentions(
1192
+ loss=loss,
1193
+ logits=lm_logits,
1194
+ past_key_values=transformer_outputs.past_key_values,
1195
+ hidden_states=transformer_outputs.hidden_states,
1196
+ attentions=transformer_outputs.attentions,
1197
+ cross_attentions=transformer_outputs.cross_attentions,
1198
+ )
1199
+
1200
+ @staticmethod
1201
+ def _reorder_cache(
1202
+ past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
1203
+ ) -> Tuple[Tuple[torch.Tensor]]:
1204
+ """
1205
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1206
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1207
+ beam_idx at every generation step.
1208
+ """
1209
+ return tuple(
1210
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
1211
+ for layer_past in past_key_values
1212
+ )
1213
+
1214
+
1215
+ @add_start_docstrings(
1216
+ """
1217
+ The Mind Model transformer with a language modeling and a multiple-choice classification head on top e.g. for
1218
+ RocStories/SWAG tasks. The two heads are two linear layers. The language modeling head has its weights tied to the
1219
+ input embeddings, the classification head takes as input the input of a specified classification token index in the
1220
+ input sequence).
1221
+ """,
1222
+ Mind_START_DOCSTRING,
1223
+ )
1224
+ class MindDoubleHeadsModel(MindPreTrainedModel):
1225
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"]
1226
+ _keys_to_ignore_on_load_missing = [r"attn.masked_bias", r"attn.bias", r"lm_head.weight"]
1227
+
1228
+ def __init__(self, config):
1229
+ super().__init__(config)
1230
+ config.num_labels = 1
1231
+ self.transformer = MindModel(config)
1232
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
1233
+ self.multiple_choice_head = SequenceSummary(config)
1234
+
1235
+ # Model parallel
1236
+ self.model_parallel = False
1237
+ self.device_map = None
1238
+
1239
+ # Initialize weights and apply final processing
1240
+ self.post_init()
1241
+
1242
+ @add_start_docstrings(PARALLELIZE_DOCSTRING)
1243
+ def parallelize(self, device_map=None):
1244
+ warnings.warn(
1245
+ "`MindDoubleHeadsModel.parallelize` is deprecated and will be removed in v5 of Transformers, you should"
1246
+ " load your model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your"
1247
+ " own `device_map` but it needs to be a dictionary module_name to device, so for instance"
1248
+ " {'transformer.h.0': 0, 'transformer.h.1': 1, ...}",
1249
+ FutureWarning,
1250
+ )
1251
+ self.device_map = (
1252
+ get_device_map(len(self.transformer.h), range(torch.cuda.device_count()))
1253
+ if device_map is None
1254
+ else device_map
1255
+ )
1256
+ assert_device_map(self.device_map, len(self.transformer.h))
1257
+ self.transformer.parallelize(self.device_map)
1258
+ self.lm_head = self.lm_head.to(self.transformer.first_device)
1259
+ self.multiple_choice_head = self.multiple_choice_head.to(self.transformer.first_device)
1260
+ self.model_parallel = True
1261
+
1262
+ @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
1263
+ def deparallelize(self):
1264
+ warnings.warn(
1265
+ "Like `parallelize`, `deparallelize` is deprecated and will be removed in v5 of Transformers.",
1266
+ FutureWarning,
1267
+ )
1268
+ self.transformer.deparallelize()
1269
+ self.transformer = self.transformer.to("cpu")
1270
+ self.lm_head = self.lm_head.to("cpu")
1271
+ self.multiple_choice_head = self.multiple_choice_head.to("cpu")
1272
+ self.model_parallel = False
1273
+ torch.cuda.empty_cache()
1274
+
1275
+ def get_output_embeddings(self):
1276
+ return self.lm_head
1277
+
1278
+ def set_output_embeddings(self, new_embeddings):
1279
+ self.lm_head = new_embeddings
1280
+
1281
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **kwargs):
1282
+ token_type_ids = kwargs.get("token_type_ids", None)
1283
+ # only last token for inputs_ids if past is defined in kwargs
1284
+ if past_key_values:
1285
+ input_ids = input_ids[:, -1].unsqueeze(-1)
1286
+ if token_type_ids is not None:
1287
+ token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
1288
+
1289
+ attention_mask = kwargs.get("attention_mask", None)
1290
+ position_ids = kwargs.get("position_ids", None)
1291
+
1292
+ if attention_mask is not None and position_ids is None:
1293
+ # create position_ids on the fly for batch generation
1294
+ position_ids = attention_mask.long().cumsum(-1) - 1
1295
+ position_ids.masked_fill_(attention_mask == 0, 1)
1296
+ if past_key_values:
1297
+ position_ids = position_ids[:, -1].unsqueeze(-1)
1298
+ else:
1299
+ position_ids = None
1300
+
1301
+ return {
1302
+ "input_ids": input_ids,
1303
+ "past_key_values": past_key_values,
1304
+ "use_cache": kwargs.get("use_cache"),
1305
+ "position_ids": position_ids,
1306
+ "attention_mask": attention_mask,
1307
+ "token_type_ids": token_type_ids,
1308
+ }
1309
+
1310
+ @add_start_docstrings_to_model_forward(Mind_INPUTS_DOCSTRING)
1311
+ @replace_return_docstrings(output_type=MindDoubleHeadsModelOutput, config_class=_CONFIG_FOR_DOC)
1312
+ def forward(
1313
+ self,
1314
+ input_ids: Optional[torch.LongTensor] = None,
1315
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1316
+ attention_mask: Optional[torch.FloatTensor] = None,
1317
+ token_type_ids: Optional[torch.LongTensor] = None,
1318
+ position_ids: Optional[torch.LongTensor] = None,
1319
+ head_mask: Optional[torch.FloatTensor] = None,
1320
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1321
+ mc_token_ids: Optional[torch.LongTensor] = None,
1322
+ labels: Optional[torch.LongTensor] = None,
1323
+ mc_labels: Optional[torch.LongTensor] = None,
1324
+ use_cache: Optional[bool] = None,
1325
+ output_attentions: Optional[bool] = None,
1326
+ output_hidden_states: Optional[bool] = None,
1327
+ return_dict: Optional[bool] = None,
1328
+ **kwargs,
1329
+ ) -> Union[Tuple, MindDoubleHeadsModelOutput]:
1330
+ r"""
1331
+ mc_token_ids (`torch.LongTensor` of shape `(batch_size, num_choices)`, *optional*, default to index of the last token of the input):
1332
+ Index of the classification token in each input sequence. Selected in the range `[0, input_ids.size(-1) -
1333
+ 1]`.
1334
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1335
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1336
+ `labels = input_ids`. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`. All labels set to
1337
+ `-100` are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size - 1]`
1338
+ mc_labels (`torch.LongTensor` of shape `(batch_size)`, *optional*):
1339
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
1340
+ where *num_choices* is the size of the second dimension of the input tensors. (see *input_ids* above)
1341
+
1342
+ Return:
1343
+
1344
+ Example:
1345
+
1346
+ ```python
1347
+ >>> import torch
1348
+ >>> from transformers import AutoTokenizer, MindDoubleHeadsModel
1349
+
1350
+ >>> tokenizer = AutoTokenizer.from_pretrained("Mind")
1351
+ >>> model = MindDoubleHeadsModel.from_pretrained("Mind")
1352
+
1353
+ >>> # Add a [CLS] to the vocabulary (we should train it also!)
1354
+ >>> num_added_tokens = tokenizer.add_special_tokens({"cls_token": "[CLS]"})
1355
+ >>> # Update the model embeddings with the new vocabulary size
1356
+ >>> embedding_layer = model.resize_token_embeddings(len(tokenizer))
1357
+
1358
+ >>> choices = ["Hello, my dog is cute [CLS]", "Hello, my cat is cute [CLS]"]
1359
+ >>> encoded_choices = [tokenizer.encode(s) for s in choices]
1360
+ >>> cls_token_location = [tokens.index(tokenizer.cls_token_id) for tokens in encoded_choices]
1361
+
1362
+ >>> input_ids = torch.tensor(encoded_choices).unsqueeze(0) # Batch size: 1, number of choices: 2
1363
+ >>> mc_token_ids = torch.tensor([cls_token_location]) # Batch size: 1
1364
+
1365
+ >>> outputs = model(input_ids, mc_token_ids=mc_token_ids)
1366
+ >>> lm_logits = outputs.logits
1367
+ >>> mc_logits = outputs.mc_logits
1368
+ ```"""
1369
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1370
+
1371
+ transformer_outputs = self.transformer(
1372
+ input_ids,
1373
+ past_key_values=past_key_values,
1374
+ attention_mask=attention_mask,
1375
+ token_type_ids=token_type_ids,
1376
+ position_ids=position_ids,
1377
+ head_mask=head_mask,
1378
+ inputs_embeds=inputs_embeds,
1379
+ use_cache=use_cache,
1380
+ output_attentions=output_attentions,
1381
+ output_hidden_states=output_hidden_states,
1382
+ return_dict=return_dict,
1383
+ )
1384
+
1385
+ hidden_states = transformer_outputs[0]
1386
+
1387
+ # Set device for model parallelism
1388
+ if self.model_parallel:
1389
+ torch.cuda.set_device(self.transformer.first_device)
1390
+ hidden_states = hidden_states.to(self.lm_head.weight.device)
1391
+
1392
+ lm_logits = self.lm_head(hidden_states)
1393
+ mc_logits = self.multiple_choice_head(hidden_states, mc_token_ids).squeeze(-1)
1394
+
1395
+ mc_loss = None
1396
+ if mc_labels is not None:
1397
+ loss_fct = CrossEntropyLoss()
1398
+ mc_loss = loss_fct(mc_logits.view(-1, mc_logits.size(-1)), mc_labels.view(-1))
1399
+ lm_loss = None
1400
+ if labels is not None:
1401
+ labels = labels.to(lm_logits.device)
1402
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1403
+ shift_labels = labels[..., 1:].contiguous()
1404
+ loss_fct = CrossEntropyLoss()
1405
+ lm_loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1406
+
1407
+ if not return_dict:
1408
+ output = (lm_logits, mc_logits) + transformer_outputs[1:]
1409
+ if mc_loss is not None:
1410
+ output = (mc_loss,) + output
1411
+ return ((lm_loss,) + output) if lm_loss is not None else output
1412
+
1413
+ return MindDoubleHeadsModelOutput(
1414
+ loss=lm_loss,
1415
+ mc_loss=mc_loss,
1416
+ logits=lm_logits,
1417
+ mc_logits=mc_logits,
1418
+ past_key_values=transformer_outputs.past_key_values,
1419
+ hidden_states=transformer_outputs.hidden_states,
1420
+ attentions=transformer_outputs.attentions,
1421
+ )
1422
+
1423
+ @staticmethod
1424
+ def _reorder_cache(
1425
+ past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
1426
+ ) -> Tuple[Tuple[torch.Tensor]]:
1427
+ """
1428
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1429
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1430
+ beam_idx at every generation step.
1431
+ """
1432
+ return tuple(
1433
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
1434
+ for layer_past in past_key_values
1435
+ )
1436
+
1437
+
1438
+ @add_start_docstrings(
1439
+ """
1440
+ The Mind Model transformer with a sequence classification head on top (linear layer).
1441
+
1442
+ [`MindForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1443
+ (e.g. GPT-1) do.
1444
+
1445
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1446
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1447
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1448
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1449
+ each row of the batch).
1450
+ """,
1451
+ Mind_START_DOCSTRING,
1452
+ )
1453
+ class MindForSequenceClassification(MindPreTrainedModel):
1454
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"]
1455
+ _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.masked_bias", r"lm_head.weight"]
1456
+
1457
+ def __init__(self, config):
1458
+ super().__init__(config)
1459
+ self.num_labels = config.num_labels
1460
+ self.transformer = MindModel(config)
1461
+ self.score = nn.Linear(config.n_embd, self.num_labels, bias=False)
1462
+
1463
+ # Model parallel
1464
+ self.model_parallel = False
1465
+ self.device_map = None
1466
+
1467
+ # Initialize weights and apply final processing
1468
+ self.post_init()
1469
+
1470
+ @add_start_docstrings_to_model_forward(Mind_INPUTS_DOCSTRING)
1471
+ @add_code_sample_docstrings(
1472
+ checkpoint="microsoft/DialogRPT-updown",
1473
+ output_type=SequenceClassifierOutputWithPast,
1474
+ config_class=_CONFIG_FOR_DOC,
1475
+ )
1476
+ def forward(
1477
+ self,
1478
+ input_ids: Optional[torch.LongTensor] = None,
1479
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1480
+ attention_mask: Optional[torch.FloatTensor] = None,
1481
+ token_type_ids: Optional[torch.LongTensor] = None,
1482
+ position_ids: Optional[torch.LongTensor] = None,
1483
+ head_mask: Optional[torch.FloatTensor] = None,
1484
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1485
+ labels: Optional[torch.LongTensor] = None,
1486
+ use_cache: Optional[bool] = None,
1487
+ output_attentions: Optional[bool] = None,
1488
+ output_hidden_states: Optional[bool] = None,
1489
+ return_dict: Optional[bool] = None,
1490
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1491
+ r"""
1492
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1493
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1494
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1495
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1496
+ """
1497
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1498
+
1499
+ transformer_outputs = self.transformer(
1500
+ input_ids,
1501
+ past_key_values=past_key_values,
1502
+ attention_mask=attention_mask,
1503
+ token_type_ids=token_type_ids,
1504
+ position_ids=position_ids,
1505
+ head_mask=head_mask,
1506
+ inputs_embeds=inputs_embeds,
1507
+ use_cache=use_cache,
1508
+ output_attentions=output_attentions,
1509
+ output_hidden_states=output_hidden_states,
1510
+ return_dict=return_dict,
1511
+ )
1512
+ hidden_states = transformer_outputs[0]
1513
+ logits = self.score(hidden_states)
1514
+
1515
+ if input_ids is not None:
1516
+ batch_size, sequence_length = input_ids.shape[:2]
1517
+ else:
1518
+ batch_size, sequence_length = inputs_embeds.shape[:2]
1519
+
1520
+ assert (
1521
+ self.config.pad_token_id is not None or batch_size == 1
1522
+ ), "Cannot handle batch sizes > 1 if no padding token is defined."
1523
+ if self.config.pad_token_id is None:
1524
+ sequence_lengths = -1
1525
+ else:
1526
+ if input_ids is not None:
1527
+ sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
1528
+ else:
1529
+ sequence_lengths = -1
1530
+ logger.warning(
1531
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1532
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1533
+ )
1534
+
1535
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1536
+
1537
+ loss = None
1538
+ if labels is not None:
1539
+ if self.config.problem_type is None:
1540
+ if self.num_labels == 1:
1541
+ self.config.problem_type = "regression"
1542
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1543
+ self.config.problem_type = "single_label_classification"
1544
+ else:
1545
+ self.config.problem_type = "multi_label_classification"
1546
+
1547
+ if self.config.problem_type == "regression":
1548
+ loss_fct = MSELoss()
1549
+ if self.num_labels == 1:
1550
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1551
+ else:
1552
+ loss = loss_fct(pooled_logits, labels)
1553
+ elif self.config.problem_type == "single_label_classification":
1554
+ loss_fct = CrossEntropyLoss()
1555
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1556
+ elif self.config.problem_type == "multi_label_classification":
1557
+ loss_fct = BCEWithLogitsLoss()
1558
+ loss = loss_fct(pooled_logits, labels)
1559
+ if not return_dict:
1560
+ output = (pooled_logits,) + transformer_outputs[1:]
1561
+ return ((loss,) + output) if loss is not None else output
1562
+
1563
+ return SequenceClassifierOutputWithPast(
1564
+ loss=loss,
1565
+ logits=pooled_logits,
1566
+ past_key_values=transformer_outputs.past_key_values,
1567
+ hidden_states=transformer_outputs.hidden_states,
1568
+ attentions=transformer_outputs.attentions,
1569
+ )
1570
+
1571
+
1572
+ @add_start_docstrings(
1573
+ """
1574
+ Mind Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1575
+ Named-Entity-Recognition (NER) tasks.
1576
+ """,
1577
+ Mind_START_DOCSTRING,
1578
+ )
1579
+ class MindForTokenClassification(MindPreTrainedModel):
1580
+ def __init__(self, config):
1581
+ super().__init__(config)
1582
+ self.num_labels = config.num_labels
1583
+
1584
+ self.transformer = MindModel(config)
1585
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1586
+ classifier_dropout = config.classifier_dropout
1587
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1588
+ classifier_dropout = config.hidden_dropout
1589
+ else:
1590
+ classifier_dropout = 0.1
1591
+ self.dropout = nn.Dropout(classifier_dropout)
1592
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1593
+
1594
+ # Model parallel
1595
+ self.model_parallel = False
1596
+ self.device_map = None
1597
+
1598
+ # Initialize weights and apply final processing
1599
+ self.post_init()
1600
+
1601
+ @add_start_docstrings_to_model_forward(Mind_INPUTS_DOCSTRING)
1602
+ # fmt: off
1603
+ @add_code_sample_docstrings(
1604
+ checkpoint="brad1141/Mind-finetuned-comp2",
1605
+ output_type=TokenClassifierOutput,
1606
+ config_class=_CONFIG_FOR_DOC,
1607
+ expected_loss=0.25,
1608
+ expected_output=["Lead", "Lead", "Lead", "Position", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead"],
1609
+ )
1610
+ # fmt: on
1611
+ def forward(
1612
+ self,
1613
+ input_ids: Optional[torch.LongTensor] = None,
1614
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1615
+ attention_mask: Optional[torch.FloatTensor] = None,
1616
+ token_type_ids: Optional[torch.LongTensor] = None,
1617
+ position_ids: Optional[torch.LongTensor] = None,
1618
+ head_mask: Optional[torch.FloatTensor] = None,
1619
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1620
+ labels: Optional[torch.LongTensor] = None,
1621
+ use_cache: Optional[bool] = None,
1622
+ output_attentions: Optional[bool] = None,
1623
+ output_hidden_states: Optional[bool] = None,
1624
+ return_dict: Optional[bool] = None,
1625
+ ) -> Union[Tuple, TokenClassifierOutput]:
1626
+ r"""
1627
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1628
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1629
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1630
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1631
+ """
1632
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1633
+
1634
+ transformer_outputs = self.transformer(
1635
+ input_ids,
1636
+ past_key_values=past_key_values,
1637
+ attention_mask=attention_mask,
1638
+ token_type_ids=token_type_ids,
1639
+ position_ids=position_ids,
1640
+ head_mask=head_mask,
1641
+ inputs_embeds=inputs_embeds,
1642
+ use_cache=use_cache,
1643
+ output_attentions=output_attentions,
1644
+ output_hidden_states=output_hidden_states,
1645
+ return_dict=return_dict,
1646
+ )
1647
+
1648
+ hidden_states = transformer_outputs[0]
1649
+ hidden_states = self.dropout(hidden_states)
1650
+ logits = self.classifier(hidden_states)
1651
+
1652
+ loss = None
1653
+ if labels is not None:
1654
+ labels = labels.to(logits.device)
1655
+ loss_fct = CrossEntropyLoss()
1656
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1657
+
1658
+ if not return_dict:
1659
+ output = (logits,) + transformer_outputs[2:]
1660
+ return ((loss,) + output) if loss is not None else output
1661
+
1662
+ return TokenClassifierOutput(
1663
+ loss=loss,
1664
+ logits=logits,
1665
+ hidden_states=transformer_outputs.hidden_states,
1666
+ attentions=transformer_outputs.attentions,
1667
+ )
1668
+
1669
+
1670
+ @add_start_docstrings(
1671
+ """
1672
+ The GPT-2 Model transformer with a span classification head on top for extractive question-answering tasks like
1673
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1674
+ """,
1675
+ Mind_START_DOCSTRING,
1676
+ )
1677
+ class MindForQuestionAnswering(MindPreTrainedModel):
1678
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"]
1679
+ _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.masked_bias", r"h\.\d+\.attn\.bias", r"lm_head.weight"]
1680
+
1681
+ def __init__(self, config):
1682
+ super().__init__(config)
1683
+ self.num_labels = config.num_labels
1684
+ self.transformer = MindModel(config)
1685
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1686
+
1687
+ # Model parallel
1688
+ self.model_parallel = False
1689
+ self.device_map = None
1690
+ self.gradient_checkpointing = False
1691
+
1692
+ # Initialize weights and apply final processing
1693
+ self.post_init()
1694
+
1695
+ @add_start_docstrings_to_model_forward(Mind_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1696
+ @add_code_sample_docstrings(
1697
+ checkpoint=_CHECKPOINT_FOR_DOC,
1698
+ output_type=QuestionAnsweringModelOutput,
1699
+ config_class=_CONFIG_FOR_DOC,
1700
+ real_checkpoint=_CHECKPOINT_FOR_DOC,
1701
+ )
1702
+ def forward(
1703
+ self,
1704
+ input_ids: Optional[torch.LongTensor] = None,
1705
+ attention_mask: Optional[torch.FloatTensor] = None,
1706
+ token_type_ids: Optional[torch.LongTensor] = None,
1707
+ position_ids: Optional[torch.LongTensor] = None,
1708
+ head_mask: Optional[torch.FloatTensor] = None,
1709
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1710
+ start_positions: Optional[torch.LongTensor] = None,
1711
+ end_positions: Optional[torch.LongTensor] = None,
1712
+ output_attentions: Optional[bool] = None,
1713
+ output_hidden_states: Optional[bool] = None,
1714
+ return_dict: Optional[bool] = None,
1715
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1716
+ r"""
1717
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1718
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1719
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1720
+ are not taken into account for computing the loss.
1721
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1722
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1723
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1724
+ are not taken into account for computing the loss.
1725
+ """
1726
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1727
+
1728
+ outputs = self.transformer(
1729
+ input_ids,
1730
+ attention_mask=attention_mask,
1731
+ token_type_ids=token_type_ids,
1732
+ position_ids=position_ids,
1733
+ head_mask=head_mask,
1734
+ inputs_embeds=inputs_embeds,
1735
+ output_attentions=output_attentions,
1736
+ output_hidden_states=output_hidden_states,
1737
+ return_dict=return_dict,
1738
+ )
1739
+
1740
+ sequence_output = outputs[0]
1741
+
1742
+ logits = self.qa_outputs(sequence_output)
1743
+ start_logits, end_logits = logits.split(1, dim=-1)
1744
+ start_logits = start_logits.squeeze(-1).contiguous()
1745
+ end_logits = end_logits.squeeze(-1).contiguous()
1746
+
1747
+ total_loss = None
1748
+ if start_positions is not None and end_positions is not None:
1749
+ # If we are on multi-GPU, split add a dimension
1750
+ if len(start_positions.size()) > 1:
1751
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
1752
+ if len(end_positions.size()) > 1:
1753
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
1754
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1755
+ ignored_index = start_logits.size(1)
1756
+ start_positions = start_positions.clamp(0, ignored_index)
1757
+ end_positions = end_positions.clamp(0, ignored_index)
1758
+
1759
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1760
+ start_loss = loss_fct(start_logits, start_positions)
1761
+ end_loss = loss_fct(end_logits, end_positions)
1762
+ total_loss = (start_loss + end_loss) / 2
1763
+
1764
+ if not return_dict:
1765
+ output = (start_logits, end_logits) + outputs[2:]
1766
+ return ((total_loss,) + output) if total_loss is not None else output
1767
+
1768
+ return QuestionAnsweringModelOutput(
1769
+ loss=total_loss,
1770
+ start_logits=start_logits,
1771
+ end_logits=end_logits,
1772
+ hidden_states=outputs.hidden_states,
1773
+ attentions=outputs.attentions,
1774
+ )
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:993a25cab4973dabfdb702a80d17b7ac29330312e2432f35f31b0a1fb0d1da34
3
+ size 13887036019
special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": true,
6
+ "rstrip": false,
7
+ "single_word": true
8
+ },
9
+ "eos_token": {
10
+ "content": "</s>",
11
+ "lstrip": false,
12
+ "normalized": true,
13
+ "rstrip": false,
14
+ "single_word": true
15
+ },
16
+ "unk_token": {
17
+ "content": "<unk>",
18
+ "lstrip": false,
19
+ "normalized": true,
20
+ "rstrip": false,
21
+ "single_word": true
22
+ },
23
+ "pad_token": {
24
+ "content": "<unk>",
25
+ "lstrip": false,
26
+ "normalized": true,
27
+ "rstrip": false,
28
+ "single_word": true
29
+ }
30
+ }
tokenization_baichuan.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, Baichuan Intelligent Technology. All rights reserved.
2
+
3
+ import os
4
+ from shutil import copyfile
5
+ from typing import Any, Dict, List, Optional, Tuple
6
+
7
+ import sentencepiece as spm
8
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
9
+ from transformers.utils import logging
10
+
11
+
12
+ logger = logging.get_logger(__name__)
13
+
14
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
15
+
16
+ PRETRAINED_VOCAB_FILES_MAP = {
17
+ "vocab_file": {},
18
+ "tokenizer_file": {},
19
+ }
20
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {}
21
+
22
+
23
+ class BaichuanTokenizer(PreTrainedTokenizer):
24
+ """
25
+ Construct a Baichuan tokenizer. Based on byte-level Byte-Pair-Encoding.
26
+
27
+ Args:
28
+ vocab_file (`str`):
29
+ Path to the vocabulary file.
30
+ """
31
+
32
+ vocab_files_names = VOCAB_FILES_NAMES
33
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
34
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
35
+ model_input_names = ["input_ids", "attention_mask"]
36
+
37
+ def __init__(
38
+ self,
39
+ vocab_file,
40
+ unk_token="<unk>",
41
+ bos_token="<s>",
42
+ eos_token="</s>",
43
+ pad_token=None,
44
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
45
+ add_bos_token=True,
46
+ add_eos_token=False,
47
+ clean_up_tokenization_spaces=False,
48
+ **kwargs,
49
+ ):
50
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
51
+ bos_token = (
52
+ AddedToken(bos_token, lstrip=False, rstrip=False)
53
+ if isinstance(bos_token, str)
54
+ else bos_token
55
+ )
56
+ eos_token = (
57
+ AddedToken(eos_token, lstrip=False, rstrip=False)
58
+ if isinstance(eos_token, str)
59
+ else eos_token
60
+ )
61
+ unk_token = (
62
+ AddedToken(unk_token, lstrip=False, rstrip=False)
63
+ if isinstance(unk_token, str)
64
+ else unk_token
65
+ )
66
+ pad_token = (
67
+ AddedToken(pad_token, lstrip=False, rstrip=False)
68
+ if isinstance(pad_token, str)
69
+ else pad_token
70
+ )
71
+ # super().__init__(
72
+ # bos_token=bos_token,
73
+ # eos_token=eos_token,
74
+ # unk_token=unk_token,
75
+ # pad_token=pad_token,
76
+ # add_bos_token=add_bos_token,
77
+ # add_eos_token=add_eos_token,
78
+ # sp_model_kwargs=self.sp_model_kwargs,
79
+ # clean_up_tokenization_spaces=clean_up_tokenization_spaces,
80
+ # **kwargs,
81
+ # )
82
+ self.vocab_file = vocab_file
83
+ self.add_bos_token = add_bos_token
84
+ self.add_eos_token = add_eos_token
85
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
86
+ self.sp_model.Load(vocab_file)
87
+ super().__init__(
88
+ bos_token=bos_token,
89
+ eos_token=eos_token,
90
+ unk_token=unk_token,
91
+ pad_token=pad_token,
92
+ add_bos_token=add_bos_token,
93
+ add_eos_token=add_eos_token,
94
+ sp_model_kwargs=self.sp_model_kwargs,
95
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
96
+ **kwargs,
97
+ )
98
+
99
+ def __getstate__(self):
100
+ state = self.__dict__.copy()
101
+ state["sp_model"] = None
102
+ return state
103
+
104
+ def __setstate__(self, d):
105
+ self.__dict__ = d
106
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
107
+ self.sp_model.Load(self.vocab_file)
108
+
109
+ @property
110
+ def vocab_size(self):
111
+ """Returns vocab size"""
112
+ return self.sp_model.get_piece_size()
113
+
114
+ def get_vocab(self):
115
+ """Returns vocab as a dict"""
116
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
117
+ vocab.update(self.added_tokens_encoder)
118
+ return vocab
119
+
120
+ def _tokenize(self, text):
121
+ """Returns a tokenized string."""
122
+ return self.sp_model.encode(text, out_type=str)
123
+
124
+ def _convert_token_to_id(self, token):
125
+ """Converts a token (str) in an id using the vocab."""
126
+ return self.sp_model.piece_to_id(token)
127
+
128
+ def _convert_id_to_token(self, index):
129
+ """Converts an index (integer) in a token (str) using the vocab."""
130
+ token = self.sp_model.IdToPiece(index)
131
+ return token
132
+
133
+ def convert_tokens_to_string(self, tokens):
134
+ """Converts a sequence of tokens (string) in a single string."""
135
+ current_sub_tokens = []
136
+ out_string = ""
137
+ prev_is_special = False
138
+ for i, token in enumerate(tokens):
139
+ # make sure that special tokens are not decoded using sentencepiece model
140
+ if token in self.all_special_tokens:
141
+ if not prev_is_special and i != 0:
142
+ out_string += " "
143
+ out_string += self.sp_model.decode(current_sub_tokens) + token
144
+ prev_is_special = True
145
+ current_sub_tokens = []
146
+ else:
147
+ current_sub_tokens.append(token)
148
+ prev_is_special = False
149
+ out_string += self.sp_model.decode(current_sub_tokens)
150
+ return out_string
151
+
152
+ def save_vocabulary(
153
+ self, save_directory, filename_prefix: Optional[str] = None
154
+ ) -> Tuple[str]:
155
+ """
156
+ Save the vocabulary and special tokens file to a directory.
157
+
158
+ Args:
159
+ save_directory (`str`):
160
+ The directory in which to save the vocabulary.
161
+
162
+ Returns:
163
+ `Tuple(str)`: Paths to the files saved.
164
+ """
165
+ if not os.path.isdir(save_directory):
166
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
167
+ return
168
+ out_vocab_file = os.path.join(
169
+ save_directory,
170
+ (filename_prefix + "-" if filename_prefix else "")
171
+ + VOCAB_FILES_NAMES["vocab_file"],
172
+ )
173
+
174
+ if os.path.abspath(self.vocab_file) != os.path.abspath(
175
+ out_vocab_file
176
+ ) and os.path.isfile(self.vocab_file):
177
+ copyfile(self.vocab_file, out_vocab_file)
178
+ elif not os.path.isfile(self.vocab_file):
179
+ with open(out_vocab_file, "wb") as fi:
180
+ content_spiece_model = self.sp_model.serialized_model_proto()
181
+ fi.write(content_spiece_model)
182
+
183
+ return (out_vocab_file,)
184
+
185
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
186
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
187
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
188
+
189
+ output = bos_token_id + token_ids_0 + eos_token_id
190
+
191
+ if token_ids_1 is not None:
192
+ output = output + bos_token_id + token_ids_1 + eos_token_id
193
+
194
+ return output
195
+
196
+ def get_special_tokens_mask(
197
+ self,
198
+ token_ids_0: List[int],
199
+ token_ids_1: Optional[List[int]] = None,
200
+ already_has_special_tokens: bool = False,
201
+ ) -> List[int]:
202
+ """
203
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
204
+ special tokens using the tokenizer `prepare_for_model` method.
205
+
206
+ Args:
207
+ token_ids_0 (`List[int]`):
208
+ List of IDs.
209
+ token_ids_1 (`List[int]`, *optional*):
210
+ Optional second list of IDs for sequence pairs.
211
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
212
+ Whether or not the token list is already formatted with special tokens for the model.
213
+
214
+ Returns:
215
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
216
+ """
217
+ if already_has_special_tokens:
218
+ return super().get_special_tokens_mask(
219
+ token_ids_0=token_ids_0,
220
+ token_ids_1=token_ids_1,
221
+ already_has_special_tokens=True,
222
+ )
223
+
224
+ bos_token_id = [1] if self.add_bos_token else []
225
+ eos_token_id = [1] if self.add_eos_token else []
226
+
227
+ if token_ids_1 is None:
228
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
229
+ return (
230
+ bos_token_id
231
+ + ([0] * len(token_ids_0))
232
+ + eos_token_id
233
+ + bos_token_id
234
+ + ([0] * len(token_ids_1))
235
+ + eos_token_id
236
+ )
237
+
238
+ def create_token_type_ids_from_sequences(
239
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
240
+ ) -> List[int]:
241
+ """
242
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
243
+ sequence pair mask has the following format:
244
+
245
+ ```
246
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
247
+ | first sequence | second sequence |
248
+ ```
249
+
250
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
251
+
252
+ Args:
253
+ token_ids_0 (`List[int]`):
254
+ List of ids.
255
+ token_ids_1 (`List[int]`, *optional*):
256
+ Optional second list of IDs for sequence pairs.
257
+
258
+ Returns:
259
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
260
+ """
261
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
262
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
263
+
264
+ output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
265
+
266
+ if token_ids_1 is not None:
267
+ output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
268
+
269
+ return output
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:79452955be6b419a65984273a9f08af86042e1c2a75ee3ba989cbf620a133cc2
3
+ size 2001107
tokenizer_config.json ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "auto_map": {
5
+ "AutoTokenizer": [
6
+ "tokenization_baichuan.BaichuanTokenizer",
7
+ null
8
+ ]
9
+ },
10
+ "bos_token": {
11
+ "__type": "AddedToken",
12
+ "content": "<s>",
13
+ "lstrip": false,
14
+ "normalized": true,
15
+ "rstrip": false,
16
+ "single_word": true
17
+ },
18
+ "clean_up_tokenization_spaces": false,
19
+ "eos_token": {
20
+ "__type": "AddedToken",
21
+ "content": "</s>",
22
+ "lstrip": false,
23
+ "normalized": true,
24
+ "rstrip": false,
25
+ "single_word": true
26
+ },
27
+ "model_max_length": 4096,
28
+ "pad_token": {
29
+ "__type": "AddedToken",
30
+ "content": "<unk>",
31
+ "lstrip": false,
32
+ "normalized": true,
33
+ "rstrip": false,
34
+ "single_word": true
35
+ },
36
+ "sp_model_kwargs": {},
37
+ "tokenizer_class": "BaichuanTokenizer",
38
+ "unk_token": {
39
+ "__type": "AddedToken",
40
+ "content": "<unk>",
41
+ "lstrip": false,
42
+ "normalized": true,
43
+ "rstrip": false,
44
+ "single_word": true
45
+ }
46
+ }