tokenization.cpp 7.38 KB
Newer Older
1
2
3
#include <algorithm>
#include <cstring>
#include <fstream>
liucong's avatar
liucong committed
4
#include <stdexcept>
5
6

#include "./tokenization.h"
liucong's avatar
liucong committed
7
#include "utf8proc.h"
8
9
10

namespace cuBERT {

liucong's avatar
liucong committed
11
12
13
14
15
void FullTokenizer::convert_tokens_to_ids(const std::vector<std::string>& tokens, uint64_t* ids)
{
    for(int i = 0; i < tokens.size(); ++i)
    {
        ids[i] = convert_token_to_id(tokens[i]);
16
    }
liucong's avatar
liucong committed
17
}
18
19

// trim from start (in place)
liucong's avatar
liucong committed
20
21
22
23
static inline void ltrim(std::string& s)
{
    s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) { return !std::isspace(ch); }));
}
24
25

// trim from end (in place)
liucong's avatar
liucong committed
26
27
28
29
30
static inline void rtrim(std::string& s)
{
    s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { return !std::isspace(ch); }).base(),
            s.end());
}
31
32

// trim from both ends (in place)
liucong's avatar
liucong committed
33
34
35
36
37
static inline void trim(std::string& s)
{
    ltrim(s);
    rtrim(s);
}
38

liucong's avatar
liucong committed
39
40
41
42
43
44
void load_vocab(const char* vocab_file, std::unordered_map<std::string, uint64_t>* vocab)
{
    std::ifstream file(vocab_file);
    if(!file)
    {
        throw std::invalid_argument("Unable to open vocab file");
45
46
    }

liucong's avatar
liucong committed
47
48
49
50
51
52
53
    unsigned int index = 0;
    std::string line;
    while(std::getline(file, line))
    {
        trim(line);
        (*vocab)[line] = index;
        index++;
54
55
    }

liucong's avatar
liucong committed
56
57
    file.close();
}
58

liucong's avatar
liucong committed
59
60
61
62
63
inline bool _is_whitespace(int c, const char* cat)
{
    if(c == ' ' || c == '\t' || c == '\n' || c == '\r')
    {
        return true;
64
    }
liucong's avatar
liucong committed
65
66
    return cat[0] == 'Z' && cat[1] == 's';
}
67

liucong's avatar
liucong committed
68
69
70
71
72
73
74
inline bool _is_control(int c, const char* cat)
{
    // These are technically control characters but we count them as whitespace
    // characters.
    if(c == '\t' || c == '\n' || c == '\r')
    {
        return false;
75
    }
liucong's avatar
liucong committed
76
77
    return 'C' == *cat;
}
78

liucong's avatar
liucong committed
79
80
81
82
83
84
85
86
87
88
inline bool _is_punctuation(int cp, const char* cat)
{
    // We treat all non-letter/number ASCII as punctuation.
    // Characters such as "^", "$", and "`" are not in the Unicode
    // Punctuation class but we treat them as punctuation anyways, for
    // consistency.
    if((cp >= 33 && cp <= 47) || (cp >= 58 && cp <= 64) || (cp >= 91 && cp <= 96) ||
       (cp >= 123 && cp <= 126))
    {
        return true;
89
    }
liucong's avatar
liucong committed
90
91
    return 'P' == *cat;
}
92

liucong's avatar
liucong committed
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
bool _is_whitespace(int c) { return _is_whitespace(c, utf8proc_category_string(c)); }

bool _is_control(int c) { return _is_control(c, utf8proc_category_string(c)); }

bool _is_punctuation(int cp) { return _is_punctuation(cp, utf8proc_category_string(cp)); }

bool BasicTokenizer::_is_chinese_char(int cp)
{
    // This defines a "chinese character" as anything in the CJK Unicode block:
    //   https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
    //
    // Note that the CJK Unicode block is NOT all Japanese and Korean characters,
    // despite its name. The modern Korean Hangul alphabet is a different block,
    // as is Japanese Hiragana and Katakana. Those alphabets are used to write
    // space-separated words, so they are not treated specially and handled
    // like the all of the other languages.
    return (cp >= 0x4E00 && cp <= 0x9FFF) || (cp >= 0x3400 && cp <= 0x4DBF) ||
           (cp >= 0x20000 && cp <= 0x2A6DF) || (cp >= 0x2A700 && cp <= 0x2B73F) ||
           (cp >= 0x2B740 && cp <= 0x2B81F) || (cp >= 0x2B820 && cp <= 0x2CEAF) ||
           (cp >= 0xF900 && cp <= 0xFAFF) || (cp >= 0x2F800 && cp <= 0x2FA1F);
}
114

