Ai::Tokenizer

Beta

Tokenizers that give the same token ids as tiktoken, Hugging Face and SentencePiece on the files they load: BPE, Unigram and WordPiece, a streaming decoder and token counting with no allocation.

Optional module: turn it on with -DETHEREAL_AI_TOKENIZER=ONInclude #include <ethereal/cpp/ai/tokenizer/tokenizer_inc.hpp>C layer

tokenizer_inc.hpp

#include <ethereal/cpp/ai/tokenizer/tokenizer_inc.hpp>

Aggregated entry point of the Ai::Tokenizer module.

Including this header brings in the whole module. The individual headers can still be included on their own.

The module is optional: it exists only in a build with ETHEREAL_AI_TOKENIZER (macro ETL_AI_TOKENIZER).

batch.hpp

#include <ethereal/cpp/ai/tokenizer/batch.hpp>

The thread seam of CTokenizer::EncodeBatch and CountBatch, and its default adapter over the job system of the Ethereal.

IParallelFor has the shape of Ml::Neural::IParallelFor: the module never creates threads, the integrator runs the tasks on its own and Run returns once all of them are done.

CJobParallelFor runs them on the workers of Job::CJobManager: one job per worker, each job in a group of its own (the manager keeps the jobs of one group on one worker), and each job, and the calling thread too, takes the next task from an atomic counter. The calling thread waits on an atomic until every task is done.

struct

IParallelFor

Ethereal::Ai::Tokenizer#
C++
struct   ETL_API   IParallelFor
{
    /// @brief  Number of workers available (at least one).
    ///
    virtual ETL_UINT32 Workers() const ETL_NOEXCEPT = 0;


    ///
    /// Run
    ///
    /// @brief  Runs @p pFn for every task and waits for all of them.
    ///
    /// @param uTasks    Number of tasks.
    /// @param pFn        Task function, called with @p pCtx and the task index.
    /// @param pCtx        Context passed to every call.
    ///
    virtual void Run( ETL_UINT32 uTasks, void ( *pFn )( void * pCtx, ETL_UINT32 uTask ) ETL_NOEXCEPT, void * pCtx ) ETL_NOEXCEPT = 0;


    /// @brief  Destructor.
    ///
    virtual ~IParallelFor() = default;
};

Thread seam of the batch functions. The integrator spreads the tasks over its own threads.

Run calls pFn once for every task index, possibly on several threads at the same time, and returns only when all of them are done. The module never creates threads.

Thread safety: the batch functions call Run from the calling thread only. An implementation decides whether several threads may call it at once.

class

CJobParallelFor

Ethereal::Ai::Tokenizer#

IParallelFor over the workers of Job::CJobManager.

class CJobParallelFor final : public IParallelFor

Workers counts the calling thread: Run submits Workers - 1 jobs to the manager (at most the twelve groups of Job::EJobGroup), each in a group of its own so the manager spreads them over different workers, and every job and the calling thread take tasks from an atomic counter until it passes the last one. The calling thread then waits on an atomic (std::atomic::wait) until every task is done. The job function is a lambda that holds one pointer: it fits in the small buffer of std::function on the usual standard libraries. No std::function runs per task.

The state of a Run lives in one small block of the allocator, freed by the last one to leave it. A job that starts late finds no task and leaves, so Run never waits for a job that cannot start: called from a worker of the manager, or with a manager that has no workers, the calling thread does the tasks. A job the manager drops (no workers) never releases its share of the block: the manager must be initialized (Job::CJobManager::Initialize) with at least Workers - 1 workers. When the block or a job cannot be created, the calling thread does the tasks. A late job can free the block after Run returns: the allocator must outlive every job submitted by every Run.

Thread safety: Run may be called from several threads at once. Each call has its own state.

const

kMaxWorkers

#
static constexpr ETL_UINT32 kMaxWorkers = 13u;

Most threads one Run uses: the twelve groups of Job::EJobGroup, plus the calling thread.

constructor

CJobParallelFor

#
explicit CJobParallelFor( ETL_UINT32 uWorkers, Memory::IAllocator * pAlloc = nullptr ) noexcept;

Binds the adapter to a number of threads.

uWorkers
Threads to use, the calling thread included. Zero becomes one, above kMaxWorkers becomes kMaxWorkers.
pAlloc
Allocator of the state of each Run. Null is the default.
function

Workers

#
ETL_UINT32 Workers() const noexcept override

The number of workers given to the constructor.

function

Run

#
void Run( ETL_UINT32 uTasks, void ( *pFn )( void * pCtx, ETL_UINT32 uTask ) noexcept, void * pCtx ) noexcept override;

Runs every task on the workers of the manager and waits.

uTasks
Number of tasks.
pFn
Task function.
pCtx
Context passed to every call.

stream_decoder.hpp

#include <ethereal/cpp/ai/tokenizer/stream_decoder.hpp>

The streaming decoder of the Ai::Tokenizer module: one id at a time, only complete UTF-8 out.

What the streaming of a language model needs: each id the model generates goes in, and what comes out is the text it completes, never a broken character. The bytes of a character split over several tokens stay inside the decoder until the character is complete.

The concatenation of every output is the CTokenizer::Decode of all the ids, for every format and decoder Decode supports, with two exceptions:

  • tiktoken: Decode gives the raw bytes (decode_bytes), the stream gives them as valid UTF-8, each invalid chunk as U+FFFD (the from_utf8_lossy of Rust, the decode of tiktoken with errors="replace").
  • The ByteFallback decoder of Hugging Face turns a whole run of byte tokens into U+FFFD when the run is not valid UTF-8. The stream holds a run until it closes, up to kStreamHoldBytes bytes. A longer run comes out as its characters complete, and if it turns invalid after that the rest of it comes out as U+FFFD (Decode would replace the whole run). A run that comes from an encode is always valid.
const

kStreamHoldBytes

Ethereal::Ai::Tokenizer#
inline constexpr std::size_t kStreamHoldBytes = 64u;
class

CStreamDecoder

Ethereal::Ai::Tokenizer#

Decodes one id at a time and gives out only complete UTF-8.

class CStreamDecoder final

Thread safety: exclusive to one thread at a time, one per stream. The tokenizer is shared. It must not be used after its tokenizer is destroyed.

Create allocates the state once (a few kilobytes). Push, Finish and Reset never allocate.

Each Push and each Finish writes at most MaxPushBytes bytes, a bound Create computes from the tokenizer (the longest token through the decoder). A buffer of that size always fits: with a smaller one the result is eBufferTooSmall and nothing changes.

constructor

CStreamDecoder

#
CStreamDecoder() noexcept = default;

Default constructor. Empty until Create.

constructor

CStreamDecoder

#
CStreamDecoder( CStreamDecoder && Other ) noexcept;

