gm.text.Tokenizer#
- class gemma.gm.text.Tokenizer(
- *,
- path: str | os.PathLike,
- custom_tokens: dict[int,
- str] = <factory>,
基类:
object
分词器的基类。
tokenizer = gm.text.Gemma2Tokenizer() tokenizer.encode('Hello world!') tokenizer.decode([10, 20, 30, 40, 50]) print(tokenizer.tokens[:200]) # Print the first 200 tokens. assert ( tokenizer.tokens[tokenizer.special_tokens.START_OF_TURN] == '<start_of_turn>' )
- path
词汇表文件的路径。
- 类型:
str | os.PathLike
- custom_tokens
Gemma 分词器有一些未使用的 tokens,用户可以在此处覆盖它们。期望一个字典,将未使用的 id (0-98) 映射到 token 字符串。 (例如:`{0: '
'}`) - 类型:
dict[int, str]
- VERSION
分词器的 Gemma 版本 (2, 3)。
- 类型:
ClassVar[int]
- FORBIDDEN_TOKENS
默认禁止的 tokens。
- 类型:
ClassVar[tuple[int, …]]
- path: str | os.PathLike
- custom_tokens: dict[int, str]
- VERSION: ClassVar[int] = 0
- FORBIDDEN_TOKENS: ClassVar[tuple[int, ...]] = ()
- classmethod from_version(
- version: int,
从版本创建分词器。
- encode(
- text: str | list[str],
- *,
- add_bos: bool = False,
- add_eos: bool = False,
将文本编码为 token id 列表。
tokenizer = gm.text.Gemma2Tokenizer() tokenizer.encode('Hello world!') pieces = tokenizer.split('Hello world!') assert pieces == ['Hello', ' world', '!'] tokenizer.encode(pieces)
- 参数:
text – 要编码的文本。可以是单个字符串或 token 列表。
add_bos – 是否预先添加 BOS token (`2`) (句子开头)。
add_eos – 是否追加 EOS token (`1`) (句子结尾)。
- 返回:
token id 列表。
- decode(
- ids: int | list[int] | etils.enp.array_types.typing.Array,
- split(text: str) list[str] [source]
将文本拆分成片段。
- property vocab_size: int
词汇表的大小。
- property tokens: list[str]
返回词汇表中所有 token `str` 的列表。
- property special_tokens: type[gemma.gm.text._tokenizer.SpecialTokens]
返回特殊 tokens。
- plot_logits(
- logits: enp.typing.Array,
- *,
- keep_top: int = 30,
绘制 logits 的分布图。
- 参数:
logits – 要绘制的 logits,在应用 softmax 之前 (由模型返回)。
keep_top – 要显示的 token 数量。
- 返回:
以 plotly 图形形式返回的图表。