Add models
Browse files- README.md +125 -0
- config.json +46 -0
- pytorch_model.bin +3 -0
- special_tokens_map.json +15 -0
- spiece.model +3 -0
- tf_model.h5 +3 -0
- tokenization_bart_japanese_news.py +294 -0
- tokenizer_config.json +27 -0
README.md
CHANGED
@@ -1,3 +1,128 @@
|
|
1 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
license: mit
|
3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
---
|
2 |
+
language: ja
|
3 |
+
tags:
|
4 |
+
- ja
|
5 |
+
- japanese
|
6 |
+
- bart
|
7 |
+
- lm
|
8 |
+
- nlp
|
9 |
license: mit
|
10 |
---
|
11 |
+
|
12 |
+
# bart-base-japanese-news(base-sized model)
|
13 |
+
This repository provides a Japanese BART model. The model was trained by [Stockmark Inc.](https://stockmark.co.jp)
|
14 |
+
|
15 |
+
|
16 |
+
## Model description
|
17 |
+
|
18 |
+
BART is a transformer encoder-decoder (seq2seq) model with a bidirectional (BERT-like) encoder and an autoregressive (GPT-like) decoder. BART is pre-trained by (1) corrupting text with an arbitrary noising function, and (2) learning a model to reconstruct the original text.
|
19 |
+
|
20 |
+
BART is particularly effective when fine-tuned for text generation (e.g. summarization, translation) but also works well for comprehension tasks (e.g. text classification, question answering).
|
21 |
+
|
22 |
+
## Intended uses & limitations
|
23 |
+
|
24 |
+
You can use the raw model for text infilling. However, the model is mostly meant to be fine-tuned on a supervised dataset.
|
25 |
+
|
26 |
+
# How to use the model
|
27 |
+
|
28 |
+
*NOTE:* Use `trust_remote_code=True` to initiate the tokenizer.
|
29 |
+
|
30 |
+
## Simple use
|
31 |
+
|
32 |
+
```python
|
33 |
+
from transformers import AutoTokenizer, BartModel
|
34 |
+
|
35 |
+
model_name = "stockmark/bart-base-japanese-news"
|
36 |
+
|
37 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
|
38 |
+
model = BartModel.from_pretrained(model_name)
|
39 |
+
|
40 |
+
inputs = tokenizer("今日は良い天気です。", return_tensors="pt")
|
41 |
+
outputs = model(**inputs)
|
42 |
+
|
43 |
+
last_hidden_states = outputs.last_hidden_state
|
44 |
+
```
|
45 |
+
|
46 |
+
## Sentence Permutation
|
47 |
+
```python
|
48 |
+
import torch
|
49 |
+
from transformers import AutoTokenizer, BartForConditionalGeneration
|
50 |
+
|
51 |
+
model_name = "stockmark/bart-base-japanese-news"
|
52 |
+
|
53 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
|
54 |
+
model = BartForConditionalGeneration.from_pretrained(model_name)
|
55 |
+
|
56 |
+
if torch.cuda.is_available():
|
57 |
+
model = model.to("cuda")
|
58 |
+
|
59 |
+
# correct order text is "明日は大雨です。電車は止まる可能性があります。ですから、自宅から働きます。"
|
60 |
+
text = "電車は止まる可能性があります。ですから、自宅から働きます。明日は大雨です。"
|
61 |
+
|
62 |
+
inputs = tokenizer([text], max_length=128, return_tensors="pt", truncation=True)
|
63 |
+
text_ids = model.generate(inputs["input_ids"].to(model.device), num_beams=3, max_length=128)
|
64 |
+
output = tokenizer.batch_decode(text_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
65 |
+
|
66 |
+
print(output)
|
67 |
+
# sample output: 明日は大雨です。電車は止まる可能性があります。ですから、自宅から働きます。
|
68 |
+
```
|
69 |
+
## Mask filing
|
70 |
+
```python
|
71 |
+
import torch
|
72 |
+
from transformers import AutoTokenizer, BartForConditionalGeneration
|
73 |
+
|
74 |
+
model_name = "stockmark/bart-base-japanese-news"
|
75 |
+
|
76 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
|
77 |
+
model = BartForConditionalGeneration.from_pretrained(model_name)
|
78 |
+
|
79 |
+
if torch.cuda.is_available():
|
80 |
+
model = model.to("cuda")
|
81 |
+
|
82 |
+
text = "今日の天気は<mask>のため、傘が必要でしょう。"
|
83 |
+
|
84 |
+
inputs = tokenizer([text], max_length=128, return_tensors="pt", truncation=True)
|
85 |
+
text_ids = model.generate(inputs["input_ids"].to(model.device), num_beams=3, max_length=128)
|
86 |
+
output = tokenizer.batch_decode(text_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
87 |
+
|
88 |
+
print(output)
|
89 |
+
# sample output: 今日の天気は、雨のため、傘が必要でしょう。
|
90 |
+
```
|
91 |
+
|
92 |
+
## Text generation
|
93 |
+
|
94 |
+
*NOTE:* You can use the raw model for text generation. However, the model is mostly meant to be fine-tuned on a supervised dataset.
|
95 |
+
|
96 |
+
```python
|
97 |
+
import torch
|
98 |
+
from transformers import AutoTokenizer, BartForConditionalGeneration
|
99 |
+
|
100 |
+
model_name = "stockmark/bart-base-japanese-news"
|
101 |
+
|
102 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
|
103 |
+
model = BartForConditionalGeneration.from_pretrained(model_name)
|
104 |
+
|
105 |
+
if torch.cuda.is_available():
|
106 |
+
model = model.to("cuda")
|
107 |
+
|
108 |
+
text = "自然言語処理(しぜんげんごしょり、略称:NLP)は、人間が日常的に使っている自然言語をコンピュータに処理させる一連の技術であり、人工知能と言語学の一分野である。「計算言語学」(computational linguistics)との類似もあるが、自然言語処理は工学的な視点からの言語処理をさすのに対して、計算言語学は言語学的視点を重視する手法をさす事が多い。"
|
109 |
+
|
110 |
+
inputs = tokenizer([text], max_length=512, return_tensors="pt", truncation=True)
|
111 |
+
text_ids = model.generate(inputs["input_ids"].to(model.device), num_beams=3, min_length=0, max_length=40)
|
112 |
+
output = tokenizer.batch_decode(text_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
113 |
+
|
114 |
+
print(output)
|
115 |
+
# sample output: 自然言語処理(しぜんげんごしょり、略称:NLP)は、人間が日常的に使っている自然言語をコンピュータに処理させる一連の技術であり、言語学の一分野である。
|
116 |
+
```
|
117 |
+
|
118 |
+
# Training
|
119 |
+
The model was trained on Japanese News Articles.
|
120 |
+
|
121 |
+
# Tokenization
|
122 |
+
The model uses a [sentencepiece](https://github.com/google/sentencepiece)-based tokenizer. The vocabulary was first trained on a selected subset from the training data using the official sentencepiece training script.
|
123 |
+
|
124 |
+
# Licenses
|
125 |
+
The pretrained models are distributed under the terms of the [MIT License](https://opensource.org/licenses/mit-license.php).
|
126 |
+
|
127 |
+
# Acknowledgement
|
128 |
+
This comparison study supported with Cloud TPUs from Google’s TensorFlow Research Cloud (TFRC).
|
config.json
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "bart-base-japanese-news",
|
3 |
+
"activation_dropout": 0.1,
|
4 |
+
"activation_function": "gelu",
|
5 |
+
"architectures": [
|
6 |
+
"BartForConditionalGeneration"
|
7 |
+
],
|
8 |
+
"attention_dropout": 0.1,
|
9 |
+
"bos_token_id": 1,
|
10 |
+
"classifier_dropout": 0.0,
|
11 |
+
"d_model": 768,
|
12 |
+
"decoder_attention_heads": 12,
|
13 |
+
"decoder_ffn_dim": 3072,
|
14 |
+
"decoder_layerdrop": 0.0,
|
15 |
+
"decoder_layers": 6,
|
16 |
+
"decoder_start_token_id": 1,
|
17 |
+
"dropout": 0.1,
|
18 |
+
"encoder_attention_heads": 12,
|
19 |
+
"encoder_ffn_dim": 3072,
|
20 |
+
"encoder_layerdrop": 0.0,
|
21 |
+
"encoder_layers": 6,
|
22 |
+
"eos_token_id": 2,
|
23 |
+
"forced_eos_token_id": 2,
|
24 |
+
"gradient_checkpointing": false,
|
25 |
+
"id2label": {
|
26 |
+
"0": "LABEL_0",
|
27 |
+
"1": "LABEL_1",
|
28 |
+
"2": "LABEL_2"
|
29 |
+
},
|
30 |
+
"init_std": 0.02,
|
31 |
+
"is_encoder_decoder": true,
|
32 |
+
"label2id": {
|
33 |
+
"LABEL_0": 0,
|
34 |
+
"LABEL_1": 1,
|
35 |
+
"LABEL_2": 2
|
36 |
+
},
|
37 |
+
"max_position_embeddings": 512,
|
38 |
+
"model_type": "bart",
|
39 |
+
"num_hidden_layers": 6,
|
40 |
+
"pad_token_id": 3,
|
41 |
+
"scale_embedding": false,
|
42 |
+
"torch_dtype": "float32",
|
43 |
+
"transformers_version": "4.21.3",
|
44 |
+
"use_cache": false,
|
45 |
+
"vocab_size": 32000
|
46 |
+
}
|
pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:73278760f95038d267440a1c703247ad8c19ba0a4a1dbb41923e046ab6a2df19
|
3 |
+
size 498636537
|
special_tokens_map.json
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": "<s>",
|
3 |
+
"cls_token": "<s>",
|
4 |
+
"eos_token": "</s>",
|
5 |
+
"mask_token": {
|
6 |
+
"content": "<mask>",
|
7 |
+
"lstrip": true,
|
8 |
+
"normalized": false,
|
9 |
+
"rstrip": false,
|
10 |
+
"single_word": false
|
11 |
+
},
|
12 |
+
"pad_token": "<pad>",
|
13 |
+
"sep_token": "</s>",
|
14 |
+
"unk_token": "<unk>"
|
15 |
+
}
|
spiece.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1ef4fcd7e2f55b4d3601f0827ca79efdfc5bfea11129c554e0991491f73ba7a0
|
3 |
+
size 828378
|
tf_model.h5
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f2c1df518fdd0baa436241ec54e81c21eef9af3a55d5de6af86a7f6d9d6c09ff
|
3 |
+
size 498843504
|
tokenization_bart_japanese_news.py
ADDED
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 Stockmark Inc.
|
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 |
+
|
16 |
+
import os
|
17 |
+
import unicodedata
|
18 |
+
from shutil import copyfile
|
19 |
+
from typing import Any, Dict, List, Optional, Tuple
|
20 |
+
|
21 |
+
import regex
|
22 |
+
import sentencepiece as spm
|
23 |
+
from transformers import AddedToken, BartTokenizer, logging
|
24 |
+
|
25 |
+
logger = logging.get_logger(__name__)
|
26 |
+
VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
|
27 |
+
|
28 |
+
PRETRAINED_VOCAB_FILES_MAP = {
|
29 |
+
"vocab_file": {
|
30 |
+
"bart-base-japanese-news": "https://huggingface.co/stockmark/bart-base-japanese-news/resolve/main/spiece.model",
|
31 |
+
}}
|
32 |
+
|
33 |
+
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
|
34 |
+
"bart-base-japanese-news": 512,
|
35 |
+
}
|
36 |
+
|
37 |
+
SPIECE_UNDERLINE = "▁"
|
38 |
+
|
39 |
+
|
40 |
+
class BartJapaneseNewsTokenizer(BartTokenizer):
|
41 |
+
"""
|
42 |
+
Construct an Bart tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
|
43 |
+
|
44 |
+
This tokenizer inherits from [`BartTokenizer`] which contains most of the main methods. Users should refer to
|
45 |
+
this superclass for more information regarding those methods.
|
46 |
+
|
47 |
+
Args:
|
48 |
+
vocab_file (`str`):
|
49 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
|
50 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
51 |
+
do_lower_case (`bool`, *optional*, defaults to `False`):
|
52 |
+
Whether or not to lowercase the input when tokenizing.
|
53 |
+
remove_space (`bool`, *optional*, defaults to `False`):
|
54 |
+
Whether or not to strip the text when tokenizing (removing excess spaces before and after the string).
|
55 |
+
clean_text (`bool`, *optional*, defaults to `False`):
|
56 |
+
Whether or not to clean input text
|
57 |
+
|
58 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
59 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
|
60 |
+
|
61 |
+
<Tip>
|
62 |
+
|
63 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
64 |
+
sequence. The token used is the `cls_token`.
|
65 |
+
|
66 |
+
</Tip>
|
67 |
+
|
68 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
69 |
+
The end of sequence token.
|
70 |
+
|
71 |
+
<Tip>
|
72 |
+
|
73 |
+
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
|
74 |
+
The token used is the `sep_token`.
|
75 |
+
|
76 |
+
</Tip>
|
77 |
+
|
78 |
+
sep_token (`str`, *optional*, defaults to `"</s>"`):
|
79 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
80 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
81 |
+
token of a sequence built with special tokens.
|
82 |
+
cls_token (`str`, *optional*, defaults to `"<s>"`):
|
83 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
84 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
85 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
86 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
87 |
+
token instead.
|
88 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
89 |
+
The token used for padding, for example when batching sequences of different lengths.
|
90 |
+
mask_token (`str`, *optional*, defaults to `"<mask>"`):
|
91 |
+
The token used for masking values. This is the token used when training this model with masked language
|
92 |
+
modeling. This is the token which the model will try to predict.
|
93 |
+
|
94 |
+
sp_model_kwargs (`dict`, *optional*):
|
95 |
+
Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
|
96 |
+
SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
|
97 |
+
to set:
|
98 |
+
|
99 |
+
- `enable_sampling`: Enable subword regularization.
|
100 |
+
- `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
|
101 |
+
|
102 |
+
- `nbest_size = {0,1}`: No sampling is performed.
|
103 |
+
- `nbest_size > 1`: samples from the nbest_size results.
|
104 |
+
- `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
|
105 |
+
using forward-filtering-and-backward-sampling algorithm.
|
106 |
+
|
107 |
+
- `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
|
108 |
+
BPE-dropout.
|
109 |
+
|
110 |
+
Attributes:
|
111 |
+
sp_model (`SentencePieceProcessor`):
|
112 |
+
The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
|
113 |
+
"""
|
114 |
+
|
115 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
116 |
+
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
|
117 |
+
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
|
118 |
+
|
119 |
+
def __init__(
|
120 |
+
self,
|
121 |
+
vocab_file,
|
122 |
+
do_lower_case=False,
|
123 |
+
remove_space=False,
|
124 |
+
clean_text=False,
|
125 |
+
bos_token="<s>",
|
126 |
+
eos_token="</s>",
|
127 |
+
unk_token="<unk>",
|
128 |
+
sep_token="</s>",
|
129 |
+
pad_token="<pad>",
|
130 |
+
cls_token="<s>",
|
131 |
+
mask_token="<mask>",
|
132 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
133 |
+
**kwargs
|
134 |
+
) -> None:
|
135 |
+
# Mask token behave like a normal word, i.e. include the space before it and
|
136 |
+
# is included in the raw text, there should be a match in a non-normalized sentence.
|
137 |
+
mask_token = (
|
138 |
+
AddedToken(mask_token, lstrip=True, rstrip=True, normalized=False)
|
139 |
+
if isinstance(mask_token, str)
|
140 |
+
else mask_token
|
141 |
+
)
|
142 |
+
|
143 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
144 |
+
|
145 |
+
super(BartTokenizer, self).__init__(
|
146 |
+
do_lower_case=do_lower_case,
|
147 |
+
remove_space=remove_space,
|
148 |
+
clean_text=clean_text,
|
149 |
+
bos_token=bos_token,
|
150 |
+
eos_token=eos_token,
|
151 |
+
unk_token=unk_token,
|
152 |
+
sep_token=sep_token,
|
153 |
+
pad_token=pad_token,
|
154 |
+
cls_token=cls_token,
|
155 |
+
mask_token=mask_token,
|
156 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
157 |
+
**kwargs,
|
158 |
+
)
|
159 |
+
|
160 |
+
self.do_lower_case = do_lower_case
|
161 |
+
self.remove_space = remove_space
|
162 |
+
self.clean_text = clean_text
|
163 |
+
self.vocab_file = vocab_file
|
164 |
+
|
165 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
166 |
+
self.sp_model.Load(vocab_file)
|
167 |
+
|
168 |
+
@property
|
169 |
+
def vocab_size(self):
|
170 |
+
return len(self.sp_model)
|
171 |
+
|
172 |
+
def get_vocab(self):
|
173 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
174 |
+
vocab.update(self.added_tokens_encoder)
|
175 |
+
return vocab
|
176 |
+
|
177 |
+
def __getstate__(self):
|
178 |
+
state = self.__dict__.copy()
|
179 |
+
state["sp_model"] = None
|
180 |
+
return state
|
181 |
+
|
182 |
+
def __setstate__(self, d):
|
183 |
+
self.__dict__ = d
|
184 |
+
|
185 |
+
# for backward compatibility
|
186 |
+
if not hasattr(self, "sp_model_kwargs"):
|
187 |
+
self.sp_model_kwargs = {}
|
188 |
+
|
189 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
190 |
+
self.sp_model.Load(self.vocab_file)
|
191 |
+
|
192 |
+
def preprocess_text(self, inputs):
|
193 |
+
if self.remove_space:
|
194 |
+
outputs = " ".join(inputs.strip().split())
|
195 |
+
else:
|
196 |
+
outputs = inputs
|
197 |
+
|
198 |
+
outputs = unicodedata.normalize("NFKD", outputs)
|
199 |
+
outputs = ''.join([ s for s in outputs if not self._is_control(s) ])
|
200 |
+
|
201 |
+
if self.clean_text:
|
202 |
+
outputs = outputs.replace('‘','\'').replace('’','\'').replace('“','"').replace('”','"')
|
203 |
+
outputs = outputs.replace('〈','<').replace('〉','>').replace('《','<').replace('》','>').replace('〔','【').replace('〕','】').replace('『','「').replace('』','」')
|
204 |
+
outputs = regex.sub(r'[\p{GeometricShapes}\p{MiscellaneousSymbols}]','*', outputs)
|
205 |
+
outputs = ''.join(regex.findall(r'[\p{InHiragana}\p{InKatakana}\p{BasicLatin}\p{Han}、。〃〆「」【】〒〜]',outputs))
|
206 |
+
|
207 |
+
if self.do_lower_case:
|
208 |
+
outputs = outputs.lower()
|
209 |
+
|
210 |
+
outputs = unicodedata.normalize('NFKC',outputs)
|
211 |
+
outputs = outputs.strip()
|
212 |
+
return outputs
|
213 |
+
|
214 |
+
def _tokenize(self, text: str) -> List[str]:
|
215 |
+
"""Tokenize a string."""
|
216 |
+
text = self.preprocess_text(text)
|
217 |
+
pieces = self.sp_model.encode(text, out_type=str)
|
218 |
+
new_pieces = []
|
219 |
+
for piece in pieces:
|
220 |
+
if len(piece) > 1 and piece[-1] == str(",") and piece[-2].isdigit():
|
221 |
+
cur_pieces = self.sp_model.EncodeAsPieces(piece[:-1].replace(SPIECE_UNDERLINE, ""))
|
222 |
+
if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
|
223 |
+
if len(cur_pieces[0]) == 1:
|
224 |
+
cur_pieces = cur_pieces[1:]
|
225 |
+
else:
|
226 |
+
cur_pieces[0] = cur_pieces[0][1:]
|
227 |
+
cur_pieces.append(piece[-1])
|
228 |
+
new_pieces.extend(cur_pieces)
|
229 |
+
else:
|
230 |
+
new_pieces.append(piece)
|
231 |
+
|
232 |
+
return new_pieces
|
233 |
+
|
234 |
+
def _convert_token_to_id(self, token):
|
235 |
+
"""Converts a token (str) in an id using the vocab."""
|
236 |
+
return self.sp_model.PieceToId(token)
|
237 |
+
|
238 |
+
def _convert_id_to_token(self, index):
|
239 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
240 |
+
return self.sp_model.IdToPiece(index)
|
241 |
+
|
242 |
+
def convert_tokens_to_string(self, tokens):
|
243 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
244 |
+
current_sub_tokens = []
|
245 |
+
out_string = ""
|
246 |
+
prev_is_special = False
|
247 |
+
for token in tokens:
|
248 |
+
# make sure that special tokens are not decoded using sentencepiece model
|
249 |
+
if token in self.all_special_tokens:
|
250 |
+
if not prev_is_special:
|
251 |
+
out_string += " "
|
252 |
+
out_string += self.sp_model.decode(current_sub_tokens) + token
|
253 |
+
prev_is_special = True
|
254 |
+
current_sub_tokens = []
|
255 |
+
else:
|
256 |
+
current_sub_tokens.append(token)
|
257 |
+
prev_is_special = False
|
258 |
+
out_string += self.sp_model.decode(current_sub_tokens)
|
259 |
+
return out_string.strip()
|
260 |
+
|
261 |
+
def _is_control(self, char):
|
262 |
+
'''
|
263 |
+
Check control char
|
264 |
+
Args:
|
265 |
+
char (str):
|
266 |
+
Returns:
|
267 |
+
bool:
|
268 |
+
'''
|
269 |
+
if char == "\t" or char == "\n" or char == "\r":
|
270 |
+
return False
|
271 |
+
cat = unicodedata.category(char)
|
272 |
+
if cat.startswith("C") or ord(char)==0 or ord(char)==0xfffd:
|
273 |
+
return True
|
274 |
+
return False
|
275 |
+
|
276 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
277 |
+
if not os.path.isdir(save_directory):
|
278 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
279 |
+
return
|
280 |
+
out_vocab_file = os.path.join(
|
281 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
282 |
+
)
|
283 |
+
|
284 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
285 |
+
copyfile(self.vocab_file, out_vocab_file)
|
286 |
+
elif not os.path.isfile(self.vocab_file):
|
287 |
+
with open(out_vocab_file, "wb") as fi:
|
288 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
289 |
+
fi.write(content_spiece_model)
|
290 |
+
|
291 |
+
return (out_vocab_file,)
|
292 |
+
|
293 |
+
def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
|
294 |
+
return super(BartTokenizer, self).prepare_for_tokenization(text, is_split_into_words=False, **kwargs)
|
tokenizer_config.json
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": "<s>",
|
3 |
+
"clean_text": false,
|
4 |
+
"cls_token": "<s>",
|
5 |
+
"do_lower_case": false,
|
6 |
+
"eos_token": "</s>",
|
7 |
+
"mask_token": {
|
8 |
+
"__type": "AddedToken",
|
9 |
+
"content": "<mask>",
|
10 |
+
"lstrip": true,
|
11 |
+
"normalized": false,
|
12 |
+
"rstrip": false,
|
13 |
+
"single_word": false
|
14 |
+
},
|
15 |
+
"pad_token": "<pad>",
|
16 |
+
"remove_space": false,
|
17 |
+
"sep_token": "</s>",
|
18 |
+
"sp_model_kwargs": {},
|
19 |
+
"tokenizer_class": "BartJapaneseNewsTokenizer",
|
20 |
+
"unk_token": "<unk>",
|
21 |
+
"auto_map": {
|
22 |
+
"AutoTokenizer": [
|
23 |
+
"tokenization_bart_japanese_news.BartJapaneseNewsTokenizer",
|
24 |
+
null
|
25 |
+
]
|
26 |
+
}
|
27 |
+
}
|