Move constructor. Other is left empty.

operator

operator=

#
CStreamDecoder & operator=( CStreamDecoder && Other ) noexcept;

Move assignment. Releases this one first. Other is left empty.

function

Create

#
EStatus Create( const CTokenizer & Tokenizer, const SDecodeOptions & Options = SDecodeOptions{}, Memory::IAllocator * pAlloc = nullptr ) noexcept;

Creates the stream for a tokenizer. Releases the previous one first.

Tokenizer
The tokenizer, loaded.
Options
Whether the special tokens are left out.
pAlloc
Allocator of the state. Null is the default allocator.
eOk, eInvalidArgument (the tokenizer is empty), eUnsupportedFeature (a decoder Decode refuses too), eLimitExceeded (the bound of one Push passes 16 MB, a Strip with a huge stop) or eOutOfMemory. The stream is empty on failure. eNotLicensed when the library is not licensed.
function

Destroy

#
void Destroy() noexcept;

Releases the state and leaves the stream empty. Safe on an empty one.

function

IsCreated

#
bool IsCreated() const noexcept

Create succeeded.

function

MaxPushBytes

#
std::size_t MaxPushBytes() const noexcept;

The most bytes one Push or Finish writes. Zero when empty.

function

Push

#
EStatus Push( ETL_UINT32 uId, char * pOut, std::size_t uCapacity, std::size_t * pWritten ) noexcept;

Decodes one more id and writes the text it completes.

The text is complete UTF-8: a character whose bytes are not all in yet stays inside. An id that is not a token is left out (Hugging Face and 'vocab.txt', as Decode) or refused (tiktoken and '.model', eInvalidArgument, and the stream is unchanged).

uId
The id.
pOut
Receives the text. May be null when uCapacity is zero.
uCapacity
Bytes that fit in pOut.
pWritten
Receives the number of bytes written (MaxPushBytes with eBufferTooSmall).
eOk, eInvalidArgument (also a stream that is empty, or a Strip decoder that cuts past a token, after which the stream needs Reset) or eBufferTooSmall (uCapacity below MaxPushBytes).
function

Finish

#
EStatus Finish( char * pOut, std::size_t uCapacity, std::size_t * pWritten ) noexcept;

Ends the stream: writes what was held (an incomplete character becomes U+FFFD, as in Decode) and starts a new stream.

pOut
Receives the text. May be null when uCapacity is zero.
uCapacity
Bytes that fit in pOut.
pWritten
Receives the number of bytes written (MaxPushBytes with eBufferTooSmall).
eOk, eInvalidArgument (empty stream, or a Strip decoder that cuts past the text: the stream is reset anyway) or eBufferTooSmall.
function

Reset

#
void Reset() noexcept;

Drops what was held and starts a new stream. Safe on an empty one.

function

Internal

#
Detail::SStreamState * Internal() noexcept

The internal state, for the library itself and its tests. Not a stable interface. Null when empty.

tokenizer.hpp

#include <ethereal/cpp/ai/tokenizer/tokenizer.hpp>

The tokenizer object of the Ai::Tokenizer module and its loaders.

Four sources: a '.tiktoken' file (or the GPT-2 'vocab.bpe' and 'encoder.json' pair), a Hugging Face 'tokenizer.json', a SentencePiece '.model', and a WordPiece 'vocab.txt' with an explicit configuration. Each loader exists by path and by memory (pointer and size), so a client can embed its vocabulary in the binary. The library embeds none.

A load copies what it needs into memory of the tokenizer, taken from the IAllocator given (null is the default allocator). The input can be released right after.

Whatever the file asks for and this code does not implement gives eUnsupportedFeature with the name of the component, never a silently different behaviour.

class

CTokenizer

Ethereal::Ai::Tokenizer#

A loaded tokenizer.

class CTokenizer final

Immutable after the load. Every const method can run on several threads at the same time over the same object, without a lock (Encode with one CWorkspace per thread). Loading, Destroy and the moves need exclusive access.

Ids: VocabSize is the highest id plus one. The ids of a vocabulary can have holes (cl100k_base has no token at 100256 nor from 100261 to 100275). IdToToken returns false on a hole.

Tokens: the bytes as the reference keeps them. Raw bytes for tiktoken. The text of the file for Hugging Face (with the byte level alphabet, where U+0120 stands for the space), SentencePiece (U+2581 for the space, "<0x41>" for a byte) and WordPiece ("##ing").

constructor

CTokenizer

#
CTokenizer() noexcept = default;

Default constructor. The tokenizer starts empty.

constructor

CTokenizer

#
CTokenizer( CTokenizer && Other ) noexcept;

Move constructor. Other is left empty.

operator

operator=

#
CTokenizer & operator=( CTokenizer && Other ) noexcept;

Move assignment. Releases this one first. Other is left empty.

function

LoadTiktokenFile

#
static EStatus LoadTiktokenFile( std::string_view sPath, ETiktokenPattern ePattern, Memory::IAllocator * pAlloc, CTokenizer * pOut, const SLoadLimits & Limits = SLoadLimits{}, SLoadError * pError = nullptr ) noexcept;

Loads a '.tiktoken' file.

One token per line: the bytes in base64 (standard alphabet, padded), a space and the rank. Empty lines are skipped. A rank is the token id and its merge priority. The special tokens come from ePattern. A duplicated token or rank is an error.

sPath
Path of the file (UTF-8).
ePattern
Pattern of the vocabulary (selects the special tokens).
pAlloc
Allocator of the tokenizer. Null is the default.
pOut
Receives the tokenizer. Emptied first, and left empty on failure.
Limits
Limits of the load.
pError
Receives the details of a failure. May be null.
eOk, eInvalidArgument, eIoError, eFormatError, eLimitExceeded or eOutOfMemory. eNotLicensed when the library is not licensed.
function

LoadTiktokenFromMemory

#
static EStatus LoadTiktokenFromMemory( const void * pData, std::size_t uSize, ETiktokenPattern ePattern, Memory::IAllocator * pAlloc, CTokenizer * pOut, const SLoadLimits & Limits = SLoadLimits{}, SLoadError * pError = nullptr ) noexcept;

Loads a '.tiktoken' file from memory. See LoadTiktokenFile.

pData
The bytes of the file. Not kept after the call.
uSize
Number of bytes.
ePattern
Pattern of the vocabulary.
pAlloc
Allocator of the tokenizer. Null is the default.
pOut
Receives the tokenizer.
Limits
Limits of the load.
pError
Receives the details of a failure. May be null.
eOk, eInvalidArgument, eFormatError, eLimitExceeded or eOutOfMemory. eNotLicensed when the library is not licensed.
function

LoadTiktokenDataGymFile

