MCPcopy Create free account
hub / github.com/Luce-Org/lucebox-hub / bpe_encode_piece

Method bpe_encode_piece

server/src/server/tokenizer.cpp:364–518  ·  view source on GitHub ↗

Encode a single pre-tokenized piece using BPE merges.

Source from the content-addressed store, hash-verified

362
363// Encode a single pre-tokenized piece using BPE merges.
364std::vector<int32_t> Tokenizer::bpe_encode_piece(const std::string & piece) const {
365 if (piece.empty()) return {};
366
367 std::vector<std::string> symbols;
368
369 if (is_sentencepiece_) {
370 // SentencePiece: replace leading space with ▁, tokens are raw UTF-8.
371 std::string sp_piece;
372 sp_piece.reserve(piece.size() + 2);
373 size_t start = 0;
374 if (!piece.empty() && piece[0] == ' ') {
375 sp_piece += "\xe2\x96\x81"; // ▁ (U+2581)
376 start = 1;
377 }
378 sp_piece += piece.substr(start);
379 // Replace any remaining spaces with ▁
380 std::string encoded;
381 encoded.reserve(sp_piece.size());
382 for (char c : sp_piece) {
383 if (c == ' ') {
384 encoded += "\xe2\x96\x81";
385 } else {
386 encoded += c;
387 }
388 }
389
390 // Try whole piece as single token.
391 auto it = token_to_id_.find(encoded);
392 if (it != token_to_id_.end()) {
393 return { it->second };
394 }
395
396 // Split into individual UTF-8 characters as initial BPE symbols.
397 const char * p = encoded.c_str();
398 const char * end = p + encoded.size();
399 while (p < end) {
400 int cplen;
401 utf8_decode(p, (size_t)(end - p), &cplen);
402 if (cplen <= 0) cplen = 1;
403 std::string sym(p, cplen);
404 auto sit = token_to_id_.find(sym);
405 if (sit != token_to_id_.end()) {
406 symbols.push_back(sym);
407 } else {
408 // Byte-fallback: <0xNN>
409 char buf[8];
410 std::snprintf(buf, sizeof(buf), "<0x%02X>", (unsigned)(uint8_t)*p);
411 symbols.push_back(buf);
412 }
413 p += cplen;
414 }
415 } else {
416 // GPT-2 BPE: convert raw text to GPT-2 byte encoding for vocab lookup.
417 std::string encoded = encode_gpt2_bpe(piece);
418
419 // Try to find the encoded piece as a single token first.
420 auto it = token_to_id_.find(encoded);
421 if (it != token_to_id_.end()) {

Callers

nothing calls this directly

Calls 5

utf8_decodeFunction · 0.85
encode_gpt2_bpeFunction · 0.85
byte_to_gpt2_unicodeFunction · 0.85
emptyMethod · 0.45
sizeMethod · 0.45

Tested by

no test coverage detected