├── LICENSE ├── README.md ├── config.yaml ├── main.py ├── models.py ├── requirements.txt └── tokenizer.py /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Japanese RoBERTa 2 | This repository provides snippets to use RoBERTa pre-trained on Japanese corpus. 3 | Our dataset consists of Japanese Wikipedia and web-scrolled articles, 25GB in total. 4 | The released model is built based on that from [HuggingFace](https://huggingface.co/docs/transformers/index). 5 | 6 | ## Details 7 | 8 | ### Preprocessing 9 | We used [Juman++](https://github.com/ku-nlp/jumanpp) (version 2.0.0-rc3) as a morphological analyzer, 10 | and also applied WordPiece embedding ([subword-nmt](https://github.com/rsennrich/subword-nmt)) to split each word into word pieces. 11 | 12 | ### Model 13 | Configurations of our model are following. 14 | Please refer to [HuggingFace page](https://huggingface.co/docs/transformers/model_doc/roberta#transformers.RobertaConfig) for definitions of each parameter. 15 | ~~~ 16 | { 17 | "attention_probs_dropout_prob": 0.1, 18 | "bos_token_id": 3, 19 | "classifier_dropout": null, 20 | "eos_token_id": 0, 21 | "gradient_checkpointing": false, 22 | "hidden_act": "gelu", 23 | "hidden_dropout_prob": 0.1, 24 | "hidden_size": 768, 25 | "initializer_range": 0.02, 26 | "intermediate_size": 3072, 27 | "layer_norm_eps": 1e-12, 28 | "max_position_embeddings": 515, 29 | "max_seq_length": 512, 30 | "model_type": "roberta", 31 | "num_attention_heads": 12, 32 | "num_hidden_layers": 12, 33 | "pad_token_id": 2, 34 | "position_embedding_type": "absolute", 35 | "transformers_version": "4.16.2", 36 | "type_vocab_size": 2, 37 | "use_cache": true, 38 | "vocab_size": 32005 39 | } 40 | ~~~ 41 | ### Training 42 | We trained our model in the same way as RoBERTa. We optimized our model using the masked language modeling (MLM) objective. 43 | The accuracy of the MLM is 72.0%. 44 | 45 | ## How to use our model 46 | 1. Install Juman++ following the instructions from [this repository](https://github.com/ku-nlp/jumanpp). 47 | 2. Install PyTorch following the instructions from [this page](https://pytorch.org/get-started/locally/#start-locally). 48 | 3. Install all of the necessary python packages. 49 | ~~~ 50 | pip install -r requirements.txt 51 | ~~~ 52 | 4. Download weight files and configuration files. 53 | 54 | | Files | Description | 55 | | --- | --- | 56 | | [roberta.pth](https://ifx-bert.s3.ap-northeast-1.amazonaws.com/files/roberta.pth) | Trained weights of RobertaModel from HuggingFace | 57 | | [linear_word.pth](https://ifx-bert.s3.ap-northeast-1.amazonaws.com/files/linear_word.pth) | Trained weights of linear layer for MLM | 58 | | [roberta_config.json](https://ifx-bert.s3.ap-northeast-1.amazonaws.com/files/roberta_config.json) | Configurations for RobertaModel | 59 | | [bpe.txt](https://ifx-bert.s3.ap-northeast-1.amazonaws.com/files/bpe.txt) | Rules for splitting each word into word pieces | 60 | | [bpe_dict.csv](https://ifx-bert.s3.ap-northeast-1.amazonaws.com/files/bpe_dict.csv) | Dictionary of word pieces | 61 | 62 | 5. Load weights and configurations. 63 | ~~~ 64 | # Paths to each file 65 | bpe_file = 66 | count_file = 67 | roberta_config_path = 68 | juman_config_path = 69 | 70 | roberta_weight_path = 71 | linear_weight_path = 72 | 73 | # load tokenizer 74 | processor = TextProcessor(bpe_file=bpe_file, count_file=count_file) 75 | 76 | # load pretrained roberta model 77 | with open(roberta_config_path, "r") as f: 78 | config_dict = json.load(f) 79 | config_bert = RobertaConfig().from_dict(config_dict) 80 | roberta = RobertaModel(config=config_roberta) 81 | roberta.load_state_dict(torch.load(roberta_weight_path, map_location=device)) 82 | 83 | # load pretained decoder 84 | ifxroberta = IFXRoberta(roberta) 85 | ifxroberta.linear_word.load_state_dict(torch.load(linear_weight_path, map_location=device)) 86 | ~~~ 87 | 6. Encode inputs. 88 | ~~~ 89 | # infer 90 | inp_text = "コンピュータ技術およびその関連技術に対する研究開発に努め、自己研鑽に励み、専門的な技術集団を形成する。" 91 | bpe_text = processor.encode(inp_text) 92 | with torch.no_grad(): 93 | inp_tensor = torch.LongTensor([bpe_text]) 94 | inp_tensor.to(device) 95 | out_tensor = ifxroberta(inp_tensor) 96 | ~~~ 97 | 7. Decode model outputs. 98 | ~~~ 99 | # decoding output 100 | out_text_code = torch.max(out_tensor, dim=-1, keepdim=True)[1][0] 101 | ids = out_text_code.squeeze(-1).cpu().numpy().tolist() 102 | ignore_idx = np.where(np.array(bpe_ids) < 5)[0] 103 | out_text = processor.decode(ids, ignore_idx=ignore_idx) 104 | ~~~ 105 | 8. `main.py` helps you understand how to use our model. 106 | 107 | ## License 108 | [The Apache 2.0 license](https://www.apache.org/licenses/LICENSE-2.0) 109 | -------------------------------------------------------------------------------- /config.yaml: -------------------------------------------------------------------------------- 1 | file_paths: 2 | bpe_file: "\bpe.txt" 3 | count_file: "\bpe_dict.csv" 4 | roberta_weight: "\roberta.pth" 5 | linear_weight: "\linear_word.pth" 6 | roberta_config: "\roberta_config.json" 7 | juman_config: # Path to config file for juman. Default is none 8 | 9 | device_type: "cuda" 10 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | # Copyright 2022 Informatix Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import json 16 | 17 | import numpy as np 18 | import torch 19 | from transformers import RobertaConfig, RobertaModel 20 | import yaml 21 | 22 | from tokenizer import TextProcessor 23 | from models import IFXRoberta 24 | 25 | if __name__ == "__main__": 26 | # load config file 27 | with open("config.yaml") as f: 28 | conf = yaml.safe_load(f) 29 | bpe_file = conf["file_paths"]["bpe_file"] 30 | count_file = conf["file_paths"]["count_file"] 31 | roberta_weight_path = conf["file_paths"]["roberta_weight"] 32 | linear_weight_path = conf["file_paths"]["linear_weight"] 33 | roberta_config_path = conf["file_paths"]["roberta_config"] 34 | juman_config_path = conf["file_paths"]["juman_config"] 35 | device_type = conf["device_type"] 36 | 37 | device = torch.device(device_type) 38 | 39 | # load tokenizer 40 | processor = TextProcessor(bpe_file=bpe_file, count_file=count_file, juman_conf_file=juman_config_path) 41 | 42 | # load pretrained bert model 43 | with open(roberta_config_path, "r") as f: 44 | config_dict = json.load(f) 45 | config_bert = RobertaConfig().from_dict(config_dict) 46 | roberta = RobertaModel(config=config_bert) 47 | roberta.load_state_dict(torch.load(roberta_weight_path, map_location=device)) 48 | 49 | # load pretained decoder 50 | ifxroberta = IFXRoberta(roberta) 51 | ifxroberta.linear_word.load_state_dict(torch.load(linear_weight_path, map_location=device)) 52 | ifxroberta.eval() 53 | 54 | # infer 55 | rinen1 = "世の中に己の能力をもって奉仕することにより、己の価値を問い、己の存在を主張し、そしてまた、世の中から求められる己の存在価値を創造する。" 56 | rinen2 = "コンピュータ技術およびその関連技術に対する研究開発に努め、自己研鑽に励み、専門的な技術集団を形成する。" 57 | rinen3 = "人間関係が常に仕事の基本にあることを認識し、仕事を通じて、より建設的な人間関係を形成することを追求する。" 58 | inp_text = rinen1 + rinen2 + rinen3 59 | bpe_ids = processor.encode(inp_text) 60 | masked_ids = processor.random_mask(bpe_ids) 61 | with torch.no_grad(): 62 | inp_tensor = torch.LongTensor([masked_ids]) 63 | inp_tensor.to(device) 64 | out_tensor = ifxroberta(inp_tensor) 65 | 66 | # decoding masked text and model output 67 | out_text_code = torch.max(out_tensor, dim=-1, keepdim=True)[1][0] 68 | ids = out_text_code.squeeze(-1).cpu().numpy().tolist() 69 | ignore_idx = np.where(np.array(bpe_ids) < 5)[0] 70 | out_text = processor.decode(ids, ignore_idx=ignore_idx) 71 | masked_text = processor.decode(masked_ids) 72 | print("原文:", inp_text) 73 | print("入力:", "".join(masked_text).replace("@@", "")) 74 | print("出力:", "".join(out_text).replace("@@", "")) 75 | -------------------------------------------------------------------------------- /models.py: -------------------------------------------------------------------------------- 1 | # Copyright 2022 Informatix Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from typing import Optional 16 | 17 | from transformers import RobertaModel 18 | import torch 19 | from torch import nn 20 | 21 | 22 | class IFXRoberta(nn.Module): 23 | def __init__(self, roberta: RobertaModel, vocab_size: int = 32005, model_dim: int = 768): 24 | super().__init__() 25 | self.roberta = roberta 26 | self.linear_word = nn.Linear(model_dim, vocab_size) 27 | 28 | def forward(self, x: torch.LongTensor, attention_mask: Optional[torch.FloatTensor] = None) -> torch.Tensor: 29 | out = self.roberta(x, attention_mask=attention_mask) 30 | x = out.last_hidden_state 31 | return self.masked_lm(x) 32 | 33 | def masked_lm(self, x: torch.FloatTensor) -> torch.Tensor: 34 | return torch.log_softmax(self.linear_word(x), dim=-1) 35 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | mojimoji==0.0.11 2 | pyknp==0.4.1 3 | subword-nmt==0.3.7 4 | transformers==4.16.2 5 | -------------------------------------------------------------------------------- /tokenizer.py: -------------------------------------------------------------------------------- 1 | # Copyright 2022 Informatix Inc. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import csv 16 | import re 17 | import sys 18 | import traceback 19 | import unicodedata 20 | 21 | import mojimoji 22 | import numpy as np 23 | from pyknp import Juman 24 | from subword_nmt.apply_bpe import BPE 25 | from typing import List, Optional 26 | 27 | 28 | class JumanSeparator: 29 | def __init__(self, juman_conf_file: Optional[str], period: Optional[str] = "。"): 30 | assert period is None or type(period) is str 31 | if juman_conf_file: 32 | self.jumanpp = Juman(option="-c {}".format(juman_conf_file)) 33 | else: 34 | self.jumanpp = Juman() 35 | space_chars = "".join(chr(c) for c in range(sys.maxunicode + 1)) 36 | self.white_space = "|".join(re.findall(r"\s", space_chars)) 37 | self.period = period 38 | 39 | def __call__(self, doc: str) -> List[List[str]]: 40 | separate_list = [] 41 | lines = doc.split("\n") 42 | for l in lines: 43 | splits = l.split(self.period) if self.period else [l] 44 | for spl in splits: 45 | sentence = spl.strip() 46 | if not sentence: 47 | continue 48 | if self.period: 49 | sentence += self.period 50 | # normalize and clean senetence 51 | sentence = unicodedata.normalize("NFKC", sentence) 52 | sentence = re.sub(self.white_space, "", sentence) 53 | sentence = mojimoji.han_to_zen(sentence) 54 | 55 | try: 56 | mlist = self.jumanpp.analysis(sentence) 57 | except Exception: 58 | print(traceback.format_exc()) 59 | continue 60 | 61 | mlist = [mrph.midasi for mrph in mlist.mrph_list()] 62 | separate_list.append(mlist) 63 | 64 | return separate_list 65 | 66 | 67 | class BPEClassifier: 68 | def __init__(self, bpe_file: str, count_file: str, sep_cls: int = 0, init_cls: int = 3, unknown_cls: int = 4): 69 | # load file for "byte pair encoding" 70 | with open(bpe_file, "r", encoding="utf_8", errors="ignore") as f: 71 | self.bpe = BPE(f) 72 | 73 | # load file of "correspondence map between word piece and class number" 74 | with open(count_file, "r", encoding="utf_8", errors="ignore") as f: 75 | count_data = csv.reader(f) 76 | self.clist = [d[1] for d in count_data] 77 | 78 | self.sep_cls = sep_cls 79 | self.init_cls = init_cls 80 | self.unknown_cls = unknown_cls 81 | 82 | def __call__(self, token_list: List[List[str]]) -> List[int]: 83 | doc_cls = [self.init_cls] 84 | 85 | for tlist in token_list: 86 | # skip short sentence 87 | if len(tlist) < 2: 88 | continue 89 | segment_result = self.bpe.segment_tokens(tlist) 90 | result_cls = [self.clist.index(w) if w in self.clist else self.unknown_cls for w in segment_result] 91 | doc_cls.extend(result_cls) 92 | doc_cls.append(self.sep_cls) 93 | 94 | return doc_cls 95 | 96 | 97 | class TextProcessor: 98 | def __init__(self, bpe_file: str, count_file: str, juman_conf_file: Optional[str] = None): 99 | """ 100 | Encodes Japanese text into list of predefined class numbers, and decodes encoded text into list of word pieces. 101 | Args: 102 | bpe_file: Path to file which defines word pieces for byte pair encoding. For more detail, please refer to subword_nmt documentation. 103 | count_file: Path to file which defines correspondence between word piece and class number. 104 | juman_conf_file(optional): Path to config file for Juman. For more detail, please refer to Juman documentation. 105 | """ 106 | self.juman = JumanSeparator(juman_conf_file=juman_conf_file) 107 | self.bpe = BPEClassifier(bpe_file=bpe_file, count_file=count_file) 108 | 109 | def encode(self, text: str) -> List[int]: 110 | """ 111 | Encodes Japanese sentences into list of integers, which is predefined class numbers. 112 | Args: 113 | text: Japanese sentences. 114 | Returns: 115 | List of encoded word pieces, including special tokens. 116 | """ 117 | sep_text = self.juman(text) 118 | enc_text = self.bpe(sep_text) 119 | return enc_text 120 | 121 | def decode(self, ids: List[int], ignore_idx: List[int] = []) -> List[str]: 122 | """ 123 | Decodes a list of encoded word pieces into a list of word pieces. 124 | Args: 125 | ids: List of encoded word pieces. 126 | ignore_idx: List of index to be ignored. 127 | Returns: 128 | List of word pieces. 129 | """ 130 | return [self.bpe.clist[c] for i, c in enumerate(ids) if i not in ignore_idx] 131 | 132 | def random_mask(self, ids: List[int], mask_rate: float = 0.15, mask_cls: int = 1) -> List[int]: 133 | """ 134 | Randomly masks a list of encoded word pieces. 135 | Args: 136 | ids: List of encoded word pieces. 137 | mask_rate: Rate of replacement. 138 | mask_cls: Class number of mask tokens. 139 | Returns: 140 | List of randomly masked tokens. 141 | """ 142 | ids = np.array(ids, dtype=np.int) 143 | target_idx = np.where(ids >= 5)[0] # Avoid masking special tokens 144 | mask_idx = np.random.choice(target_idx, size=int(mask_rate * len(target_idx)), replace=False) 145 | ids[mask_idx] = mask_cls 146 | ids = ids.tolist() 147 | return ids 148 | --------------------------------------------------------------------------------