liucong's avatar
liucong committed
115
116
117
118
119
120
121
122
123
124
125
126
127
void BasicTokenizer::tokenize(const char* text,
                              std::vector<std::string>* output_tokens,
                              size_t max_length)
{
    // This was added on November 1st, 2018 for the multilingual and Chinese
    // models. This is also applied to the English models now, but it doesn't
    // matter since the English models were not trained on any Chinese data
    // and generally don't have any Chinese data in them (there are Chinese
    // characters in the vocabulary because Wikipedia does have some Chinese
    // words in the English Wikipedia.).
    if(do_lower_case)
    {
        text = (const char*)utf8proc_NFD((const utf8proc_uint8_t*)text);
128
129
    }

liucong's avatar
liucong committed
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
    size_t word_bytes = std::strlen(text);
    bool new_token    = true;
    size_t subpos     = 0;
    int cp;
    char dst[4];

    while(word_bytes > 0)
    {
        int len = utf8proc_iterate((const utf8proc_uint8_t*)text + subpos, word_bytes, &cp);
        if(len < 0)
        {
            std::cerr << "UTF-8 decode error: " << text << std::endl;
            break;
        }
        if(do_lower_case)
        {
            cp = utf8proc_tolower(cp);
147
148
        }

liucong's avatar
liucong committed
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
        const char* cat = utf8proc_category_string(cp);
        if(cp == 0 || cp == 0xfffd || _is_control(cp, cat))
        {
            // pass
        }
        else if(do_lower_case && cat[0] == 'M' && cat[1] == 'n')
        {
            // pass
        }
        else if(_is_whitespace(cp, cat))
        {
            new_token = true;
        }
        else
        {
            size_t dst_len      = len;
            const char* dst_ptr = text + subpos;
            if(do_lower_case)
            {
                dst_len = utf8proc_encode_char(cp, (utf8proc_uint8_t*)dst);
                dst_ptr = dst;
170
171
            }

liucong's avatar
liucong committed
172
173
174
            if(_is_punctuation(cp, cat) || _is_chinese_char(cp))
            {
                output_tokens->emplace_back(dst_ptr, dst_len);
175
                new_token = true;
liucong's avatar
liucong committed
176
177
178
179
180
            }
            else
            {
                if(new_token)
                {
181
                    output_tokens->emplace_back(dst_ptr, dst_len);
liucong's avatar
liucong committed
182
183
184
185
186
                    new_token = false;
                }
                else
                {
                    output_tokens->at(output_tokens->size() - 1).append(dst_ptr, dst_len);
187
188
                }
            }
liucong's avatar
liucong committed
189
        }
190

liucong's avatar
liucong committed
191
192
        word_bytes = word_bytes - len;
        subpos     = subpos + len;
193

liucong's avatar
liucong committed
194
195
196
197
        // early terminate
        if(output_tokens->size() >= max_length)
        {
            break;
198
        }
liucong's avatar
liucong committed
199
    }
200

liucong's avatar
liucong committed
201
202
203
    if(do_lower_case)
    {
        free((void*)text);
204
    }
liucong's avatar
liucong committed
205
}
206

liucong's avatar
liucong committed
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
void WordpieceTokenizer::tokenize(const std::string& token, std::vector<std::string>* output_tokens)
{
    if(token.size() > max_input_chars_per_word)
    { // FIXME: slightly different
        output_tokens->push_back(unk_token);
        return;
    }
    size_t output_tokens_len = output_tokens->size();

    for(size_t start = 0; start < token.size();)
    {
        bool is_bad = true;

        // TODO: can be optimized by prefix-tree
        for(size_t end = token.size(); start < end; --end)
        { // FIXME: slightly different
            std::string substr = start > 0 ? "##" + token.substr(start, end - start)
                                           : token.substr(start, end - start);
            if(vocab->count(substr))
            {
                is_bad = false;
                output_tokens->push_back(substr);
                start = end;
                break;
            }
        }
233

liucong's avatar
liucong committed
234
235
236
        if(is_bad)
        {
            output_tokens->resize(output_tokens_len);
237
238
239
240
            output_tokens->push_back(unk_token);
            return;
        }
    }
liucong's avatar
liucong committed
241
}
242

liucong's avatar
liucong committed
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
void FullTokenizer::tokenize(const char* text,
                             std::vector<std::string>* output_tokens,
                             size_t max_length)
{
    std::vector<std::string> tokens;
    tokens.reserve(max_length);
    basic_tokenizer->tokenize(text, &tokens, max_length);

    for(const auto& token : tokens)
    {
        wordpiece_tokenizer->tokenize(token, output_tokens);

        // early terminate
        if(output_tokens->size() >= max_length)
        {
            break;
259
260
261
        }
    }
}
liucong's avatar
liucong committed
262
} // namespace cuBERT