before_train
Browse files- config.json +27 -0
- pretokenizer.py +24 -0
- run_t5_mlm_flax.py +802 -0
- t5_tokenizer_model.py +217 -0
- tokenizer-trainer_atom.py +65 -0
- tokenizer-trainer_uni.py +69 -0
- train_scprit.sh +22 -0
- try.py +79 -0
config.json
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "/home/zoez/chemT5",
|
3 |
+
"architectures": [
|
4 |
+
"T5ForConditionalGeneration"
|
5 |
+
],
|
6 |
+
"d_ff": 2048,
|
7 |
+
"d_kv": 64,
|
8 |
+
"d_model": 768,
|
9 |
+
"decoder_start_token_id": 0,
|
10 |
+
"dropout_rate": 0.1,
|
11 |
+
"eos_token_id": 1,
|
12 |
+
"feed_forward_proj": "gated-gelu",
|
13 |
+
"initializer_factor": 1.0,
|
14 |
+
"is_encoder_decoder": true,
|
15 |
+
"layer_norm_epsilon": 1e-06,
|
16 |
+
"model_type": "t5",
|
17 |
+
"num_decoder_layers": 12,
|
18 |
+
"num_heads": 12,
|
19 |
+
"num_layers": 12,
|
20 |
+
"output_past": true,
|
21 |
+
"pad_token_id": 0,
|
22 |
+
"relative_attention_num_buckets": 32,
|
23 |
+
"tie_word_embeddings": false,
|
24 |
+
"transformers_version": "4.11.3",
|
25 |
+
"use_cache": true,
|
26 |
+
"vocab_size": 32003
|
27 |
+
}
|
pretokenizer.py
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#https://github.com/XinhaoLi74/SmilesPE/blob/master/SmilesPE/pretokenizer.py
|
2 |
+
|
3 |
+
def atomwise_tokenizer(smi, exclusive_tokens = None):
|
4 |
+
"""
|
5 |
+
Tokenize a SMILES molecule at atom-level:
|
6 |
+
(1) 'Br' and 'Cl' are two-character tokens
|
7 |
+
(2) Symbols with bracket are considered as tokens
|
8 |
+
exclusive_tokens: A list of specifical symbols with bracket you want to keep. e.g., ['[C@@H]', '[nH]'].
|
9 |
+
Other symbols with bracket will be replaced by '[UNK]'. default is `None`.
|
10 |
+
"""
|
11 |
+
import re
|
12 |
+
pattern = r"(\[[^\]]+]|Br?|Cl?|N|O|S|P|F|I|b|c|n|o|s|p|\(|\)|\.|=|#|-|\+|\\|\/|:|~|@|\?|>>?|\*|\$|\%[0-9]{2}|[0-9])"
|
13 |
+
|
14 |
+
#pattern = r"(\[[^\]]]|Br|Cl|B|C|N|O|P|S|F|c+\%[0-9]{2}|c+\%[0-9]|.+)"
|
15 |
+
regex = re.compile(pattern)
|
16 |
+
tokens = [token for token in regex.findall(smi)]
|
17 |
+
|
18 |
+
if exclusive_tokens:
|
19 |
+
for i, tok in enumerate(tokens):
|
20 |
+
if tok.startswith('['):
|
21 |
+
if tok not in exclusive_tokens:
|
22 |
+
tokens[i] = '[UNK]'
|
23 |
+
return ' '.join(tokens)
|
24 |
+
#return tokens
|
run_t5_mlm_flax.py
ADDED
@@ -0,0 +1,802 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
# coding=utf-8
|
3 |
+
# Copyright 2021 The HuggingFace Team 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 |
+
Pretraining the library models for T5-like span-masked language modeling on a text file or a dataset.
|
18 |
+
Here is the full list of checkpoints on the hub that can be pretrained by this script:
|
19 |
+
https://huggingface.co/models?filter=t5
|
20 |
+
"""
|
21 |
+
# You can also adapt this script on your own masked language modeling task. Pointers for this are left as comments.
|
22 |
+
import logging
|
23 |
+
import os
|
24 |
+
import sys
|
25 |
+
import time
|
26 |
+
from dataclasses import dataclass, field
|
27 |
+
from pathlib import Path
|
28 |
+
from typing import Dict, List, Optional
|
29 |
+
|
30 |
+
import numpy as np
|
31 |
+
from datasets import load_dataset
|
32 |
+
from tqdm import tqdm
|
33 |
+
|
34 |
+
import flax
|
35 |
+
import jax
|
36 |
+
import jax.numpy as jnp
|
37 |
+
import optax
|
38 |
+
from flax import jax_utils, traverse_util
|
39 |
+
from flax.training import train_state
|
40 |
+
from flax.training.common_utils import get_metrics, onehot, shard
|
41 |
+
from huggingface_hub import Repository
|
42 |
+
from transformers import (
|
43 |
+
CONFIG_MAPPING,
|
44 |
+
FLAX_MODEL_FOR_MASKED_LM_MAPPING,
|
45 |
+
AutoTokenizer,
|
46 |
+
BatchEncoding,
|
47 |
+
FlaxT5ForConditionalGeneration,
|
48 |
+
HfArgumentParser,
|
49 |
+
PreTrainedTokenizerBase,
|
50 |
+
T5Config,
|
51 |
+
TrainingArguments,
|
52 |
+
is_tensorboard_available,
|
53 |
+
set_seed,
|
54 |
+
)
|
55 |
+
from transformers.file_utils import get_full_repo_name
|
56 |
+
from transformers.models.t5.modeling_flax_t5 import shift_tokens_right
|
57 |
+
|
58 |
+
|
59 |
+
MODEL_CONFIG_CLASSES = list(FLAX_MODEL_FOR_MASKED_LM_MAPPING.keys())
|
60 |
+
MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
|
61 |
+
|
62 |
+
|
63 |
+
@dataclass
|
64 |
+
class ModelArguments:
|
65 |
+
"""
|
66 |
+
Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
|
67 |
+
"""
|
68 |
+
|
69 |
+
model_name_or_path: Optional[str] = field(
|
70 |
+
default=None,
|
71 |
+
metadata={
|
72 |
+
"help": "The model checkpoint for weights initialization."
|
73 |
+
"Don't set if you want to train a model from scratch."
|
74 |
+
},
|
75 |
+
)
|
76 |
+
model_type: Optional[str] = field(
|
77 |
+
default=None,
|
78 |
+
metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)},
|
79 |
+
)
|
80 |
+
config_name: Optional[str] = field(
|
81 |
+
default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
|
82 |
+
)
|
83 |
+
tokenizer_name: Optional[str] = field(
|
84 |
+
default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
|
85 |
+
)
|
86 |
+
cache_dir: Optional[str] = field(
|
87 |
+
default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
|
88 |
+
)
|
89 |
+
use_fast_tokenizer: bool = field(
|
90 |
+
default=True,
|
91 |
+
metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
|
92 |
+
)
|
93 |
+
dtype: Optional[str] = field(
|
94 |
+
default="float32",
|
95 |
+
metadata={
|
96 |
+
"help": "Floating-point format in which the model weights should be initialized and trained. Choose one of `[float32, float16, bfloat16]`."
|
97 |
+
},
|
98 |
+
)
|
99 |
+
|
100 |
+
|
101 |
+
@dataclass
|
102 |
+
class DataTrainingArguments:
|
103 |
+
"""
|
104 |
+
Arguments pertaining to what data we are going to input our model for training and eval.
|
105 |
+
"""
|
106 |
+
|
107 |
+
dataset_name: Optional[str] = field(
|
108 |
+
default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
|
109 |
+
)
|
110 |
+
dataset_config_name: Optional[str] = field(
|
111 |
+
default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
|
112 |
+
)
|
113 |
+
train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
|
114 |
+
validation_file: Optional[str] = field(
|
115 |
+
default=None,
|
116 |
+
metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
|
117 |
+
)
|
118 |
+
train_ref_file: Optional[str] = field(
|
119 |
+
default=None,
|
120 |
+
metadata={"help": "An optional input train ref data file for whole word masking in Chinese."},
|
121 |
+
)
|
122 |
+
validation_ref_file: Optional[str] = field(
|
123 |
+
default=None,
|
124 |
+
metadata={"help": "An optional input validation ref data file for whole word masking in Chinese."},
|
125 |
+
)
|
126 |
+
overwrite_cache: bool = field(
|
127 |
+
default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
|
128 |
+
)
|
129 |
+
validation_split_percentage: Optional[int] = field(
|
130 |
+
default=5,
|
131 |
+
metadata={
|
132 |
+
"help": "The percentage of the train set used as validation set in case there's no validation split"
|
133 |
+
},
|
134 |
+
)
|
135 |
+
max_seq_length: Optional[int] = field(
|
136 |
+
default=None,
|
137 |
+
metadata={
|
138 |
+
"help": "The maximum total input sequence length after tokenization and masking. Sequences longer than this will be truncated. Default to the max input length of the model."
|
139 |
+
},
|
140 |
+
)
|
141 |
+
preprocessing_num_workers: Optional[int] = field(
|
142 |
+
default=None,
|
143 |
+
metadata={"help": "The number of processes to use for the preprocessing."},
|
144 |
+
)
|
145 |
+
mlm_probability: float = field(
|
146 |
+
default=0.15, metadata={"help": "Ratio of tokens to mask for span masked language modeling loss"}
|
147 |
+
)
|
148 |
+
mean_noise_span_length: float = field(
|
149 |
+
default=3.0,
|
150 |
+
metadata={"help": "Mean span length of masked tokens"},
|
151 |
+
)
|
152 |
+
|
153 |
+
def __post_init__(self):
|
154 |
+
if self.dataset_name is None and self.train_file is None and self.validation_file is None:
|
155 |
+
raise ValueError("Need either a dataset name or a training/validation file.")
|
156 |
+
else:
|
157 |
+
if self.train_file is not None:
|
158 |
+
extension = self.train_file.split(".")[-1]
|
159 |
+
assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
|
160 |
+
if self.validation_file is not None:
|
161 |
+
extension = self.validation_file.split(".")[-1]
|
162 |
+
assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."
|
163 |
+
|
164 |
+
|
165 |
+
def compute_input_and_target_lengths(inputs_length, noise_density, mean_noise_span_length):
|
166 |
+
"""This function is copy of `random_spans_helper <https://github.com/google-research/text-to-text-transfer-transformer/blob/84f8bcc14b5f2c03de51bd3587609ba8f6bbd1cd/t5/data/preprocessors.py#L2466>`__ .
|
167 |
+
Training parameters to avoid padding with random_spans_noise_mask.
|
168 |
+
When training a model with random_spans_noise_mask, we would like to set the other
|
169 |
+
training hyperparmeters in a way that avoids padding.
|
170 |
+
This function helps us compute these hyperparameters.
|
171 |
+
We assume that each noise span in the input is replaced by extra_tokens_per_span_inputs sentinel tokens,
|
172 |
+
and each non-noise span in the targets is replaced by extra_tokens_per_span_targets sentinel tokens.
|
173 |
+
This function tells us the required number of tokens in the raw example (for split_tokens())
|
174 |
+
as well as the length of the encoded targets. Note that this function assumes
|
175 |
+
the inputs and targets will have EOS appended and includes that in the reported length.
|
176 |
+
Args:
|
177 |
+
inputs_length: an integer - desired length of the tokenized inputs sequence
|
178 |
+
noise_density: a float
|
179 |
+
mean_noise_span_length: a float
|
180 |
+
Returns:
|
181 |
+
tokens_length: length of original text in tokens
|
182 |
+
targets_length: an integer - length in tokens of encoded targets sequence
|
183 |
+
"""
|
184 |
+
|
185 |
+
def _tokens_length_to_inputs_length_targets_length(tokens_length):
|
186 |
+
num_noise_tokens = int(round(tokens_length * noise_density))
|
187 |
+
num_nonnoise_tokens = tokens_length - num_noise_tokens
|
188 |
+
num_noise_spans = int(round(num_noise_tokens / mean_noise_span_length))
|
189 |
+
# inputs contain all nonnoise tokens, sentinels for all noise spans
|
190 |
+
# and one EOS token.
|
191 |
+
_input_length = num_nonnoise_tokens + num_noise_spans + 1
|
192 |
+
_output_length = num_noise_tokens + num_noise_spans + 1
|
193 |
+
return _input_length, _output_length
|
194 |
+
|
195 |
+
tokens_length = inputs_length
|
196 |
+
|
197 |
+
while _tokens_length_to_inputs_length_targets_length(tokens_length + 1)[0] <= inputs_length:
|
198 |
+
tokens_length += 1
|
199 |
+
|
200 |
+
inputs_length, targets_length = _tokens_length_to_inputs_length_targets_length(tokens_length)
|
201 |
+
|
202 |
+
# minor hack to get the targets length to be equal to inputs length
|
203 |
+
# which is more likely to have been set to a nice round number.
|
204 |
+
if noise_density == 0.5 and targets_length > inputs_length:
|
205 |
+
tokens_length -= 1
|
206 |
+
targets_length -= 1
|
207 |
+
return tokens_length, targets_length
|
208 |
+
|
209 |
+
|
210 |
+
@flax.struct.dataclass
|
211 |
+
class FlaxDataCollatorForT5MLM:
|
212 |
+
"""
|
213 |
+
Data collator used for T5 span-masked language modeling.
|
214 |
+
It is made sure that after masking the inputs are of length `data_args.max_seq_length` and targets are also of fixed length.
|
215 |
+
For more information on how T5 span-masked language modeling works, one can take a look
|
216 |
+
at the `official paper <https://arxiv.org/pdf/1910.10683.pdf>`__
|
217 |
+
or the `official code for preprocessing <https://github.com/google-research/text-to-text-transfer-transformer/blob/master/t5/data/preprocessors.py>`__ .
|
218 |
+
Args:
|
219 |
+
tokenizer (:class:`~transformers.PreTrainedTokenizer` or :class:`~transformers.PreTrainedTokenizerFast`):
|
220 |
+
The tokenizer used for encoding the data.
|
221 |
+
noise_density (:obj:`float`):
|
222 |
+
The probability with which to (randomly) mask tokens in the input.
|
223 |
+
mean_noise_span_length (:obj:`float`):
|
224 |
+
The average span length of the masked tokens.
|
225 |
+
input_length (:obj:`int`):
|
226 |
+
The expected input length after masking.
|
227 |
+
target_length (:obj:`int`):
|
228 |
+
The expected target length after masking.
|
229 |
+
pad_token_id: (:obj:`int`):
|
230 |
+
The pad token id of the model
|
231 |
+
decoder_start_token_id: (:obj:`int):
|
232 |
+
The decoder start token id of the model
|
233 |
+
"""
|
234 |
+
|
235 |
+
tokenizer: PreTrainedTokenizerBase
|
236 |
+
noise_density: float
|
237 |
+
mean_noise_span_length: float
|
238 |
+
input_length: int
|
239 |
+
target_length: int
|
240 |
+
pad_token_id: int
|
241 |
+
decoder_start_token_id: int
|
242 |
+
|
243 |
+
def __call__(self, examples: List[Dict[str, np.ndarray]]) -> Dict[str, np.ndarray]:
|
244 |
+
|
245 |
+
# convert list to dict and tensorize input
|
246 |
+
batch = BatchEncoding(
|
247 |
+
{k: np.array([examples[i][k] for i in range(len(examples))]) for k, v in examples[0].items()}
|
248 |
+
)
|
249 |
+
|
250 |
+
input_ids = batch["input_ids"]
|
251 |
+
batch_size, expandend_input_length = input_ids.shape
|
252 |
+
|
253 |
+
mask_indices = np.asarray([self.random_spans_noise_mask(expandend_input_length) for i in range(batch_size)])
|
254 |
+
labels_mask = ~mask_indices
|
255 |
+
|
256 |
+
input_ids_sentinel = self.create_sentinel_ids(mask_indices.astype(np.int8))
|
257 |
+
labels_sentinel = self.create_sentinel_ids(labels_mask.astype(np.int8))
|
258 |
+
|
259 |
+
batch["input_ids"] = self.filter_input_ids(input_ids, input_ids_sentinel)
|
260 |
+
batch["labels"] = self.filter_input_ids(input_ids, labels_sentinel)
|
261 |
+
|
262 |
+
if batch["input_ids"].shape[-1] != self.input_length:
|
263 |
+
raise ValueError(
|
264 |
+
f"`input_ids` are incorrectly preprocessed. `input_ids` length is {batch['input_ids'].shape[-1]}, but should be {self.target_length}."
|
265 |
+
)
|
266 |
+
|
267 |
+
if batch["labels"].shape[-1] != self.target_length:
|
268 |
+
raise ValueError(
|
269 |
+
f"`labels` are incorrectly preprocessed. `labels` length is {batch['labels'].shape[-1]}, but should be {self.target_length}."
|
270 |
+
)
|
271 |
+
|
272 |
+
# to check that tokens are correctly proprocessed, one can run `self.tokenizer.batch_decode(input_ids)` and `self.tokenizer.batch_decode(labels)` here...
|
273 |
+
batch["decoder_input_ids"] = shift_tokens_right(
|
274 |
+
batch["labels"], self.pad_token_id, self.decoder_start_token_id
|
275 |
+
)
|
276 |
+
|
277 |
+
return batch
|
278 |
+
|
279 |
+
def create_sentinel_ids(self, mask_indices):
|
280 |
+
"""
|
281 |
+
Sentinel ids creation given the indices that should be masked.
|
282 |
+
The start indices of each mask are replaced by the sentinel ids in increasing
|
283 |
+
order. Consecutive mask indices to be deleted are replaced with `-1`.
|
284 |
+
"""
|
285 |
+
start_indices = mask_indices - np.roll(mask_indices, 1, axis=-1) * mask_indices
|
286 |
+
start_indices[:, 0] = mask_indices[:, 0]
|
287 |
+
|
288 |
+
sentinel_ids = np.where(start_indices != 0, np.cumsum(start_indices, axis=-1), start_indices)
|
289 |
+
sentinel_ids = np.where(sentinel_ids != 0, (sentinel_ids + self.tokenizer.vocab_size - 1), 0)
|
290 |
+
sentinel_ids -= mask_indices - start_indices
|
291 |
+
|
292 |
+
return sentinel_ids
|
293 |
+
|
294 |
+
def filter_input_ids(self, input_ids, sentinel_ids):
|
295 |
+
"""
|
296 |
+
Puts sentinel mask on `input_ids` and fuse consecutive mask tokens into a single mask token by deleting.
|
297 |
+
This will reduce the sequence length from `expanded_inputs_length` to `input_length`.
|
298 |
+
"""
|
299 |
+
batch_size = input_ids.shape[0]
|
300 |
+
|
301 |
+
input_ids_full = np.where(sentinel_ids != 0, sentinel_ids, input_ids)
|
302 |
+
input_ids = input_ids_full[input_ids_full > 0].reshape((batch_size, -1))
|
303 |
+
input_ids = np.concatenate(
|
304 |
+
[input_ids, np.full((batch_size, 1), self.tokenizer.eos_token_id, dtype=np.int32)], axis=-1
|
305 |
+
)
|
306 |
+
return input_ids
|
307 |
+
|
308 |
+
def random_spans_noise_mask(self, length):
|
309 |
+
|
310 |
+
"""This function is copy of `random_spans_helper <https://github.com/google-research/text-to-text-transfer-transformer/blob/84f8bcc14b5f2c03de51bd3587609ba8f6bbd1cd/t5/data/preprocessors.py#L2682>`__ .
|
311 |
+
Noise mask consisting of random spans of noise tokens.
|
312 |
+
The number of noise tokens and the number of noise spans and non-noise spans
|
313 |
+
are determined deterministically as follows:
|
314 |
+
num_noise_tokens = round(length * noise_density)
|
315 |
+
num_nonnoise_spans = num_noise_spans = round(num_noise_tokens / mean_noise_span_length)
|
316 |
+
Spans alternate between non-noise and noise, beginning with non-noise.
|
317 |
+
Subject to the above restrictions, all masks are equally likely.
|
318 |
+
Args:
|
319 |
+
length: an int32 scalar (length of the incoming token sequence)
|
320 |
+
noise_density: a float - approximate density of output mask
|
321 |
+
mean_noise_span_length: a number
|
322 |
+
Returns:
|
323 |
+
a boolean tensor with shape [length]
|
324 |
+
"""
|
325 |
+
|
326 |
+
orig_length = length
|
327 |
+
|
328 |
+
num_noise_tokens = int(np.round(length * self.noise_density))
|
329 |
+
# avoid degeneracy by ensuring positive numbers of noise and nonnoise tokens.
|
330 |
+
num_noise_tokens = min(max(num_noise_tokens, 1), length - 1)
|
331 |
+
num_noise_spans = int(np.round(num_noise_tokens / self.mean_noise_span_length))
|
332 |
+
|
333 |
+
# avoid degeneracy by ensuring positive number of noise spans
|
334 |
+
num_noise_spans = max(num_noise_spans, 1)
|
335 |
+
num_nonnoise_tokens = length - num_noise_tokens
|
336 |
+
|
337 |
+
# pick the lengths of the noise spans and the non-noise spans
|
338 |
+
def _random_segmentation(num_items, num_segments):
|
339 |
+
"""Partition a sequence of items randomly into non-empty segments.
|
340 |
+
Args:
|
341 |
+
num_items: an integer scalar > 0
|
342 |
+
num_segments: an integer scalar in [1, num_items]
|
343 |
+
Returns:
|
344 |
+
a Tensor with shape [num_segments] containing positive integers that add
|
345 |
+
up to num_items
|
346 |
+
"""
|
347 |
+
mask_indices = np.arange(num_items - 1) < (num_segments - 1)
|
348 |
+
np.random.shuffle(mask_indices)
|
349 |
+
first_in_segment = np.pad(mask_indices, [[1, 0]])
|
350 |
+
segment_id = np.cumsum(first_in_segment)
|
351 |
+
# count length of sub segments assuming that list is sorted
|
352 |
+
_, segment_length = np.unique(segment_id, return_counts=True)
|
353 |
+
return segment_length
|
354 |
+
|
355 |
+
noise_span_lengths = _random_segmentation(num_noise_tokens, num_noise_spans)
|
356 |
+
nonnoise_span_lengths = _random_segmentation(num_nonnoise_tokens, num_noise_spans)
|
357 |
+
|
358 |
+
interleaved_span_lengths = np.reshape(
|
359 |
+
np.stack([nonnoise_span_lengths, noise_span_lengths], axis=1), [num_noise_spans * 2]
|
360 |
+
)
|
361 |
+
span_starts = np.cumsum(interleaved_span_lengths)[:-1]
|
362 |
+
span_start_indicator = np.zeros((length,), dtype=np.int8)
|
363 |
+
span_start_indicator[span_starts] = True
|
364 |
+
span_num = np.cumsum(span_start_indicator)
|
365 |
+
is_noise = np.equal(span_num % 2, 1)
|
366 |
+
|
367 |
+
return is_noise[:orig_length]
|
368 |
+
|
369 |
+
|
370 |
+
def generate_batch_splits(samples_idx: jnp.ndarray, batch_size: int) -> jnp.ndarray:
|
371 |
+
num_samples = len(samples_idx)
|
372 |
+
samples_to_remove = num_samples % batch_size
|
373 |
+
|
374 |
+
if samples_to_remove != 0:
|
375 |
+
samples_idx = samples_idx[:-samples_to_remove]
|
376 |
+
sections_split = num_samples // batch_size
|
377 |
+
batch_idx = np.split(samples_idx, sections_split)
|
378 |
+
return batch_idx
|
379 |
+
|
380 |
+
|
381 |
+
def write_train_metric(summary_writer, train_metrics, train_time, step):
|
382 |
+
summary_writer.scalar("train_time", train_time, step)
|
383 |
+
|
384 |
+
train_metrics = get_metrics(train_metrics)
|
385 |
+
for key, vals in train_metrics.items():
|
386 |
+
tag = f"train_{key}"
|
387 |
+
for i, val in enumerate(vals):
|
388 |
+
summary_writer.scalar(tag, val, step - len(vals) + i + 1)
|
389 |
+
|
390 |
+
|
391 |
+
def write_eval_metric(summary_writer, eval_metrics, step):
|
392 |
+
for metric_name, value in eval_metrics.items():
|
393 |
+
summary_writer.scalar(f"eval_{metric_name}", value, step)
|
394 |
+
|
395 |
+
|
396 |
+
if __name__ == "__main__":
|
397 |
+
# See all possible arguments in src/transformers/training_args.py
|
398 |
+
# or by passing the --help flag to this script.
|
399 |
+
# We now keep distinct sets of args, for a cleaner separation of concerns.
|
400 |
+
|
401 |
+
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
|
402 |
+
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
|
403 |
+
# If we pass only one argument to the script and it's the path to a json file,
|
404 |
+
# let's parse it to get our arguments.
|
405 |
+
model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
|
406 |
+
else:
|
407 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
408 |
+
|
409 |
+
if (
|
410 |
+
os.path.exists(training_args.output_dir)
|
411 |
+
and os.listdir(training_args.output_dir)
|
412 |
+
and training_args.do_train
|
413 |
+
and not training_args.overwrite_output_dir
|
414 |
+
):
|
415 |
+
raise ValueError(
|
416 |
+
f"Output directory ({training_args.output_dir}) already exists and is not empty."
|
417 |
+
"Use --overwrite_output_dir to overcome."
|
418 |
+
)
|
419 |
+
|
420 |
+
# Setup logging
|
421 |
+
logging.basicConfig(
|
422 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
423 |
+
level="NOTSET",
|
424 |
+
datefmt="[%X]",
|
425 |
+
)
|
426 |
+
|
427 |
+
# Log on each process the small summary:
|
428 |
+
logger = logging.getLogger(__name__)
|
429 |
+
|
430 |
+
# Set the verbosity to info of the Transformers logger (on main process only):
|
431 |
+
logger.info(f"Training/evaluation parameters {training_args}")
|
432 |
+
|
433 |
+
# Set seed before initializing model.
|
434 |
+
set_seed(training_args.seed)
|
435 |
+
|
436 |
+
# Handle the repository creation
|
437 |
+
if training_args.push_to_hub:
|
438 |
+
if training_args.hub_model_id is None:
|
439 |
+
repo_name = get_full_repo_name(
|
440 |
+
Path(training_args.output_dir).absolute().name, token=training_args.hub_token
|
441 |
+
)
|
442 |
+
else:
|
443 |
+
repo_name = training_args.hub_model_id
|
444 |
+
repo = Repository(training_args.output_dir, clone_from=repo_name)
|
445 |
+
|
446 |
+
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
|
447 |
+
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
|
448 |
+
# (the dataset will be downloaded automatically from the datasets Hub).
|
449 |
+
#
|
450 |
+
# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
|
451 |
+
# 'text' is found. You can easily tweak this behavior (see below).
|
452 |
+
if data_args.dataset_name is not None:
|
453 |
+
# Downloading and loading a dataset from the hub.
|
454 |
+
datasets = load_dataset(data_args.dataset_name, data_args.dataset_config_name, cache_dir=model_args.cache_dir)
|
455 |
+
|
456 |
+
if "validation" not in datasets.keys():
|
457 |
+
datasets["validation"] = load_dataset(
|
458 |
+
data_args.dataset_name,
|
459 |
+
data_args.dataset_config_name,
|
460 |
+
split=f"train[:{data_args.validation_split_percentage}%]",
|
461 |
+
cache_dir=model_args.cache_dir,
|
462 |
+
)
|
463 |
+
datasets["train"] = load_dataset(
|
464 |
+
data_args.dataset_name,
|
465 |
+
data_args.dataset_config_name,
|
466 |
+
split=f"train[{data_args.validation_split_percentage}%:]",
|
467 |
+
cache_dir=model_args.cache_dir,
|
468 |
+
)
|
469 |
+
else:
|
470 |
+
data_files = {}
|
471 |
+
if data_args.train_file is not None:
|
472 |
+
data_files["train"] = data_args.train_file
|
473 |
+
if data_args.validation_file is not None:
|
474 |
+
data_files["validation"] = data_args.validation_file
|
475 |
+
extension = data_args.train_file.split(".")[-1]
|
476 |
+
if extension == "txt":
|
477 |
+
extension = "text"
|
478 |
+
datasets = load_dataset(extension, data_files=data_files, cache_dir=model_args.cache_dir)
|
479 |
+
|
480 |
+
if "validation" not in datasets.keys():
|
481 |
+
datasets["validation"] = load_dataset(
|
482 |
+
extension,
|
483 |
+
data_files=data_files,
|
484 |
+
split=f"train[:{data_args.validation_split_percentage}%]",
|
485 |
+
cache_dir=model_args.cache_dir,
|
486 |
+
)
|
487 |
+
datasets["train"] = load_dataset(
|
488 |
+
extension,
|
489 |
+
data_files=data_files,
|
490 |
+
split=f"train[{data_args.validation_split_percentage}%:]",
|
491 |
+
cache_dir=model_args.cache_dir,
|
492 |
+
)
|
493 |
+
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
|
494 |
+
# https://huggingface.co/docs/datasets/loading_datasets.html.
|
495 |
+
|
496 |
+
# Load pretrained model and tokenizer
|
497 |
+
|
498 |
+
if model_args.tokenizer_name:
|
499 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
500 |
+
model_args.tokenizer_name, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
|
501 |
+
)
|
502 |
+
elif model_args.model_name_or_path:
|
503 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
504 |
+
model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
|
505 |
+
)
|
506 |
+
else:
|
507 |
+
raise ValueError(
|
508 |
+
"You are instantiating a new tokenizer from scratch. This is not supported by this script."
|
509 |
+
"You can do it from another script, save it, and load it from here, using --tokenizer_name."
|
510 |
+
)
|
511 |
+
|
512 |
+
if model_args.config_name:
|
513 |
+
config = T5Config.from_pretrained(
|
514 |
+
model_args.config_name, cache_dir=model_args.cache_dir, vocab_size=len(tokenizer)
|
515 |
+
)
|
516 |
+
elif model_args.model_name_or_path:
|
517 |
+
config = T5Config.from_pretrained(
|
518 |
+
model_args.model_name_or_path, cache_dir=model_args.cache_dir, vocab_size=len(tokenizer)
|
519 |
+
)
|
520 |
+
else:
|
521 |
+
config = CONFIG_MAPPING[model_args.model_type]()
|
522 |
+
logger.warning("You are instantiating a new config instance from scratch.")
|
523 |
+
|
524 |
+
# Preprocessing the datasets.
|
525 |
+
# First we tokenize all the texts.
|
526 |
+
if training_args.do_train:
|
527 |
+
column_names = datasets["train"].column_names
|
528 |
+
else:
|
529 |
+
column_names = datasets["validation"].column_names
|
530 |
+
text_column_name = "text" if "text" in column_names else column_names[0]
|
531 |
+
|
532 |
+
max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
|
533 |
+
|
534 |
+
# Otherwise, we tokenize every text, then concatenate them together before splitting them in smaller parts.
|
535 |
+
# Since we make sure that all sequences are of the same length, no attention_mask is needed.
|
536 |
+
def tokenize_function(examples):
|
537 |
+
return tokenizer(examples[text_column_name], return_attention_mask=False)
|
538 |
+
|
539 |
+
tokenized_datasets = datasets.map(
|
540 |
+
tokenize_function,
|
541 |
+
batched=True,
|
542 |
+
num_proc=data_args.preprocessing_num_workers,
|
543 |
+
remove_columns=column_names,
|
544 |
+
load_from_cache_file=not data_args.overwrite_cache,
|
545 |
+
)
|
546 |
+
|
547 |
+
# T5-like span masked language modeling will fuse consecutively masked tokens to a single sentinel token.
|
548 |
+
# To ensure that the input length is `max_seq_length`, we need to increase the maximum length
|
549 |
+
# according to `mlm_probability` and `mean_noise_span_length`. We can also define the label length accordingly.
|
550 |
+
expanded_inputs_length, targets_length = compute_input_and_target_lengths(
|
551 |
+
inputs_length=max_seq_length,
|
552 |
+
noise_density=data_args.mlm_probability,
|
553 |
+
mean_noise_span_length=data_args.mean_noise_span_length,
|
554 |
+
)
|
555 |
+
|
556 |
+
# Main data processing function that will concatenate all texts from our dataset and generate chunks of expanded_inputs_length.
|
557 |
+
def group_texts(examples):
|
558 |
+
# Concatenate all texts.
|
559 |
+
concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()}
|
560 |
+
total_length = len(concatenated_examples[list(examples.keys())[0]])
|
561 |
+
# We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
|
562 |
+
# customize this part to your needs.
|
563 |
+
if total_length >= expanded_inputs_length:
|
564 |
+
total_length = (total_length // expanded_inputs_length) * expanded_inputs_length
|
565 |
+
# Split by chunks of max_len.
|
566 |
+
result = {
|
567 |
+
k: [t[i : i + expanded_inputs_length] for i in range(0, total_length, expanded_inputs_length)]
|
568 |
+
for k, t in concatenated_examples.items()
|
569 |
+
}
|
570 |
+
return result
|
571 |
+
|
572 |
+
# Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a
|
573 |
+
# remainder for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value
|
574 |
+
# might be slower to preprocess.
|
575 |
+
#
|
576 |
+
# To speed up this part, we use multiprocessing. See the documentation of the map method for more information:
|
577 |
+
# https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map
|
578 |
+
tokenized_datasets = tokenized_datasets.map(
|
579 |
+
group_texts,
|
580 |
+
batched=True,
|
581 |
+
num_proc=data_args.preprocessing_num_workers,
|
582 |
+
load_from_cache_file=not data_args.overwrite_cache,
|
583 |
+
)
|
584 |
+
|
585 |
+
# Enable tensorboard only on the master node
|
586 |
+
has_tensorboard = is_tensorboard_available()
|
587 |
+
if has_tensorboard and jax.process_index() == 0:
|
588 |
+
try:
|
589 |
+
from flax.metrics.tensorboard import SummaryWriter
|
590 |
+
|
591 |
+
summary_writer = SummaryWriter(log_dir=Path(training_args.output_dir))
|
592 |
+
except ImportError as ie:
|
593 |
+
has_tensorboard = False
|
594 |
+
logger.warning(
|
595 |
+
f"Unable to display metrics through TensorBoard because some package are not installed: {ie}"
|
596 |
+
)
|
597 |
+
else:
|
598 |
+
logger.warning(
|
599 |
+
"Unable to display metrics through TensorBoard because the package is not installed: "
|
600 |
+
"Please run pip install tensorboard to enable."
|
601 |
+
)
|
602 |
+
|
603 |
+
# Initialize our training
|
604 |
+
rng = jax.random.PRNGKey(training_args.seed)
|
605 |
+
dropout_rngs = jax.random.split(rng, jax.local_device_count())
|
606 |
+
|
607 |
+
if model_args.model_name_or_path:
|
608 |
+
model = FlaxT5ForConditionalGeneration.from_pretrained(
|
609 |
+
model_args.model_name_or_path, config=config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
|
610 |
+
)
|
611 |
+
else:
|
612 |
+
model = FlaxT5ForConditionalGeneration(config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype))
|
613 |
+
|
614 |
+
# Data collator
|
615 |
+
# This one will take care of randomly masking the tokens.
|
616 |
+
data_collator = FlaxDataCollatorForT5MLM(
|
617 |
+
tokenizer=tokenizer,
|
618 |
+
noise_density=data_args.mlm_probability,
|
619 |
+
mean_noise_span_length=data_args.mean_noise_span_length,
|
620 |
+
input_length=max_seq_length,
|
621 |
+
target_length=targets_length,
|
622 |
+
pad_token_id=model.config.pad_token_id,
|
623 |
+
decoder_start_token_id=model.config.decoder_start_token_id,
|
624 |
+
)
|
625 |
+
|
626 |
+
# Store some constant
|
627 |
+
num_epochs = int(training_args.num_train_epochs)
|
628 |
+
train_batch_size = int(training_args.per_device_train_batch_size) * jax.device_count()
|
629 |
+
eval_batch_size = int(training_args.per_device_eval_batch_size) * jax.device_count()
|
630 |
+
|
631 |
+
num_train_steps = len(tokenized_datasets["train"]) // train_batch_size * num_epochs
|
632 |
+
|
633 |
+
# Create learning rate schedule
|
634 |
+
warmup_fn = optax.linear_schedule(
|
635 |
+
init_value=0.0, end_value=training_args.learning_rate, transition_steps=training_args.warmup_steps
|
636 |
+
)
|
637 |
+
decay_fn = optax.linear_schedule(
|
638 |
+
init_value=training_args.learning_rate,
|
639 |
+
end_value=0,
|
640 |
+
transition_steps=num_train_steps - training_args.warmup_steps,
|
641 |
+
)
|
642 |
+
linear_decay_lr_schedule_fn = optax.join_schedules(
|
643 |
+
schedules=[warmup_fn, decay_fn], boundaries=[training_args.warmup_steps]
|
644 |
+
)
|
645 |
+
|
646 |
+
# We use Optax's "masking" functionality to not apply weight decay
|
647 |
+
# to bias and LayerNorm scale parameters. decay_mask_fn returns a
|
648 |
+
# mask boolean with the same structure as the parameters.
|
649 |
+
# The mask is True for parameters that should be decayed.
|
650 |
+
def decay_mask_fn(params):
|
651 |
+
flat_params = traverse_util.flatten_dict(params)
|
652 |
+
flat_mask = {
|
653 |
+
path: (path[-1] != "bias" and path[-2:] not in [("layer_norm", "scale"), ("final_layer_norm", "scale")])
|
654 |
+
for path in flat_params
|
655 |
+
}
|
656 |
+
return traverse_util.unflatten_dict(flat_mask)
|
657 |
+
|
658 |
+
# create adam optimizer
|
659 |
+
if training_args.adafactor:
|
660 |
+
# We use the default parameters here to initialize adafactor,
|
661 |
+
# For more details about the parameters please check https://github.com/deepmind/optax/blob/ed02befef9bf81cbbf236be3d2b0e032e9ed4a40/optax/_src/alias.py#L74
|
662 |
+
optimizer = optax.adafactor(
|
663 |
+
learning_rate=linear_decay_lr_schedule_fn,
|
664 |
+
)
|
665 |
+
else:
|
666 |
+
optimizer = optax.adamw(
|
667 |
+
learning_rate=linear_decay_lr_schedule_fn,
|
668 |
+
b1=training_args.adam_beta1,
|
669 |
+
b2=training_args.adam_beta2,
|
670 |
+
weight_decay=training_args.weight_decay,
|
671 |
+
mask=decay_mask_fn,
|
672 |
+
)
|
673 |
+
|
674 |
+
# Setup train state
|
675 |
+
state = train_state.TrainState.create(apply_fn=model.__call__, params=model.params, tx=optimizer)
|
676 |
+
|
677 |
+
# Define gradient update step fn
|
678 |
+
def train_step(state, batch, dropout_rng):
|
679 |
+
dropout_rng, new_dropout_rng = jax.random.split(dropout_rng)
|
680 |
+
|
681 |
+
def loss_fn(params):
|
682 |
+
labels = batch.pop("labels")
|
683 |
+
|
684 |
+
logits = state.apply_fn(**batch, params=params, dropout_rng=dropout_rng, train=True)[0]
|
685 |
+
|
686 |
+
# compute loss
|
687 |
+
loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])).mean()
|
688 |
+
|
689 |
+
return loss
|
690 |
+
|
691 |
+
grad_fn = jax.value_and_grad(loss_fn)
|
692 |
+
loss, grad = grad_fn(state.params)
|
693 |
+
grad = jax.lax.pmean(grad, "batch")
|
694 |
+
new_state = state.apply_gradients(grads=grad)
|
695 |
+
|
696 |
+
metrics = jax.lax.pmean(
|
697 |
+
{"loss": loss, "learning_rate": linear_decay_lr_schedule_fn(state.step)}, axis_name="batch"
|
698 |
+
)
|
699 |
+
|
700 |
+
return new_state, metrics, new_dropout_rng
|
701 |
+
|
702 |
+
# Create parallel version of the train step
|
703 |
+
p_train_step = jax.pmap(train_step, "batch", donate_argnums=(0,))
|
704 |
+
|
705 |
+
# Define eval fn
|
706 |
+
def eval_step(params, batch):
|
707 |
+
labels = batch.pop("labels")
|
708 |
+
|
709 |
+
logits = model(**batch, params=params, train=False)[0]
|
710 |
+
|
711 |
+
# compute loss
|
712 |
+
loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1]))
|
713 |
+
|
714 |
+
# compute accuracy
|
715 |
+
accuracy = jnp.equal(jnp.argmax(logits, axis=-1), labels)
|
716 |
+
|
717 |
+
# summarize metrics
|
718 |
+
metrics = {"loss": loss.mean(), "accuracy": accuracy.mean()}
|
719 |
+
metrics = jax.lax.pmean(metrics, axis_name="batch")
|
720 |
+
|
721 |
+
return metrics
|
722 |
+
|
723 |
+
p_eval_step = jax.pmap(eval_step, "batch", donate_argnums=(0,))
|
724 |
+
|
725 |
+
# Replicate the train state on each device
|
726 |
+
state = jax_utils.replicate(state)
|
727 |
+
|
728 |
+
train_time = 0
|
729 |
+
epochs = tqdm(range(num_epochs), desc="Epoch ... ", position=0)
|
730 |
+
for epoch in epochs:
|
731 |
+
# ======================== Training ================================
|
732 |
+
train_start = time.time()
|
733 |
+
train_metrics = []
|
734 |
+
|
735 |
+
# Create sampling rng
|
736 |
+
rng, input_rng = jax.random.split(rng)
|
737 |
+
|
738 |
+
# Generate an epoch by shuffling sampling indices from the train dataset
|
739 |
+
num_train_samples = len(tokenized_datasets["train"])
|
740 |
+
train_samples_idx = jax.random.permutation(input_rng, jnp.arange(num_train_samples))
|
741 |
+
train_batch_idx = generate_batch_splits(train_samples_idx, train_batch_size)
|
742 |
+
|
743 |
+
# Gather the indexes for creating the batch and do a training step
|
744 |
+
for step, batch_idx in enumerate(tqdm(train_batch_idx, desc="Training...", position=1)):
|
745 |
+
samples = [tokenized_datasets["train"][int(idx)] for idx in batch_idx]
|
746 |
+
model_inputs = data_collator(samples)
|
747 |
+
|
748 |
+
# Model forward
|
749 |
+
model_inputs = shard(model_inputs.data)
|
750 |
+
state, train_metric, dropout_rngs = p_train_step(state, model_inputs, dropout_rngs)
|
751 |
+
train_metrics.append(train_metric)
|
752 |
+
|
753 |
+
cur_step = epoch * (num_train_samples // train_batch_size) + step
|
754 |
+
|
755 |
+
if cur_step % training_args.logging_steps == 0 and cur_step > 0:
|
756 |
+
# Save metrics
|
757 |
+
train_metric = jax_utils.unreplicate(train_metric)
|
758 |
+
train_time += time.time() - train_start
|
759 |
+
if has_tensorboard and jax.process_index() == 0:
|
760 |
+
write_train_metric(summary_writer, train_metrics, train_time, cur_step)
|
761 |
+
|
762 |
+
epochs.write(
|
763 |
+
f"Step... ({cur_step} | Loss: {train_metric['loss'].mean()}, Learning Rate: {train_metric['learning_rate'].mean()})"
|
764 |
+
)
|
765 |
+
|
766 |
+
train_metrics = []
|
767 |
+
|
768 |
+
if cur_step % training_args.eval_steps == 0 and cur_step > 0:
|
769 |
+
# ======================== Evaluating ==============================
|
770 |
+
num_eval_samples = len(tokenized_datasets["validation"])
|
771 |
+
eval_samples_idx = jnp.arange(num_eval_samples)
|
772 |
+
eval_batch_idx = generate_batch_splits(eval_samples_idx, eval_batch_size)
|
773 |
+
|
774 |
+
eval_metrics = []
|
775 |
+
for i, batch_idx in enumerate(tqdm(eval_batch_idx, desc="Evaluating ...", position=2)):
|
776 |
+
samples = [tokenized_datasets["validation"][int(idx)] for idx in batch_idx]
|
777 |
+
model_inputs = data_collator(samples)
|
778 |
+
|
779 |
+
# Model forward
|
780 |
+
model_inputs = shard(model_inputs.data)
|
781 |
+
metrics = p_eval_step(state.params, model_inputs)
|
782 |
+
eval_metrics.append(metrics)
|
783 |
+
|
784 |
+
# get eval metrics
|
785 |
+
eval_metrics = get_metrics(eval_metrics)
|
786 |
+
eval_metrics = jax.tree_map(jnp.mean, eval_metrics)
|
787 |
+
|
788 |
+
# Update progress bar
|
789 |
+
epochs.write(f"Step... ({cur_step} | Loss: {eval_metrics['loss']}, Acc: {eval_metrics['accuracy']})")
|
790 |
+
|
791 |
+
# Save metrics
|
792 |
+
if has_tensorboard and jax.process_index() == 0:
|
793 |
+
write_eval_metric(summary_writer, eval_metrics, cur_step)
|
794 |
+
|
795 |
+
if cur_step % training_args.save_steps == 0 and cur_step > 0:
|
796 |
+
# save checkpoint after each epoch and push checkpoint to the hub
|
797 |
+
if jax.process_index() == 0:
|
798 |
+
params = jax.device_get(jax.tree_map(lambda x: x[0], state.params))
|
799 |
+
model.save_pretrained(training_args.output_dir, params=params)
|
800 |
+
tokenizer.save_pretrained(training_args.output_dir)
|
801 |
+
if training_args.push_to_hub:
|
802 |
+
repo.push_to_hub(commit_message=f"Saving weights and logs of step {cur_step}", blocking=False)
|
t5_tokenizer_model.py
ADDED
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
import json
|
3 |
+
from typing import Iterator, List, Union
|
4 |
+
|
5 |
+
from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers
|
6 |
+
from tokenizers.implementations.base_tokenizer import BaseTokenizer
|
7 |
+
from tokenizers.models import BPE, Unigram
|
8 |
+
from tokenizers.processors import TemplateProcessing
|
9 |
+
|
10 |
+
|
11 |
+
class SentencePieceUnigramTokenizer(BaseTokenizer):
|
12 |
+
"""
|
13 |
+
This class is a copy of `DeDLOC's tokenizer implementation <https://github.com/yandex-research/DeDLOC/blob/main/sahajbert/tokenizer/tokenizer_model.py>`__ .
|
14 |
+
Custom SentencePiece Unigram Tokenizer with NMT, NKFC, spaces and lower-casing characters normalization
|
15 |
+
Represents the Unigram algorithm, with the pretokenization used by SentencePiece
|
16 |
+
"""
|
17 |
+
|
18 |
+
def __init__(
|
19 |
+
self,
|
20 |
+
replacement: str = "▁",
|
21 |
+
add_prefix_space: bool = True,
|
22 |
+
unk_token: Union[str, AddedToken] = "<unk>",
|
23 |
+
eos_token: Union[str, AddedToken] = "</s>",
|
24 |
+
pad_token: Union[str, AddedToken] = "<pad>",
|
25 |
+
):
|
26 |
+
self.special_tokens = {
|
27 |
+
"pad": {"id": 0, "token": pad_token},
|
28 |
+
"eos": {"id": 1, "token": eos_token},
|
29 |
+
"unk": {"id": 2, "token": unk_token},
|
30 |
+
}
|
31 |
+
|
32 |
+
self.special_tokens_list = [None] * len(self.special_tokens)
|
33 |
+
for token_dict in self.special_tokens.values():
|
34 |
+
self.special_tokens_list[token_dict["id"]] = token_dict["token"]
|
35 |
+
|
36 |
+
tokenizer = Tokenizer(Unigram())
|
37 |
+
|
38 |
+
tokenizer.normalizer = normalizers.Sequence(
|
39 |
+
[
|
40 |
+
normalizers.Nmt(),
|
41 |
+
normalizers.NFKC(),
|
42 |
+
normalizers.Replace(Regex(" {2,}"), " "),
|
43 |
+
#commented to be cased
|
44 |
+
#normalizers.Lowercase(),
|
45 |
+
]
|
46 |
+
)
|
47 |
+
tokenizer.pre_tokenizer = pre_tokenizers.Sequence(
|
48 |
+
[
|
49 |
+
#pre_tokenizers.Metaspace(replacement=replacement, add_prefix_space=add_prefix_space),
|
50 |
+
#pre_tokenizers.Split(pattern='&',behavior='removed',invert=False),
|
51 |
+
#pre_tokenizers.Digits(),#individual_digits=True
|
52 |
+
pre_tokenizers.Metaspace(replacement=replacement, add_prefix_space=add_prefix_space),
|
53 |
+
#pre_tokenizers.Punctuation(),
|
54 |
+
]
|
55 |
+
)
|
56 |
+
tokenizer.decoder = decoders.Metaspace(replacement=replacement, add_prefix_space=add_prefix_space)
|
57 |
+
|
58 |
+
tokenizer.post_processor = TemplateProcessing(
|
59 |
+
single=f"$A {self.special_tokens['eos']['token']}",
|
60 |
+
special_tokens=[(self.special_tokens["eos"]["token"], self.special_tokens["eos"]["id"])],
|
61 |
+
)
|
62 |
+
|
63 |
+
parameters = {
|
64 |
+
"model": "SentencePieceUnigram",
|
65 |
+
"replacement": replacement,
|
66 |
+
"add_prefix_space": add_prefix_space,
|
67 |
+
}
|
68 |
+
|
69 |
+
super().__init__(tokenizer, parameters)
|
70 |
+
|
71 |
+
def train(
|
72 |
+
self,
|
73 |
+
files: Union[str, List[str]],
|
74 |
+
vocab_size: int = 8000,
|
75 |
+
show_progress: bool = True,
|
76 |
+
):
|
77 |
+
"""Train the model using the given files"""
|
78 |
+
|
79 |
+
trainer = trainers.UnigramTrainer(
|
80 |
+
vocab_size=vocab_size,
|
81 |
+
special_tokens=self.special_tokens_list,
|
82 |
+
show_progress=show_progress,
|
83 |
+
)
|
84 |
+
|
85 |
+
if isinstance(files, str):
|
86 |
+
files = [files]
|
87 |
+
self._tokenizer.train(files, trainer=trainer)
|
88 |
+
|
89 |
+
self.add_unk_id()
|
90 |
+
|
91 |
+
def train_from_iterator(
|
92 |
+
self,
|
93 |
+
iterator: Union[Iterator[str], Iterator[Iterator[str]]],
|
94 |
+
vocab_size: int = 8000,
|
95 |
+
show_progress: bool = True,
|
96 |
+
):
|
97 |
+
"""Train the model using the given iterator"""
|
98 |
+
|
99 |
+
trainer = trainers.UnigramTrainer(
|
100 |
+
vocab_size=vocab_size,
|
101 |
+
special_tokens=self.special_tokens_list,
|
102 |
+
show_progress=show_progress,
|
103 |
+
)
|
104 |
+
|
105 |
+
self._tokenizer.train_from_iterator(iterator, trainer=trainer)
|
106 |
+
|
107 |
+
self.add_unk_id()
|
108 |
+
|
109 |
+
def add_unk_id(self):
|
110 |
+
tokenizer_json = json.loads(self._tokenizer.to_str())
|
111 |
+
|
112 |
+
tokenizer_json["model"]["unk_id"] = self.special_tokens["unk"]["id"]
|
113 |
+
|
114 |
+
self._tokenizer = Tokenizer.from_str(json.dumps(tokenizer_json))
|
115 |
+
|
116 |
+
class SentencePieceBPETokenizer(BaseTokenizer):
|
117 |
+
"""
|
118 |
+
This class is a copy of `DeDLOC's tokenizer implementation <https://github.com/yandex-research/DeDLOC/blob/main/sahajbert/tokenizer/tokenizer_model.py>`__ .
|
119 |
+
Custom SentencePiece Unigram Tokenizer with NMT, NKFC, spaces and lower-casing characters normalization
|
120 |
+
Represents the Unigram algorithm, with the pretokenization used by SentencePiece
|
121 |
+
"""
|
122 |
+
|
123 |
+
def __init__(
|
124 |
+
self,
|
125 |
+
replacement: str = "▁",
|
126 |
+
add_prefix_space: bool = True,
|
127 |
+
unk_token: Union[str, AddedToken] = "<unk>",
|
128 |
+
eos_token: Union[str, AddedToken] = "</s>",
|
129 |
+
pad_token: Union[str, AddedToken] = "<pad>",
|
130 |
+
):
|
131 |
+
self.special_tokens = {
|
132 |
+
"pad": {"id": 0, "token": pad_token},
|
133 |
+
"eos": {"id": 1, "token": eos_token},
|
134 |
+
"unk": {"id": 2, "token": unk_token},
|
135 |
+
}
|
136 |
+
|
137 |
+
self.special_tokens_list = [None] * len(self.special_tokens)
|
138 |
+
for token_dict in self.special_tokens.values():
|
139 |
+
self.special_tokens_list[token_dict["id"]] = token_dict["token"]
|
140 |
+
|
141 |
+
tokenizer = Tokenizer(BPE())
|
142 |
+
|
143 |
+
tokenizer.normalizer = normalizers.Sequence(
|
144 |
+
[
|
145 |
+
normalizers.Nmt(),
|
146 |
+
normalizers.NFKC(),
|
147 |
+
normalizers.Replace(Regex(" {2,}"), " "),
|
148 |
+
#commented to be cased
|
149 |
+
#normalizers.Lowercase(),
|
150 |
+
]
|
151 |
+
)
|
152 |
+
tokenizer.pre_tokenizer = pre_tokenizers.Sequence(
|
153 |
+
[
|
154 |
+
#pre_tokenizers.Metaspace(replacement=replacement, add_prefix_space=add_prefix_space),
|
155 |
+
pre_tokenizers.Digits(individual_digits=True),
|
156 |
+
pre_tokenizers.Punctuation(),
|
157 |
+
]
|
158 |
+
)
|
159 |
+
#tokenizer.decoder = decoders.Metaspace(replacement=replacement, add_prefix_space=add_prefix_space)
|
160 |
+
|
161 |
+
tokenizer.post_processor = TemplateProcessing(
|
162 |
+
single=f"$A {self.special_tokens['eos']['token']}",
|
163 |
+
special_tokens=[(self.special_tokens["eos"]["token"], self.special_tokens["eos"]["id"])],
|
164 |
+
)
|
165 |
+
|
166 |
+
parameters = {
|
167 |
+
"model": "SentencePieceBPE",
|
168 |
+
"replacement": replacement,
|
169 |
+
"add_prefix_space": add_prefix_space,
|
170 |
+
}
|
171 |
+
|
172 |
+
super().__init__(tokenizer, parameters)
|
173 |
+
|
174 |
+
def train(
|
175 |
+
self,
|
176 |
+
files: Union[str, List[str]],
|
177 |
+
vocab_size: int = 8000,
|
178 |
+
show_progress: bool = True,
|
179 |
+
):
|
180 |
+
"""Train the model using the given files"""
|
181 |
+
|
182 |
+
trainer = trainers.BpeTrainer(
|
183 |
+
vocab_size=vocab_size,
|
184 |
+
special_tokens=self.special_tokens_list,
|
185 |
+
show_progress=show_progress,
|
186 |
+
)
|
187 |
+
|
188 |
+
if isinstance(files, str):
|
189 |
+
files = [files]
|
190 |
+
self._tokenizer.train(files, trainer=trainer)
|
191 |
+
|
192 |
+
self.add_unk_id()
|
193 |
+
|
194 |
+
def train_from_iterator(
|
195 |
+
self,
|
196 |
+
iterator: Union[Iterator[str], Iterator[Iterator[str]]],
|
197 |
+
vocab_size: int = 8000,
|
198 |
+
show_progress: bool = True,
|
199 |
+
):
|
200 |
+
"""Train the model using the given iterator"""
|
201 |
+
|
202 |
+
trainer = trainers.BpeTrainer(
|
203 |
+
vocab_size=vocab_size,
|
204 |
+
special_tokens=self.special_tokens_list,
|
205 |
+
show_progress=show_progress,
|
206 |
+
)
|
207 |
+
|
208 |
+
self._tokenizer.train_from_iterator(iterator, trainer=trainer)
|
209 |
+
|
210 |
+
self.add_unk_id()
|
211 |
+
|
212 |
+
def add_unk_id(self):
|
213 |
+
tokenizer_json = json.loads(self._tokenizer.to_str())
|
214 |
+
|
215 |
+
tokenizer_json["model"]["unk_id"] = self.special_tokens["unk"]["id"]
|
216 |
+
|
217 |
+
self._tokenizer = Tokenizer.from_str(json.dumps(tokenizer_json))
|
tokenizer-trainer_atom.py
ADDED
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pandas as pd
|
3 |
+
import re
|
4 |
+
from t5_tokenizer_model import SentencePieceAtomwiseTokenizer
|
5 |
+
from pretokenizer import atomwise_tokenizer
|
6 |
+
from tqdm import tqdm
|
7 |
+
|
8 |
+
|
9 |
+
|
10 |
+
vocab_size = 32_000
|
11 |
+
input_sentence_size = None
|
12 |
+
|
13 |
+
# Initialize a dataset
|
14 |
+
#dataset = load_dataset('csv', data_files='/home/zoez/Chem-T5/train-file.csv',split="train")
|
15 |
+
dataset = pd.read_csv('/home/zoez/Chem-T5/train-file.csv')
|
16 |
+
|
17 |
+
tokenizer = SentencePieceAtomwiseTokenizer(unk_token="<unk>", eos_token="</s>", pad_token="<pad>")
|
18 |
+
dataset.columns=['SMILES']
|
19 |
+
#print(dataset.columns)
|
20 |
+
dataset=pd.DataFrame(columns=['SMILES','SMILESs'],data=dataset)
|
21 |
+
dataset.fillna('', inplace=True)
|
22 |
+
#print(dataset.iloc[0])
|
23 |
+
#trainset=pd.DataFrame(columns=['SMILESs'])
|
24 |
+
|
25 |
+
for i, line in tqdm(enumerate(dataset['SMILES'])):
|
26 |
+
line = re.sub('\d+\t', '',line)
|
27 |
+
#print(line)
|
28 |
+
newLine=atomwise_tokenizer(line)
|
29 |
+
#print(newLine)
|
30 |
+
#print(int(i/10))
|
31 |
+
dataset.iloc[int(i/50)]['SMILESs']+="&"+newLine
|
32 |
+
#print(dataset.loc[int(i/10)]['SMILESs'])
|
33 |
+
#dataset.iloc[i]['SMILES']=newLine
|
34 |
+
#dataset = dataset.iloc
|
35 |
+
|
36 |
+
#print(dataset.iloc[5]['SMILESs'])
|
37 |
+
# Build an iterator over this dataset
|
38 |
+
def batch_iterator(input_sentence_size=None):
|
39 |
+
if input_sentence_size is None:
|
40 |
+
input_sentence_size = len(dataset)
|
41 |
+
batch_length = 100
|
42 |
+
for i in range(0, input_sentence_size, batch_length):
|
43 |
+
#print(dataset[i: i + batch_length]['SMILES'])
|
44 |
+
yield dataset[i: i + batch_length]['SMILESs']
|
45 |
+
|
46 |
+
|
47 |
+
# Train tokenizer
|
48 |
+
tokenizer.train_from_iterator(
|
49 |
+
iterator=batch_iterator(input_sentence_size=input_sentence_size),
|
50 |
+
vocab_size=vocab_size,
|
51 |
+
show_progress=True,
|
52 |
+
)
|
53 |
+
|
54 |
+
|
55 |
+
# Save files to disk
|
56 |
+
tokenizer.save("/home/zoez/chemT5/tokenizer.json")
|
57 |
+
|
58 |
+
|
59 |
+
print(tokenizer.encode(atomwise_tokenizer("O=[N+]([O-])c1ccc(Cl)cc1O=[N+]([O-])c1ccc(Cl)cc1")).tokens)
|
60 |
+
|
61 |
+
#from transformers import T5Config
|
62 |
+
|
63 |
+
|
64 |
+
#config = T5Config.from_pretrained("google/t5-v1_1-base", vocab_size=tokenizer.get_vocab_size())
|
65 |
+
#config.save_pretrained("/home/zoez/chem-T5")
|
tokenizer-trainer_uni.py
ADDED
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pandas as pd
|
3 |
+
import re
|
4 |
+
from t5_tokenizer_model import SentencePieceUnigramTokenizer
|
5 |
+
#from pretokenizer import atomwise_tokenizer
|
6 |
+
from tqdm import tqdm
|
7 |
+
|
8 |
+
|
9 |
+
|
10 |
+
vocab_size = 32_000
|
11 |
+
input_sentence_size = None
|
12 |
+
|
13 |
+
# Initialize a dataset
|
14 |
+
#dataset = load_dataset('csv', data_files='/home/zoez/Chem-T5/train-file.csv',split="train")
|
15 |
+
dataset = pd.read_csv('./chemT5_data.csv')#('/home/zoez/Chem-T5/train-file.csv')
|
16 |
+
#print(dataset.iloc[0])
|
17 |
+
tokenizer = SentencePieceUnigramTokenizer(unk_token="<unk>", eos_token="</s>", pad_token="<pad>")
|
18 |
+
dataset=pd.DataFrame(columns=['SMILES'],data=dataset)
|
19 |
+
#dataset.drop('Unnamed: 0',1)
|
20 |
+
#print(dataset.columns)
|
21 |
+
dataset.columns=['SMILES']
|
22 |
+
|
23 |
+
|
24 |
+
dataset.fillna('', inplace=True)
|
25 |
+
#print(dataset.iloc[0])
|
26 |
+
#trainset=pd.DataFrame(columns=['SMILESs'])
|
27 |
+
|
28 |
+
#dataset = dataset.iloc[:10000]
|
29 |
+
for i, line in tqdm(enumerate(dataset['SMILES'])):
|
30 |
+
#line = re.sub('\d+\t', '',line)
|
31 |
+
#print(line)
|
32 |
+
newLine=line#atomwise_tokenizer(line)
|
33 |
+
#print(newLine)
|
34 |
+
#print(int(i/10))
|
35 |
+
dataset.iloc[i]['SMILES']=newLine
|
36 |
+
#print(dataset.loc[int(i/10)]['SMILESs'])
|
37 |
+
#dataset.iloc[i]['SMILES']=newLine
|
38 |
+
#dataset = dataset.iloc
|
39 |
+
|
40 |
+
#print(dataset.iloc[5]['SMILESs'])
|
41 |
+
# Build an iterator over this dataset
|
42 |
+
def batch_iterator(input_sentence_size=None):
|
43 |
+
if input_sentence_size is None:
|
44 |
+
input_sentence_size = len(dataset)
|
45 |
+
batch_length = 100
|
46 |
+
for i in range(0, input_sentence_size, batch_length):
|
47 |
+
#print(dataset[i: i + batch_length]['SMILES'])
|
48 |
+
yield dataset[i: i + batch_length]['SMILES']
|
49 |
+
|
50 |
+
|
51 |
+
# Train tokenizer
|
52 |
+
tokenizer.train_from_iterator(
|
53 |
+
iterator=batch_iterator(input_sentence_size=input_sentence_size),
|
54 |
+
vocab_size=vocab_size,
|
55 |
+
show_progress=True,
|
56 |
+
)
|
57 |
+
|
58 |
+
|
59 |
+
# Save files to disk
|
60 |
+
tokenizer.save("/home/zoez/chemT5/uni-tokenizer.json")
|
61 |
+
|
62 |
+
|
63 |
+
print(tokenizer.encode("O=[N+]([O-])c1ccc(Cl)cc1").tokens)
|
64 |
+
|
65 |
+
from transformers import T5Config
|
66 |
+
|
67 |
+
|
68 |
+
config = T5Config.from_pretrained("google/t5-v1_1-base", vocab_size=tokenizer.get_vocab_size())
|
69 |
+
config.save_pretrained("./")
|
train_scprit.sh
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env bash
|
2 |
+
python run_t5_mlm_flax.py \
|
3 |
+
--output_dir="./" \
|
4 |
+
--model_type="t5" \
|
5 |
+
--config_name="./" \
|
6 |
+
--tokenizer_name="./" \
|
7 |
+
--train_file="chemT5_data.csv" \
|
8 |
+
--max_seq_length="256" \
|
9 |
+
--per_device_train_batch_size="16" \
|
10 |
+
--per_device_eval_batch_size="16" \
|
11 |
+
--adafactor \
|
12 |
+
--learning_rate="0.005" \
|
13 |
+
--weight_decay="0.001" \
|
14 |
+
--warmup_steps="2000" \
|
15 |
+
--overwrite_output_dir \
|
16 |
+
--logging_steps="500" \
|
17 |
+
--save_steps="10000" \
|
18 |
+
--eval_steps="2500" \
|
19 |
+
--push_to_hub
|
20 |
+
|
21 |
+
|
22 |
+
|
try.py
ADDED
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#from rdkit import Chem
|
2 |
+
import tensorflow as tf
|
3 |
+
import torch as pt
|
4 |
+
#from t5_tokenizer_model import SentencePieceUnigramTokenizer
|
5 |
+
from pretokenizer import atomwise_tokenizer
|
6 |
+
from transformers import AutoTokenizer, T5Tokenizer, T5ForConditionalGeneration, T5Config
|
7 |
+
from tokenizers import Tokenizer
|
8 |
+
import numpy as np
|
9 |
+
|
10 |
+
|
11 |
+
#device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
12 |
+
|
13 |
+
|
14 |
+
|
15 |
+
|
16 |
+
#model = T5ForConditionalGeneration.from_pretrained(pretrained_model_name_or_path="/home/zoez/Chem-T5", from_flax=True)
|
17 |
+
tokenizer = AutoTokenizer.from_pretrained("/home/zoez/chemT5")
|
18 |
+
#tokenizer = Tokenizer.from_file("/home/zoez/Chem-T5/tokenizer.json")
|
19 |
+
#model = model.to(device)
|
20 |
+
|
21 |
+
print(tokenizer.encode(atomwise_tokenizer("O=[N+]([O-])c1ccc(Cl)cc1O=[N+]([O-])c1ccc(Cl)cc1")).tokens)
|
22 |
+
|
23 |
+
|
24 |
+
# # encode context the generation is conditioned on
|
25 |
+
# input_ids1 = tokenizer.encode(": O[N+]([O-])c1ccc(Cl)cc1",return_tensors='pt')
|
26 |
+
|
27 |
+
# # activate beam search and early_stopping
|
28 |
+
# beam_output1 = model.generate(
|
29 |
+
# input_ids1,
|
30 |
+
# max_length=50,
|
31 |
+
# num_beams=5,
|
32 |
+
# early_stopping=True
|
33 |
+
# )
|
34 |
+
# #print(tokenizer.encode("O=[N+]([O-])c1ccc(Cl)cc1").tokens)
|
35 |
+
# print("Output: 1\n" + 100 * '-')
|
36 |
+
# print(tokenizer.decode(beam_output1[0], skip_special_tokens=True))
|
37 |
+
|
38 |
+
# # encode context the generation is conditioned on
|
39 |
+
# input_ids2 = tokenizer.encode("SMILES: ",return_tensors='pt')
|
40 |
+
|
41 |
+
# # activate beam search and early_stopping
|
42 |
+
# beam_output2 = model.generate(
|
43 |
+
# input_ids2,
|
44 |
+
# max_length=50,
|
45 |
+
# num_beams=9,
|
46 |
+
# no_repeat_ngram_size=2,
|
47 |
+
# num_return_sequences=9,
|
48 |
+
# early_stopping=True
|
49 |
+
# )
|
50 |
+
# #print(tokenizer.encode("O=[N+]([O-])c1ccc(Cl)cc1").tokens)
|
51 |
+
# print("Output: 2\n" + 100 * '-')
|
52 |
+
# #print(tokenizer.decode(beam_output2[0], skip_special_tokens=True))
|
53 |
+
|
54 |
+
# #start = latent_to_string(latent0)
|
55 |
+
# #destination = latent_to_string(latent1)
|
56 |
+
# mols1 = []
|
57 |
+
# step = np.linspace(0,1,100)
|
58 |
+
# invalid = 0
|
59 |
+
# steps = []
|
60 |
+
# step_invalid = []
|
61 |
+
# # Generate molcules using interpolation
|
62 |
+
# for i, beam in enumerate(beam_output2):
|
63 |
+
# #target_latent = (1.0-step[i])*latent0 + step[i]*latent1
|
64 |
+
# #string = latent_to_string(target_latent)
|
65 |
+
# smiles = tokenizer.decode(beam, skip_special_tokens=True) # when using smies
|
66 |
+
# print(tokenizer.decode(beam, skip_special_tokens=True))
|
67 |
+
# #smiles = sel.decoder(string) # when using SELFIES
|
68 |
+
# mol = Chem.MolFromSmiles(smiles)
|
69 |
+
# if mol:
|
70 |
+
# if smiles not in mols1:
|
71 |
+
# mols1.append(smiles)
|
72 |
+
# steps.append(i)
|
73 |
+
# else:
|
74 |
+
# invalid = invalid + 1
|
75 |
+
# step_invalid.append(i)
|
76 |
+
# #print("starting mol:", start)
|
77 |
+
# #print('destination mol:', destination)
|
78 |
+
# print("generated mols:", mols1)
|
79 |
+
|