#
static EStatus LoadTiktokenDataGymFile( std::string_view sVocabBpePath, std::string_view sEncoderJsonPath, ETiktokenPattern ePattern, Memory::IAllocator * pAlloc, CTokenizer * pOut, const SLoadLimits & Limits = SLoadLimits{}, SLoadError * pError = nullptr ) noexcept;

Loads the GPT-2 pair 'vocab.bpe' and 'encoder.json', as tiktoken builds its 'gpt2' encoding.

The ranks are the 256 bytes (in the order of the GPT-2 byte alphabet) followed by the merges of 'vocab.bpe', one rank per line after the version line. 'encoder.json' is the cross-check tiktoken also does: without its two special tokens it must give exactly the same tokens and ranks.

sVocabBpePath
Path of 'vocab.bpe'.
sEncoderJsonPath
Path of 'encoder.json'.
ePattern
Pattern (eGpt2 for the real files).
pAlloc
Allocator of the tokenizer. Null is the default.
pOut
Receives the tokenizer.
Limits
Limits of the load (the file limit applies to each).
pError
Receives the details of a failure. May be null.
eOk, eInvalidArgument, eIoError, eFormatError, eLimitExceeded or eOutOfMemory. eNotLicensed when the library is not licensed.
function

LoadTiktokenDataGymFromMemory

#
static EStatus LoadTiktokenDataGymFromMemory( const void * pVocabBpe, std::size_t uVocabBpeSize, const void * pEncoderJson, std::size_t uEncoderJsonSize, ETiktokenPattern ePattern, Memory::IAllocator * pAlloc, CTokenizer * pOut, const SLoadLimits & Limits = SLoadLimits{}, SLoadError * pError = nullptr ) noexcept;

Loads the GPT-2 pair from memory. See LoadTiktokenDataGymFile.

pVocabBpe
Bytes of 'vocab.bpe'.
uVocabBpeSize
Number of bytes.
pEncoderJson
Bytes of 'encoder.json'.
uEncoderJsonSize
Number of bytes.
ePattern
Pattern (eGpt2 for the real files).
pAlloc
Allocator of the tokenizer. Null is the default.
pOut
Receives the tokenizer.
Limits
Limits of the load.
pError
Receives the details of a failure. May be null.
eOk, eInvalidArgument, eFormatError, eLimitExceeded or eOutOfMemory. eNotLicensed when the library is not licensed.
function

LoadHuggingFaceFile

#
static EStatus LoadHuggingFaceFile( std::string_view sPath, Memory::IAllocator * pAlloc, CTokenizer * pOut, const SLoadLimits & Limits = SLoadLimits{}, SLoadError * pError = nullptr ) noexcept;

Loads a 'tokenizer.json' of Hugging Face.

Models BPE, WordPiece and Unigram (by "type", or by their fields when there is no "type", as Hugging Face does). The normalizer, pre-tokenizer, post-processor, decoder and the added tokens are kept for the encode. A component outside the supported list, a non null "truncation" or "padding", or a BPE dropout gives eUnsupportedFeature with its name.

Added tokens get their ids as Hugging Face gives them: the id of the model when the text is in the vocabulary, otherwise the next id. The "id" of the file is not used, as in Hugging Face.

sPath
Path of the file.
pAlloc
Allocator of the tokenizer. Null is the default.
pOut
Receives the tokenizer.
Limits
Limits of the load.
pError
Receives the details of a failure. May be null.
eOk, eInvalidArgument, eIoError, eFormatError, eUnsupportedFeature, eLimitExceeded or eOutOfMemory. eNotLicensed when the library is not licensed.
function

LoadHuggingFaceFromMemory

#
static EStatus LoadHuggingFaceFromMemory( const void * pData, std::size_t uSize, Memory::IAllocator * pAlloc, CTokenizer * pOut, const SLoadLimits & Limits = SLoadLimits{}, SLoadError * pError = nullptr ) noexcept;

Loads a 'tokenizer.json' from memory. See LoadHuggingFaceFile.

pData
The bytes of the file. Not kept after the call.
uSize
Number of bytes.
pAlloc
Allocator of the tokenizer. Null is the default.
pOut
Receives the tokenizer.
Limits
Limits of the load.
pError
Receives the details of a failure. May be null.
eOk, eInvalidArgument, eFormatError, eUnsupportedFeature, eLimitExceeded or eOutOfMemory. eNotLicensed when the library is not licensed.
function

LoadSentencePieceFile

#
static EStatus LoadSentencePieceFile( std::string_view sPath, Memory::IAllocator * pAlloc, CTokenizer * pOut, const SLoadLimits & Limits = SLoadLimits{}, SLoadError * pError = nullptr ) noexcept;

Loads a SentencePiece '.model' (protobuf ModelProto).

Reads the pieces (text, score, type), the trainer specification (model type, byte fallback, the special ids and pieces, the whitespace options) and the normalizer specification (name, precompiled charsmap, dummy prefix, extra whitespace, whitespace escape). Unigram and BPE. WORD and CHAR models, and a denormalizer with rules, give eUnsupportedFeature.

sPath
Path of the file.
pAlloc
Allocator of the tokenizer. Null is the default.
pOut
Receives the tokenizer.
Limits
Limits of the load.
pError
Receives the details of a failure. May be null.
eOk, eInvalidArgument, eIoError, eFormatError, eUnsupportedFeature, eLimitExceeded or eOutOfMemory. eNotLicensed when the library is not licensed.
function

LoadSentencePieceFromMemory

#
static EStatus LoadSentencePieceFromMemory( const void * pData, std::size_t uSize, Memory::IAllocator * pAlloc, CTokenizer * pOut, const SLoadLimits & Limits = SLoadLimits{}, SLoadError * pError = nullptr ) noexcept;

Loads a SentencePiece model from memory. See LoadSentencePieceFile.

pData
The bytes of the file. Not kept after the call.
uSize
Number of bytes.
pAlloc
Allocator of the tokenizer. Null is the default.
pOut
Receives the tokenizer.
Limits
Limits of the load.
pError
Receives the details of a failure. May be null.
eOk, eInvalidArgument, eFormatError, eUnsupportedFeature, eLimitExceeded or eOutOfMemory. eNotLicensed when the library is not licensed.
function

LoadWordPieceFile

#
static EStatus LoadWordPieceFile( std::string_view sPath, const SWordPieceConfig & Config, Memory::IAllocator * pAlloc, CTokenizer * pOut, const SLoadLimits & Limits = SLoadLimits{}, SLoadError * pError = nullptr ) noexcept;

Loads a WordPiece 'vocab.txt': one token per line, the id is the line number from 0.

