Skip to content

Instantly share code, notes, and snippets.

@JorgeV92
Last active April 8, 2025 03:42
Show Gist options
  • Select an option

  • Save JorgeV92/5382b8819794ab7ed9036879576618d3 to your computer and use it in GitHub Desktop.

Select an option

Save JorgeV92/5382b8819794ab7ed9036879576618d3 to your computer and use it in GitHub Desktop.

Google Summer of Code 2025 Proposal

Better LLMs Support in OpenCV: Tokenizer Integration into DNN Module

Student: Jorge Velez
Email: jorgev2@illinois.edu
GitHub: JorgeV92
LinkedIn: jorge-velez-cs
Website: jorgevelezcs.com
Institution: University of Illinois Urbana-Champaign
Major Computer Science
Mentor: Yuantao Feng


About Me

I am a recent graduate (December 2024) with a Bachelor of Science in Computer Science from UIUC. I've always been curious about open source and finding meaningful projects to get involved with. OpenCV, in particular, has been a technology I've wanted to explore deeply, especially after becoming interested in computer vision through reading David Marr's Vision and recognizing OpenCV as a part of realizing Marr's ideas. My goal is to gain experience in industry and open source before pursuing a master's degree in computer science. I also plan to use open source projects as inspiration to identify potential research ideas and directions for my master's studies.

Integrating Tokenizer Support into OpenCV DNN for LLMs

Overview: OpenCV DNN and the Need for Tokenization

OpenCV’s Deep Neural Network (DNN) module is a framework for running neural network inference (primarily vision models) in C++ and Python. It supports loading models (e.g. from ONNX, TensorFlow, Caffe) and executing them on images or other numeric data. However, it currently lacks native text preprocessing/tokenization support, which is crucial for Large Language Models (LLMs). In practice, this means that if you want to run an LLM (like GPT-2/3) with OpenCV, you must use an external tokenizer library to convert text to token IDs before feeding it to the network (Contribution to OpenCV DNN Module – Tokenizer Integration) (opencv/samples/dnn/gpt2_inference.py at 5.x · opencv/opencv · GitHub). For example, the OpenCV sample for GPT-2 relies on OpenAI’s tiktoken to encode the input text and decode outputs (opencv/samples/dnn/gpt2_inference.py at 5.x · opencv/opencv · GitHub). This external dependency adds complexity and overhead. Integrating a tokenizer into OpenCV’s DNN module would enable end-to-end pipelines entirely within OpenCV – raw text → tokens → DNN → output tokens → text, without leaving the OpenCV environment (Contribution to OpenCV DNN Module – Tokenizer Integration).

LLM tokenization pipeline

