MCPcopy Create free account
hub / github.com/AI-Hypercomputer/maxtext / encode

Method encode

src/MaxText/tokenizer.py:86–145  ·  view source on GitHub ↗

Encodes a string into a list of token IDs. Args: s (str): The input string to be encoded. bos (bool): Whether to prepend the beginning-of-sequence token. eos (bool): Whether to append the end-of-sequence token. allowed_tokens ("all"|set[str]): allowed specia

(
      self,
      s: str,
      *,
      allowed_special: Literal["all"] | Collection[str] = (),
      disallowed_special: Literal["all"] | Collection[str] = (),
  )

Source from the content-addressed store, hash-verified

84 max_logging.log(f"#words: {self.n_words} - BOS ID: {self.bos_id} - EOS ID: {self.eos_id}")
85
86 def encode(
87 self,
88 s: str,
89 *,
90 allowed_special: Literal["all"] | Collection[str] = (),
91 disallowed_special: Literal["all"] | Collection[str] = (),
92 ) -> list[int]:
93 """
94 Encodes a string into a list of token IDs.
95
96 Args:
97 s (str): The input string to be encoded.
98 bos (bool): Whether to prepend the beginning-of-sequence token.
99 eos (bool): Whether to append the end-of-sequence token.
100 allowed_tokens ("all"|set[str]): allowed special tokens in string
101 disallowed_tokens ("all"|set[str]): special tokens that raise an error when in string
102
103 Returns:
104 list[int]: A list of token IDs.
105
106 By default, setting disallowed_special=() encodes a string by ignoring
107 special tokens. Specifically:
108 - Setting `disallowed_special` to () will cause all text corresponding
109 to special tokens to be encoded as natural text (insteading of raising
110 an error).
111 - Setting `allowed_special` to "all" will treat all text corresponding
112 to special tokens to be encoded as special tokens.
113 """
114 assert isinstance(s, str)
115
116 # The tiktoken tokenizer can handle <=400k chars without
117 # pyo3_runtime.PanicException.
118 TIKTOKEN_MAX_ENCODE_CHARS = 400_000
119
120 # https://github.com/openai/tiktoken/issues/195
121 # Here we iterate over subsequences and split if we exceed the limit
122 # of max consecutive non-whitespace or whitespace characters.
123 MAX_NO_WHITESPACES_CHARS = 25_000
124
125 substrs = (
126 substr
127 for i in range(0, len(s), TIKTOKEN_MAX_ENCODE_CHARS)
128 for substr in self._split_whitespaces_or_nonwhitespaces(
129 s[i : i + TIKTOKEN_MAX_ENCODE_CHARS], MAX_NO_WHITESPACES_CHARS
130 )
131 )
132 t: list[int] = []
133 for substr in substrs:
134 t.extend(
135 self.model.encode(
136 substr,
137 allowed_special=set(allowed_special),
138 disallowed_special=disallowed_special,
139 )
140 )
141 if self.bos:
142 t.insert(0, self.bos_id)
143 if self.eos:

Callers

nothing calls this directly

Calls 3

insertMethod · 0.80
encodeMethod · 0.45

Tested by

no test coverage detected