Trailing whitespace of a line is not part of the token, as in Hugging Face. An empty token or a duplicated one is an error. The normalizer, the pre-tokenizer, the decoder and the post-processor come from Config, as BertWordPieceTokenizer builds them. The special tokens of Config that are in the vocabulary become special.

sPath
Path of the file.
Config
What the file does not say.
pAlloc
Allocator of the tokenizer. Null is the default.
pOut
Receives the tokenizer.
Limits
Limits of the load.
pError
Receives the details of a failure. May be null.
eOk, eInvalidArgument, eIoError, eFormatError, eLimitExceeded or eOutOfMemory. eNotLicensed when the library is not licensed.
function

LoadWordPieceFromMemory

#
static EStatus LoadWordPieceFromMemory( const void * pData, std::size_t uSize, const SWordPieceConfig & Config, Memory::IAllocator * pAlloc, CTokenizer * pOut, const SLoadLimits & Limits = SLoadLimits{}, SLoadError * pError = nullptr ) noexcept;

Loads a WordPiece 'vocab.txt' from memory. See LoadWordPieceFile.

pData
The bytes of the file. Not kept after the call.
uSize
Number of bytes.
Config
What the file does not say.
pAlloc
Allocator of the tokenizer. Null is the default.
pOut
Receives the tokenizer.
Limits
Limits of the load.
pError
Receives the details of a failure. May be null.
eOk, eInvalidArgument, eFormatError, eLimitExceeded or eOutOfMemory. eNotLicensed when the library is not licensed.
function

Encode

#
EStatus Encode( std::string_view sText, const SEncodeOptions & Options, CWorkspace & Work, ETL_UINT32 * pOut, std::size_t uCapacity, std::size_t * pWritten ) const noexcept;

Encodes a text into token ids, written to a buffer of the caller.

Every format and model: tiktoken (the five patterns), the BPE, WordPiece and Unigram models of a 'tokenizer.json', a 'vocab.txt' (WordPiece) and a '.model' (SentencePiece BPE and Unigram). The ids are those of the reference: tiktoken 'encode' with the mode of Options, Hugging Face 'encode' without the post-processor (add_special_tokens=False), the BertWordPieceTokenizer of the tokenizers for a 'vocab.txt', and sentencepiece 'EncodeAsIds' without bos or eos for a '.model'.

tiktoken takes any bytes: a run of invalid UTF-8 is a piece of its own, merged like any other, so Decode gives the bytes back. Hugging Face and 'vocab.txt' take valid UTF-8 only, as the reference. A '.model' takes any bytes, as the C++ of SentencePiece: each invalid byte becomes U+FFFD. SentencePiece never looks for its control symbols in the text, so the mode of the special tokens changes nothing for a '.model'.

bApplyPostProcessor, bAddBos and bAddEos work as in the Encode with SEncodeOutput. bWantOffsets needs that one: here it is eInvalidArgument.

When uCapacity is short the first uCapacity ids are written, pWritten receives the number needed and the result is eBufferTooSmall. No allocation once Work is warm.

sText
The text.
Options
The mode of the special tokens.
Work
The workspace of the calling thread.
pOut
Receives the ids. May be null when uCapacity is zero.
uCapacity
Number of ids that fit in pOut.
pWritten
Receives the number of ids (the number needed with eBufferTooSmall).
eOk, eInvalidArgument, eBufferTooSmall, eInvalidUtf8 (Hugging Face and 'vocab.txt'), eDisallowedSpecial, eFormatError (the unknown token is needed and is not in the vocabulary, or a Unigram has no unk_id, the error of the reference), eLimitExceeded (a text of 4 GB or more, 1 GB for a '.model') or eOutOfMemory.
function

Encode

#
EStatus Encode( std::string_view sText, const SEncodeOptions & Options, CWorkspace & Work, CIdBuffer & Out ) const noexcept;

Encodes a text into a buffer that grows. See the other Encode.

sText
The text.
Options
The mode of the special tokens.
Work
The workspace of the calling thread.
Out
Receives the ids (emptied first, left empty on failure).
eOk, eInvalidArgument, eInvalidUtf8, eDisallowedSpecial, eUnsupportedFeature, eFormatError, eLimitExceeded or eOutOfMemory.
function

Encode

#
EStatus Encode( std::string_view sText, const SEncodeOptions & Options, CWorkspace & Work, const SEncodeOutput & Out, std::size_t * pWritten ) const noexcept;

Encodes a text into the arrays of Out: the ids and, when asked, the type ids, the attention mask, the special tokens mask and the offsets.

With SEncodeOptions::bApplyPostProcessor the post-processor of the 'tokenizer.json' (TemplateProcessing, BertProcessing, RobertaProcessing, ByteLevel, Sequence) or the BertProcessing of a 'vocab.txt' puts its special tokens around the text, as the encode of Hugging Face with add_special_tokens=True. Without it the type ids are still those of the post-processor, as in Hugging Face. With bAddBos and bAddEos a '.model' gets its bos and eos pieces.

The offsets (bWantOffsets) are those of the reference in bytes of the text (see SOffset). Hugging Face trims them with the trim_offsets of ByteLevel and RobertaProcessing.

When Out is short the first values are written, pWritten receives the number needed and the result is eBufferTooSmall. No allocation once Work is warm.

sText
The text.
Options
The options.
Work
The workspace of the calling thread.
Out
The arrays of the caller.
pWritten
Receives the number of tokens (the number needed with eBufferTooSmall).
As the other Encode, plus eUnsupportedFeature (a post-processor that is a Sequence of more than one of TemplateProcessing, BertProcessing and RobertaProcessing, or offsets of a BPE model with byte_fallback and a subword prefix or suffix, whose reference offsets go past the word).
function

EncodePair

#
EStatus EncodePair( std::string_view sFirst, std::string_view sSecond, const SEncodeOptions & Options, CWorkspace & Work, const SEncodeOutput & Out, std::size_t * pWritten ) const noexcept;

Encodes a pair of texts, as the encode of Hugging Face with a pair.

The post-processor puts the two sequences in its pair template (with bApplyPostProcessor the special tokens too). Without one, the first sequence has type id 0 and the second type id 1. tiktoken and '.model' put the second after the first, each with its own bos and eos when asked. The offsets of the second sequence are relative to sSecond.

sFirst
The first text.
sSecond
The second text.
Options
The options.
Work
The workspace of the calling thread.
Out
The arrays of the caller.
pWritten
Receives the number of tokens.
As the Encode with SEncodeOutput.
function

Count

#
EStatus Count( std::string_view sText, const SEncodeOptions & Options, CWorkspace & Work, std::size_t * pCount ) const noexcept;

The number of tokens of Encode, without writing them.

The same encode with nowhere to write: no buffer of ids is needed and none is touched. bApplyPostProcessor, bAddBos and bAddEos count the tokens they add. bWantOffsets is ignored. No allocation once Work is warm.

