tokenizing_ernie.py 10.3 KB
Newer Older
M
Meiyim 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals

import sys
import os
import six
import re
import logging
import tempfile
C
chenxuyi 已提交
26
from pathlib import Path
M
Meiyim 已提交
27
from functools import partial
W
Weiyue Su 已提交
28 29 30 31
if six.PY2:
    from pathlib2 import Path
else:
    from pathlib import Path
M
Meiyim 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44

from tqdm import tqdm
import numpy as np

from ernie.file_utils import _fetch_from_remote
import io

open = partial(io.open, encoding='utf8')

log = logging.getLogger(__name__)

_max_input_chars_per_word = 100

C
chenxuyi 已提交
45

M
Meiyim 已提交
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
def _wordpiece(token, vocab, unk_token, prefix='##', sentencepiece_prefix=''):
    """ wordpiece: helloworld => [hello, ##world] """
    chars = list(token)
    if len(chars) > _max_input_chars_per_word:
        return [unk_token], [(0, len(chars))]

    is_bad = False
    start = 0
    sub_tokens = []
    sub_pos = []
    while start < len(chars):
        end = len(chars)
        cur_substr = None
        while start < end:
            substr = "".join(chars[start:end])
            if start == 0:
                substr = sentencepiece_prefix + substr
            if start > 0:
                substr = prefix + substr
            if substr in vocab:
                cur_substr = substr
                break
            end -= 1
        if cur_substr is None:
            is_bad = True
            break
        sub_tokens.append(cur_substr)
        sub_pos.append((start, end))
        start = end
    if is_bad:
        return [unk_token], [(0, len(chars))]
    else:
        return sub_tokens, sub_pos


class ErnieTokenizer(object):
    bce = 'https://ernie-github.cdn.bcebos.com/'
    resource_map = {
        'ernie-1.0': bce + 'model-ernie1.0.1.tar.gz',
        'ernie-2.0-en': bce + 'model-ernie2.0-en.1.tar.gz',
C
chenxuyi 已提交
86
        'ernie-2.0-large-en': bce + 'model-ernie2.0-large-en.1.tar.gz',
M
Meiyim 已提交
87
        'ernie-tiny': bce + 'model-ernie_tiny.1.tar.gz',
C
chenxuyi 已提交
88 89
        'ernie-gen-base-en': bce + 'model-ernie-gen-base-en.1.tar.gz',
        'ernie-gen-large-en': bce + 'model-ernie-gen-large-en.1.tar.gz',
Z
zhanghan17 已提交
90 91
        'ernie-gram-zh': bce + 'model-ernie-gram-zh.1.tar.gz',
        'ernie-gram-en': bce + 'model-ernie-gram-en.1.tar.gz',
M
Meiyim 已提交
92
    }
C
chenxuyi 已提交
93

M
Meiyim 已提交
94
    @classmethod
C
chenxuyi 已提交
95 96 97 98 99 100 101
    def from_pretrained(cls,
                        pretrain_dir_or_url,
                        force_download=False,
                        **kwargs):
        if not Path(pretrain_dir_or_url).exists() and str(
                pretrain_dir_or_url) in cls.resource_map:
            url = cls.resource_map[str(pretrain_dir_or_url)]
M
Meiyim 已提交
102
            log.info('get pretrain dir from %s' % url)
C
chenxuyi 已提交
103 104
            pretrain_dir = _fetch_from_remote(
                url, force_download=force_download)
M
Meiyim 已提交
105
        else:
C
chenxuyi 已提交
106 107
            log.info('pretrain dir %s not in %s, read from local' %
                     (pretrain_dir_or_url, repr(cls.resource_map)))
W
Weiyue Su 已提交
108
            pretrain_dir = Path(pretrain_dir_or_url)
M
Meiyim 已提交
109
        if not pretrain_dir.exists():
C
chenxuyi 已提交
110
            raise ValueError('pretrain dir not found: %s, optional: %s' % (pretrain_dir, cls.resource_map.keys()))
M
Meiyim 已提交
111 112
        vocab_path = pretrain_dir / 'vocab.txt'
        if not vocab_path.exists():
