Splits text into word tokens following the CLIP pattern: <|startoftext|> | <|endoftext|> | 's|'t|'re|'ve|'m|'ll|'d | [\p{L}]+ | [\p{N}] | [^\s\p{L}\p{N}]+
| 1323 | // <|startoftext|> | <|endoftext|> | 's|'t|'re|'ve|'m|'ll|'d |
| 1324 | // | [\p{L}]+ | [\p{N}] | [^\s\p{L}\p{N}]+ |
| 1325 | static std::vector<std::string> sam3_pretokenize(const std::string& text) { |
| 1326 | std::vector<std::string> tokens; |
| 1327 | size_t i = 0; |
| 1328 | const size_t n = text.size(); |
| 1329 | |
| 1330 | while (i < n) { |
| 1331 | uint8_t c = (uint8_t)text[i]; |
| 1332 | |
| 1333 | if (c == ' ' || c == '\t' || c == '\n' || c == '\r') { |
| 1334 | i++; |
| 1335 | continue; |
| 1336 | } |
| 1337 | |
| 1338 | if (i + 15 <= n && text.compare(i, 15, "<|startoftext|>") == 0) { |
| 1339 | tokens.push_back("<|startoftext|>"); |
| 1340 | i += 15; |
| 1341 | continue; |
| 1342 | } |
| 1343 | if (i + 13 <= n && text.compare(i, 13, "<|endoftext|>") == 0) { |
| 1344 | tokens.push_back("<|endoftext|>"); |
| 1345 | i += 13; |
| 1346 | continue; |
| 1347 | } |
| 1348 | |
| 1349 | // Must check contractions before letters since ' isn't a letter |
| 1350 | if (c == '\'') { |
| 1351 | if (i + 2 <= n) { |
| 1352 | char c2 = text[i + 1]; |
| 1353 | if (c2 == 's' || c2 == 't' || c2 == 'm' || c2 == 'd') { |
| 1354 | tokens.push_back(text.substr(i, 2)); |
| 1355 | i += 2; |
| 1356 | continue; |
| 1357 | } |
| 1358 | } |
| 1359 | if (i + 3 <= n) { |
| 1360 | std::string c3 = text.substr(i + 1, 2); |
| 1361 | if (c3 == "re" || c3 == "ve" || c3 == "ll") { |
| 1362 | tokens.push_back(text.substr(i, 3)); |
| 1363 | i += 3; |
| 1364 | continue; |
| 1365 | } |
| 1366 | } |
| 1367 | // Fall through — not a contraction |
| 1368 | } |
| 1369 | |
| 1370 | if (sam3_is_letter(text, i)) { |
| 1371 | size_t start = i; |
| 1372 | while (i < n && sam3_is_letter(text, i)) { |
| 1373 | i += sam3_utf8_len((uint8_t)text[i]); |
| 1374 | } |
| 1375 | tokens.push_back(text.substr(start, i - start)); |
| 1376 | continue; |
| 1377 | } |
| 1378 | |
| 1379 | if (c >= '0' && c <= '9') { |
| 1380 | tokens.push_back(text.substr(i, 1)); |
| 1381 | i++; |
| 1382 | continue; |
no test coverage detected