sText
The text.
Options
The options.
Work
The workspace of the calling thread.
pCount
Receives the number of tokens.
As Encode, never eBufferTooSmall.
function

Truncate

#
EStatus Truncate( std::string_view sText, std::size_t uMaxTokens, const SEncodeOptions & Options, CWorkspace & Work, std::size_t * pByteOffset ) const noexcept;

Where to cut a text so that it keeps at most uMaxTokens tokens.

The text is encoded once and the cut is the start of the first token that does not fit, in bytes of the text: the tokens before the cut are the first tokens of the encode of the whole text. The cut never falls inside a code point: when a token starts inside one (tiktoken and byte level BPE split a code point between two tokens), the cut goes back to the start of that code point, and the token that crosses the cut is left out with the rest. A text that fits gives its size. With bApplyPostProcessor (or bAddBos and bAddEos) the tokens they add count against uMaxTokens, as the truncation of Hugging Face does, and the cut never falls inside an added token of the text. No allocation once Work is warm.

sText
The text.
uMaxTokens
The most tokens to keep.
Options
The options (bWantOffsets is ignored).
Work
The workspace of the calling thread.
pByteOffset
Receives the cut, from 0 to the size of the text.
As Count.
function

EncodeBatch

#
EStatus EncodeBatch( const std::string_view * pTexts, std::size_t uCount, const SEncodeOptions & Options, CWorkspace * pWorks, std::size_t uWorks, IParallelFor * pParallel, CIdBuffer * pOut, EStatus * pStatus = nullptr ) const noexcept;

Encodes many texts, spread over the workers of pParallel.

Each text is encoded on its own, as Encode would, into its own CIdBuffer: the result is the same as encoding them one by one. pParallel runs one task per workspace used (at most its Workers and uWorks), and each task takes the next text from an atomic counter. Null runs everything on the calling thread with the first workspace. No allocation once the workspaces and the buffers are warm.

pTexts
The texts.
uCount
Number of texts.
Options
The options (bWantOffsets is refused: eInvalidArgument).
pWorks
The workspaces, one per worker, created for this tokenizer.
uWorks
Number of workspaces, at least one.
pParallel
The thread seam, or null.
pOut
One buffer per text.
pStatus
Receives the status of each text. May be null.
eOk when every text gives eOk, otherwise the status of the first text that failed (in the order of pTexts), or eInvalidArgument.
function

CountBatch

#
EStatus CountBatch( const std::string_view * pTexts, std::size_t uCount, const SEncodeOptions & Options, CWorkspace * pWorks, std::size_t uWorks, IParallelFor * pParallel, std::size_t * pCounts, EStatus * pStatus = nullptr ) const noexcept;

Counts the tokens of many texts, spread over the workers of pParallel. See EncodeBatch.

pTexts
The texts.
uCount
Number of texts.
Options
The options.
pWorks
The workspaces, one per worker, created for this tokenizer.
uWorks
Number of workspaces, at least one.
pParallel
The thread seam, or null.
pCounts
Receives the number of tokens of each text.
pStatus
Receives the status of each text. May be null.
eOk when every text gives eOk, otherwise the status of the first text that failed, or eInvalidArgument.
function

Decode

#
EStatus Decode( const ETL_UINT32 * pIds, std::size_t uCount, const SDecodeOptions & Options, char * pOut, std::size_t uCapacity, std::size_t * pWritten ) const noexcept;

Decodes token ids into bytes, written to a buffer of the caller.

tiktoken: the bytes of each id (decode_bytes). An id that is not a token is eInvalidArgument, as the KeyError of the reference.

Hugging Face and 'vocab.txt': the decoder of the file, as the tokenizers 0.23.3 runs it (ByteLevel, WordPiece with cleanup, Metaspace, ByteFallback, Fuse, Strip, Replace with a string, and Sequence of them), or the tokens joined by a space without a decoder. An added token gives its normalized form when it has one. An id that is not a token is left out, as in the reference. The output of ByteLevel goes through the from_utf8_lossy of the reference: each invalid UTF-8 chunk becomes U+FFFD. A Replace with a regex, a ByteLevel that is not the first decoder of a Sequence, two ByteFallback in one Sequence, a pattern or a WordPiece prefix longer than 64 bytes, or more than 16 decoders give eUnsupportedFeature. A Strip that would cut past a token (the reference panics) gives eInvalidArgument.

SentencePiece '.model': DecodeIds of sentencepiece 0.2.2. Each U+2581 becomes a space and the one that starts the text goes away, the bytes of the byte fallback are joined (an invalid byte becomes U+FFFD), a control piece has no text and the unknown piece gives the unk_surface. An id out of the pieces is eInvalidArgument. With bSkipSpecialTokens the unknown piece is left out too.

When uCapacity is short the first uCapacity bytes are written and pWritten receives the number needed. Nothing is allocated.

pIds
The ids. May be null when uCount is zero.
uCount
Number of ids.
Options
Whether the special tokens are left out.
pOut
Receives the bytes. May be null when uCapacity is zero.
uCapacity
Number of bytes that fit in pOut.
pWritten
Receives the number of bytes (the number needed with eBufferTooSmall).
eOk, eInvalidArgument, eBufferTooSmall or eUnsupportedFeature.
CStreamDecoder (stream_decoder.hpp) decodes one id at a time.
function

Destroy

#
void Destroy() noexcept;

Releases the tokenizer and leaves it empty. Safe on an empty one.

function

IsLoaded

#
bool IsLoaded() const noexcept

A vocabulary is loaded.

function

VocabSize

#
ETL_UINT32 VocabSize() const noexcept;

Highest id plus one, special and added tokens included. Zero when empty.

function

Kind

#
EModelKind Kind() const noexcept;

Algorithm of the model. eBytePairEncoding when empty.

function

Format

#
EFormat Format() const noexcept;

Format the tokenizer was loaded from. eTiktoken when empty.

function

TokenToId

#
bool TokenToId( std::string_view sToken, ETL_UINT32 * pId ) const noexcept;

Finds the id of a token, special and added tokens included.

sToken
The bytes of the token, as IdToToken gives them.
pId
Receives the id.
true when the token exists.
function

IdToToken

#
bool IdToToken( ETL_UINT32 uId, std::string_view * pToken ) const noexcept;

Gives the bytes of a token.

uId
The id.
pToken
Receives a view of the bytes, valid while the tokenizer lives.
true when the id is a token, false on a hole or out of range.
function

IsSpecial

#
bool IsSpecial( ETL_UINT32 uId ) const noexcept;

The id is a special token (tiktoken special, Hugging Face added token marked special, SentencePiece control or unknown piece, or a special token of the WordPiece configuration).

function

Internal

#
const Detail::SModel * Internal() const noexcept

The internal representation, for the library itself and its tests. Not a stable interface. Null when empty.

tokenizer_types.hpp

#include <ethereal/cpp/ai/tokenizer/tokenizer_types.hpp>

Vocabulary of the Ai::Tokenizer module: status, kinds, patterns, load limits and the load error.

Every limit of a load has a safe default and can be raised. The vocabulary files come from outside the program and are untrusted input: a hostile file must give an error, never a crash or a huge allocation.

enum

EStatus

Ethereal::Ai::Tokenizer#
C++
enum class   EStatus : ETL_UINT32
{
    /// @brief  Success.
    eOk = 0,

    /// @brief  An argument is null, empty or out of range.
    eInvalidArgument,

    /// @brief  The output buffer is too short. The size needed is reported.
    eBufferTooSmall,

    /// @brief  The text is not valid UTF-8.
    eInvalidUtf8,

    /// @brief  A special token appeared in the text and the mode refuses it.
    eDisallowedSpecial,

    /// @brief  The vocabulary file is malformed. SLoadError says where.
    eFormatError,

    /// @brief  The file asks for a component or option this code does not
    ///             implement. SLoadError names it. Never replaced by a different
    ///             behaviour.
    eUnsupportedFeature,

    /// @brief  The file could not be opened, sized or mapped.
    eIoError,

    /// @brief  The allocator returned null.
    eOutOfMemory,

    /// @brief  The file goes beyond a limit of SLoadLimits. SLoadError names it.
    eLimitExceeded,

    /// @brief  Refused: no license was accepted and the evaluation of this machine has
    ///             ended, or the license passed was refused (see Bundle::UnlockBundle).
    eNotLicensed
};

Result of a tokenizer operation.

function

StatusName

Ethereal::Ai::Tokenizer#
const char * StatusName( EStatus eStatus ) noexcept;

Name of a status, for messages. Never returns null.

enum

EModelKind

Ethereal::Ai::Tokenizer#
C++
enum class   EModelKind : ETL_UINT8
{
    /// @brief  Byte pair encoding by merge rank: tiktoken (bytes) and the BPE model of
    ///             Hugging Face (merges list).
    eBytePairEncoding = 0,

    /// @brief  SentencePiece BPE: merges chosen by piece score.
    eSentencePieceBpe,

    /// @brief  Unigram language model (Viterbi): SentencePiece and Hugging Face.
    eSentencePieceUnigram,

    /// @brief  WordPiece, greedy longest match (the BERT family).
    eWordPiece
};

Algorithm of the model.

enum

EFormat

Ethereal::Ai::Tokenizer#
C++
enum class   EFormat : ETL_UINT8
{
    /// @brief  A '.tiktoken' file (base64 token and rank per line).
    eTiktoken = 0,

    /// @brief  The 'vocab.bpe' and 'encoder.json' pair of GPT-2 (tiktoken 'gpt2').
    eTiktokenDataGym,

    /// @brief  A 'tokenizer.json' of Hugging Face.
    eHuggingFace,

    /// @brief  A SentencePiece '.model' (protobuf ModelProto).
    eSentencePiece,

    /// @brief  A WordPiece 'vocab.txt' with an explicit configuration.
    eWordPieceVocab
};

Format the tokenizer was loaded from.

enum

ETiktokenPattern

Ethereal::Ai::Tokenizer#
C++
enum class   ETiktokenPattern : ETL_UINT8
{
    /// @brief  'gpt2': r50k pattern, <|endoftext|> 50256, 50257 ids.
    eGpt2 = 0,

    /// @brief  'r50k_base': r50k pattern, <|endoftext|> 50256, 50257 ids.
    eR50kBase,

    /// @brief  'p50k_base': r50k pattern, <|endoftext|> 50256, 50281 ids.
    eP50kBase,

    /// @brief  'cl100k_base': <|endoftext|> 100257, the three FIM tokens 100258 to
    ///             100260, <|endofprompt|> 100276.
    eCl100kBase,

    /// @brief  'o200k_base': <|endoftext|> 199999, <|endofprompt|> 200018.
    eO200kBase
};

Pre-tokenization pattern of a tiktoken vocabulary. It also selects the special tokens, as in tiktoken 0.14.0.

function

PatternName

Ethereal::Ai::Tokenizer#
const char * PatternName( ETiktokenPattern ePattern ) noexcept;

Name of a pattern ("cl100k_base"). Never returns null.

function

PatternFromName

Ethereal::Ai::Tokenizer#
bool PatternFromName( std::string_view sName, ETiktokenPattern * pOut ) noexcept;

Finds a pattern by its tiktoken name.

sName
"gpt2", "r50k_base", "p50k_base", "cl100k_base" or "o200k_base".
pOut
Receives the pattern.
true when the name is known.
const

kNoToken

Ethereal::Ai::Tokenizer#
inline constexpr ETL_UINT32 kNoToken = 0xFFFFFFFFu;

Not a token id: a hole in the ids, or a token that does not exist.

const

~ETL_UINT64

Ethereal::Ai::Tokenizer#
inline constexpr ETL_UINT64 kNoPosition = ~ETL_UINT64( 0 );

No position in the input (SLoadError).

enum

ESpecialMode

Ethereal::Ai::Tokenizer#
C++
enum class   ESpecialMode : ETL_UINT8
{
    /// @brief  A special token in the text is an error (eDisallowedSpecial). The default
    ///             of tiktoken 'encode'.
    eDisallow = 0,

    /// @brief  Every special token becomes its id. tiktoken
    ///             allowed_special="all", and the encode of Hugging Face.
    eAllowAll,

    /// @brief  The special tokens of SEncodeOptions::pAllowList become their ids and any
    ///             other one is an error: tiktoken allowed_special={...} with its default
    ///             disallowed_special="all".
    eAllowList,

    /// @brief  The special tokens are plain text. tiktoken encode_ordinary, and Hugging
    ///             Face with encode_special_tokens=True.
    eTreatAsText
};

What the encode does with the special tokens it finds in the text. The modes of tiktoken 0.14.0.

The special tokens are those of CTokenizer::IsSpecial: the special tokens of tiktoken and the added tokens of Hugging Face marked special. In tiktoken a special token is found as a plain substring. In Hugging Face it is found by the matching of the added vocabulary (single_word, lstrip, rstrip, normalized), and the added tokens that are not special always match, in every mode, as in Hugging Face.

struct

SEncodeOptions

Ethereal::Ai::Tokenizer#
C++
struct   SEncodeOptions   final
{
    /// @brief  The mode of the special tokens.
    ESpecialMode        eSpecialMode = ESpecialMode::eDisallow;

