Module Brot
Tokenization for OCaml.
Brot tokenizes text into token IDs for language models and reverses the process. Tokenization proceeds through configurable stages:
- Normalization: clean and normalize text (lowercase, accent removal, Unicode normalization). See
Normalizer. - Pre-tokenization: split text into words or sub-words. See
Pre_tokenizer. - Tokenization: apply vocabulary-based encoding (BPE, WordPiece, Unigram, word-level, or character-level).
- Post-processing: add special tokens and set type IDs. See
Post_processor. - Padding/Truncation: adjust sequence lengths for batching.
Each stage is optional and configurable. Open the module to use it.
The pre-tokenizer cuts text into pretokens (HuggingFace calls them words); Encoding.word_ids numbers them.
Quick start
Load a pretrained tokenizer:
let tokenizer = Brot.from_file "tokenizer.json" |> Result.get_ok in let encoding = Brot.encode tokenizer "Hello world!" in let _ids = Encoding.ids encoding
Create a BPE tokenizer from scratch:
let tokenizer = Brot.bpe ~vocab:[("hello", 0); ("world", 1); ("[PAD]", 2)] ~merges:[] () in let encoding = Brot.encode tokenizer "hello world" in let _text = Brot.decode tokenizer (Encoding.ids encoding)
Train a new tokenizer:
let texts = [ "Hello world"; "How are you?"; "Hello again" ] in let tokenizer = Brot.train_bpe (`Seq (List.to_seq texts)) ~vocab_size:1000 ~pre:(Brot.Pre_tokenizer.byte_level ()) in Brot.save_pretrained tokenizer ~path:"./my_tokenizer"
EncodingTokenization encodings.NormalizerText normalization.Pre_tokenizerPre-tokenization.Post_processorPost-processing tokenization output with special tokens.DecoderDecoding tokens back to text.
module Normalizer : sig ... endText normalization.
module Pre_tokenizer : sig ... endPre-tokenization.
module Post_processor : sig ... endPost-processing tokenization output with special tokens.
Types
type tThe type for tokenizers. What a tokenizer gives is a function of its configuration alone. It holds encoder states, the pretoken caches and buffers that encodings reuse, which grow as it encodes and are freed with it. One tokenizer can encode from several domains and threads at once.
The type for padding and truncation directions. `Left operates at the beginning of the sequence, `Right at the end.
type added_token = {- #
content : string;(*The token text:
*)"[CLS]"for a special one,"<name>"for an ordinary vocabulary entry matched atomically. - #
special : bool;(*Whether decoding may skip this token.
*) - #
single_word : bool;(*Whether this token must match whole words only.
*) - #
lstrip : bool;(*Whether a match extends over the whitespace preceding it.
*) - #
rstrip : bool;(*Whether a match extends over the whitespace following it.
*) - #
normalized : bool;(*Whether this token is matched against normalized text rather than against the raw input.
*)
}The type for added token configurations.
Added tokens are matched atomically in the input, ahead of the pre-tokenizer and the model, so "a<pad>b" encodes as "a", "<pad>", "b" whatever the model would make of "<pad>". A token with normalized unset is matched against the raw input, before normalization; one with it set is matched against the normalized text, and emits what it matched there. At a given position the longest token wins, and earlier positions win over later ones.
Token IDs are assigned automatically: a token already in the model vocabulary keeps its ID, the others are numbered from the end of it. A token with special set is skipped by decode when skip_special_tokens is true; one without it is an ordinary vocabulary entry that happens to be matched atomically. The semantic role (pad, unk, bos, etc.) is contextual, not encoded in the type.
The type for padding length strategies.
`Batch_longest: pad to the longest sequence in the batch.`Fixed n: pad every sequence to exactlyntokens.`To_multiple n: pad to the smallest multiple ofnthat is at least the sequence length.
type padding = {- #
length : pad_length; - #
direction : direction; - #
pad_id : int option; - #
pad_type_id : int option; - #
pad_token : string option;
}The type for padding configurations.
When pad_id, pad_type_id, or pad_token are None, the tokenizer's configured padding token is used. Raises Invalid_argument at padding time if no padding token is configured and these fields are None.
The type for truncation configurations. Sequences exceeding max_length tokens are trimmed from the given direction; stride is the overlap between successive overflow windows.
The type for training data sources.
`Files paths: read training text from files, one line per example. A line keeps the newline that ends it, so a byte-level pipeline trained from a file learns a token for it.`Seq seq: use a sequence of strings.
val added_token :
?special:bool ->
?single_word:bool ->
?lstrip:bool ->
?rstrip:bool ->
?normalized:bool ->
string ->
added_tokenadded_token content is an added token configuration for content.
special defaults to true; pass ~special:false for a token that is matched atomically but never skipped when decoding. single_word, lstrip and rstrip default to false. normalized defaults to not special.
The defaults line the two HuggingFace registrations up one for one: added_token c is add_special_tokens([c]) (special set, normalized unset) and added_token ~special:false c is add_tokens([c]) (special unset, normalized set).
val padding :
?direction:direction ->
?pad_id:int ->
?pad_type_id:int ->
?pad_token:string ->
pad_length ->
paddingpadding length is a padding configuration for the given length strategy.
direction defaults to `Right. Other fields default to None (falls back to the tokenizer's configured padding token).
val truncation : ?stride:int -> ?direction:direction -> int -> truncationtruncation max_length is a truncation configuration limiting sequences to max_length tokens. direction defaults to `Right: the tokens kept are the first max_length, and `Left keeps the last.
Truncation runs before the post-processor, on what is left of max_length once the special tokens it will add are counted, so a special token never pushes content out. A max_length at or below that count leaves no room for content: the special tokens are still added and the result is longer than max_length.
stride is the overlap between successive overflow windows: each window in Encoding.overflowing opens stride tokens before the end of the one before it, which is how the sliding-window question-answering workflow keeps context across windows. Defaults to 0. It must be less than the tokens left for content — on a pair, less than either sequence's share — or encode raises Invalid_argument.
Constructors
val bpe :
?normalizer:Normalizer.t ->
?pre:Pre_tokenizer.t ->
?post:Post_processor.t ->
?decoder:Decoder.t ->
?added_tokens:added_token list ->
?bos_token:string ->
?eos_token:string ->
?pad_token:string ->
?unk_token:string ->
?vocab:(string * int) list ->
?merges:(string * string) list ->
?cache_capacity:int ->
?dropout:float ->
?continuing_subword_prefix:string ->
?end_of_word_suffix:string ->
?fuse_unk:bool ->
?byte_fallback:bool ->
?ignore_merges:bool ->
unit ->
tbpe () is a BPE (Byte Pair Encoding) tokenizer. Used by GPT-2, GPT-3, RoBERTa.
normalizer: text normalization. Default: none.pre: pre-tokenization strategy. Default: none.post: post-processor for special tokens. Default: none.decoder: decoding strategy. Default: none.added_tokens: added tokens. They are matched atomically in the input onencode— against the raw text before normalization whennormalizedis unset, against the normalized text when it is set — and are numbered from the end ofvocabwithout entering it. RaisesInvalid_argumentwhen a normalized token normalizes to the empty text, and when two of different content match the same text, as two normalized tokens whose contents normalize alike do. Default:[].bos_token,eos_token,pad_token: role markers. Each is a special token in its own right, matched in the input like the entries ofadded_tokensand numbered like them whenvocabdoes not hold it. Default: none.unk_token: token for unknown characters. Configures both the role and the BPE model's unknown handling. It is a model parameter, never matched atomically in the input. Default: none.vocab: initial vocabulary as(token, id)pairs. A token given twice keeps only its last pair. Default:[].merges: merge rules as(left, right)pairs learned during training. Default:[].cache_capacity: the most entries of a pretoken cache, rounded up to a power of two, which keeps the ids of pretokens of up to 15 bytes so that one seen before is not merged again. The tokenizer makes a cache for each encoding that runs while the others are in use, from any domains or threads, and holds at mostDomain.recommended_domain_count ()of them at any time, in use or not, for as long as it lives; an encoding past that runs without one. Each starts at 16 KB, grows to hold the vocabulary's short entries, and doubles as the pretokens it meets fill half of it, up to 32 bytes per entry, and never shrinks: about 32 MB over 100 MB of web text. While it doubles, an encoding briefly holds the table it leaves too, half the size of the new one, and several encodings may double at once. Default:1048576: 32 MB each at most, 48 MB while it doubles, so a tokenizer's caches hold at mostDomain.recommended_domain_count ()times 32 MB between encodings (448 MB on 14 cores) and times 48 MB while they all double (672 MB).0disables caching.dropout: probability [0;1] of skipping merges (data augmentation). Default: none (no dropout).continuing_subword_prefix: prefix for non-initial subwords (e.g.,"##"). Default: none;""is the same as none.end_of_word_suffix: suffix marking word boundaries (e.g.,"</w>"). Default: none;""is the same as none.fuse_unk: merge consecutive unknown tokens. Default:false.byte_fallback: use byte-level fallback ("<0x00>") instead of unknown token. Default:false.ignore_merges: emit a word that is itself invocabas that single token, skipping the merges for it. Has no effect underdropout. Default:false.
val wordpiece :
?normalizer:Normalizer.t ->
?pre:Pre_tokenizer.t ->
?post:Post_processor.t ->
?decoder:Decoder.t ->
?added_tokens:added_token list ->
?bos_token:string ->
?eos_token:string ->
?pad_token:string ->
?unk_token:string ->
?vocab:(string * int) list ->
?continuing_subword_prefix:string ->
?max_input_chars_per_word:int ->
?cache_capacity:int ->
unit ->
twordpiece () is a WordPiece tokenizer. Used by BERT, DistilBERT, Electra.
WordPiece uses a greedy longest-match-first algorithm to split words into subword pieces prefixed with a continuation marker (e.g., "running" becomes ["run"; "##ning"]).
vocab: initial vocabulary as(token, id)pairs. A token given twice keeps only its last pair. Default:[].unk_token: token for out-of-vocabulary words. Default:"[UNK]".continuing_subword_prefix: prefix for non-initial subwords. Default:"##".max_input_chars_per_word: words of more characters than this, a byte that opens no whole character counting as one, are replaced withunk_token. Default:100.cache_capacity: the most entries of a pretoken cache, which keeps the ids of pretokens of up to 15 bytes so that one seen before is not encoded again. The tokenizer makes a cache for each encoding that runs while the others are in use, from any domains or threads, and holds at mostDomain.recommended_domain_count ()of them at any time, in use or not, for as long as it lives; an encoding past that runs without one. Each starts at 144 KB and doubles as it fills, up to 128 KB plus 32 bytes per entry.0disables them. Default:262144(8 MB each at most).
Pipeline parameters (normalizer, pre, post, decoder, added_tokens, bos_token, eos_token, pad_token) are as in bpe.
val word_level :
?normalizer:Normalizer.t ->
?pre:Pre_tokenizer.t ->
?post:Post_processor.t ->
?decoder:Decoder.t ->
?added_tokens:added_token list ->
?bos_token:string ->
?eos_token:string ->
?pad_token:string ->
?unk_token:string ->
?vocab:(string * int) list ->
unit ->
tword_level () is a word-level tokenizer.
Maps each word directly to a token ID. No subword splitting is performed. Words not in vocabulary map to unk_token.
Note. When pre is not provided, Pre_tokenizer.whitespace is used by default.
vocab: initial vocabulary as(word, id)pairs. Default:[].unk_token: token for out-of-vocabulary words. Default:"<unk>".
Pipeline parameters (normalizer, pre, post, decoder, added_tokens, bos_token, eos_token, pad_token) are as in bpe.
val unigram :
?normalizer:Normalizer.t ->
?pre:Pre_tokenizer.t ->
?post:Post_processor.t ->
?decoder:Decoder.t ->
?added_tokens:added_token list ->
?bos_token:string ->
?eos_token:string ->
?pad_token:string ->
?unk_token:string ->
?vocab:(string * float) list ->
?unk_id:int ->
?byte_fallback:bool ->
?cache_capacity:int ->
unit ->
tunigram () is a Unigram tokenizer. Used by AlBERT, T5, mBART.
A pretoken is cut into the vocabulary pieces whose scores add up to the most, rather than into the longest match at each byte. The scores are summed from the left, and of the cuts whose sums are equal the one whose last piece starts first is kept, then the one whose piece before that starts first, and so on. A character no piece covers costs an unknown token, scored ten below the rarest piece of the vocabulary.
vocab: initial vocabulary as(token, score)pairs where scores are log-probabilities (negative numbers). An entry is identified by its position. Default:[].unk_id: the entry standing for a run of characters the vocabulary does not hold, one token for the whole run, as atokenizer.jsonnames it. Without one, encoding raisesFailureas soon as the best path into some character would spend an unknown token on it. Default: the position ofunk_tokeninvocab, if it is there.byte_fallback: spell such a run out as byte tokens ("<0xFF>") when the vocabulary holds one for every byte of it. Default:false.unk_token: the role marker, and the model's unknown entry whenvocabholds it andunk_idis not given. Default: none.cache_capacity: the most entries of a pretoken cache, which keeps the ids of pretokens of up to 15 bytes so that one seen before is not encoded again. The tokenizer makes a cache for each encoding that runs while the others are in use, from any domains or threads, and holds at mostDomain.recommended_domain_count ()of them at any time, in use or not, for as long as it lives; an encoding past that runs without one. Each starts at 144 KB and doubles as it fills, up to 128 KB plus 32 bytes per entry.0disables them. Default:262144(8 MB each at most).
Pipeline parameters (normalizer, pre, post, decoder, added_tokens, bos_token, eos_token, pad_token) are as in bpe.
val chars :
?normalizer:Normalizer.t ->
?pre:Pre_tokenizer.t ->
?post:Post_processor.t ->
?decoder:Decoder.t ->
?added_tokens:added_token list ->
?bos_token:string ->
?eos_token:string ->
?pad_token:string ->
?unk_token:string ->
unit ->
tchars () is a byte-level tokenizer: each byte of the input is one token whose ID is the byte's value. A multi-byte character is as many tokens as it has bytes. No vocabulary is required.
Pipeline parameters (normalizer, pre, post, decoder, added_tokens, bos_token, eos_token, pad_token) are as in bpe.
val from_model_file :
vocab:string ->
?merges:string ->
?normalizer:Normalizer.t ->
?pre:Pre_tokenizer.t ->
?post:Post_processor.t ->
?decoder:Decoder.t ->
?added_tokens:added_token list ->
?bos_token:string ->
?eos_token:string ->
?pad_token:string ->
?unk_token:string ->
unit ->
tfrom_model_file ~vocab () loads a tokenizer from HuggingFace model files.
The model type is inferred from the arguments: if merges is provided, a BPE tokenizer is created; otherwise WordPiece.
vocab: path to the vocabulary file. Withmerges, avocab.json: a JSON object mapping tokens to IDs ({"hello": 0, "world": 1}). Withoutmerges, a BERT-stylevocab.txt: one token per line, trimmed, its ID the line's number from 0. A blank line holds the empty token.merges: path to merges file (merges.txt). One merge per line as space-separated token pairs. Lines starting with"#version"are skipped.
Raises Sys_error if a file cannot be read.
Pipeline parameters (normalizer, pre, post, decoder, added_tokens, bos_token, eos_token, pad_token, unk_token) are as in bpe.
val add_tokens : t -> added_token list -> tadd_tokens t tokens is t with tokens registered as added tokens, exactly as if they had been passed as added_tokens at construction: matched atomically in the input, numbered from the end of the vocabulary, and skipped by decode when their special is set. Works for every model.
A token t already holds keeps the ID it has; its flags are replaced by the new ones. Added tokens never enter the model's own vocabulary: to build one, pass vocab to the constructor.
Accessors
val normalizer : t -> Normalizer.t optionnormalizer t is t's normalizer, if any.
val pre_tokenizer : t -> Pre_tokenizer.t optionpre_tokenizer t is t's pre-tokenizer, if any.
val post_processor : t -> Post_processor.t optionpost_processor t is t's post-processor, if any.
val added_tokens : t -> added_token listadded_tokens t is t's added tokens: those given as added_tokens at construction, plus the bos_token, eos_token and pad_token role markers. This is what to_json writes.
Vocabulary
vocab t is t's vocabulary as (token, id) pairs, the model's followed by the added tokens it does not already hold.
vocab_size t is the number of tokens in t's vocabulary, added tokens included.
token_to_id t token is the ID of token in t, if any. Added tokens take precedence over the model.
id_to_token t id is the token string for id in t, if any. Added tokens take precedence over the model, and an added token matched against normalized text gives the normalized form of its content, since that is the text it stood for: on a SentencePiece model, id_to_token t 2 is "\u{2581}</s>" where token_to_id takes "</s>".
Encoding and decoding
val encode :
t ->
?pair:string ->
?add_special_tokens:bool ->
?match_special_tokens:bool ->
?padding:padding ->
?truncation:truncation ->
string ->
Encoding.tencode t text is the encoding of text by t.
Added tokens occurring in text are matched atomically and emitted with their own ID, whatever add_special_tokens is. Text that comes from a user must be encoded with ~match_special_tokens:false, so that typing "<|endoftext|>" does not end the text. The model can still give a special token's ID when its vocabulary holds that token's text as a piece, as T5's holds "</s>".
text need not be valid UTF-8: a byte that opens no whole character, a lead byte without the continuation bytes it asks for or a continuation byte with no lead, is read by every stage as a character of one byte.
Encoding.offsets are byte spans of text itself, not of the normalized form: a token of "café" under a normalizer that strips accents reports the bytes of the accented text. Encoding.word_ids number the pretokens of text from 0, an added token counting as one. Both are worked out when they are first read, so a caller that only wants Encoding.ids pays for neither; the Encoding module doc says how that first read behaves across domains.
pair: a second sentence for sentence-pair tasks. The post-processor merges both sequences with appropriate type IDs. Default: none.add_special_tokens: whether to insert special tokens via the post-processor. Default:true.match_special_tokens: whether the added tokens whosespecialis set are matched intextandpair. Withfalse, the text of such a token is normalized, pre-tokenized and encoded by the model like the text around it. The other added tokens are still matched, except inside such a token's text by one matched against the same form of the text, raw or normalized. Default:true.padding: padding configuration. Default: none (no padding).truncation: truncation configuration. Default: none (no truncation).
type exec = int -> (int -> unit) -> unitThe type for executors, which run the tasks of a batch on the program's domains. exec n task calls task i once for each i from 0 to n - 1, on any domains and in any order, and returns once every call has returned. A task never raises: a batch records what its work raised and re-raises it once exec returns.
The batch plans the work, since only it knows where a text may be cut and how padding spans the rows; each task takes chunks of it until none is left. A batch calls its executor at most once, so an executor over a pool the program already runs spreads every batch without starting a domain. Over domainslib's Task pool, for instance:
let exec pool n task = Domainslib.Task.run pool (fun () -> Domainslib.Task.parallel_for pool ~start:0 ~finish:(n - 1) ~body:task)
A batch asks for at most Domain.recommended_domain_count () tasks, so an executor may start a domain for each.
An executor over d domains started for the call, the caller's among them. A domain runs the program's signal handlers, and a handler that raises on a new domain before the runtime has set it up crashes the program. So the executor blocks the signals the program handles while it starts its domains, which keep that mask. Blocking them takes the threads.posix and unix libraries in the caller's program; brot depends on neither. On Windows, which has no signal masks, signals is [].
let spawn ~signals d n task = let next = Atomic.make 0 in let rec pull () = let i = Atomic.fetch_and_add next 1 in if i < n then (task i; pull ()) in let start () = List.init (min d n - 1) (fun _ -> Domain.spawn pull) in let others = if signals = [] then start () else let mask = Thread.sigmask Unix.SIG_BLOCK signals in let restore () = ignore (Thread.sigmask Unix.SIG_SETMASK mask) in Fun.protect ~finally:restore start in pull (); List.iter Domain.join others
A domain that ends stops every domain for a collection, so a program that encodes many batches passes an executor over a pool.
val encode_batch :
t ->
?add_special_tokens:bool ->
?match_special_tokens:bool ->
?padding:padding ->
?truncation:truncation ->
?exec:exec ->
string list ->
Encoding.t listencode_batch t texts is the encoding of each text in texts.
A batch is encoded on the calling domain unless an executor spreads it over others: where a program's work runs is its decision.
exec: the executor the batch is spread through, asexecsays. Default: none, and the batch is encoded on the calling domain. The work is planned in chunks of consecutive texts holding 64 KB to 256 KB, handed out largest first; a batch holding under 64 KB is encoded on the calling domain without callingexec. The result does not depend onexec. RaisesInvalid_argumentifexecreturns before every chunk is encoded, and whatexecraises.- Other optional parameters are as in
encode. For sentence-pair tasks, useencode_batch_pairs.
val encode_batch_pairs :
t ->
?add_special_tokens:bool ->
?match_special_tokens:bool ->
?padding:padding ->
?truncation:truncation ->
?exec:exec ->
(string * string) list ->
Encoding.t listencode_batch_pairs t pairs encodes a batch of sentence pairs. Each element is (primary, secondary).
There is no ids fast path for pairs: a pair-throughput workload goes through this function and reads Encoding.ids off each encoding.
Optional parameters are as in encode_batch.
val encode_ids :
t ->
?pair:string ->
?add_special_tokens:bool ->
?match_special_tokens:bool ->
?padding:padding ->
?truncation:truncation ->
string ->
int arrayencode_ids t text is Encoding.ids (encode t text), without building the encoding when it can be avoided: the alignment metadata is what costs, and this asks for none of it.
Optional parameters are as in encode.
type ids =
(int32, Stdlib.Bigarray.int32_elt, Stdlib.Bigarray.c_layout)
Stdlib.Bigarray.Array1.tThe type for flat token id buffers: the rows of a batch, one after the other. Nx.of_bigarray (Bigarray.genarray_of_array1 ids) copies one into a host value.
val encode_batch_ids :
t ->
?add_special_tokens:bool ->
?match_special_tokens:bool ->
?padding:padding ->
?truncation:truncation ->
?exec:exec ->
string list ->
ids * int arrayencode_batch_ids t texts is (ids, lengths): the token ids of every text end to end in one buffer, and the number of ids each of them holds. Row i starts at the sum of lengths.(0) up to lengths.(i - 1); under a padding that makes the rows equal, a buffer with at least one row reshapes to Array.length lengths by lengths.(0).
This is the throughput path. It builds no Encoding.t and allocates nothing per token: a row is what encode_ids gives for that text, with `Batch_longest resolved over the whole batch as encode_batch resolves it. Overflowing windows produced by truncation are dropped, since an ids buffer has nowhere to put them; encode_batch keeps them. A long text is spread through exec too, in pieces cut where the pipeline cannot tell the difference — a pipeline with a normalizer, or one that does not split on spaces, encodes each text in one piece.
Identifiers are narrowed to 32 bits. No vocabulary reaches that far: an identifier is an index into the token table, which holds one string per token.
The ids are gathered in buffers, one per domain encoding the batch, before they are copied into the result. t keeps them for the batches after, at most Domain.recommended_domain_count () buffers of at most 8 MB each, and they are collected with t.
Optional parameters are as in encode_batch.
decode t ids is the text obtained by decoding ids through t's vocabulary and decoder. An ID outside the vocabulary gives no text. A tokenizer without a decoder joins the tokens with a space between two.
skip_special_tokens defaults to false. It drops the added tokens whose special is set, and only those.
Streaming decoding
A model generates its output one token at a time, and a reader wants each piece of text as soon as it is final. Decoding each token on its own gets that text wrong. The decoder of a byte-level model may need several tokens for one character outside ASCII, and a SentencePiece decoder drops the space before the first word only. A stream decodes the tokens as they come and gives out the text no later token changes, keeping the rest. A stream is a value. A step gives a new stream and leaves the old one as it was, so a stream can be kept to decode another continuation from it.
A stream keeps text back in these cases only, and gives it out once the token that settles it arrives or at decode_finish:
- under a
Decoder.bpedecoder, the last token, while it holds the suffix, which becomes a space unless the token is the last; - under
Decoder.byte_fallback, an open run of byte tokens, however long, since one byte that is not UTF-8 turns each byte of the run into a replacement character; - under
Decoder.byte_level, up to three bytes that start a character not yet complete. A byte no later byte can complete, such as\xff, is given its replacement character at once; - after a
Decoder.byte_levelorDecoder.fusedecoder in aDecoder.sequence, the start of aDecoder.replacepattern that may yet complete, the occurrences aDecoder.stripmay yet cut from either end, and everything when aDecoder.byte_levelorDecoder.byte_fallbackdecoder follows, since it reads the text whole.
let print_tokens tokenizer ids = let s = ref (Brot.decode_stream tokenizer) in Array.iter (fun id -> let text, next = Brot.decode_step !s id in print_string text; s := next) ids; print_string (Brot.decode_finish !s)
type streamThe type for streaming decodings.
decode_stream t is a decoding by t that has been fed no token. skip_special_tokens is as in decode.
decode_step s id is (text, s'), where s' is s fed id and text is the text that no id fed after id changes, less what earlier steps gave. text is empty when id settles nothing, as when it ends in part of a character or extends a run of byte-fallback tokens.
The texts of every step, followed by decode_finish, make up decode of the ids fed. Each is valid UTF-8 when the vocabulary is, as no text ends inside a character.
decode_finish s is the text of the ids fed to s that no step has given out yet, decoded as the end of the ids.
Training
val train_bpe :
?init:t ->
?normalizer:Normalizer.t ->
?pre:Pre_tokenizer.t ->
?post:Post_processor.t ->
?decoder:Decoder.t ->
?added_tokens:added_token list ->
?bos_token:string ->
?eos_token:string ->
?pad_token:string ->
?unk_token:string ->
?vocab_size:int ->
?min_frequency:int ->
?limit_alphabet:int ->
?initial_alphabet:string list ->
?continuing_subword_prefix:string ->
?end_of_word_suffix:string ->
?max_token_length:int ->
data ->
ttrain_bpe data trains a BPE tokenizer from data.
The words counted are the pretokens the trained tokenizer will itself produce: every text is normalized by normalizer, then cut by pre, and each pretoken counts as one word — for a byte-level pre the words are in encoded form, and merges are learned over that form. With no pre a whole text is one word, so training on space-separated words needs ~pre:(Pre_tokenizer.whitespace_split ()).
The most frequent adjacent pair of characters is then merged over and over until vocab_size is reached, no pair is left, or the best pair falls below min_frequency.
init: a tokenizer whose added and special tokens carry over into the trained one. Its model does not: training always starts from an empty vocabulary. Default: create new.vocab_size: target vocabulary size including special tokens. Default:30000.min_frequency: minimum pair frequency to be merged. Default:0.limit_alphabet: maximum number of distinct characters to keep; the rarest go first, and words drop the characters that did not make the cut. Default: none (keep all).initial_alphabet: characters to keep whatever their frequency. Each string stands for the code point it starts with, so"été"and"é"both meané; a string that starts with no code point — empty, or not valid UTF-8 — is dropped. Default:[].continuing_subword_prefix: prefix put on every character of a word but the first, before any pair is counted, so merges are learned — and written — over the affixed forms. Default: none.end_of_word_suffix: suffix put on the last character of a word, before any pair is counted. Default: none.max_token_length: holds a merge back once the run of characters it would join reaches that many, so tokens stay shorter than it. The merges of single characters that open the training are exempt. Default: none.
Pipeline parameters (normalizer, pre, post, decoder, added_tokens, bos_token, eos_token, pad_token, unk_token) are as in bpe.
val train_wordpiece :
?init:t ->
?normalizer:Normalizer.t ->
?pre:Pre_tokenizer.t ->
?post:Post_processor.t ->
?decoder:Decoder.t ->
?added_tokens:added_token list ->
?bos_token:string ->
?eos_token:string ->
?pad_token:string ->
?unk_token:string ->
?vocab_size:int ->
?min_frequency:int ->
?limit_alphabet:int ->
?initial_alphabet:string list ->
?continuing_subword_prefix:string ->
?end_of_word_suffix:string ->
data ->
ttrain_wordpiece data trains a WordPiece tokenizer from data.
Learns the vocabulary with the BPE merge training of train_bpe, over the same words, and keeps the merged tokens as WordPiece subwords.
init: a tokenizer whose added and special tokens carry over into the trained one. Its model does not. Default: create new.vocab_size: target vocabulary size including special tokens. Default:30000.min_frequency: minimum pair frequency to be merged. Default:0.limit_alphabet: maximum number of distinct characters to keep. Default: none (keep all).initial_alphabet: characters to keep whatever their frequency, one code point per string as intrain_bpe. Default:[].continuing_subword_prefix: prefix for non-initial subwords. Default:"##".end_of_word_suffix: suffix marking word boundaries. Default: none.
Pipeline parameters (normalizer, pre, post, decoder, added_tokens, bos_token, eos_token, pad_token, unk_token) are as in bpe.
val train_word_level :
?init:t ->
?normalizer:Normalizer.t ->
?pre:Pre_tokenizer.t ->
?post:Post_processor.t ->
?decoder:Decoder.t ->
?added_tokens:added_token list ->
?bos_token:string ->
?eos_token:string ->
?pad_token:string ->
?unk_token:string ->
?vocab_size:int ->
?min_frequency:int ->
data ->
ttrain_word_level data trains a word-level tokenizer from data.
The vocabulary is the most frequent of the words counted as in train_bpe, so it holds whole pretokens and nothing is split further.
init: a tokenizer whose added and special tokens carry over into the trained one. Its model does not. Default: create new.vocab_size: target vocabulary size including special tokens. Default:30000.min_frequency: minimum frequency for a word to be included. Default:0.
Pipeline parameters (normalizer, pre, post, decoder, added_tokens, bos_token, eos_token, pad_token, unk_token) are as in bpe.
val train_unigram :
?init:t ->
?normalizer:Normalizer.t ->
?pre:Pre_tokenizer.t ->
?post:Post_processor.t ->
?decoder:Decoder.t ->
?added_tokens:added_token list ->
?bos_token:string ->
?eos_token:string ->
?pad_token:string ->
?unk_token:string ->
?vocab_size:int ->
data ->
ttrain_unigram data trains a Unigram tokenizer from data.
Warning. The EM training of the unigram model is not implemented: the vocabulary is the most frequent of the words counted as in train_bpe, each scored by how often it occurs, and no subword piece is ever proposed.
init: a tokenizer whose added and special tokens carry over into the trained one. Its model does not. Default: create new.vocab_size: target vocabulary size including special tokens. Default:8000.unk_token: also names the model's unknown entry whenadded_tokensorinitcarries it, since a trained vocabulary of whole words covers no character on its own. Without one, the trained tokenizer raisesFailureon any word it was not trained on. Default: none.
Pipeline parameters (normalizer, pre, post, decoder, added_tokens, bos_token, eos_token, pad_token, unk_token) are as in bpe.
Model files
export_tiktoken t ~merges_path ~vocab_path exports t's BPE merges and vocabulary in tiktoken-compatible format.
Warning. Only BPE tokenizers are supported. Raises Failure for other model types.
save_model_files t ~folder saves t's underlying model files (vocabulary and merges) to folder and returns the list of created file paths.
prefix defaults to "".
HuggingFace compatibility
from_file path is a tokenizer loaded from a HuggingFace tokenizer.json file. Errors if the file cannot be read or has invalid format.
A Unigram model's scores are read from their text as HuggingFace's tokenizers reads them. It rounds the digits, as a 64-bit integer, to a double, and scales that by one multiplication or division by the double nearest a power of ten, dividing by 10308 first for as long as the exponent is below -308. The roundings can land one unit in the last place from the double the text names: T5's -12.130167007446289 reads as -12.130167007446287. That unit can decide a tie between two cuts, and the cut follows tokenizers. A score tokenizers refuses as out of range is an error.
of_json json is a tokenizer deserialized from HuggingFace JSON format. Errors if json has a missing or unknown model type, or invalid parameters.
The numbers of json are taken as given. A tree decoded from text holds each number as the double its text names, which can differ in the last place from what from_file reads off the same text. Either way a BPE dropout is held in single precision, as tokenizers holds it.
The added_tokens member gives the tokens matched atomically in the input. A missing special member reads as true, and a missing normalized as not special, as in added_token. Their IDs are reassigned as documented in added_token, not read from the file.
to_json t is t serialized to HuggingFace JSON format. Its numbers are doubles. Encoding the tree with jsont writes them as jsont writes numbers, and save_pretrained writes them as tokenizers does.
save_pretrained t ~path saves t to path in HuggingFace format. Creates path/tokenizer.json.
Numbers are written as tokenizers writes them, the same on every system. A Unigram score is the shortest decimal that reads back as the double, and a BPE dropout the shortest that reads back in single precision, as in 0.1, 0.0, 0.00001, 1.5e-7 and 1e+16. Integers are written as their digits.
Raises Sys_error if path cannot be written.