Figure: LLM tokenization pipeline – raw text is converted to a sequence of token IDs by a Tokenizer, which the DNN (LLM) model processes. The model’s output tokens are then decoded back to text (The Technical User's Introduction to LLM Tokenization). Integrating this tokenization step into OpenCV’s DNN module allows seamless text→model→text workflows.

OpenCV DNN Architecture and Integration Points

The OpenCV DNN module is designed around a cv::dnn::Net class that encapsulates a neural network, with methods to set input blobs and run forward passes. Inputs to a network are typically provided as numeric arrays (e.g. images turned into multi-dimensional blobs). Currently, there is no built-in mechanism to accept raw text as input – any text must be converted to numeric token IDs externally. The goal is to introduce a tokenizer component within the DNN module that can handle this conversion.

A logical design is to add a new class (or set of classes) under the cv::dnn namespace, for example cv::dnn::Tokenizer. This class would be responsible for:

  • Encoding: Converting an input string (raw text) into a sequence of integer token IDs (per a specified tokenizer algorithm/vocabulary).
  • Decoding: Converting a sequence of token IDs back into a human-readable string.

This tokenizer could be used in conjunction with cv::dnn::Net. For instance, one would load an LLM model (cv::dnn::Net net = cv::dnn::readNet("model.onnx")), prepare a tokenizer (cv::dnn::Tokenizer tok; tok.loadVocab("vocab.json", "merges.txt")), then encode an input sentence and feed it to the network:

std::vector<int> tokens = tok.encode("Hello, OpenCV!");
cv::Mat input = cv::Mat(tokens).reshape(1, {1, (int)tokens.size()});  // 1xN int32 tensor
net.setInput(input, "input_ids");  // feed token IDs to the model's input
cv::Mat output_ids = net.forward(); 
std::string resultText = tok.decode(output_ids);

In Python, after exposing the class, it would look similar (e.g. tokenizer = cv.dnn.Tokenizer() then tokens = tokenizer.encode("Hello, OpenCV!"), etc.). By integrating at this level, tokenization becomes a first-class part of the OpenCV inference pipeline, much like image preprocessing (e.g. blobFromImage) is for vision models. The GSoC proposal highlights exactly this goal: introducing a dnn::Tokenizer sub-module to handle the “text → token → DNN network → decoded text” workflow seamlessly. Tokenized sequences (arrays of ints) would be treated just like any other network input, and the DNN module would ensure they can be passed into embedding layers or other components of an LLM model.

Where to integrate in code structure? OpenCV’s dnn is modular: new functionality is usually added either as utility functions or new classes. For tokenization, adding a new source file (e.g. tokenizer.cpp/tokenizer.hpp in the dnn module) for the Tokenizer class is appropriate. This class would not be a neural network layer but a separate utility (similar in spirit to how cv::dnn::blobFromImage is a utility for image preprocessing). It may also be useful to integrate the tokenizer with high-level model APIs – OpenCV has classes like cv::dnn::TextDetectionModel for OCR; similarly, a future cv::dnn::TextGenerationModel or LanguageModel wrapper could combine a Net and a Tokenizer for convenience. Initially, however, focusing on the tokenizer component itself keeps the design clean.

Another consideration is flexible input shapes for LLMs. Unlike vision models (which have fixed-size inputs), text sequences are variable length. OpenCV’s DNN engine historically allocates fixed buffers based on the model’s graph. Part of “better LLM support” (another GSoC idea) is updating DNN to handle dynamic lengths (GSoC_2025 · opencv/opencv Wiki · GitHub). The tokenizer integration ties into this: we should design the API such that the token sequences can be of arbitrary length (e.g. the encode method returns a std::vector<int> which can then be turned into a cv::Mat of appropriate shape). OpenCV DNN already supports int32 input blobs (for example, GPT-2 models expect input_ids as int32 and OpenCV can set those inputs (opencv/samples/dnn/gpt2_inference.py at 5.x · opencv/opencv · GitHub)), so the numeric backend is capable of handling token data.

In summary, the integration point is primarily at the interface level: providing a tool in the DNN module to convert text to the numeric tensors that the networks can consume. Now, to design such a tokenizer, we should draw on the experience of existing tokenization implementations.

Learning from Existing Tokenizer Implementations

OpenAI’s Tiktoken and GPT Tokenizer Internals

OpenAI’s tiktoken is a fast implementation of the GPT-family tokenizers. It uses the Byte Pair Encoding (BPE) algorithm (specifically, GPT-2’s byte-level BPE) to convert text to tokens (GitHub - openai/tiktoken: tiktoken is a fast BPE tokeniser for use with OpenAI's models.). At a high level, BPE starts with a base vocabulary of single characters and iteratively merges the most frequent pair of symbols in a training corpus to form new tokens. This results in a vocabulary of subword units that efficiently represent the language. For encoding new text, the BPE algorithm will:

  1. Normalize/prepare text (GPT uses a byte-level approach: the input text is converted to a stream of bytes, e.g., UTF-8 bytes, ensuring even unseen characters can be handled).
  2. Initial tokenization into basic units. In GPT-2’s case, each byte is initially considered a token; (historically, GPT-2 also applied a regex to segment text into words and punctuation, then byte-encoded those segments).
  3. Greedy merges: Repeatedly merge adjacent tokens if the pair appears in the BPE merge table (vocabulary). This is done until no more merges apply. The result is a sequence of subword tokens, as large as possible. In LLaMA’s implementation (which also uses a BPE tokenizer via SentencePiece), “the tokenization process starts by breaking down the prompt into single-character tokens. Then, it iteratively merges each pair of consecutive tokens into a larger token as long as the merged token is in the vocabulary, ensuring the final tokens are as large as possible” (Understanding how LLM inference works with llama.cpp).
  4. Lookup token IDs: Each resulting token (subword string) is mapped to an integer ID via the vocabulary dictionary. These IDs are what the model uses as input.

Decoding is the reverse: map IDs to tokens (subword text) and concatenate them to form the output string (with any necessary post-processing, e.g., merging byte sequences back into Unicode text).

OpenAI’s tiktoken implements this very efficiently. Notably, tiktoken is written in Rust and optimized for speed, since tokenization can be a bottleneck for large text. It likely uses a precomputed trie or hashmap of token substrings to merge in linear time. The repository describes it as “a fast BPE tokenizer for use with OpenAI’s models” (GitHub - openai/tiktoken: tiktoken is a fast BPE tokeniser for use with OpenAI's models.). One interesting design choice of GPT tokenizers is they often treat whitespace as a significant token: for example, GPT-2’s vocabulary includes a special space character (▁ or Ġ in various notations) to preserve word boundaries. All these details need to be handled for compatibility.

For our OpenCV integration, the lessons from tiktoken are: use BPE for broad model compatibility (many LLMs use BPE or similar subword methods), and focus on performance (we might implement in C++ for speed, possibly using efficient data structures to mimic tiktoken’s performance). We also see that tiktoken provides a simple API: e.g. enc = tiktoken.get_encoding('gpt2') to load a specific tokenizer, then enc.encode(text) and enc.decode(tokens) (opencv/samples/dnn/gpt2_inference.py at 5.x · opencv/opencv · GitHub). We can aim for a similarly simple interface in OpenCV (perhaps Tokenizer::create("gpt2") or a load function with vocab files).

Hugging Face’s AutoTokenizer and Tokenizers Library

Hugging Face Transformers provides AutoTokenizer as a high-level factory that can load the correct tokenizer for a given model name. Internally, it has mappings from model types to specific tokenizer classes (for example, "bert" → BertTokenizer or BertTokenizerFast; "gpt2" → GPT2Tokenizer etc.) (transformers/src/transformers/models/auto/tokenization_auto.py at main · huggingface/transformers · GitHub). When you call AutoTokenizer.from_pretrained("gpt2"), it will load GPT-2’s vocabulary and merges, and instantiate a GPT2Tokenizer. If available, it prefers the “Fast” version of the tokenizer (implemented with the HuggingFace tokenizers library in Rust) (transformers/src/transformers/models/auto/tokenization_auto.py at main · huggingface/transformers · GitHub). The AutoTokenizer logic checks the model config for model_type to select the appropriate algorithm (transformers/src/transformers/models/auto/tokenization_auto.py at main · huggingface/transformers · GitHub) – for instance, BERT uses WordPiece tokenization (a variant of BPE), GPT-2 uses byte-level BPE, others might use SentencePiece or Unigram, etc.

Key design takeaways from Hugging Face:

  • They separate the tokenizer logic by model/algorithm, but provide a unified API. We can do something similar: design our cv::dnn::Tokenizer to be flexible enough to support different tokenization strategies (BPE, WordPiece, etc.) while presenting a single interface to the user. In practice, this could mean an internal strategy pattern or an enum to select the algorithm. Initially, implementing one (BPE) is the priority, but structuring the code to allow adding others (like WordPiece or character tokenization) will future-proof the design.

  • The HuggingFace tokenizers library (which powers the “Fast” tokenizers) is written in Rust and is optimized. It uses a pipeline: Normalization (unicode fixes, lowercasing, etc.), Pre-tokenization (e.g., splitting on whitespace/punctuation), the Model (core algorithm like BPE or Unigram), and then Post-processing (adding special tokens) and Decoding. For integration into OpenCV, we should identify which parts we need. Likely, we will implement a basic normalization (or assume input is already normalized UTF-8), and focus on the core Model part (BPE). We should also handle special tokens in a simple way (the tokenizer class can allow adding tokens like <PAD> or <EOS> that map to an ID and are never split further).

  • HuggingFace tokenizers allow training a tokenizer from scratch (given a corpus) and saving/loading it. In our context, training BPE might be out of scope for the initial integration (it’s a heavy task), but we can implement the same merging algorithm if needed. A GSoC contributor has suggested starting with implementing BPE training in C++ (Add a Tokenizer for Text Processing in OpenCV(dnn module), Starting with Byte Pair Encoding (BPE) · Issue #27121 · opencv/opencv · GitHub). The basic steps (count symbol pairs, merge most frequent, etc.) are documented and could be included for completeness. At minimum, we should support loading existing vocabularies (e.g., from a file or from known presets), but it’s a bonus if we can also build a vocabulary from a corpus.

In short, HuggingFace’s approach teaches us to design the API for ease of use and flexibility. For OpenCV, we might not need the full complexity of AutoTokenizer.from_pretrained (since OpenCV won’t ship with dozens of model configs), but we can mirror its functionality by allowing either a preset name or file-based initialization. We should also follow their practice of providing both C++ and Python access – OpenCV’s build will automatically wrap our C++ Tokenizer class into Python, so users of the cv2 Python API can do the same text encoding.

GPT Tokenizer Walkthrough (Karpathy’s Video and Others)

The referenced walkthrough (e.g., Andrej Karpathy’s “Let's build the GPT tokenizer”) reinforces many of the above points and dives into code-level understanding of BPE.

  • Unicode handling: Karpathy discusses why GPT-2 doesn’t just use raw Unicode code points (inefficient large vocab) and instead uses byte encoding with BPE (The Technical User's Introduction to LLM Tokenization). Our implementation should likewise operate on a stable encoding (UTF-8 bytes) for consistency with existing models.

  • Vocabulary size trade-offs: BPE finds a sweet spot between too large a vocab (every word as a token) and too small (character tokens) (The Technical User's Introduction to LLM Tokenization). GPT-2’s vocab is ~50k. We won’t be choosing vocab size in integration (since we’ll use pre-made vocab), but this contextualizes why BPE is used.

  • Reversibility: BPE tokenization is lossless – it can be reversed to exactly the original text (The Technical User's Introduction to LLM Tokenization). This is important: our encode/decode must round-trip perfectly for all valid inputs (including spaces, punctuation, etc.). Testing on edge cases (like trailing spaces, unusual characters) is needed to ensure our implementation matches, for example, GPT-2’s tokenizer behavior (the Karpathy lecture lists several LLM quirks that boil down to tokenization issues – e.g., why certain strings like "SolidGoldMagikarp" or trailing spaces cause strange outputs.

  • Algorithm implementation: We might also consider the data structures Karpathy or others use in such an implementation (possibly a dictionary of pairs to scores, etc.) and adapt that to C++. An efficient approach is to compile the list of BPE merges into a trie of possible tokens for encoding, so that the input string can be consumed in linear time by matching the longest possible token at each position. This is how many modern tokenizers achieve speed – by avoiding repeated pair merge scans.

By studying these resources, we ensure our design choices align with proven methods. In summary, existing implementations teach us to: use BPE as a baseline (robust, widely used), treat tokenization as a distinct preprocessing step (not part of the model graph), optimize for performance (consider algorithmic efficiency in C++), and design a friendly API.

Best Practices for a C++ Tokenizer Implementation in OpenCV

With the context above, here’s how we can approach implementing the tokenizer in C++ to fit OpenCV’s design principles:

  • Keep it Lightweight and Self-Contained: OpenCV prefers minimal external dependencies. Thus, reimplementing the core tokenization logic in C++ is preferable to relying on an external library. This sentiment is echoed by OpenCV maintainers: “Reimplementing a part of HuggingFace’s tokenizers in C++ (I guess it's done in llama.cpp and maybe a few other places) would be a good contribution.” (Contribution to OpenCV DNN Module – Tokenizer Integration). This means we should write our own BPE (and potentially other algorithms) in pure C++, referencing existing open-source implementations for guidance but not adding heavy new libraries to OpenCV. Projects like llama.cpp demonstrate this is feasible – they have a llama_tokenize() function in C++ that performs SentencePiece BPE tokenization efficiently (Understanding how LLM inference works with llama.cpp).

  • Data Structures and Performance: Tokenization needs to be fast, especially for long inputs or when generating many tokens. In C++, we can use structures like std::unordered_map or std::unordered_set for vocab and merges. For BPE encoding, one approach is:

    • Store the vocabulary (token -> id mapping) in a hash map for O(1) lookup of token IDs.
    • Store the merge rules in a structure that allows quickly checking if a pair of tokens can be merged. For example, a std::unordered_set<std::pair<int,int>> of mergeable token id pairs could be used to guide merging by token IDs. Alternatively, store a mapping from token-pair string to merged token string (like how one would during training). However, a more optimal method is to preconstruct a trie of all multi-character tokens: each path in the trie represents a valid token. To encode, iterate through characters of the input and walk the trie to find the longest matching token. This avoids the iterative pair merging and directly yields tokens. This trie approach is effectively what the HuggingFace fast tokenizers do under the hood for BPE and can be very efficient.

    Initially, a simpler greedy merge implementation is fine (merge pairs iteratively as Karpathy shows). We can optimize later if needed. The important thing is to use efficient string handling (perhaps avoid constructing too many temporary strings during merges by working with indices or char arrays). Since GPT tokenization works at byte level, we will often be manipulating binary data – C++ std::string can handle that since it’s basically a byte array.

  • Memory considerations: Storing a large vocabulary (50k tokens) and corresponding data is not too heavy. But we should be mindful of memory when building/training tokenizers. If we implement training (which involves scanning a corpus and counting pairs), we should do so efficiently (e.g., using a dictionary of pairs to counts). We can use such references to ensure our implementation is correct and optimized (SentencePiece is written in C++ and optimized; while we may not incorporate it directly, we can borrow ideas).

  • Compatibility and Testing: We must ensure that our tokenizer produces the same tokenization as the reference (e.g., HuggingFace or OpenAI) for the same vocab. A good practice is to write unit tests with known examples. For instance, encode and decode some sample sentences with our implementation and compare against transformers library outputs or known token id sequences. This will catch issues with handling of spaces, unicode, or special tokens.

  • Special Tokens and Configurability: The tokenizer should allow defining special tokens (like [PAD], [CLS], <|endoftext|>). These are tokens that might be added to the vocab with a specific ID and should not be split or merged. We can handle this by simply including them in the vocabulary mapping (so if encountered in text exactly, they’re treated as one token) or by providing a method to add them. For decoding, these might be filtered out or handled specially (e.g., do not print an end-of-text token). OpenCV’s design can keep this simple: e.g., a method tokenizer.addSpecialToken("[PAD]", id) which inserts it into the vocab map.

  • Thread Safety and Reusability: Typically, OpenCV objects can be reused across calls, and users might call encode on multiple threads. Our Tokenizer class should be mostly read-only after initialization (vocab and merges are fixed), so it could be used from multiple threads to encode different texts. We should ensure that encode and decode do not use any shared mutable state without locks (if they just read from the vocab maps and such, it’s fine). This way, performance can scale in multithreaded environments.

  • Integration with OpenCV’s Python: To expose the C++ class to Python, we will use OpenCV’s binding generation (by marking the class with CV_EXPORTS_W and its methods with CV_WRAP). For example, CV_WRAP std::vector<int> encode(const cv::String& text); would allow Python to call encode() and get a Python list of ints (or numpy array). Likewise, decode can return a cv::String. We should test the Python API to ensure it’s convenient (possibly returning list of ints is fine; or we could even return a NumPy array for direct use with net.setInput). Aligning with OpenCV’s conventions, we might use cv::String (which is a typedef for std::string) for text to ensure UTF-8 handling.

  • Design for Multiple Algorithms: While BPE is the first target, we can design the class to handle alternatives. One approach is to have an abstract base Tokenizer with subclasses like BPETokenizer, WordPieceTokenizer, etc., and maybe a static method Tokenizer::create(Algorithm, args) to instantiate the desired one. However, given GSoC time constraints, a simpler approach is a single class that can be configured. For example, Tokenizer tokenizer; tokenizer.setAlgorithm(BPE); tokenizer.loadVocabulary(files...);. Internally, if WordPiece was chosen, the encode method might do slight variations (WordPiece is similar to BPE but uses a prefix (e.g., "##") for continuation pieces and might not operate byte-level). The initial implementation can focus on BPE logic; but keeping the interface generic (e.g., using terms like “vocab” and “tokenize” that apply to any subword tokenizer) will make it easier to extend.

  • Use of existing files/formats: We should support loading vocabulary files in common formats. For GPT-2/GPT-3, HuggingFace distributes a vocab.json (mapping token -> id) and merges.txt (list of BPE merges). We can parse these: the vocab JSON is straightforward, and the merges.txt lists pairs of tokens to merge (in order of precedence). SentencePiece uses a single .model or .txt with scores – supporting that would be nice but not necessary initially. Perhaps focusing on the GPT-2 format (since we have those files for GPT-2, and they’re easy to parse) is enough for a start. This will directly enable using OpenAI’s or HuggingFace’s vocab files with OpenCV’s tokenizer.

  • Vocabulary management: The tokenizer class should store the mapping from string->id and id->string. We can use std::unordered_map<std::string,int> for the forward map, and a std::vector<std::string> for id->token (assuming IDs are dense 0..N-1, which they usually are). Memory for 50k strings is fine. We might also store the merges as needed (possibly as a map from a pair of token strings to a new token string for encoding if using the pair-merge process).

To illustrate a step-by-step plan for integration:

  1. Design the Class Interface: Define class Tokenizer with methods bool loadVocabulary(const std::string& vocabFile, const std::string& mergesFile), std::vector<int> encode(const std::string& text), and std::string decode(const std::vector<int>& tokens). Also possibly trainBPE(corpus, vocab_size) if training is intended. Decide on any flags (like whether to use byte-level encoding, etc., which for GPT-2 BPE is true by default).
  2. Parsing Files: Implement loadVocabulary to read the vocab (JSON or txt) and merges. Construct the internal data structures (vocab map, reverse vocab, merges). For merges, one approach is to produce a structure mapping each possible pair of tokens (as strings or as IDs) to a new token ID – essentially replicating the merge table. However, a simpler implementation is to just store the merge ranks: e.g., load merges into a map of pair->rank (priority), then during encoding use that to decide which pair to merge next (the one with lowest rank number). This is how one would implement the iterative BPE merge: find the pair with highest priority (lowest rank) among adjacent tokens and merge it, repeat. We can optimize by scanning the text once to initialize pairs, then using a heap or priority queue of pairs. Since this is complex to implement live, an alternative is as mentioned earlier: build a trie of tokens directly from the vocab. For a first iteration, the iterative merge is fine.
  3. Encoding Implementation: Implement encode(). Likely process: if using byte-level, convert input string to a vector of bytes (0-255 values). Then convert that byte vector to a vector of token strings (each byte as a string, or potentially use a special representation for bytes). Then apply BPE merges: iterate merging adjacent tokens greedily. In code, one can represent the current tokenization as a list of tokens (starting as single-character strings). Then while any adjacent pair of tokens is in the merges table, merge the earliest such pair (or in proper BPE, merge all occurrences of the highest-priority pair in one pass). The output tokens then get looked up in the vocab map to get IDs. Important: If a token from the text is not in vocab (shouldn’t happen in BPE if you go down to single bytes – since all bytes 0-255 are in vocab for GPT-2), but for WordPiece or others, an unknown token might occur. In such case, one usually has an [UNK] token. For BPE/byte-level, no explicit [UNK] is needed because any string can be expressed as bytes. We should still design how to handle unknown gracefully (maybe throw or return an <UNK> id if configured).
    We can cite that “the tokenization splits the prompt into single characters and then merges consecutive tokens as long as the merged token is part of the vocabulary” (Understanding how LLM inference works with llama.cpp) as our guiding method.
  4. Decoding Implementation: This is simpler – map each token ID back to its string (byte sequence), and concatenate. Then, if byte-level encoding was used, we need to turn the bytes back into a UTF-8 string. Essentially, decode will map ids -> bytes -> string. We must be careful to correctly handle special tokens (e.g., if an ID corresponds to <PAD>, we might want to optionally remove it or leave it as is in the output). Typically, decoding returns the raw text exactly as originally encoded (if no special tokens that indicate truncation, etc., are present).
  5. Testing: Compare the output of our encode on sample texts with known outputs from HuggingFace’s tokenizer (for GPT-2, for example). Ensure that decoding those ids returns the original text. Test edge cases like an empty string, strings with only spaces, non-ASCII characters (e.g. emoji, CJK characters – these will be byte-encoded and should round-trip).
  6. Optimization: If performance is an issue, consider implementing a more direct encoding (trie-based). Also consider memory of merges: our naive approach might be O(N^2) for long texts if merging one pair at a time. Tools like huggingface/tokenizers achieve near linear time; we should strive for an efficient approach but it’s acceptable to start simple and improve. The OpenCV community can help optimize later if the functionality is in place.
  7. Python Binding: Ensure the class and methods are annotated for Python. Once built, test usage from Python: e.g.
    tok = cv.dnn.Tokenizer()
    tok.loadVocabulary("gpt2_vocab.json", "gpt2_merges.txt")
    ids = tok.encode("Hello world!")
    print(ids)                # e.g. [15496, 995] etc.
    print(tok.decode(ids))    # should print "Hello world!"
    This will be the ultimate user-facing proof of integration.
  • Design Alignment with OpenCV: The API should feel like OpenCV. That means using OpenCV data types (cv::String, cv::Mat where appropriate) and being consistent in naming. Possibly the class could be named cv::dnn::TextTokenizer or just Tokenizer. The GSoC idea simply calls it Tokenizer. Methods should be camelCase (encode, decode, etc.). Documentation in doxygen style should be added, as users will read the generated docs to understand usage.

Reimplement vs. Wrap: Trade-offs

One major decision is whether to write our own tokenizer or wrap an existing one. Given OpenCV’s context, reimplementation in C++ is favored. Let’s consider the options:

  • Reimplementing (C++ from scratch): This gives full control. We can tailor the implementation to OpenCV’s needs (perhaps not all bells and whistles, but enough for common use). There’s no additional runtime dependency – a user just gets the functionality out of the box. Licensing is also straightforward since our code will be original or based on permissible references (OpenCV is BSD-3 licensed, and we can incorporate ideas from Apache/MIT licensed projects like SentencePiece or HuggingFace tokenizers if needed). Maintenance might require some ongoing updates if new tokenization methods are added, but the core algorithms (BPE, WordPiece) are relatively stable and well-known. The GSoC mentor explicitly leaned towards this approach (Contribution to OpenCV DNN Module – Tokenizer Integration). The downside is the initial development effort and ensuring parity with existing tokenizers, which is achievable with thorough testing.

  • Wrapping an Existing Library: For example, we could try to use HuggingFace’s tokenizers library or Google’s SentencePiece by linking against them. However, this introduces several issues:

    • Dependency and Build Complexity: HuggingFace’s tokenizers is in Rust – integrating that into OpenCV C++ would be non-trivial. We would need a C API or use the Python binding, which defeats the purpose (since in C++ we don’t want to invoke Python). SentencePiece is C++ and could be more directly integrated, but it’s a fairly large library to include/maintain inside OpenCV, and it might overlap with what we can implement more lightly.
    • Binary Size: Adding a large third-party can bloat OpenCV.
    • Partial Functionality: We might not need everything those libraries offer (they support many algorithms, training, etc.). Using them would be like using a small part of a big tool.
    • License: Both tokenizers and SentencePiece are permissive (Apache 2.0), so legally it’s fine, but we’d need to make sure it’s acceptable to include or require users to install them.
    • Alternatives: We could call out to Python’s HuggingFace from C++ if Python is available, but OpenCV shouldn’t assume a Python environment in its C++ usage. So that’s not a general solution (though a user who is already in Python can just use HF directly – our goal is to benefit C++ usage and also simplify the pipeline for all).

Given these points, the most practical approach is to implement at least a basic tokenizer natively. This is in line with other projects: e.g., llama.cpp implemented a C++ SentencePiece BPE tokenizer for LLaMA models rather than depending on the Python SentencePiece. The OpenCV team also seems receptive to a custom implementation for GSoC (Contribution to OpenCV DNN Module – Tokenizer Integration).

One could consider a hybrid: perhaps using existing vocabulary data but with our code. That is fine – e.g., load the exact GPT-2 vocab files distributed by OpenAI/HF. This ensures compatibility without needing to embed those large lists in code.

In the long run, if our implementation proves too slow or incomplete, we could revisit integration with an optimized library. But starting with an OpenCV-managed implementation ensures we get the feature in a controllable way. Optimizations (even using SIMD or linking in parts of faster libraries) could be explored later if needed.

Proposed API Design (C++ & Python)

Taking all the above into account, here is a sketch of the proposed API and usage patterns:

C++ API Example:

#include <opencv2/dnn.hpp>

// Initialize tokenizer (e.g., BPE tokenizer with GPT-2 vocabulary)
cv::dnn::Tokenizer tokenizer;
tokenizer.loadVocabulary("gpt2_vocab.json", "gpt2_merges.txt");  // load BPE vocab

std::string text = "OpenCV integration with LLMs!";
std::vector<int> tokenIds = tokenizer.encode(text);

// Prepare input for DNN (batch size 1, seq length = tokenIds.size())
cv::Mat input(1, (int)tokenIds.size(), CV_32S, tokenIds.data());
// (Alternatively, use cv::Mat::reshape as shown earlier to make it 1xN)

// Load and run network
cv::dnn::Net net = cv::dnn::readNet("llm.onnx");
net.setInput(input, "input_ids");  // assuming the model expects "input_ids"
cv::Mat output = net.forward();

// Suppose output is a 1xM of token ids for generated text:
std::vector<int> outIds;
output.copyTo(outIds);  // extract output IDs from the Mat
std::string generatedText = tokenizer.decode(outIds);
std::cout << generatedText << std::endl;

Python API Example:

import cv2 as cv
tokenizer = cv.dnn.Tokenizer()
tokenizer.loadVocabulary("gpt2_vocab.json", "gpt2_merges.txt")

text = "OpenCV integration with LLMs!"
ids = tokenizer.encode(text)
print("Token IDs:", ids)

# Prepare network input
import numpy as np
input_array = np.array(ids, dtype=np.int32)[None, :]  # shape (1, N)
net = cv.dnn.readNet("llm.onnx")
net.setInput(input_array, "input_ids")
output = net.forward()  # assume output is (1, M) token IDs
out_ids = output.astype(np.int32).flatten().tolist()
print("Generated text:", tokenizer.decode(out_ids))

This demonstrates an end-to-end usage. The Tokenizer class here is simple to use: loadVocabulary could also infer the algorithm (for instance, if merges file is provided, we assume BPE). We might also allow something like tokenizer = cv.dnn.Tokenizer::createBPETokenizer(vocab, merges) as a static constructor for clarity.

We should also think about extensibility in the API: If later we add another algorithm (say, WordPiece for BERT), how will the user specify it? We might include an enum Tokenizer::Algorithm { BPE, WORDPIECE, SENTENCEPIECE } and perhaps a parameter in loadVocabulary or a separate method. For now, if only BPE is implemented, we can document that it supports BPE and possibly autodetect based on input files (e.g., WordPiece might only have a vocab file without merges).

Integration with DNN Module: Aside from the standalone usage, we could consider small conveniences. For example, if a model is known to be an LLM, a user might want to do net.setInputText("some prompt", tokenizer) and have it internally encode. This could be a nice addition: overloads that accept std::string and a Tokenizer to do setInput. However, this is sugar and not strictly necessary. It might be better to keep the tokenizer use explicit, which is clearer.

Error handling: If the user tries to encode text without loading a vocab, or if files aren’t found, we should throw exceptions or CV_Error to signal the issue. Similarly, if an unknown token is encountered and no [UNK] is defined, we should warn or handle it (in BPE this likely won’t happen if implemented correctly). Robustness is key for a good user experience.

Timeline

  • Community Bonding (May 8 – June 1) – Familiarization and Planning: During the community bonding period, I will immerse myself in the OpenCV codebase and understand the current state of LLM support (e.g. reviewing the GPT-2 inference sample in OpenCV’s repository (GSoC_2025 · opencv/opencv Wiki · GitHub)). I will research tokenizer libraries and algorithms (such as OpenAI’s Tiktoken and Hugging Face’s AutoTokenizer (GSoC_2025 · opencv/opencv Wiki · GitHub)) to decide on an integration approach. This period will be used to refine the project plan with my mentor, finalize the design for the tokenizer interface in the DNN module, set up the development environment, and resolve any initial setup issues. By the end of bonding, I aim to have a clear implementation roadmap and perhaps a simple proof-of-concept tokenizer in Python or pseudo-code for OpenCV.

  • Phase 1 – First Coding Period (June 2 – July 18) – Implement Tokenizer Infrastructure: Coding begins on June 2 . In the first weeks, I will implement the core tokenizer support within OpenCV’s DNN module. This involves developing a C++ class or utility that can convert raw text into tokens and back, likely starting with a basic Byte Pair Encoding (BPE) tokenizer (suitable for a model like GPT-2). By mid-June, a minimal tokenization pipeline should be operational (able to take a string and produce token IDs compatible with a known model). Next, I will integrate this tokenizer with the DNN module’s inference workflow – for example, allowing an OpenCV cv::dnn::Net to accept text input by internally calling the tokenizer. I will test this integration with a small pre-trained language model (using the existing GPT-2 example to validate that text -> tokens -> model -> output sequence works end-to-end). Throughout late June and early July, I’ll iterate on the implementation: improving efficiency (since tokenization can be CPU-intensive), handling edge cases like unknown tokens or varying sequence lengths, and ensuring the design is flexible for different tokenization schemes. Midterm Evaluation (July 14–18) – By the time of the midterm evaluation, I plan to have a working tokenizer integrated into OpenCV’s DNN module. Specifically, the deliverable will be a demo (and code submitted to the OpenCV repository) showing that an input sentence can be tokenized and fed into an LLM model via OpenCV, producing a valid output. I will prepare documentation for this new feature (usage instructions, API details) in draft form for midterm review. Successful completion of Phase 1 means the fundamental tokenizer functionality is in place and has been tested on at least one model.

  • Phase 2 – Second Coding Period (July 19 – August 25) – Extend Compatibility, Testing, and Optimization: After the midterm, I will focus on broadening and polishing the tokenizer integration. One goal is to support multiple tokenization schemes and model types – for example, integrating a WordPiece tokenizer for BERT-based models or allowing loading of custom vocabulary files so that various LLMs can be supported, not just GPT-style BPE. I will work on making the tokenizer component robust and easy to use: possibly adding Python bindings or helper functions so that users can easily apply the tokenizer in OpenCV’s Python API as well. During this phase, I will also emphasize testing and optimization. I plan to create a suite of unit tests to verify that the tokenization output matches known implementations (comparing against reference outputs from Hugging Face tokenizers for the same text inputs, ensuring our OpenCV tokenizer is correct). Performance tests will be conducted to ensure that tokenization does not become a bottleneck when processing large text inputs. If any performance issues are found, I’ll profile and optimize the code (e.g., using efficient data structures or parallelizing tokenization if feasible). By early August, I expect the extended features (multi-model support, etc.) to be implemented, and I will then concentrate on documentation and examples. I will write comprehensive documentation for the OpenCV official docs: explaining how to use the new tokenizer support, with examples of initializing a tokenizer, feeding text into a network, and decoding outputs. I will also prepare one or two example demos (possibly an OpenCV sample script) to showcase real-world usage – for instance, a demo that uses OpenCV to run a text generation or fill-in-the-blank task with an LLM, using the tokenizer integration seamlessly.

  • Final Submission and Wrap-Up (Late August) – Completion, Polish, and Submission: In the final weeks of August, I will finalize all aspects of the project. From August 18 onward, I will focus on any remaining bug fixes, code refactoring, and incorporating final feedback from mentors and the OpenCV community. I will ensure that the code adheres to OpenCV’s contributing guidelines and is well-documented and tested. The last few days before the deadline will be for double-checking that all deliverables are complete: the code (merged or ready to merge), documentation pages updated, and sample demo scripts contributed. I will also take this time to write a short report or blog post summarizing the project, challenges overcome, and instructions for future users – to be shared with the community. By August 25, which is the firm deadline for students to submit their work product, I will submit the final code and project report. During August 25–31, I’ll assist in the mentor’s final evaluations, ensure my work is properly handed off, and address any last-minute review comments. By the end of GSoC, the OpenCV codebase will include robust tokenizer support in the DNN module, delivering on the project’s goal.

Why Me

I view GSoC as more than just an internship; it’s a stepping stone toward my future in research and development. I am fully committed to the open-source ethos. Contributing to OpenCV during GSoC 2025 is especially meaningful to me because OpenCV was one of the first libraries that got me interested in computer vision, and now I have a chance to give back to it. I plan to pursue a Master’s degree in computer science, focusing on AI and possibly the intersection of vision and language. This project aligns perfectly with that trajectory, as it will deepen my knowledge in both domains and give me hands-on experience in integrating them. Successfully completing this project will not only enhance OpenCV, but also equip me with research-oriented skills like reading scientific literature (for tokenization and model integration techniques), writing efficient C++/Python code, and communicating complex ideas clearly. I am confident yet humble about “Why me” – confident that I will bring energy, dedication, and thoroughness to the project, and humble in acknowledging that I have a lot to learn. I will listen carefully to my mentors and the community, iterate based on feedback, and constantly improve. My genuine enthusiasm for open source and this project means I will persevere through any obstacles. I believe these qualities make me a strong candidate to deliver on the proposal and to become a long-term contributor to OpenCV even beyond GSoC.

Sources:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment