Files
opencv-MIRROR/modules/dnn/src/tokenizer/utils.hpp
Jaivardhan Bhola 84c2360c27 Merge pull request #29675 from jaivardhan-bhola:generalized-tokenizer
Generalize tokenizer loading to support method-based family dispatch in DNN - #29675

Companion PR: https://github.com/opencv/opencv_extra/pull/1402

### Changes
Added ALBERT and BERT support end-to-end, with `samples/dnn/albert_inference.py `and `samples/dnn/bert_inference.py `as validation samples, plus expanded coverage in modules/dnn/test/test_tokenizer.cpp. Required changes to `cv::dnn::dnn.hpp`, `graph_fusion_attention.cpp`, and `unicode.cpp/unicode.hpp` to support Unigram and WordPiece tokenizers.

To back ALBERT/BERT, generalized `cv::dnn::Tokenizer `from a single BPE implementation into a method-dispatched frontend, adding `core_wordpiece.cpp/hpp` (WordPiece) and `core_unigram.cpp/hpp` (Unigram) as new backends. `tokenizer.cpp` now routes by method across BPE, Gemma,, SentencePiece, Unigram, and WordPiece behind one shared interface.

Tested against the following samples and the output matches to old tokenizer:

```
gpt2_inference.py
qwen_inference.py
gemma3_inference.py
```
GPT2:

```
Preparing GPT-2 model...
Inferencing GPT-2 model...
Hello, I'm a language model, not a programming language. I'm a language model. I'm a language model. I'm a language model. I'm a language model. I'm a
```

Gemma3:
```
Preparing Gemma3 model...
Prompt:
<start_of_turn>user
What is OpenCV?<end_of_turn>
<start_of_turn>model

Inferencing Gemma3 model...
Response:
Okay, let's break down what OpenCV is.

**What is OpenCV?**

OpenCV (Open Source Computer Vision Library) is a powerful and
```

Qwen2.5:
```
Preparing Qwen2.5 model...
Prompt:
<|im_start|>user
What is OpenCV?<|im_end|>
<|im_start|>assistant

Inferencing Qwen2.5 model...
Response:
OpenCV is a set of computer vision libraries in C++ designed to be used for image and video processing. It provides a wide range of tools and functions for
```

### Tokenizer References 
Byte-level BPE: [tokenizers/src/pre_tokenizers/byte_level.rs](https://github.com/huggingface/tokenizers/blob/main/tokenizers/src/pre_tokenizers/byte_level.rs)
(This defines the byte-level mapping rules, which is used in conjunction with the [BPE model](https://www.google.com/search?q=https://github.com/huggingface/tokenizers/blob/main/tokenizers/src/models/bpe/mod.rs))

SentencePiece BPE (Metaspace): [tokenizers/src/pre_tokenizers/metaspace.rs](https://www.google.com/search?q=https://github.com/huggingface/tokenizers/blob/main/tokenizers/src/pre_tokenizers/metaspace.rs)
(This defines the rule for replacing whitespace with the U+2581 _ character and handling byte fallback)

Unigram: [tokenizers/src/models/unigram/mod.rs](https://www.google.com/search?q=https://github.com/huggingface/tokenizers/blob/main/tokenizers/src/models/unigram/mod.rs)
(This contains the core logic for the Unigram lattice scoring and probabilistic tokenization rules)

WordPiece: [tokenizers/src/models/wordpiece/mod.rs](https://www.google.com/search?q=https://github.com/huggingface/tokenizers/blob/main/tokenizers/src/models/wordpiece/mod.rs)
(This explicitly cites Schuster & Nakajima in the code comments and implements the greedy longest-match rule with the ## prefix)

### Pull Request Readiness Checklist

- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on
      code under GPL or another license incompatible with OpenCV.
- [x] The PR is proposed to the proper branch (`5.x`).
- [x] There is a reference to the original bug report and related work.
- [x] There is accuracy test and test data in `opencv_extra`, same
      branch name (`generalized-tokenizer`) — `bert/`, `t5/` fixtures
      back the new C++ tests.
- [x] The feature is documented and sample code builds with project CMake.
2026-09-23 16:20:33 +03:00

93 lines
3.3 KiB
C++

// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#ifndef __OPENCV_DNN_TOKENIZER_UTILS_HPP__
#define __OPENCV_DNN_TOKENIZER_UTILS_HPP__
#include <string>
#include <unordered_map>
namespace cv { namespace dnn {
// Counts codepoints without decoding; continuation bytes are 0b10xxxxxx.
static inline size_t utf8CodepointCount(const std::string& s)
{
size_t n = 0;
for (char c : s)
n += ((unsigned char)c & 0xC0) != 0x80;
return n;
}
// Splits 'text' on the longest-matching entries of 'specialToId' that pass
// 'isAllowed', calling 'onLiteral' for each in-between run and 'onSpecialId'
// for each match, left to right. Shared by WordPiece and Unigram, whose
// special-token pre-splitting is otherwise identical.
template <typename AllowedFn, typename LiteralFn, typename SpecialFn>
static void splitOnSpecialTokens(const std::string& text,
const std::unordered_map<std::string, int>& specialToId,
AllowedFn isAllowed, LiteralFn onLiteral, SpecialFn onSpecialId)
{
size_t chunkStart = 0;
size_t pos = 0;
while (pos < text.size()) {
std::string matched;
int matchedId = -1;
const char head = text[pos];
for (const auto& kv : specialToId) {
const std::string& sp = kv.first;
if (sp.empty() || sp[0] != head) continue;
if (pos + sp.size() > text.size()) continue;
if (sp.size() <= matched.size()) continue;
if (!isAllowed(sp)) continue;
if (text.compare(pos, sp.size(), sp) != 0) continue;
matched = sp; matchedId = kv.second;
}
if (matchedId >= 0) {
if (pos > chunkStart) onLiteral(text.substr(chunkStart, pos - chunkStart));
onSpecialId(matchedId);
pos += matched.size();
chunkStart = pos;
} else {
++pos;
}
}
if (chunkStart < text.size()) onLiteral(text.substr(chunkStart));
}
// R"R50K('(?:[sdmt]|ll|ve|re)| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+$|\s+(?!\S)|\s)R50K"
static const std::string R50K_UTF8 = "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)";
// Extracts and erases a JSON string field FileStorage cannot parse: it caps string
// literals at CV_FS_MAX_LEN (4096), a precompiled_charsmap is hundreds of KB.
static inline std::string extractAndStripBase64Field(std::string& jsonText,
const std::string& fieldKey)
{
std::string extracted;
const std::string needle = "\"" + fieldKey + "\"";
size_t keyPos = jsonText.find(needle);
if (keyPos == std::string::npos)
return extracted;
size_t colon = jsonText.find(':', keyPos + needle.size());
if (colon == std::string::npos)
return extracted;
size_t valueStart = jsonText.find('"', colon + 1);
if (valueStart == std::string::npos)
return extracted;
++valueStart;
size_t valueEnd = jsonText.find('"', valueStart);
if (valueEnd == std::string::npos)
return extracted;
extracted = jsonText.substr(valueStart, valueEnd - valueStart);
jsonText.erase(valueStart, valueEnd - valueStart);
return extracted;
}
}}
#endif