C
chenxuyi 已提交
113 114 115 116 117 118 119
            raise ValueError('no vocab file in pretrain dir: %s' %
                             pretrain_dir)
        vocab_dict = {
            j.strip().split('\t')[0]: i
            for i, j in enumerate(
                vocab_path.open(encoding='utf8').readlines())
        }
M
Meiyim 已提交
120 121 122
        t = cls(vocab_dict, **kwargs)
        return t

C
chenxuyi 已提交
123 124 125 126 127 128 129 130 131 132 133 134
    def __init__(self,
                 vocab,
                 unk_token='[UNK]',
                 sep_token='[SEP]',
                 cls_token='[CLS]',
                 pad_token='[PAD]',
                 mask_token='[MASK]',
                 wordpiece_prefix='##',
                 sentencepiece_prefix='',
                 lower=True,
                 encoding='utf8',
                 special_token_list=[]):
M
Meiyim 已提交
135
        if not isinstance(vocab, dict):
C
chenxuyi 已提交
136 137
            raise ValueError('expect `vocab` to be instance of dict, got %s' %
                             type(vocab))
M
Meiyim 已提交
138 139 140 141 142 143 144 145 146 147
        self.vocab = vocab
        self.lower = lower
        self.prefix = wordpiece_prefix
        self.sentencepiece_prefix = sentencepiece_prefix
        self.pad_id = self.vocab[pad_token]
        self.cls_id = cls_token and self.vocab[cls_token]
        self.sep_id = sep_token and self.vocab[sep_token]
        self.unk_id = unk_token and self.vocab[unk_token]
        self.mask_id = mask_token and self.vocab[mask_token]
        self.unk_token = unk_token
C
chenxuyi 已提交
148 149 150
        special_tokens = {
            pad_token, cls_token, sep_token, unk_token, mask_token
        } | set(special_token_list)
M
Meiyim 已提交
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
        pat_str = ''
        for t in special_tokens:
            if t is None:
                continue
            pat_str += '(%s)|' % re.escape(t)
        pat_str += r'([a-zA-Z0-9]+|\S)'
        log.debug('regex: %s' % pat_str)
        self.pat = re.compile(pat_str)
        self.encoding = encoding

    def tokenize(self, text):
        if len(text) == 0:
            return []
        if six.PY3 and not isinstance(text, six.string_types):
            text = text.decode(self.encoding)
        if six.PY2 and isinstance(text, str):
            text = text.decode(self.encoding)
C
chenxuyi 已提交
168

M
Meiyim 已提交
169 170 171 172 173 174
        res = []
        for match in self.pat.finditer(text):
            match_group = match.group(0)
            if match.groups()[-1]:
                if self.lower:
                    match_group = match_group.lower()
C
chenxuyi 已提交
175 176 177 178 179 180
                words, _ = _wordpiece(
                    match_group,
                    vocab=self.vocab,
                    unk_token=self.unk_token,
                    prefix=self.prefix,
                    sentencepiece_prefix=self.sentencepiece_prefix)
M
Meiyim 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193
            else:
                words = [match_group]
            res += words
        return res

    def convert_tokens_to_ids(self, tokens):
        return [self.vocab.get(t, self.unk_id) for t in tokens]

    def truncate(self, id1, id2, seqlen):
        len1 = len(id1)
        len2 = len(id2)
        half = seqlen // 2
        if len1 > len2:
C
chenxuyi 已提交
194 195
            len1_truncated, len2_truncated = max(half, seqlen - len2), min(
                half, len2)
M
Meiyim 已提交
196
        else:
C
chenxuyi 已提交
197 198 199
            len1_truncated, len2_truncated = min(half, seqlen - len1), max(
                half, seqlen - len1)
        return id1[:len1_truncated], id2[:len2_truncated]
M
Meiyim 已提交
200 201 202 203 204 205 206 207 208 209 210 211 212 213

    def build_for_ernie(self, text_id, pair_id=[]):
        """build sentence type id, add [CLS] [SEP]"""
        text_id_type = np.zeros_like(text_id, dtype=np.int64)
        ret_id = np.concatenate([[self.cls_id], text_id, [self.sep_id]], 0)
        ret_id_type = np.concatenate([[0], text_id_type, [0]], 0)

        if len(pair_id):
            pair_id_type = np.ones_like(pair_id, dtype=np.int64)
            ret_id = np.concatenate([ret_id, pair_id, [self.sep_id]], 0)
            ret_id_type = np.concatenate([ret_id_type, pair_id_type, [1]], 0)
        return ret_id, ret_id_type

    def encode(self, text, pair=None, truncate_to=None):