    /// @brief  eAllowList: the ids of the allowed special tokens. Each one must be a
    ///             special token of the tokenizer (otherwise eInvalidArgument).
    const ETL_UINT32 *    pAllowList = nullptr;

    /// @brief  eAllowList: number of ids in pAllowList.
    std::size_t            uAllowCount = 0u;

    /// @brief  Runs the post-processor of a 'tokenizer.json' or of a 'vocab.txt' with
    ///             add_special_tokens=True: the special tokens of its template around
    ///             the sequences. False is add_special_tokens=False. tiktoken and
    ///             '.model' have no post-processor (see bAddBos and bAddEos).
    bool                bApplyPostProcessor = false;

    /// @brief  Computes the offsets of each token (SEncodeOutput::pOffsets). Off by
    ///             default, and then they cost nothing.
    bool                bWantOffsets = false;

    /// @brief  '.model' only: puts the bos piece first (add_bos of sentencepiece),
    ///             when the model has one. Any other format refuses it
    ///             (eInvalidArgument).
    bool                bAddBos = false;

    /// @brief  '.model' only: puts the eos piece last (add_eos of sentencepiece),
    ///             when the model has one. Any other format refuses it
    ///             (eInvalidArgument).
    bool                bAddEos = false;
};

Options of CTokenizer::Encode. The defaults are those of tiktoken 'encode' (a special token in the text is an error).

struct

SOffset

Ethereal::Ai::Tokenizer#
C++
struct   SOffset   final
{
    /// @brief  Start, in bytes.
    ETL_UINT32    uBegin = 0u;

    /// @brief  End, in bytes.
    ETL_UINT32    uEnd = 0u;
};

The range of a token in the original text, in bytes: [uBegin, uEnd).

The offsets of the reference, converted to bytes: Hugging Face (the character offsets of its Python binding), sentencepiece (the begin and end of its pieces). tiktoken has no offsets: a token covers its own bytes, so a token can start or end inside a code point. A token added by the post-processor has [0, 0), as in Hugging Face. In a pair, the offsets of the second sequence are relative to its own text.

The trim_offsets of ByteLevel and RobertaProcessing moves the offsets by characters, as the Python binding sees them. The Rust API of Hugging Face moves them by bytes instead: the two differ only when a token starts or ends with a whitespace of more than one byte.

A '.model' gives the begin and end of the pieces of sentencepiece: an unknown piece covers the whole run, the bytes of the byte fallback are empty at the start of the character except the last one, the bos piece has [0, 0) and the eos piece is empty at the end.

struct

SEncodeOutput

Ethereal::Ai::Tokenizer#
C++
struct   SEncodeOutput   final
{
    /// @brief  The ids. May be null when uCapacity is zero.
    ETL_UINT32 *    pIds = nullptr;

    /// @brief  The type id of each token (token_type_ids). Optional.
    ETL_UINT32 *    pTypeIds = nullptr;

    /// @brief  The attention mask: 1 for every token (there is no padding).
    ///             Optional.
    ETL_UINT8 *        pAttentionMask = nullptr;

    /// @brief  1 for the tokens the post-processor (or bAddBos and bAddEos) added, 0
    ///             for the tokens of the text, as the special_tokens_mask of Hugging
    ///             Face. Optional.
    ETL_UINT8 *        pSpecialTokensMask = nullptr;

    /// @brief  The offsets, with SEncodeOptions::bWantOffsets (required then, unless
    ///             uCapacity is zero).
    SOffset *        pOffsets = nullptr;

    /// @brief  How many values fit in each array.
    std::size_t        uCapacity = 0u;
};

Where an encode writes, every array in a buffer of the caller with room for uCapacity values. Only pIds is required.

struct

SDecodeOptions

Ethereal::Ai::Tokenizer#
C++
struct   SDecodeOptions   final
{
    /// @brief  Leaves the special tokens out (skip_special_tokens of Hugging Face).
    ///             tiktoken has no such option: decode_bytes keeps them, as false does.
    bool    bSkipSpecialTokens = false;
};

Options of CTokenizer::Decode and of CStreamDecoder.

struct

SLoadLimits

Ethereal::Ai::Tokenizer#
C++
struct   SLoadLimits   final
{
    /// @brief  Largest input, in bytes. For a pair of files, each one.
    ETL_UINT64        uMaxFileBytes = ETL_UINT64( 64 ) << 20;

    /// @brief  Most tokens, and the bound of the ids: every id is below it.
    ETL_UINT32        uMaxTokens = 1u << 22;

    /// @brief  Longest token, in bytes (the tiktoken files go up to 128).
    ETL_UINT32        uMaxTokenBytes = 4096u;

    /// @brief  Most merges of a BPE model.
    ETL_UINT32        uMaxMerges = 1u << 22;

    /// @brief  tiktoken: most bytes hashed per byte of the tokens while deriving the
    ///             merges from the ranks (one lookup per split of each token). The real
    ///             vocabularies need about 6. Without the limit, a file of long tokens
    ///             that share prefixes costs time quadratic in the token size.
    ETL_UINT32        uMaxMergeWorkPerByte = 32u;

    /// @brief  Most special and added tokens.
    ETL_UINT32        uMaxAddedTokens = 1u << 16;

    /// @brief  Most components of the pipeline of a 'tokenizer.json', nested ones
    ///             included.
    ETL_UINT32        uMaxComponents = 1024u;

    /// @brief  Deepest JSON nesting (objects and arrays). The parser is recursive.
    ETL_UINT32        uMaxJsonDepth = 128u;

    /// @brief  Most JSON values of a 'tokenizer.json'. Each one costs a node of the
    ///             Config parser (about 100 bytes) while loading.
    ETL_UINT64        uMaxJsonNodes = ETL_UINT64( 8 ) << 20;
};

Limits of a 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) and keep a hostile file from exhausting memory.

const

kLoadErrorComponentSize

Ethereal::Ai::Tokenizer#
inline constexpr std::size_t kLoadErrorComponentSize = 64u;

Size of SLoadError::aComponent, the terminator included.

struct

SLoadError

Ethereal::Ai::Tokenizer#
C++
struct   SLoadError   final
{
    /// @brief  The status of the load.
    EStatus        eStatus = EStatus::eOk;

    /// @brief  Which input, for the loaders that take two (0 the first, 1 the
    ///             second).
    ETL_UINT32    uInput = 0u;

    /// @brief  Line of the input, starting at 1. Zero when it does not apply.
    ETL_UINT64    uLine = 0u;

    /// @brief  Byte offset in the input, or kNoPosition.
    ETL_UINT64    uOffset = kNoPosition;

    /// @brief  Short static description. Never null.
    const char *    pMessage = "";

