TorchLean API

NN.API.Text.Bpe

GPT-2 Byte-Pair Encoding #

Lean-native support for GPT-2-style byte-level BPE tokenizers.

This module lives in NN.API.Text rather than a model file: any Transformer, diffusion LM, or verifier that wants GPT-2-compatible tokenization should share the same implementation. The implementation parses the standard vocab.json and merges.txt files directly in Lean.

The pre-tokenizer implements the GPT-2 regex shape:

's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+

The Unicode \p{L}, \p{N}, and \s predicates are supplied by NN.API.Text.Unicode, rather than Lean's ASCII-oriented Char.isAlpha / Char.isDigit helpers.

Data #

One token-to-id entry from GPT-2's vocab.json.

  • token : String

    Token spelling after GPT-2 byte-to-unicode escaping.

  • id :

    Token id.

Instances For

    One ranked merge from GPT-2's merges.txt. Lower rank is applied earlier.

    • left : String

      Left symbol.

    • right : String

      Right symbol.

    • rank :

      Merge priority.

    Instances For

      Loaded GPT-2 BPE tokenizer.

      Instances For

        One merge that is currently applicable to a BPE symbol sequence.

        Instances For

          Byte Escaping #

          Bytes that GPT-2 leaves at their visible Unicode code points.

          Instances For

            First Latin-1 byte range kept visible by GPT-2 byte escaping.

            Instances For

              Second Latin-1 byte range kept visible by GPT-2 byte escaping.

              Instances For

                Bytes that do not need synthetic code points in GPT-2 byte escaping.

                Instances For

                  Boolean membership test used while constructing the byte escape table.

                  Instances For

                    GPT-2 byte-to-Unicode code-point table for all 256 byte values.

                    Instances For

                      GPT-2 byte-to-unicode escape for one byte.

                      Instances For

                        Shared inverse byte-escape lookup, constructed once for the fixed GPT-2 byte alphabet.

                        Instances For

                          Inverse of byteToChar, used when decoding BPE token strings back to UTF-8.

                          Instances For

                            Reversible GPT-2 byte-to-unicode escape for a string fragment.

                            Instances For

                              Decode GPT-2 byte-to-unicode escaped text back into a UTF-8 string.

                              Instances For

                                Pre-tokenization #

                                Character classes used by the GPT-2 pre-tokenizer branches.

                                Instances For

                                  Character predicate for GPT-2's non-whitespace, non-letter, non-number regex branch.

                                  Instances For

                                    Test whether a character belongs to one of the GPT-2 regex classes.

                                    Instances For

                                      Consume one GPT-2 contraction token such as 's or 'll, if present.

                                      Instances For

                                        Consume one GPT-2 letter/number/other run, allowing a leading ASCII space.

                                        Instances For

                                          Consume the GPT-2 branch \s+(?!\S).

                                          Python's regex engine greedily takes a whitespace run but may backtrack so the negative lookahead sees either end-of-input or another whitespace character. For a whitespace run before a non-space token, this consumes all but the final whitespace; the final ASCII space can then attach to the next letter/number/punctuation branch, matching GPT-2's standard token boundaries.

                                          Instances For

                                            Consume a plain whitespace run when the lookahead-sensitive branch did not apply.

                                            Instances For

                                              Fuel-bounded worker for GPT-2 regex pre-token fragments before byte escaping and BPE merges.

                                              The branch order mirrors GPT-2's tokenizer regex exactly: contractions, optional-space letter runs, optional-space number runs, optional-space non-space/non-letter/non-number runs, whitespace not followed by non-space, and finally a plain whitespace run. The fuel argument keeps this definition total; pretokenize supplies enough fuel for the whole input.

                                              Instances For

                                                Split a string into GPT-2-style pre-token fragments.

                                                Instances For

                                                  BPE Merging #

                                                  Look up a token id in a loaded tokenizer.

                                                  Instances For

                                                    Look up the token spelling for a token id.

                                                    Instances For

                                                      Look up the merge rank for an adjacent pair of BPE symbols.

                                                      Instances For

                                                        Find the lowest-ranked merge currently available in a symbol list.

                                                        Instances For

                                                          Apply one BPE merge everywhere it appears in the current symbol list.

                                                          Instances For

                                                            Fuel-bounded BPE merge loop for a single escaped pre-token fragment.

                                                            Instances For

                                                              Apply BPE to one pre-tokenized fragment.

                                                              Instances For

                                                                Build the token-to-id lookup table stored in a loaded GPT-2 BPE tokenizer.

                                                                Instances For

                                                                  Build the id-to-token lookup table stored in a loaded GPT-2 BPE tokenizer.

                                                                  Instances For

                                                                    Build the pair-to-rank lookup table stored in a loaded GPT-2 BPE tokenizer.

                                                                    Instances For

                                                                      Assemble a tokenizer and its lookup maps from parsed GPT-2 vocabulary and merge tables.

                                                                      Instances For

                                                                        Loaded GPT-2 BPE tokenizer.

                                                                        The representation is intentionally hidden. In particular, callers cannot construct a tokenizer whose lookup tables disagree with its vocabulary or merge list; use load.

                                                                        Instances For
                                                                          opaque TorchLean.text.GPT2BPE.Tokenizer.Internal.create (representation : Internal.Tokenizer) (isCanonical : representation = Internal.buildTokenizer representation.vocabulary representation.merges) :

                                                                          Wrap a canonical GPT-2 BPE representation at the public API boundary.

                                                                          Reveal the canonical tokenizer representation only to implementation code.

                                                                          Number of tokens in a loaded GPT-2 vocabulary.

                                                                          Instances For

                                                                            Look up a complete vocabulary token, including special tokens, without splitting it as text.

                                                                            Instances For

                                                                              Encode text using the loaded GPT-2 BPE files.

                                                                              Instances For

                                                                                Decode GPT-2 BPE ids back to text.

                                                                                Instances For

                                                                                  File Loading #

                                                                                  The standard GPT-2 vocab.json is a single flat JSON object from token strings to numeric ids. Using Lean's fully general JSON object parser is convenient but slow for interactive examples because it builds a 50k-entry tree before we immediately flatten it again. The small parser below recognizes exactly the JSON shape used by GPT-2 vocab files and decodes JSON string escapes, including \uXXXX escapes for byte-to-unicode code points.

                                                                                  Read a character for the specialized vocab.json parser, using NUL past the input boundary.

                                                                                  Instances For

                                                                                    Skip JSON whitespace in the specialized GPT-2 vocabulary parser.

                                                                                    Instances For

                                                                                      Interpret one hexadecimal digit from a JSON unicode escape.

                                                                                      Instances For

                                                                                        Parse four hexadecimal digits starting at i.

                                                                                        Instances For

                                                                                          Combine a JSON UTF-16 surrogate pair into one Unicode code point.

                                                                                          Instances For

                                                                                            Fuel-bounded worker for JSON string parsing with escape handling.

                                                                                            Instances For

                                                                                              Parse a JSON string beginning at index i.

                                                                                              Instances For

                                                                                                Parse a natural-number literal beginning at index i.

                                                                                                Instances For

                                                                                                  Finish the object only when its closing brace is followed by JSON whitespace.

                                                                                                  Instances For

                                                                                                    Fuel-bounded loop for the specialized GPT-2 vocab.json object parser.

                                                                                                    Instances For

                                                                                                      Parse GPT-2 vocab.json, requiring unique tokens and contiguous token ids from zero.

                                                                                                      Instances For

                                                                                                        Parse one merges.txt line, skipping the version header and blank lines.

                                                                                                        Instances For

                                                                                                          Parse GPT-2 merges.txt, retaining hash-prefixed symbols and rejecting malformed pairs.

                                                                                                          Instances For
                                                                                                            def TorchLean.text.GPT2BPE.load (vocabularyFile mergesFile : System.FilePath) (progress : Bool := false) (label : String := "GPT2BPE") :

                                                                                                            Load GPT-2 BPE files directly in Lean. Vocabulary tokens and ids must be unique, with ids covering 0 .. vocabularySize - 1.

                                                                                                            Set progress := true to print progress for larger vocab.json and merges.txt assets. The optional label prefixes those messages.

                                                                                                            Instances For