yairschiff commited on
Commit
7e50af1
·
verified ·
1 Parent(s): 3b1dab2

Upload tokenizer

Browse files
Files changed (5) hide show
  1. README.md +199 -0
  2. special_tokens_map.json +7 -0
  3. tokenizer.py +264 -0
  4. tokenizer_config.json +58 -0
  5. vocab.json +37 -0
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "<bos>",
3
+ "mask_token": "<mask>",
4
+ "pad_token": "<pad>",
5
+ "sep_token": "<eos>",
6
+ "unk_token": "<unk>"
7
+ }
tokenizer.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Custom Tokenization classes."""
2
+
3
+ import collections
4
+ import json
5
+ import os
6
+ import re
7
+ from typing import List, Optional, Tuple, Union
8
+
9
+ from transformers.tokenization_utils import PreTrainedTokenizer
10
+ from transformers.utils import logging
11
+
12
+
13
+ logger = logging.get_logger(__name__)
14
+
15
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.json"}
16
+ PRETRAINED_VOCAB_FILES_MAP = {
17
+ "vocab_file": {
18
+ "yairschiff/qm9-tokenizer": "https://huggingface.co/yairschiff/qm9-tokenizer/resolve/main/vocab.json",
19
+ }
20
+ }
21
+
22
+
23
+ class QM9Tokenizer(PreTrainedTokenizer):
24
+ r"""
25
+ Construct a tokenizer for QM9 dataset. Based on regex.
26
+
27
+ This tokenizer inherits from [`PreTrainedTokenizer`]
28
+ which contains most of the main methods. Users should
29
+ refer to this superclass for more information regarding
30
+ those methods.
31
+
32
+ Adapted from:
33
+ https://huggingface.co/ibm/MoLFormer-XL-both-10pct
34
+
35
+ Args:
36
+ vocab_file (`str`):
37
+ File containing the vocabulary.
38
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
39
+ The unknown token. A token not in the vocabulary
40
+ cannot be converted to an ID and is set to be
41
+ this token instead.
42
+ sep_token (`str`, *optional*, defaults to `"<eos>"`):
43
+ The separator token, which is used when building
44
+ a sequence from multiple sequences, e.g., two
45
+ sequences for sequence classification or for a
46
+ text and a question for question answering.
47
+ It is also used as the last token of a sequence
48
+ built with special tokens.
49
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
50
+ The token used for padding, for example, when
51
+ batching sequences of different lengths.
52
+ cls_token (`str`, *optional*, defaults to `"<bos>"`):
53
+ The classifier token which is used when doing
54
+ sequence classification (classification of the
55
+ whole sequence
56
+ instead of per-token classification). It is the
57
+ first token of the sequence when built with
58
+ special tokens.
59
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
60
+ The token used for masking values. This is the
61
+ token used when training this model with masked
62
+ language modeling. This is the token, which the
63
+ model will try to predict.
64
+ """
65
+
66
+ vocab_files_names = VOCAB_FILES_NAMES
67
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
68
+ model_input_names = ["input_ids", "attention_mask"]
69
+
70
+ def __init__(
71
+ self,
72
+ vocab_file,
73
+ unk_token='<unk>',
74
+ sep_token='<eos>',
75
+ pad_token='<pad>',
76
+ cls_token='<bos>',
77
+ mask_token='<mask>',
78
+ **kwargs,
79
+ ):
80
+ if not os.path.isfile(vocab_file):
81
+ raise ValueError(
82
+ "Can't find a vocabulary file at path"
83
+ f"'{vocab_file}'."
84
+ )
85
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
86
+ vocab_from_file = json.load(vocab_handle)
87
+ # Re-index to account for special tokens
88
+ self.vocab = {
89
+ cls_token: 0,
90
+ sep_token: 1,
91
+ mask_token: 2,
92
+ pad_token: 3,
93
+ unk_token: 4,
94
+ **{k: v + 5 for k, v in vocab_from_file.items()}
95
+ }
96
+
97
+ self.ids_to_tokens = collections.OrderedDict(
98
+ [(ids, tok) for tok, ids in self.vocab.items()])
99
+ # Regex pattern taken from:
100
+ # https://github.com/pschwllr/MolecularTransformer
101
+ self.pattern = (
102
+ r"(\[[^\]]+]|Br?|Cl?|N|O|S|P|F|I|b|c|n|o|s|p|\(|\)|\.|=|#|-|\+|\\|\/|:|~|@|\?|>|\*|\$|\%[0-9]{2}|[0-9])"
103
+ )
104
+ self.regex_tokenizer = re.compile(self.pattern)
105
+
106
+ super().__init__(
107
+ unk_token=unk_token,
108
+ sep_token=sep_token,
109
+ pad_token=pad_token,
110
+ cls_token=cls_token,
111
+ mask_token=mask_token,
112
+ **kwargs,
113
+ )
114
+
115
+ @property
116
+ def vocab_size(self):
117
+ return len(self.vocab)
118
+
119
+ def get_vocab(self):
120
+ return dict(self.vocab, **self.added_tokens_encoder)
121
+
122
+ def _tokenize(self, text, **kwargs):
123
+ split_tokens = self.regex_tokenizer.findall(text)
124
+ return split_tokens
125
+
126
+ def _convert_token_to_id(self, token):
127
+ """Converts token (str) in an id using the vocab."""
128
+ return self.vocab.get(token, self.vocab.get(self.unk_token))
129
+
130
+ def _convert_id_to_token(self, index):
131
+ """Converts index (integer) in a token (str) using the vocab."""
132
+ return self.ids_to_tokens.get(index, self.unk_token)
133
+
134
+ def convert_tokens_to_string(self, tokens):
135
+ """Converts sequence of tokens (string) in a single string."""
136
+ out_string = "".join(tokens).strip()
137
+ return out_string
138
+
139
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.build_inputs_with_special_tokens
140
+ def build_inputs_with_special_tokens(
141
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
142
+ ) -> List[int]:
143
+ """
144
+ Build model inputs from a sequence or a pair of
145
+ sequences for sequence classification tasks by
146
+ concatenating and adding special tokens.
147
+ A BERT sequence has the following format:
148
+
149
+ - single sequence: `[CLS] X [SEP]`
150
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
151
+
152
+ Args:
153
+ token_ids_0 (`List[int]`):
154
+ List of IDs to which the special tokens will
155
+ be added.
156
+ token_ids_1 (`List[int]`, *optional*):
157
+ Optional second list of IDs for sequence
158
+ pairs.
159
+
160
+ Returns:
161
+ `List[int]`: List of [input IDs](../glossary#input-ids)
162
+ with the appropriate special tokens.
163
+ """
164
+ if token_ids_1 is None:
165
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
166
+ cls = [self.cls_token_id]
167
+ sep = [self.sep_token_id]
168
+ return cls + token_ids_0 + sep + token_ids_1 + sep
169
+
170
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.get_special_tokens_mask
171
+ def get_special_tokens_mask(
172
+ self,
173
+ token_ids_0: List[int],
174
+ token_ids_1: Optional[List[int]] = None,
175
+ already_has_special_tokens: bool = False
176
+ ) -> List[int]:
177
+ """
178
+ Retrieve sequence ids from a token list that has no
179
+ special tokens added. This method is called when
180
+ adding special tokens using the tokenizer
181
+ `prepare_for_model` method.
182
+
183
+ Args:
184
+ token_ids_0 (`List[int]`):
185
+ List of IDs.
186
+ token_ids_1 (`List[int]`, *optional*):
187
+ Optional second list of IDs for sequence pairs.
188
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
189
+ Whether the token list is already formatted
190
+ with special tokens for the model.
191
+
192
+ Returns:
193
+ `List[int]`: A list of integers in the range
194
+ [0, 1]: 1 for a special token, 0 for a sequence
195
+ token.
196
+ """
197
+
198
+ if already_has_special_tokens:
199
+ return super().get_special_tokens_mask(
200
+ token_ids_0=token_ids_0,
201
+ token_ids_1=token_ids_1,
202
+ already_has_special_tokens=True
203
+ )
204
+
205
+ if token_ids_1 is not None:
206
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
207
+ return [1] + ([0] * len(token_ids_0)) + [1]
208
+
209
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.create_token_type_ids_from_sequences
210
+ def create_token_type_ids_from_sequences(
211
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
212
+ ) -> List[int]:
213
+ """
214
+ Create a mask from the two sequences passed to be
215
+ used in a sequence-pair classification task.
216
+ A BERT sequence pair mask has the following format:
217
+
218
+ ```
219
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
220
+ | first sequence | second sequence |
221
+ ```
222
+
223
+ If `token_ids_1` is `None`, this method only returns
224
+ the first portion of the mask (0s).
225
+
226
+ Args:
227
+ token_ids_0 (`List[int]`):
228
+ List of IDs.
229
+ token_ids_1 (`List[int]`, *optional*):
230
+ Optional second list of IDs for sequence
231
+ pairs.
232
+
233
+ Returns:
234
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
235
+ """
236
+ sep = [self.sep_token_id]
237
+ cls = [self.cls_token_id]
238
+ if token_ids_1 is None:
239
+ return len(cls + token_ids_0 + sep) * [0]
240
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
241
+
242
+ def save_vocabulary(
243
+ self, save_directory: str,
244
+ filename_prefix: Optional[str] = None
245
+ ) -> Union[Tuple[str], None]:
246
+ if not os.path.isdir(save_directory):
247
+ logger.error(
248
+ f"Vocabulary path ({save_directory}) should"
249
+ "be a directory.")
250
+ return None
251
+ vocab_file = os.path.join(
252
+ save_directory,
253
+ (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
254
+ )
255
+
256
+ with open(vocab_file, "w", encoding="utf-8") as f:
257
+ f.write(
258
+ json.dumps(
259
+ self.vocab,
260
+ indent=2,
261
+ sort_keys=True,
262
+ ensure_ascii=False
263
+ ) + "\n")
264
+ return (vocab_file,)
tokenizer_config.json ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "<bos>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "<eos>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "<mask>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "<pad>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "4": {
36
+ "content": "<unk>",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "auto_map": {
45
+ "AutoTokenizer": [
46
+ "tokenizer.QM9Tokenizer",
47
+ null
48
+ ]
49
+ },
50
+ "clean_up_tokenization_spaces": true,
51
+ "cls_token": "<bos>",
52
+ "mask_token": "<mask>",
53
+ "model_max_length": 1000000000000000019884624838656,
54
+ "pad_token": "<pad>",
55
+ "sep_token": "<eos>",
56
+ "tokenizer_class": "QM9Tokenizer",
57
+ "unk_token": "<unk>"
58
+ }
vocab.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "#": 5,
3
+ "(": 6,
4
+ ")": 7,
5
+ "-": 8,
6
+ "1": 9,
7
+ "2": 10,
8
+ "3": 11,
9
+ "4": 12,
10
+ "5": 13,
11
+ "<bos>": 0,
12
+ "<eos>": 1,
13
+ "<mask>": 2,
14
+ "<pad>": 3,
15
+ "<unk>": 4,
16
+ "=": 14,
17
+ "C": 15,
18
+ "F": 16,
19
+ "N": 17,
20
+ "O": 18,
21
+ "[C-]": 19,
22
+ "[CH-]": 20,
23
+ "[N+]": 21,
24
+ "[N-]": 22,
25
+ "[NH+]": 23,
26
+ "[NH2+]": 24,
27
+ "[NH3+]": 25,
28
+ "[O-]": 26,
29
+ "[c-]": 27,
30
+ "[cH-]": 28,
31
+ "[n-]": 29,
32
+ "[nH+]": 30,
33
+ "[nH]": 31,
34
+ "c": 32,
35
+ "n": 33,
36
+ "o": 34
37
+ }