O que faz
- Os mesmos ids de token do tiktoken, do Hugging Face e do SentencePiece nos arquivos que carrega
- BPE, Unigram e WordPiece
- Decoder em streaming
- Contagem de tokens sem alocação
Medido
- tiktoken cl100k_base: 26,2 MB/s, 3,2x a referência (tiktoken 0.14.0)
- Hugging Face gpt2: 23,3 MB/s, 15,3x a referência (tokenizers 0.23.3)
- SentencePiece Mistral: 7,6 MB/s, 1,2x a referência (sentencepiece 0.2.2)
- String curta, cache quente: mediana de 320 ns no cl100k_base. Sem alocação depois do aquecimento
Limites conhecidos
- Não treina tokenizers. Sem templates de chat em Jinja, sem tokenizers de imagem ou de áudio
- Um tokenizer.json que define truncation ou padding é recusado na carga, assim como o modelo WordLevel e os decoders CTC e BPEDecoder
Tokenizer for language models (Ethereal::Ai::Tokenizer). It loads the vocabulary of a model and turns text into token ids, and ids back into text, with the same ids as the reference libraries: tiktoken 0.14.0, Hugging Face tokenizers 0.23.3 and sentencepiece 0.2.2. No external dependency, no allocation once the workspace is warm, and a C layer that covers the whole surface.
The module is optional: -DETHEREAL_AI_TOKENIZER=ON (off by default). It needs ETHEREAL_TEXT and ETHEREAL_TEXT_NORMALIZATION, which are on by default, for the Unicode classes and the normalizers. CMake stops with the reason when either is off.
#include <ethereal/cpp/ai/tokenizer/tokenizer_inc.hpp>
namespace T = Ethereal::Ai::Tokenizer;
T::CTokenizer Tok;
T::SLoadError Err;
if( T::CTokenizer::LoadHuggingFaceFile( "tokenizer.json", nullptr, &Tok, {}, &Err ) != T::EStatus::eOk )
return; // Err.uLine, Err.pMessage, Err.aComponent
T::CWorkspace Work; // one per thread
Work.Create( Tok );
T::CIdBuffer Ids;
Tok.Encode( "Hello, world!", T::SEncodeOptions{}, Work, Ids ); // grows on its own
std::size_t uTokens = 0;
Tok.Count( "Hello, world!", T::SEncodeOptions{}, Work, &uTokens ); // no ids written
char aText[ 256 ];
std::size_t n = 0;
Tok.Decode( Ids.Data(), Ids.Size(), T::SDecodeOptions{}, aText, sizeof( aText ), &n );Always include tokenizer_inc.hpp: it brings in the entire module in the right order. The SDK ships a complete program in examples/modules/tokenizer.cpp: it loads a WordPiece vocabulary from memory, encodes with the [CLS] and [SEP] of the model, and decodes without them.
---
What it loads
| Format | Loader | Models | Reference |
|---|---|---|---|
.tiktoken (OpenAI) | LoadTiktokenFile | BPE by rank, patterns gpt2, r50k_base, p50k_base, cl100k_base, o200k_base | tiktoken 0.14.0 |
vocab.bpe + encoder.json (GPT-2) | LoadTiktokenDataGymFile | BPE by rank | tiktoken 0.14.0 |
tokenizer.json (Hugging Face) | LoadHuggingFaceFile | BPE, WordPiece, Unigram, with the normalizer, pre-tokenizer, post-processor, decoder and added tokens | tokenizers 0.23.3 |
.model (SentencePiece) | LoadSentencePieceFile | BPE and Unigram, with the precompiled charsmap of the normalizer | sentencepiece 0.2.2 |
vocab.txt (BERT) | LoadWordPieceFile | WordPiece, with the BertNormalizer and BertProcessing built from SWordPieceConfig | BertWordPieceTokenizer of tokenizers 0.23.3 |
Each loader has a FromMemory variant (LoadTiktokenFromMemory, LoadHuggingFaceFromMemory and so on) that does not keep the bytes after the call. The tiktoken loaders take an ETiktokenPattern, which also selects the special tokens, as tiktoken does. SWordPieceConfig says what a vocab.txt does not: the special token texts, the ## prefix, lowercasing, accent stripping, CJK spacing, text cleanup and whether to add [CLS] and [SEP]. Its defaults are those of bert-base-uncased.
A component outside the supported list gives eUnsupportedFeature, with its name in SLoadError::aComponent (for example pre_tokenizer.CharDelimiterSplit). The behavior is never replaced by a similar one. The same goes for a non null truncation or padding in a tokenizer.json, a BPE dropout, a SentencePiece WORD or CHAR model, and a denormalizer with rules.
Load limits
Vocabulary files come from outside the program and are treated as untrusted input. SLoadLimits bounds every load. The defaults take every known vocabulary with room to spare (the largest known tokenizer.json files have about 35 MB and 260,000 tokens). A file that goes beyond a limit gives eLimitExceeded, with the field named in aComponent.
| Field | Default |
|---|---|
uMaxFileBytes | 64 MiB (each file of a pair) |
uMaxTokens | 4,194,304 (also the bound of every id) |
uMaxTokenBytes | 4,096 |
uMaxMerges | 4,194,304 |
uMaxMergeWorkPerByte | 32 (tiktoken, deriving merges from ranks) |
uMaxAddedTokens | 65,536 |
uMaxComponents | 1,024 |
uMaxJsonDepth | 128 |
uMaxJsonNodes | 8,388,608 |
---
The API
| Piece | What it does |
|---|---|
CTokenizer | a loaded tokenizer. Immutable after the load, movable, not copyable |
Encode( text, options, work, pOut, capacity, &written ) | ids into a buffer of the caller. Short buffer: eBufferTooSmall and the size needed |
Encode( text, options, work, CIdBuffer & ) | ids into a buffer that grows |
Encode( text, options, work, SEncodeOutput, &written ) | ids plus, on request, type ids, attention mask, special tokens mask and offsets |
EncodePair( first, second, ... ) | a pair of texts, as Hugging Face encodes a pair |
Count( text, options, work, &count ) | the number of tokens of Encode, without writing ids |
Truncate( text, maxTokens, options, work, &byteOffset ) | where to cut the text so that it keeps at most N tokens |
EncodeBatch / CountBatch | many texts spread over threads through an IParallelFor |
Decode( ids, count, options, pOut, capacity, &written ) | ids back into bytes |
VocabSize(), Kind(), Format(), IsLoaded(), Destroy() | queries and release |
TokenToId( token, &id ), IdToToken( id, &view ), IsSpecial( id ) | vocabulary lookups |
CWorkspace::Create( tokenizer, pAlloc, SWorkspaceOptions ) | the scratch memory of the encode, one per thread |
CIdBuffer | Data, Size, Capacity, Clear, Reserve, Release. Doubles when full and keeps its capacity |
CStreamDecoder | Create, Push, Finish, Reset, MaxPushBytes. Decodes one id at a time |
IParallelFor / CJobParallelFor | the thread seam of the batch functions, and its adapter over the job system |
StatusName, PatternName, PatternFromName | names for messages, and the pattern from its tiktoken name |
Result codes
| Code | When |
|---|---|
eOk | success |
eInvalidArgument | a null, empty or out of range argument, an id that is not a token (tiktoken and .model decode) |
eBufferTooSmall | the output buffer is short. The size needed is reported |
eInvalidUtf8 | the text is not valid UTF-8 (Hugging Face and vocab.txt only) |
eDisallowedSpecial | a special token appeared in the text and the mode refuses it |
eFormatError | the vocabulary file is malformed (SLoadError says where), or the encode needs an unknown token the vocabulary does not have |
eUnsupportedFeature | the file asks for a component or option this code does not implement |
eIoError | the file could not be opened, sized or mapped |
eOutOfMemory | the allocator returned null |
eLimitExceeded | a load limit, or a text of 4 GB or more (1 GB for a .model) |
eNotLicensed | the library is not licensed (see [licensing](licensing.md)) |
Special tokens and post-processing
SEncodeOptions::eSpecialMode decides what happens to a special token found in the text. The modes are those of tiktoken:
| Mode | Behavior |
|---|---|
eDisallow (default) | an error, eDisallowedSpecial, as tiktoken encode |
eAllowAll | every special token becomes its id |
eAllowList | only the ids in pAllowList / uAllowCount, any other special token is an error |
eTreatAsText | special tokens are plain text, as tiktoken encode_ordinary |
In a tokenizer.json, added tokens that are not special always match, in every mode, as in Hugging Face. SentencePiece never looks for its control symbols in the text, so the mode changes nothing for a .model.
bApplyPostProcessor puts the special tokens of the model around the text, as add_special_tokens=True in Hugging Face ([CLS] ... [SEP], the Llama template). The supported post-processors are TemplateProcessing, BertProcessing, RobertaProcessing, ByteLevel and Sequence. bAddBos and bAddEos do the same for a .model, and any other format refuses them.
bWantOffsets fills SEncodeOutput::pOffsets with the start and end of each token in bytes of the original text (SOffset). It costs nothing when off. A token added by the post-processor has [0, 0), as in Hugging Face. tiktoken has no offsets of its own: a token covers its own bytes, so it can start or end inside a code point.
Count, truncate, stream
Countruns the same encode with nowhere to write. Tokens added by the post-processor,bAddBosandbAddEosare counted.Truncatereturns the cut in bytes. The tokens before the cut are the first tokens of the encode of the whole text, and the cut never falls inside a code point or inside an added token. Tokens added by the post-processor count against the limit, as Hugging Face truncation does.CStreamDecodertakes one id at a time, as they arrive from a model generating text. EachPushwrites only complete UTF-8 characters, at mostMaxPushBytes()bytes, and the concatenation of the outputs is theDecodeof all the ids.Finishwrites what was held (an incomplete character becomes U+FFFD) and starts a new stream.EncodeBatchandCountBatchgive the same result as encoding the texts one by one. The integrator supplies anIParallelFor, or usesCJobParallelForoverJob::CJobManager(up to 13 threads, the calling one included, and the manager must have at leastWorkers - 1workers). Null runs everything on the calling thread. The module never creates threads.
---
Threads and memory
CTokenizeris immutable after the load: several threads use the same one without a lock, each with its ownCWorkspace. A workspace, aCStreamDecoderand aCIdBufferbelong to one thread at a time.Encode,Count,Truncate,Decodeand the stream do not allocate once the workspace has grown to the largest text. The loads and theCreatecalls allocate through theIAllocatorgiven (null is the default allocator).Decodenever allocates.- The workspace keeps a piece cache (
SWorkspaceOptions::uPieceCacheEntries, 4,096 entries of 64 bytes, 256 KB). It is worth 10% to 30% on BPE. Zero turns it off, and the ids are the same either way.
---
Limits and behavior
- Input text. tiktoken accepts any bytes: a run of invalid UTF-8 is a piece of its own, and
Decodegives the bytes back. A.modelaccepts any bytes, as the C++ of SentencePiece does: each invalid byte becomes U+FFFD. Hugging Face andvocab.txtrequire valid UTF-8. - Ids can have holes.
VocabSizeis the highest id plus one.cl100k_basehas no token at 100256 nor from 100261 to 100275, andIdToTokenreturns false on a hole. - Token bytes are kept as the reference keeps them: raw bytes for tiktoken, the text of the file for Hugging Face (U+0120 for the space in the byte level alphabet), SentencePiece (U+2581 for the space,
<0x41>for a byte) and WordPiece (##ing). - Decoders.
Decoderuns the decoder of atokenizer.jsonas tokenizers 0.23.3 does: ByteLevel, WordPiece with cleanup, Metaspace, ByteFallback, Fuse, Strip, Replace with a string, and Sequence of them. A Replace with a regex, a ByteLevel that is not the first decoder of a Sequence, two ByteFallback in one Sequence and more than 16 decoders giveeUnsupportedFeature. - Offsets. The
trim_offsetsof ByteLevel and RobertaProcessing moves offsets by characters, as the Python binding of Hugging Face sees them. The Rust API moves them by bytes. The two differ only when a token starts or ends with a whitespace of more than one byte. - Out of scope: training tokenizers, Jinja chat templates, image and audio tokenizers.
---
C layer
Header ethereal/c/ai/tokenizer.h, the full surface of the C++ side and nothing more. Opaque handles (ETLC_Tokenizer, ETLC_TokenizerWorkspace, ETLC_TokenizerStream, ETLC_TokenizerIdBuffer), the ETLC_STATUS return shared by every C layer, and one code of its own, ETLC_AI_DISALLOWED_SPECIAL (-5801), declared in ethereal/c/ai/ai.h. Every struct carries its size in the first field (iStructSize), and zero or a size smaller than the one of this version is refused. Where a struct is optional, NULL gives the defaults of the C++ side, and the ETLC_Tokenizer*Default functions fill a struct with them.
ETLC_Tokenizer h = NULL;
ETLC_TokenizerWorkspace w = NULL;
ETL_UINT32 aIds[ 64 ];
size_t n = 0;
if( ETLC_TokenizerLoadTiktokenFile( "cl100k_base.tiktoken", ETLC_TOKENIZER_PATTERN_CL100K_BASE, NULL, &h, NULL ) == ETLC_OK &&
ETLC_TokenizerWorkspaceCreate( h, NULL, &w ) == ETLC_OK )
ETLC_TokenizerEncode( h, w, "hello world", 11, NULL, aIds, 64, &n );
ETLC_TokenizerWorkspaceDestroy( w );
ETLC_TokenizerDestroy( h );ETLC_TokenizerEncodeEx and ETLC_TokenizerEncodePair write the extra arrays, ETLC_TokenizerEncodeBatch and ETLC_TokenizerCountBatch take an ETLC_TokenizerParallel (a runner of the caller, or the job system), and ETLC_TokenizerStream* is the streaming decoder. The layer is tested as C11 and C17 without extensions.
---
What was verified
| Criterion | Target | Measured | Status |
|---|---|---|---|
| Ids equal to tiktoken, tokenizers and sentencepiece | 100% on the test corpus | 100% | met |
Encode cl100k_base against tiktoken | 3x | 3.2x | met |
| Encode against tokenizers (BPE) | 2x | 15.3x (gpt2) | met |
Count against Encode | 1.3x faster | 1.0x | not met |
| Short string latency, p50 | 200 ns | 320 ns (cl100k_base) | not met |
| Batch scaling up to 8 threads | 0.8 of linear | 0.92 to 0.97 at 2, 0.63 to 0.94 at 4, 0.43 to 0.67 at 8 | not met |
| Allocations after warmup | 0 | 0 | met |
| Fuzzing, each parser (tiktoken, Hugging Face, SentencePiece, WordPiece) | 1 hour without a finding | 3,605 s each, 0 findings | met |
| Line coverage | 90% | 94.1% | met |
Why three targets are not met:
- **
Count** saves only the write of one integer per token, which weighs little next to the pre-tokenizer, the hash and the merge. A BPE has no way to count tokens without finding them. - Short string latency. The time of a short string is in the pre-tokenizer, which classifies one code point at a time, and in the lookup of each piece. Classifying 16 to 32 bytes at a time with SIMD is not done.
- Batch scaling. The measuring machine has 4 cores with hyper-threading: 0.8 of linear at 8 threads would be 6.4x, above what the processor gives. At 4 threads the cores share an 8 MB L3, smaller than the
cl100k_basetables. The target needs a machine with 8 physical cores.
---
Throughput
Measured on an i7-6700, GCC 15.2 -O3, one thread, over a mixed corpus of 2,329 documents (9.65 MB), the best of five passes. The reference libraries were measured on the same machine.
| Tokenizer | MB/s | Reference MB/s | Ratio |
|---|---|---|---|
tiktoken cl100k_base | 26.2 | 8.17 (tiktoken 0.14.0) | 3.2x |
tiktoken o200k_base | 22.2 | 11.07 | 2.0x |
tiktoken r50k_base | 32.5 | ||
| Hugging Face gpt2 | 23.3 | 1.52 (tokenizers 0.23.3) | 15.3x |
| Hugging Face Qwen2 | 14.7 | ||
| Hugging Face bert-base-uncased | 19.2 | 1.95 | 9.9x |
SentencePiece .model Mistral | 7.6 | 6.37 (sentencepiece 0.2.2) | 1.2x |
Latency of a short string (8 to 64 ASCII bytes, warm cache, median): 320 ns on cl100k_base, 280 ns on r50k_base, 840 ns on the Hugging Face gpt2.