    /// @brief  The component, option or field concerned (for example
    ///             "pre_tokenizer.CharDelimiterSplit" with eUnsupportedFeature, or
    ///             "uMaxTokens" with eLimitExceeded). Empty when none. Truncated to
    ///             fit, always terminated.
    char        aComponent[ kLoadErrorComponentSize ] = {};
};

What went wrong in a load, and where.

Fixed size and no allocation, so it can be filled on the out of memory path too.

struct

SWordPieceConfig

Ethereal::Ai::Tokenizer#
C++
struct   SWordPieceConfig   final
{
    /// @brief  Token for a word that cannot be split.
    std::string_view    sUnkToken = "[UNK]";

    /// @brief  Prefix of a piece that continues a word.
    std::string_view    sContinuingSubwordPrefix = "##";

    /// @brief  Classification token, put first by the post-processor.
    std::string_view    sClsToken = "[CLS]";

    /// @brief  Separator token, put last by the post-processor.
    std::string_view    sSepToken = "[SEP]";

    /// @brief  Padding token.
    std::string_view    sPadToken = "[PAD]";

    /// @brief  Mask token.
    std::string_view    sMaskToken = "[MASK]";

    /// @brief  A word longer than this, in code points, becomes the unknown token.
    ETL_UINT32            uMaxInputCharsPerWord = 100u;

    /// @brief  Lowercases the text (BertNormalizer).
    bool                bLowercase = true;

    /// @brief  Removes the accents (Mn after NFD, BertNormalizer).
    bool                bStripAccents = true;

    /// @brief  Puts spaces around the CJK ideographs (BertNormalizer).
    bool                bHandleChineseChars = true;

    /// @brief  Removes control characters and turns whitespace into spaces
    ///             (BertNormalizer).
    bool                bCleanText = true;

    /// @brief  Adds the BERT post-processor ([CLS] A [SEP] and [CLS] A [SEP] B [SEP]).
    ///             The two tokens must be in the vocabulary.
    bool                bAddClsSep = true;
};

What a 'vocab.txt' does not say. The defaults are those of the BertWordPieceTokenizer of Hugging Face (bert-base-uncased).

The texts are copied by the load. They need to live only during the call.

workspace.hpp

#include <ethereal/cpp/ai/tokenizer/workspace.hpp>

The scratch memory of the encode (CWorkspace) and the growing id buffer (CIdBuffer) of the Ai::Tokenizer module.

CTokenizer is immutable and shared by every thread. Whatever an encode writes while it runs lives in a CWorkspace, one per thread: the normalized text, the pre-tokens, the symbols of the merge. Its buffers come from the IAllocator given to Create and grow to the largest text seen, so once warm an encode allocates nothing.

CIdBuffer is the output of the encode that grows by itself, through an IAllocator, for a caller that does not want to size a buffer of ids first.

struct

SWorkspaceOptions

Ethereal::Ai::Tokenizer#
C++
struct   SWorkspaceOptions   final
{
    /// @brief  Entries of the piece cache. A piece that is not a token goes through
    ///             the merge, and the cache keeps the ids of the last ones by their bytes
    ///             (up to 24 bytes and 6 ids each), so a repeated word skips it. Rounded up
    ///             to a power of two sets of four. Each entry takes 64 bytes: the default
    ///             takes 256 KB. Zero turns the cache off. The ids are the same either way.
    ETL_UINT32    uPieceCacheEntries = 4096u;
};
class

CWorkspace

Ethereal::Ai::Tokenizer#

The scratch memory of the encode, for one thread.

class CWorkspace final

Thread safety: exclusive to one thread at a time. Each thread that encodes needs its own workspace, while the tokenizer itself is shared. Create, Destroy and the moves need exclusive access too.

Created from a tokenizer: it is sized and bound to it (the Regex areas of its patterns), and with it an encode allocates nothing once the buffers have grown to the largest text (warmup). It also works with another tokenizer, rebinding itself, which allocates. It must not be used after its tokenizer is destroyed, and it may be destroyed after it.

constructor

CWorkspace

#
CWorkspace() noexcept = default;

Default constructor. Empty until Create.

constructor

CWorkspace

#
CWorkspace( CWorkspace && Other ) noexcept;

Move constructor. Other is left empty.

operator

operator=

#
CWorkspace & operator=( CWorkspace && Other ) noexcept;

Move assignment. Releases this one first. Other is left empty.

function

Create

#
EStatus Create( const CTokenizer & Tokenizer, Memory::IAllocator * pAlloc = nullptr, const SWorkspaceOptions & Options = SWorkspaceOptions{} ) noexcept;

Creates the workspace for a tokenizer. Releases the previous one first.

Tokenizer
The tokenizer, loaded.
pAlloc
Allocator of every buffer. Null is the default allocator.
Options
The size of the piece cache.
eOk, eInvalidArgument (the tokenizer is empty) or eOutOfMemory (the workspace is then empty). eNotLicensed when the library is not licensed.
function

Destroy

#
void Destroy() noexcept;

Releases the buffers and leaves the workspace empty. Safe on an empty one.

function

IsCreated

#
bool IsCreated() const noexcept

Create succeeded.

function

Internal

#
Detail::SWorkspace * Internal() noexcept

The internal state, for the library itself and its tests. Not a stable interface. Null when empty.

class

CIdBuffer

Ethereal::Ai::Tokenizer#

A buffer of token ids that grows through an IAllocator.

class CIdBuffer final

The output of CTokenizer::Encode when the caller does not size the buffer. It doubles when full and keeps its capacity: reused, it stops allocating once it has grown to the largest output.

Thread safety: exclusive to one thread at a time.

constructor

CIdBuffer

#
explicit CIdBuffer( Memory::IAllocator * pAlloc = nullptr ) noexcept;

Binds the allocator (null is the default). Nothing is allocated yet.

constructor

CIdBuffer

#
CIdBuffer( CIdBuffer && Other ) noexcept;

Move constructor. Other is left empty, with the same allocator.

operator

operator=

#
CIdBuffer & operator=( CIdBuffer && Other ) noexcept;

Move assignment. Releases this one first. Other is left empty.

function

Data

#
const ETL_UINT32 * Data() const noexcept

The ids. Null while nothing was allocated.

function

Size

#
std::size_t Size() const noexcept

Number of ids.

function

Capacity

#
std::size_t Capacity() const noexcept

Number of ids that fit before the next growth.

function

Clear

#
void Clear() noexcept

Empties the buffer and keeps the memory.

function

Reserve

#
bool Reserve( std::size_t uCapacity ) noexcept;

Makes room for uCapacity ids, keeping the ones there.

uCapacity
The capacity wanted.
false when out of memory (nothing changes then).
function

Release

#
void Release() noexcept;

Releases the memory. The buffer is left empty, with its allocator.