C
chenxuyi 已提交
214 215
        text_id = np.array(
            self.convert_tokens_to_ids(self.tokenize(text)), dtype=np.int64)
M
Meiyim 已提交
216 217
        text_id_type = np.zeros_like(text_id, dtype=np.int64)
        if pair is not None:
C
chenxuyi 已提交
218 219 220
            pair_id = np.array(
                self.convert_tokens_to_ids(self.tokenize(pair)),
                dtype=np.int64)
M
Meiyim 已提交
221 222 223
        else:
            pair_id = []
        if truncate_to is not None:
C
chenxuyi 已提交
224 225
            text_id, pair_id = self.truncate(text_id, [] if pair_id is None
                                             else pair_id, truncate_to)
M
Meiyim 已提交
226 227 228 229 230 231 232 233

        ret_id, ret_id_type = self.build_for_ernie(text_id, pair_id)
        return ret_id, ret_id_type


class ErnieTinyTokenizer(ErnieTokenizer):
    bce = 'https://ernie-github.cdn.bcebos.com/'
    resource_map = {'ernie-tiny': bce + 'model-ernie_tiny.1.tar.gz'}
C
chenxuyi 已提交
234

M
Meiyim 已提交
235
    @classmethod
C
chenxuyi 已提交
236 237 238 239 240 241 242
    def from_pretrained(cls,
                        pretrain_dir_or_url,
                        force_download=False,
                        **kwargs):
        if not Path(pretrain_dir_or_url).exists() and str(
                pretrain_dir_or_url) in cls.resource_map:
            url = cls.resource_map[str(pretrain_dir_or_url)]
M
Meiyim 已提交
243 244 245
            log.info('get pretrain dir from %s' % url)
            pretrain_dir = _fetch_from_remote(url, force_download)
        else:
C
chenxuyi 已提交
246 247
            log.info('pretrain dir %s not in %s, read from local' %
                     (pretrain_dir_or_url, repr(cls.resource_map)))
W
Weiyue Su 已提交
248
            pretrain_dir = Path(pretrain_dir_or_url)
M
Meiyim 已提交
249
        if not pretrain_dir.exists():
M
Meiyim 已提交
250
            raise ValueError('pretrain dir not found: %s' % pretrain_dir)
M
Meiyim 已提交
251 252
        vocab_path = pretrain_dir / 'vocab.txt'
        sp_model_path = pretrain_dir / 'subword/spm_cased_simp_sampled.model'
M
Meiyim 已提交
253

M
Meiyim 已提交
254
        if not vocab_path.exists():
C
chenxuyi 已提交
255 256 257 258 259 260 261
            raise ValueError('no vocab file in pretrain dir: %s' %
                             pretrain_dir)
        vocab_dict = {
            j.strip().split('\t')[0]: i
            for i, j in enumerate(
                vocab_path.open(encoding='utf8').readlines())
        }
M
Meiyim 已提交
262 263 264 265 266 267 268

        t = cls(vocab_dict, sp_model_path, **kwargs)
        return t

    def __init__(self, vocab, sp_model_path, **kwargs):
        super(ErnieTinyTokenizer, self).__init__(vocab, **kwargs)
        import sentencepiece as spm
M
Meiyim 已提交
269
        import jieba as jb
M
Meiyim 已提交
270 271 272
        self.sp_model = spm.SentencePieceProcessor()
        self.window_size = 5
        self.sp_model.Load(sp_model_path)
M
Meiyim 已提交
273
        self.jb = jb
M
Meiyim 已提交
274 275

    def cut(self, sentence):
M
Meiyim 已提交
276
        return self.jb.cut(sentence)
M
Meiyim 已提交
277 278 279 280 281 282 283 284 285 286 287 288 289

    def tokenize(self, text):
        if len(text) == 0:
            return []
        if not isinstance(text, six.string_types):
            text = text.decode(self.encoding)
        if self.lower:
            text = text.lower()

        res = []
        for match in self.cut(text):
            res += self.sp_model.EncodeAsPieces(match)
        return res